Core Java Material
Core Java Material
Introduction:
In the olden days before introducing computer technology
into the market electronic devices were highly consumed. We already
know to operate the electronic devices we have to run the
microprocessor which is available inside the circuit. At this particular
requirement for running the microprocessor we have to implement the
programming code. This requirement gave the life for evaluating the
computer technologies into the market. We already know requirement is
one of the important roles playing in the software industry. So on the
basis of above requirement they developed first language called machine
language. On developing the applications (programs) on this language
leads to following drawbacks.
1) Code complexity
2) Understanding the language is very difficult.
Encapsulation:-
Combining both data and code into single unit is called
encapsulation.
Note: - It provides security
Polymorphism:-
One object is behaving differently in different situations we say
that particular object is exhibiting polymorphism.
In java there are two types of polymorphism
1) Static polymorphism
2) Dynamic polymorphism
Dynamic polymorphism:-
Linking method call to method definition at run time itself is called
dynamic polymorphism. It is also called late binding.
Inheritance:-
Aquiring superclass properties from subclass is called
inheritance.
Note:- It provides code reusability.
After seeing the features of object oriented programming structure we
discuss some of the important points of usage of java in real time
environment.
1. Why java?
A) It is used in realtime environment for developing the projects
due to the base on these factors……..
1) Developing the java on basis of object oriented programming
structure it provides security and reducing the code complexity.
2) Platform independency
b) Platform Independency:-
The languages which has been implemented on the basis of object
oriented approach is called platform independence applications.
Ex:-java etc……….
Suppose we compile the java program with a java compiler it provides a
class file. Class file means combination of byte code designed by
ByteEngineeringLibrary(BEL). This class file we have to execute on
java platform with the help of JVM(java virtual machine) provided by
our jdk(java development kit) software released by sun networks.
Introduction to loops:-
There are 3 loops
1) While loop
2) For loop
3) Do while loop
While loop:-
It checks the condition first when ever condition
becomes true it enters into the loop and the loop will be repeated until
the condition will be false. If the condition is false the controller
comes out of the loop.
Syntax:
While(condition)
{
}
Ex:-
For example i=1;
while(i<=10)
{
[Link](i);
i++;//value is post incremented every time.
}
Here output is 1….10 is printed.
For loop:-
It initializes the value first, after that it checks the condition
whenever it is true it enters after that it increment the value again like
that it processed.
Syntax:
for(initialization;condition;incrementation)
{
}
Ex:-
for(int i=1;i<=10;i++)
{
[Link](i);
}
doWhile:-
It enters into the loop with out checking the condition first after
executing the statement one time then it checks the condition if it is true
the loop will be repeated otherwise the controller comes out of the loop.
Ex:
int i=1;
do
{
[Link](i);
i++;
}while(i<=10);
INTRODUCTION TO DATATYPES:-
There are two types:
1) Primitive data types
2) Advanced data types
Primitive data types:-
The primitive data type is a data type it stores single value.
Ex:- int , float etc
Advanced data types:-
The advanced data type is a data type it holds multiple values.
Ex:- String , boolean
Step 5:
After compiling the program we have to execute it by using java virtual
machine………as shown in below fig5…..
JIT compiler:-
It is known as just in time compiler. It reduces the processor time and
increases the programming speed. It is responsible to convert our byte
code to machine code and viceversa. It invokes the interpreter when ever
in your program mathematical logic is supplied.
Local variable:-
The variable which is defined in inside a method is called
local variable.
Example program of showing the difference between local variable and
class variable.
class A
{
int a;//class variable
void f1()
{
int b;//local variable--1
[Link](a);
[Link](b);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();//object created
ob.f1();//calling f1 method
}
}
Explanation:
If you are trying to compile the above program it shows a
compilation error saying that
Output:-
Note:-
1) Jvm supplies default values to a class variable.
2) Jvm does not supplies any default values to class variable.
3) Whenever local variable is declared it is mandatory to assign a
value to that variable otherwise compiler gives an error.
In the above program modify at the 1 like as
int b=10 ;
The program is executed we get an output like………..
Explanation on object creation process:-
In the above program inside the main method we are created the object
with the syntax like
A ob=new A();
At this stage object creation process was involved into four steps…….
1) New operator allocating memory to variables.
2) JVM supplies default values to a class variables.
3) A special method constructor is executed.
4) New operator returns the object address.
Garbage collection:-
When ever object is no longer in use jvm calls
implicitly finalize method to destroy the object due to the presence of
memory leakage.
Note:
In java objects was not call methods directly in this case object
references were created for every object. object reference is also called
as reference variable.
Argument passing:-
It is of two types
1) Pass by value
2) Pass by reference
Pass by value:
Supplying actual parameter value to the formal parameter
is known as pass by value.
Formal parameter:-
The parmeters which has been defined in the method
signature.
Actual parameters:
The parameters which has been defined inside the method
calling with the object reference.
We see the actual parameter and the formal parameter in the below
program………..
class A
{
int result;
void f1(int a,int b)
{
result=a+b;
[Link]("Sumis:"+result);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
ob.f1(10,20);
}
}
Output:
E:\coredemo>javac [Link]
E:\coredemo>java B
Sumis:30
We see the pass by reference concept after the constructor
concept………..
Method overloading:
Defining more than one method with the same name
in a single class with different parameters we say that method is
overloading
Program :
class A
{
int a;
String b;
void f1()
{
[Link](a);
[Link](b);
}
void f1(float a)
{
[Link](a);
}
void f1(double a,char b)
{
[Link](a);
[Link](b);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
ob.f1();
}
}
Output:
E:\coredemo>javac [Link]
E:\coredemo>java B
0
Null
Constructor:-
It is a special method in java which is used for object creation
purpose.
There are two types of constructors in java…….
1) Implicit constructor
2) Explicit constructor
Implicit constructor:
If you are not providing any constructor in your
program compiler supplies default constructor implicitly. Default
constructor is also called no-argument constructor.
Explicit constructor:-
It is an explicit constructor provided by our
programmer. At this case default constructor was not provided by
our compiler why because we are providing constructor in your
program explicitly.
Note:
The constructor should be matched to the given class name other
wise compiler is doesnot treat as a constructor it gives an compile time
error.
Program:
class A
{
A()
{
[Link]("a's constructor");
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
}
}
Output:
E:\coredemo>javac [Link]
E:\coredemo>java B
a's constructor
Constructor overloading:
Defining more than one constructor in a single class
with different parameters we say that constructor is overloading.
Program:
class A
{
String a;
boolean b;
A()
{
[Link](a);
[Link](b);
}
A(int a)
{
[Link](a);
}
A(float a,char b)
{
[Link](a);
[Link](b);
}
}
class B
{
public static void main(String args[])
{
A ob=new A(20.9f,'a');
}
}
Output:
E:\coredemo>javac [Link]
E:\coredemo>java B
20.9
A
this keyword:
It has two functions
1) It shows the difference between local variable and class
variable to the compiler when they are of same name.
2) It calls one constructor to the another constructor.
Program on first function:-
class A
{
int a;
void f1(int a)
{
this.a=a;
}
void display()
{
[Link]("Value of a is:"+a);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
ob.f1(10);
[Link]();
}
}
Output:
E:\coredemo>javac [Link]
E:\coredemo>java B
Value of a is:10
Suppose if your not giving this keyword behind the variable the output
is zero why because the compiler confused when the variable is of same
name.
Program on this keyword second function:-
class A
{
String a;
float b;
A()
{
this(10.9,'a');
[Link](a);
[Link](b);
}
A(int a)
{
[Link](a);
}
A(double a,char b)
{
this(10);
[Link](a);
[Link](b);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java B
10
10.9
a
null
0.0
Introduction to inheritance:
Creating sub class from existing super class is called inheritance.
Method overriding:-
Redefining the functionality of method name with in the super class and
in the sub class with same parameters we say that method is overriding.
Program:-
class A
{
void f1(int a)
{
[Link]("Super class:"+a);
}
}
class B extends A
{
void f1(int a)
{
[Link]("Sub class:"+a);
}
}
class C
{
public static void main(String args[])
{
B ob=new B();
ob.f1(10);
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java C
Sub class:10
Note:- In the above program class A is called super class i.e. overridden
method and class B is called sub class i.e. overriding method.
b) cyclic inheritance:-
Note:- java does not support multiple inheritance directly means we
cannot extends more than one class at a time. So this concept shows we
can create number of subclasses to the any class by extending only one
class at a time.
Program:-
class A
{
void f1()
{
[Link]("a's class");
}
}
class B extends A
{
void f2()
{
[Link]("b's class");
}
}
class C extends B
{
void f3()
{
[Link]("c's class");
}
}
class cyclic
{
public static void main(String args[])
{
C ob=new C();
ob.f1();
ob.f2();
ob.f3();
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java cyclic
a's class
b's class
c's class
Constructors in inheritance:-
Example program on super keyword second use:-
class A
{
A(int a)
{
[Link]("value of a is:"+a);
}
}
class B extends A
{
B()
{
[Link]("b's constructor");
}
}
class C
{
public static void main(String args[])
{
B ob=new B();
}
}
Output:-
E:\coredemo>javac [Link]
[Link]: cannot find symbol
symbol : constructor A()
location: class A
{
^
1 error
Note:-
The above program shows a compilation error why because at the time
of object creation super class default constructor and sub class default
constructor should be available to the compiler other wise object
creation fails. In the above program your not providing any default
constructor in class A so the compiler throws an error default
constructor is missing in class A. To solve the above problem we have
two solutions…….
1) We have to provide the default constructor in class A
2) By the use of super keyword
Example program on first solution:-
class A
{
A()
{
[Link]("a's constructor");
}
A(int a)
{
[Link]("value of a is:"+a);
}
}
class B extends A
{
B()
{
[Link]("b's constructor");
}
}
class C
{
public static void main(String args[])
{
B ob=new B();
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java C
a's constructor
b's constructor
Example program on second solution:-
class A
{
A(int a)
{
[Link]("value of a is:"+a);
}
}
class B extends A
{
B()
{
super(10);
[Link]("b's constructor");
}
}
class C
{
public static void main(String args[])
{
B ob=new B();
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java C
value of a is:10
b's constructor
Dynamic method dispatch:-
Whenever method overriding is implemented super class reference is
given to the sub class object this mechanism is called dynamic method
dispatch.
Program:-
class A
{
void f1()
{
[Link]("a's class");
}
}
class B extends A
{
void f1()
{
[Link]("b's class");
}
}
class C
{
public static void main(String args[])
{
//create the reference to the super class
A ob;
//pass the above ob reference to the sub class
ob=new B();//dynamic dispatch
ob.f1();
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java C
b's class
Access specifiers:-
There are four types…………..
1) Public
2) Private
3) Protected
4) Default
Public:-
Whenever we declare class and methods as public we can access at
anywhere in java environment.
Private :-
Whenever we declare variables and methods as private it can be
accessible only in that same class only.
Protected:-
Whenever we declare variables and method as protected it can be
accessible only for the subclasses and in the same package.
We see the examples of public and protected in the next concept
package.
Packages:-
It is one of the most important concept in java.
Def: collection of class files grouping into a single folder is called
package.
There are two types of packages in java……..
1) Standard defined package
2) User defined package
// package program
//save this file as [Link]
package nit;
public class A
{
public void f1()
{
[Link]("Hi your are using the package");
}
}
Note:- whenever we give the public to the class the class name must
match to the file name otherwise it gives a compilation error.
Steps to create a main program:-
1) We have to import our package program into our main program.
2) We have to set the class path to the class loader for the location of
package program.
//main program
class usepack
{
public static void main(String args[])
{
nit.A ob=new nit.A();
ob.f1();
}
}
Compile the package program:-
E:\coredemo>javac -d . [Link]
Here in above command “.” Means current working directory.
After compiling the package program the package nit folder is created
inside the “coredemo” directory as shown below……….
Compile and execute the main program:-
Suppose this program is save in c drive so change the location to c drive
as shown below………..
Type 2:-
In this we are creating addition and subtraction package programs as
shown below……….
//[Link]
package [Link];
public class Addition
{
int result;
public void add(int a,int b)
{
result=a+b;
[Link]("Sumis:"+result);
}
}
//[Link]
package [Link];
public class Subtraction
{
int result;
public void sub(int a,int b)
{
result=a-b;
[Link]("subis:"+result);
}
}
After that create a main program by using the above two
packages…………..
import [Link];
import [Link];
class usepack
{
public static void main(String args[])
{
Addition ob=new Addition();
Subtraction ob1=new Subtraction();
[Link](10,20);
[Link](50,10);
}
}
After that compile and execute the above programs as shown
below………..
Type 3:-
//[Link]
package [Link];
public class Addition
{
int result;
public void add(int a,int b)
{
result=a+b;
[Link]("Sumis:"+result);
}
}
//[Link]
package [Link];
public class Subtraction
{
int result;
public void sub(int a,int b)
{
result=a-b;
[Link]("subis:"+result);
}
}
Note:- Type 3 says that if you want to import the two class files which is
available in the same package then we can give * after defining the
package command as shown in the below program………..
//[Link]
import [Link].*;
class usepack
{
public static void main(String args[])
{
Addition ob=new Addition();
Subtraction ob1=new Subtraction();
[Link](10,20);
[Link](50,10);
}
}
Note:- Before compiling the usepack program make sure that the
addition and subtraction java file should be compiled and after that the
source code should not be available in coredemo directory. If do so it
gives a compilation error……….so put this two source code files in
other directory as shown below……………
First way:-
//[Link]
package [Link];
public class Addition
{
int result;
protected void add(int a,int b)
{
result=a+b;
[Link]("Sum is:"+result);
}
}
//[Link]
package [Link];
public class Subtraction
{
int result;
public void sub(int a,int b)
{
result=a-b;
[Link]("Sub is:"+result);
}
}
//[Link]
import [Link];
import [Link];
class usepack extends Addition
{
public static void main(String args[])
{
usepack ob=new usepack();
Subtraction ob1=new Subtraction();
[Link](10,20);
[Link](50,10);
}
}
Compiling and executing the above programs as shown in below
fig……………
Second way:-
In the second way iam giving the same package name to the main
program i.e to [Link]
//[Link]
package [Link];
public class Addition
{
int result;
protected void add(int a,int b)
{
result=a+b;
[Link]("Sum is:"+result);
}
}
//[Link]
package [Link];
public class Subtraction
{
int result;
public void sub(int a,int b)
{
result=a-b;
[Link]("Sub is:"+result);
}
}
//[Link]
package [Link];
import [Link];
import [Link];
class usepack
{
public static void main(String args[])
{
usepack ob=new usepack();
Subtraction ob1=new Subtraction();
[Link](10,20);
[Link](50,10);
}
}
Type casting:-
Casting means converting one value into another value.
In java there are two types of conversions…….
1) Widening conversion
2) Narrowing conversion
Widening conversion:-
It is an implicit conversion done by the
compiler automatically. Converting lower value to higher value is
known as widening conversion.
Narrowing conversion:-
It is an explicit conversion done by the
programmer. Converting higher value to lower value is known as
narrowing conversion.
Program 1:-
class A
{
//widening conversion
void f1(int a)
{
float b=a;
[Link](b);
}
//narrowing conversion
void f2(float a)
{
int b=(int)a;
[Link](b);
}
}
class casting
{
public static void main(String args[])
{
A ob=new A();
ob.f1(10);
ob.f2(100.9f);
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java casting
10.0
100
Note: The drawback in narrowing conversion is fraction part was
truncated.
Program 2:-
class A
{
//widening conversion
void f1(char a)
{
int b=a;
[Link](b);
}
//narrowing conversion
void f2(int a)
{
char b=(char)a;
[Link](b);
}
}
class casting1
{
public static void main(String args[])
{
A ob=new A();
ob.f1('A');
ob.f2(68);
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java casting1
65
D
Note:-
In the above program when ever we are converting char to int
“ASCII” code is provided for every character.
Wrapper classes:-
If you want to convert data type value into string value widening and
narrowing conversions failed in this case, because the string and
Boolean or advanced data types. So advanced types was not performed
in casting because it hold multiple values for example in String we can
pass either numbers and characters also so that type of dual conversion
was not allowed.
To solve this problem wrapper class was developed.
It has two functions
1) It converts string value into any data type value except character.
2) It converts data type value into wrapped object.
First function:-
In this below program we are converting String value into int value for
this case Integer wrapper class is available. By using this we convert that
string value into data type value and also see the below table for
different wrapper classes available for different data types…………
Data types wrapper classes
int Integer
float Float
char Character
double Double
Program:-
class A
{
void f1(String a)
{
int b=[Link](a);
[Link](b);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
ob.f1("10");
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java B
10
Second function:-
The second function was developed for the collection framework we
discuss this concept later……
In the collection framework there are some predefined collection classes
was available suppose we want to pass the data type value to those
collection class it was not accepted why because it take only objects in
order to convert that data type value into object wrapper class introduced
another mechanism called wrapping.
Wrapping: It is a process of converting data type value into wrapped
object value.
Program:-
class A
{
void f1()
{
Integer i=new Integer(10);//wrapped the 10 value into i object
int j=[Link]();
/*intValue() is the predefined
static method which is available
inside the Integer wrapper class
it converts wrapped object value into
data type value*/
[Link](j);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
ob.f1();
}
}
Output:-
E:\coredemo>javac [Link]
E:\coredemo>java B
10
Arrays:-
Arrays is nothing but collection of homogenous(similar) elements
referred by the same name is known as array.
Ex:- int arr[]={10,20,30…….n};
We can also supply n number of values to single variable as shown
above………
Static :-
Whenever we declare variable and method as static with out object
creation we can call directly with that class name.
Program:-
class A
{
static int a=10;
static void f1()
{
[Link]("f1 method");
}
}
class B
{
public static void main(String args[])
{
[Link](A.a);
A.f1();
}
}
Output:-
Note:-
Whenever class is loaded into memory whatever we declare with static
one copy instance is created dynamically.
Q) can we execute our program without main method or not???
A) yes we can execute our program using static block.
Example program on use of static block:-
class A
{
static void f1()
{
[Link]("Hi you are using static");
}
static
{
[Link]("static block");
f1();
}
}
Output:-
Final:-
Whenever we declare variable as final the value cannot be changed
programmatically.
Program:-
class A
{
final int a=10;
void f1()
{
a=20;
[Link]("Value of a is:"+a);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
ob.f1();
}
}
The above program shows a compilation error because we cannot
reinitialize a value to a final variable as shown in below fig…..
Output:-
Abstract:-
A class represents a base class which another types to be a subtype of a
class.
1) Whenever we declare method as abstract it has no
implementation(body not be provided) just definition only.
2) Whenever we declare method as abstract it is mandatory to declare
the class also a abstract.
3) Object was not created for abstract class.
4) In abstract class we can also provide concrete methods and
constructors also.
5) In abstract class we can have zero or more abstract methods.
Output:-
Interface:-
1) In the most common form, an interface is a group of related
methods with empty bodies.
2) Implementing an interface allows a class to become more formal
about the behavior it promises to provide.
3) Interfaces form a contract between the class and the outside world,
and this contract is enforced at build time by the compiler.
4) If your class claims to implement an interface, all methods defined
by that interface must appear in its source code before the class
will successfully compile.
5) One interface can extends another interface also
6) Object was not created for interface only reference will be created.
Syntax of interface:-
Program:-
interface CarDetails
{
void setName(String a);
String getName();
void setMielage(int b);
int getMielage();
void setGears(int c);
int getGears();
}
class Alto implements CarDetails
{
String a;
int b,c;
public void setName(String a)
{
this.a=a;
}
public String getName()
{
return a;
}
public void setMielage(int b)
{
this.b=b;
}
public int getMielage()
{
return b;
}
public void setGears(int c)
{
this.c=c;
}
public int getGears()
{
return c;
}
}
class Santro implements CarDetails
{
String a;
int b,c;
public void setName(String a)
{
this.a=a;
}
public String getName()
{
return a;
}
public void setMielage(int b)
{
this.b=b;
}
public int getMielage()
{
return b;
}
public void setGears(int c)
{
this.c=c;
}
public int getGears()
{
return c;
}
}
class useofinterface
{
public static void main(String args[])
{
Alto al=new Alto();
[Link]("Alto");
[Link](13);
[Link](5);
[Link]("Car Details are.....");
[Link]("Car name is:"+[Link]());
[Link]("Car mielage is:"+[Link]());
[Link]("Car gears is:"+[Link]());
[Link]("------------------------");
Santro st=new Santro();
[Link]("santro");
[Link](15);
[Link](4);
[Link]("Car Details are.....");
[Link]("Car name is:"+[Link]());
[Link]("Car mileage is:"+[Link]());
[Link]("Car gears is:"+[Link]());
}
}
Output:-
Note:-
When you implement an interface method it must declared as public.
Nested interface:-
An interface can be declared a member of a class or another interface.
Such an interface called a member interface or nested interface.
Program:-
class A
{
public interface NestedIf
{
boolean isNotNegative(int x);
}
}
class B implements [Link]
{
public boolean isNotNegative(int x)
{
if(x<0)
return false;
else
return true;
}
}
class NestedIfDemo
{
public static void main(String args[])
{
//use a nested interface reference
[Link] nif=new B();
int no=[Link](args[0]);
if([Link](no)==true)
[Link]("Number is not negative");
else
[Link]("Number is negative");
}
}
Output:-
Nested classes:-
Defining one class in another class is called nested classes.
In java there are two types……
Errors:-
It is a unreported exception that occurs during the
compilation time itself. To handle this kind of exception java
provides a keyword called throws.
Exception:-
It is of two types
1) Checked exception
2) Unchecked exception
Checked exception:-
It is a reported exception that occurs during
the runtime itself. Application programmer can handle this kind of
exception directly. Java provides three keywords to handle this
kind of exception.
1. Try
2. Catch
3. Finally
Try:-
Whatever doubtful code we know in the program keep it
inside the try block.
Catch:-
Whatever exception is generated inside the try block that
exception object is hold by the catch block.
Finally:-
Whether the exception is generated or not whatever we
defined inside the finally is compulsory to be executed.
Output:-
IOProgramming:-
Stream:-
It is a predefined object in java. It takes input stream and converts into
output stream and viceversa.
There are two types of streams in java
1) Byte oriented stream
2) Character oriented stream
Output:-
Output:-
Object serialization:-
It is the process of converting stream code into object code( byte code)
Program:-
import [Link].*;
class student implements Serializable
{
int rollno;
student(int rollno)
{
[Link]=rollno;
}
void display()
{
[Link]("Rollno:"+rollno);
}
}
class objser
{
public static void main(String args[])throws Exception
{
FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);
student s=new student(101);
[Link](s);
[Link]("Object is serialized");
[Link]();
[Link]();
}
}
Output:-
Object deserialization:-
It is the process of converting object code into stream code.
Program:-
import [Link].*;
class student implements Serializable
{
int rollno;
student(int rollno)
{
[Link]=rollno;
}
void display()
{
[Link]("Rollno:"+rollno);
}
}
class objdser
{
public static void main(String args[])throws Exception
{
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);
student st=(student)[Link]();
[Link]("Object is deserialized");
[Link]();
[Link]();
[Link]();
}
}
Output:-
Networking:-
Communication between two machines is called networking.
Socket:-
It is an end point communication between two systems.
In java communication is of two types………
class Client
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",9999);
[Link]("connection is established to server");
OutputStream os=[Link]();
PrintWriter pw=new PrintWriter(os);
[Link]("Hello Server");
[Link]();
[Link]();
}
}
//[Link]
import [Link].*;
import [Link].*;
class Server
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(9999);
[Link]("serversocket object is created");
[Link]("server is ready to interact with client");
Socket s=[Link]();
InputStream is=[Link]();
BufferedReader br=new BufferedReader(new
InputStreamReader(is));
String fromclient=[Link]();
[Link]("FromClient:"+fromclient);
[Link]();
[Link]();
}
}
Output:-
Thread:-
A single sequential flow of process is known as thread.
There are two ways of creating a thread in java…..
1) Our class must be extends Thread class.
2) Our class must be implements Runnable interface.
New state:-
Whenever we create a object to the subclass of the thread class the
thread enters into the new state.
Active state:-
Whenever we call the start method on the subclass object the
controller invokes the run method the thread enters into the active
state.
Blocked state:-
Whenever we perform the suspending operations inside the run
method the thread enters into the blocked state.
Dead state:-
Whenever the code is executed successfully inside the run method
automatically jvm calls internally a predefined method called kill
and thread becomes dead means the thread object is garbage
collected by the garbage collector.
Program:-
Output:-
Whenever if you want to share the same object values to different
threads at this case we should not get the exact output what we have
expected.
Program:-
class reserve implements Runnable
{
int available=1;
int wanted;
reserve(int i)
{
wanted=i;
}
public void run()
{
if(available>=wanted)
{
[Link]("Available berths is:"+available);
String n=[Link]().getName();
[Link](available+":berth is reserved to
passenger:"+n);
try
{
[Link]("Transaction is under processing");
[Link](5000);
available=available-wanted;
}
catch(Exception e){}
}
else
[Link]("Sorry no berths");
}
}
class UnSafe
{
public static void main(String args[])
{
reserve res=new reserve(1);
Thread t1=new Thread(res);
Thread t2=new Thread(res);
[Link](“sai”);
[Link](“lakshman”);
[Link]();
[Link]();
}
}
Output:-
So the two passengers was booked the same berth so the expected output
was not presented means thread safe was not provided. To overcome this
drawback java provides a mechanism called synchronization to make the
thread applications as thread safe.
Synchronization:-
Allowing only one thread at a time and keeping remaining threads under
waiting condition. This mechanism is called synchronization.
Program:-
class reserve implements Runnable
{
int available=1;
int wanted;
reserve(int i)
{
wanted=i;
}
synchronized void check()
{
if(available>=wanted)
{
[Link]("Available berths is:"+available);
String n=[Link]().getName();
[Link](available+":berth is reserved to
passenger:"+n);
try
{
[Link]("Transaction is under processing");
[Link](5000);
available=available-wanted;
}
catch(Exception e){}
}
else
[Link]("Sorry no berths");
}
}
class Safe
{
public static void main(String args[])
{
reserve res=new reserve(1);
Thread t1=new Thread(res);
Thread t2=new Thread(res);
[Link]("sai");
[Link]("lakhsman");
[Link]();
[Link]();
}
}
Output:-
DeadLock:-
Deadlock describes a situation where two or more threads blocked
forever and waiting for each other this situation is called deadlock.
Program:-
class BookTicket extends Thread
{
Object train,compt;
BookTicket(Object train,Object compt)
{
[Link]=train;
[Link]=compt;
}
public void run()
{
synchronized(train)
{
[Link]("BookTicket is blocked on train
object");
try
{
[Link]("BookTicket is waiting to
block on compt object");
[Link](100);
}
catch(Exception e){}
synchronized(compt)
{
[Link]("BookTicket is blocked
on compt object");
}
}
}
}
class CancelTicket extends Thread
{
Object train,compt;
CancelTicket(Object train,Object compt)
{
[Link]=train;
[Link]=compt;
}
public void run()
{
synchronized(compt)
{
[Link]("CancelTicket is blocked on compt
object");
try
{
[Link]("CancelTicket is waiting to
block on train object");
[Link](200);
}
catch(Exception e){}
synchronized(train)
{
[Link]("CancelTicket is blocked on
train object");
}
}
}
}
class DeadLock
{
public static void main(String args[])
{
Object train=new Object();
Object compt=new Object();
BookTicket bt=new BookTicket(train,compt);
CancelTicket ct=new CancelTicket(train,compt);
[Link]();
[Link]();
}
}
Output:-
Inter thread communication:-
Java provides a very efficient way through which multiple threads
communicate with each other. This way reduces the cpus idle time i.e A
process where a thread is paused running in its critical region and
another thread allowed to enter(or lock) in the same critical section to be
executed. This technique is known as inter thread communication which
is implemented by some methods as shown below…….
1) wait():- It indicates the calling thread to give up the monitor and go
to sleep until some other threads enters the same monitor and calls
method notify() or notifyAll().
2) notify():- It wakes up the first thread that called wait() on the same
object.
3) notifyAll():- wakes up all the threads that called wait() on the same
object. The important point is highest priority thread will run first.
Note:-
All these methods must be call in a try-catch block.
}
}
class Demo1 extends Thread
{
DemoWait d;
Demo1(DemoWait d)
{
this.d=d;
start();
}
public void run()
{
try
{
[Link]("Demo1 value is"+[Link]);
[Link](40);
}
catch(Exception e){}
}
}
Output:-
Collection framework:-
It standardizes the way in which groups of objects are handled
by your programs. It was designed to meet several goals.
1) The framework had to be high performance and implementations
of dynamic arrays are highly efficient.
2) It had to allow different types of collections to work in a similar
manner and with a high degree of interoperability.
case 3:
try
{
[Link]("wait is under processing
of elements");
[Link](5000);
}
catch(Exception e){}
[Link]("Elements of an Arraylist
are........."+al);
[Link]("To go back to main menu
type 5");
option=[Link]([Link]());
break;
case 4:
[Link]("successfully exited");
repeat=false;
break;
case 5:
[Link]("Select the operation below");
[Link]("[Link] element,[Link]
element,[Link] elements [Link]");
option=[Link]([Link]());
break;
}
}
return option;
}
//[Link]([Link]());
[Link]("city","hyd");
[Link]("city","delhi");
[Link]("addr","ammerpet");
[Link]("After adding elements size
is:"+[Link]());
Enumeration en=[Link]();
[Link]("Elements are.......");
while([Link]()!=false)
{
Object o=[Link]();
[Link](o);
}
}
}
Output:-
Note:-
Make sure that we have to install the java1.6 or 1.5 software to work out
the below features
1) Autoboxing
2) For-each loop
3) Generics
4) Enum types
5) Varargs
6) Reflection api
7) Annotations
8) Static import
Auto boxing:-
Java added two important features
1) Auto boxing
2) Auto un boxing
Auto boxing:-
It is the process by which a primitive data type is
automatically encapsulated(boxed) into its equivalent type
wrapper whenever an object of that type is needed. There is no
need to explicitly construct an object.
Auto un boxing:-
It is the process by which the value of a boxed
object is automatically extracted(unboxed) from a type wrapper
when its value is needed. So there is no need to call explicitly
such as intValue() or doubleValue().
Program:-
class A
{
void f1()
{
Integer i=10;//auto in boxing
int j=i;//auto out boxing
[Link]("Value of j is:"+j);
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
ob.f1();
}
}
Output:-
For-each loop:-
It is designed to cycle through a collection of objects such as an
array, in strictly sequential order from start to finish. In c# that
implements a for-each loop by using the keyword foreach. Java
adds the for-each capability by enhancing the for statement
Program:-
class A
{
int arr[]={10,20,30,40,50};
void f1()
{
[Link]("Array elements are......");
for(int a:arr)
{
[Link](a);
}
}
}
class B
{
public static void main(String args[])
{
A ob=new A();
ob.f1();
}
}
Output:-
Generics:-
The term generics means parameterized types. Parameterized types are
important because they allow you to create classes , interfaces , and
methods in which the type of data upon which they operate as a
specified parameter. By using generics it is possible to create a single
class that automatically works for different data types of data.
Program:-
class A<t>
{
t a;
A(t a)
{
this.a=a;
}
t f1()
{
return a;
}
}
class UseOfGenerics
{
public static void main(String args[])
{
Integer i=10;//auto boxing
A<Integer> ob=new A<Integer>(i);
[Link]("Hi ur using generic");
[Link]("Value of a is:"+ob.f1());
}
}
Output:-
Note:-
1. In the above program where t is the name of type parameter.
2. Generics work only with the objects for example you cannot pass like
this if do so it gives a compilation error.
Ex:- A<int> ob=new A<int)(53);//compilation error.
Enumeration:-
A enumeration is a list of named constants. In java to declare a variable
as constant it provides keyword called final. Java enumerations are
appear similar to enumerations in other languages. In languages such as
c++, enumerations are simply lists of named integer constants. In java an
enumerations defines a class type. In java an enumeration can have
constructors, methods and instance variables.
values():-
This method returns an enum array type that contains a list of the
enumeration constants.
valueOf():-
This method returns the enumeration constant whose value corresponds
to the string passed in argument.
Example program shows how to use the values and valueOf methods:-
enum city
{
hyderabad,mumbai,chennai;
}
class EnumDemo1
{
public static void main(String args[])
{
city c;
//use values()
city c1[]=[Link]();
[Link]("city constants are......");
for(city c2:c1)
{
[Link](c2);
}
[Link]("----------------------");
//use valueOf()
c=[Link]("mumbai");
[Link]("C contains:"+c);
}
}
Output:-
Varargs:-
It simplifies the creation of methods that need to take a variable number
of arguments. This feature is called varargs and its short for variable
number of arguments.
Note :-
A variable length argument is specified by three periods(…).
Program:-
class A
{
void f1(int...v)
{
[Link]("Number of args:"+[Link]+"contents");
for(int x:v)
[Link](x+"");
}
}
class VarargsDemo
{
public static void main(String args[])
{
A ob=new A();
ob.f1(10);
ob.f1(20,30);
ob.f1();
}
}
Output:-
Note:-
1) In the above program v is operated as an array
2) The syntax … simply tells to the compiler that a variable number
of arguments will be used and these arguments will be stored in the
array referred to by v.
3) In the case of no arguments the length of an array is zero.
Q) can we overloaded a vararg methods or not???
a) yes we can overload a vararg methods
Reflection api:-
Reflection is commonly used by the programs which require the ability
to examine or modify the runtime behavior of applications running in the
java virtual machine.
Output:-
Example program on getting the details of constructors in other class.
import [Link].*;
class A
{
A(int a)
{
[Link]("value of a is:"+a);
}
}
class B
{
public static void main(String args[])
{
A ob=new A(10);
Class c=[Link]();
Constructor cn[]=[Link]();
for(int i=0;i<[Link];i++)
{
Class c1[]=cn[i].getParameterTypes();
[Link]("Constructor Name is:"+cn[i].getName());
[Link]("Constructor Parameter
types:"+c1[i].getName());
}
}
}
Output:-
Annotations:-
It is a new facility added to a java that enables you to embed
supplemental information into a source file. This information is called an
annotation. It does not change the actions of a program. This information
is used by various tools during both development and deployment.
Output:-
RetentionPolicy:-
A retention policy determines at what point an annotation is not needed.
Java defined three such policies which are encapsulated with in the
[Link] enumeration. They are SOURCE,
CLASS and RUNTIME.
Note:-
If no retention policy is specified in the annotation, then the default
policy of CLASS is used.
Marker annotations:-
A marker annotation is a special kind of annotation which has no
members.
Ex:-
@interface marker{}