You are on page 1of 167

Identifier

A name in a java Program is called an Identifier.Which can be


used for representing classes, methods, variables and labels.
Rules:
1.Java Identifier is composed of a sequence of charaters,Which each
charater may be a letter from a to b or A to B or digit from 0 to 9 or
currency symbol ($) or connecting symbol (_).If we use other charater
we will get commpail time error saying illegal charater.
2. No identifier starts with the digit.
3. There is no length limit for java identifier, but SUN highly
recommened upto 15 charaters .
4. Identifier in java are casesensitive.
5. We are not allowed to use reserved words as identifier.
6. All predefined java class names, you are allowed to use as
identifiers.
Examples:
Total (√)
total123 (√)
123total (×)
total$ (√)
_total (√)
total# (×)
total_numbers (√)
total-numbers (×)
Java KeyWords
Some identifiers are reserved in Java which has saparate functionality
and meaning such type of reserved indentifiers are called reserved
words.
53 reserved words are there in java
50 are keywords-----------48 used keywords, 2 unused keywords
(goto,const)
3 reserved literals----------true,false,null
Keywords for premitive datatypes:
*byte *short *int *long *float *double
*char *boolean
Keywords for fow control:
*if *else *switch *case *default *for
*do *while *break *continue *return
Keywords for Exception Handling:
*try *catch *finally *throw *throws *assert
Keywords for modifiers:
*public *private *protected *static *abstract *strictfp
*final *transient *native *volitle *synchronised
Class related key words:
*class *interface *package
*extends *implements *import
Object related key words:
*new *instanceOf *super *this
Other:
Void
Unused keywords: *const *goto
Example:
class KeyEx1
{
int goto=10; ←---------------here we will get identifier expected error
}
Reserved literals:
*true *flase *null
New key words in j2SE 1.5: *enum
All the key words contains only lower case alphabate symbols
Java Data Types
In java any variable has a type, any express as a type and every type
is strictly defind.Compiler will check all asignments for type
compatability .Hence java is considered as strong typed language.
Java Language is not considered as pure oop language because some
non-object (primitive data types) we have to maintain in our code sun
people has interduced wrapper class to convert primitive to object
form.

Data type --------------------- Wrapperclass


byte ------------------------- Byte
short ------------------------- Short
char ------------------------- Character
int ------------------------ Integer
float ------------------------ Float
double ----------------------- Double
boolean ---------------------- Boolean
long ----------------------- Long
Primitive types:
Numeric types:
Integral types for whole numbers
byte short int long
Floating point data types:
float double
char for character data type
boolean for logical values
except boolean and char the remaining data types are signed
datatypes. Ie. we can represent both positive and negative numbers
by using numerical datatype.

java byte Datatype :


size---------8bits or 1 byte
range------ -128 to +127
native numbers are represented in 2’s complement form
this data type is best suitable of your handling data in terms of
streams from a file or network
byte b=100; (valid)
byte b=200; (invalid)-----PLP found int required byte

short Datatype:
size------------16 bits or 2 bytes
range--------- -2 pow 15 to + 2 pow 15-1 i.e -32768 to 32767
this data type is very rarely used type in java.but best suitable for 16
bit process(these 16 bit processer are completely out dated and hence
also the short data type is out dated now a days)

int data type:


size----------- 32 bits or 4bytes
range-------- -2 pow 31 to 2 pow 31-1 i.e -2147483648 to +2147483648
in c language the size of int is varied from platform to platform .the c
program written for 32 bit proccesser can not run on 16 bit
processor.hence chance of failing of c programe is very high .if we
change plaiform. As a result c is not considered as a robust language.
But in the case of java the size of any data type is fixed for any
platform. Hence chance of failing of java program is very very class. If
we change platform As a result java is considered as a robust
language.

Long datatype:
Size----------64 bits or 8bytes
Range------- -2 pow 63 to 2 pow 63 -1
If int is not enough to hold big values like the amount of distence
trvelled by light in 1000 days,we shoud go for long datatype only.

Float datatype:
Size--------------32bits or 4 bytes
Range---------- -3.4e38 to + 3.4e38
For 6 to 7 decimal places of accuracy , we should for float data type.so
this is less accuracy.

Double datatype:
Size--------------64bits or 8 bytes
Range---------- -1.7e308 to + 1.7e308
For 14 to 15 decimal places of accuracy , we should for double data
type.so this is more accurency.

Boolean datatype:
The size of boolean is not applicable.(it is purely depend on the
underlying jvm).range not applicable.
But allowed values are true or flase. TRUE or FALSE are not allowed.

Char datatype:
Size--------------16 bits or 2 bytes.
Range----------- 0 to 65535.
This is to providing unicodes for all the worldwide charater sets.
java Literals
A constant value which can be assigned to a variable is known
as Literal.If we are assigning any outside range value for any data
type, we will get a compile time error saying Possible Loss of Precision
found int required byte.
For the integral data types (int, byte, short, long): we are allowed to
specify a literal value of any any one of the following three forms.
---> Decimal literal (normal way)
--->Octa literal (prefixed with 0 )
--->Hexa decimal (prefixed with 0x )

int x=10 ------------> Decimal


int x=010 ------------>Octa
int x=0X10 -------------->Hexa
In the Hexa decimal notation for the extra digits we are allowed to
specify either small or upper case a,b,c or A,B,C (this is one of the few
places where java is not case sensitive).
Example:
class Sample {
public static void main(String add[]) {
int i = 10;
int j=010;
int k=0x10;
System.out.println( i+”….”+j+”…”+k);
}}
Output: 10,8,16
JVM gives only decimal form as output regardless of input as octa or
hexa.
All the integral literals (decimal.octa,hexa) are by default int.
We can specify explicitly a long literal by suffixing l or L.
There is no direct way to specify the short,byte values.
Assigning chart (Possible assignments):
With out final compiler gives error .with final is possible because int
has 4 bytes by declaring it final and that literal (10) is with in the size
of byte.

int Literal Example:


class Literalone {
public static void main(String ass[]) {
int i='a';
byte b1='b';
char ch='b';
//byte b=ch; ---------->error (PLP found : char required: byte
System.out.println(i); -------------> output is 97
//System.out.println(b);
}}

floating Point Literal:


The floating point literals by default double.
Ex: float f=123.453; ----------> is invalid
Got error as PLP required :float found:double
A floating point literal can be specified as float type by suffixing with f
or F
Example:
float f=128.453f or F (valid)
float f=123.456; (not valid)
double d=123.456; (valid)
double d=123.453f; (valid)
double d=123.345d or D; (valid)
A floating point literal can be explicitly double by suffixing with D or d;
float f=123.56d; (not valid)
A floating point literals must always specify in the decimal form only
.there is no hexa decimal or octal form.
float f=123.0; (not valid)
float f=123; (valid)
float f= 0123; (valid)
float f=0x123; (valid)
We can assign an integral literal (decimal,octal,hexa) to the float data
type directly (*no need to specify the f or F).
We can’t assign a floating point literal to the integral types.
int i=123.34 (not valid)

boolean Literal:
boolean valid literals are true or flase
boolean b=10; (not valid error PLP found:int reqired :boolean)
char literals:
A char literal can be specified as a single charter in single codes.
Ex: char ch=’@’; (valid)
char ch=a; (not valid)
char ch=’ad’; (not valid) error unclosed character literal.
An integral literal which represents the Unicode value of the character.
Ex: char ch=97; output: a
The valid integral literals must be from 0 to 65535.
for the Unicode values which are not sported by the system,we get ‘?’
as output.
char ch=0x(face) (valid)
char ch=ox61; output:1
The Unicode may be in octal /hexa decimal form.
char ch=97 ;
char ch= ‘a’;
char ch= 0x61;
char ch=’\uXXXX’; --------------------->Unicode representation
Ex: char ch=’\u0061’; output=a;
Unicode representation in nothing but \u followed by 4 digit
hexadecimal number .(only small u,capital u is not allowed).
char ch=’\uface’; valid output: ?
char ch=’\ubeef’; valid
char ch=\ubeef; invalid ‘ ‘ missed.
char ch=’\ibeef’; invalid u missed.
Escape charater
Ex: char ch=’\b’; valid
char ch=’\t’; valid
char ch=’\n’; valid
char ch=’\f’; valid
char ch=’\k’; not valid
Escape sequences:
unicode value charater
\u0008 backspace
\u0009 horizental tab
\u000a new line
\u000d carriage return
\u000c form feed
\u0027 single quote
\u0022 double quote
\u005c back space

String literal:
Instead of \n and /r we are not allowed to the corresponding unicode
charater \u000a and \u000d
Vailation leads to compail time error ever in the comments also.
String s=” laxman scjp”; (valid)
String s=”laxman \n scjp”; (valid)
String s=”laxman \t scjp”; (valid)
String s= “laxman \u0009 scjp”; (valid)
String s= “laxman \u000a scjp”; (not valid) gives error illegal escape
character
String s=”laxman \u000d scjp”; (not valid) gives error illegal eacape
chracter
Java Variables
Depends on the content hold by the variables are divided into two
categories.
1. Reference variable
2. Primitive variable
reference variable can be used to hold object references.
Ex: String s=”Laxman”;
Here s is a String object
Primitive variable can be used to hold primitive values.
Example: int i=10;
int[][] a={{1,2},{3,4,5},{6,7,8,9},{}};
for(int i=0;i <= a ;i++)
System.out.println(a[i].length);
}
output: 2,3 ,4,0
Depends on the position at which it is declared all the
variables divided into 3 categories.
1.instance variables/attributes/member variables
2.static variables
3.local variables
Example:
class Student {
String name;
int rollno;
public static void main(String arg[]) {
Student s=new Student();
}
}

Instance variables:
If the values of the variables are varied from instance to instance3,
such type of variables are called instance variables.We can declare
instance variables with in class ,but outside of any method or
block.These are also known as attributes /properties/member
variables.The instance variable will create when ever an object
is created and destroyed ,whenever garbage collection
destroys this object.Instance variable will get default variable
no need to perform ,explicit initialization.

Static variables:
A single copy of the static variable will maintain and shared by
all instances .the value of the static variable is the same for
the all instances.The static variable will create whenever the
class loaded into the memory and destroy whenever the class
is unloaded from the memory.These variables are also known
as fields.
Example:
class Student {
String name;
int rollno;
static String collname;
Public static void main(String arg[]) {
Student s1=new Student();
System.out.println(s1.name); // null
System.out.println(collname); // null
}
}
With out s1 and static Compile time error
Static variables will get default values .No need to perform explicit
initialization.
System.out.println(Student.collname);
System.out.println(s1.collname);
Static variables we can access by using either class name
(highly recommended) or by using object reference.

Local variables:
The variables which are declared inside a method or block or
constructor or as method argument are called local variables.Also
known as temporary variables /stack variable/automatic
variables.The local variables will create as the part of the method
execution and will destroy when ever the method terminates.The
local variables never get default values and must be initialized
before using that local variable.Violation leads to CTE saying
variable I might not have been initialized.

Example:
case1:
class Sample{
public static void main(String arg[]){
int i;
System.out.println(”hello”); // hello
}}
Case2: class Sample{
public static void main(String arg[]) {
int i;
System.out.println(i); // CTE variable I might not have been initialized.
}}
Case3: class Sample {
public static void main(String arg[]) {
int i=10;
System.out.println(i); // 10
}}
Case4: class Sample {
public static void main(String arg[]) {
int i;
if(arg.length>0) {
i=20;
}
System.out.println(i); // error
}}
It is not recommended to initialized local variable with in the logical
blocks .(But legal)
Case 5:class Sample {
public static void main(String arg[]) {
int i;
if(arg.length>0) {
i=20;
}
else{
i=40;
}
System.out.println(i); // valid
}}
Case6: class Sample{
int[] a;
public static void main(String arg[]) {
Sample s=new Sample();
System.out.println(s.a); // null
System.out.println(a) // error
System.out.println(s.a[0]); //RTE ---> null pointer exception
System.out.println(a.length); // RTE ---> null pointer exception
}}
case 7: If we declare as static int [] a;
System.out.println(a) // null
System.out.println(a[0]); //RTE ---> null pointer exception
System.out.println(a.length); // RTE ---> null pointer exception
Case8: static int [] a =new int[6];
public static void main(String arg[]) {
Sample s=new Sample();
System.out.println(a) // [I@add234]
System.out.println(a[0]); //0
System.out.println(a.length); //6
}
case9: class Sample {
public static void main(String arg[]) {
int [] a;
System.out.println(a); // error
System.otu.println(a[0]);
System.out.println(a.length);
}}
case10: class Sample {
public static void main(String arg[]) {
int [] a=new int[6];
System.out.println(a); // [I@add34]
System.out.println(a[0]); // 0
System.out.println(a.length); // 6
}}
Once an array object is created its elements will always get default
values.
summarization:
Instance array:
int [] a;
System.out.println(objref.a) //null
System.out.println(objref.a[0]); // null pointer exception
System.out.println(objref.a.length); //null pointer Exception
int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); //6
Static array:
static int [] a;
System.out.println(objref.a); //null
System.out.println(objref.a[0]); // null pointer exception
System.out.println(objref.a.length); //null pointer Exception
static int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); //6
Local array:
int [] a;
System.out.println(objref.a) //CTE
System.out.println(objref.a[0]); // CTE
System.out.println(objref.a.length); //CTE
int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); / /6
Coding Standards
Java coding standards:
Sun recommended the following for the naming conventions.

1. In case of classes:
The first letter should be capitalized and if the several words are linked
together to form the name ,the first letter of the inner words should be
upper case.
For the classes the names should be nouns.
Ex: Student, Customer, Employee etc.
2. In case of Interfaces:
For the interfaces the names should be adjective and follows camel
case.
Ex:
Runnable .Serializable,cloneable,Comparable,Movable etc

3.In case of Methods:


The first letter should be lower case and then normal camel case rules
should be used.
The names should be verb –noun pairs
Ex: getBalance(); doCalculation(); setCustomerName();

4.In case of variables:


Like methods the camel case format should be used stating with a
lower case letter.
Ex: buttonwidth; accountBalance; mystring

5.Constants:
java constants are created by marking variables as and final.
They should be named using upper case letter with unscore (_) is the
saperator.
Ex: MIN_HIGHT, MAX_HIGHT

Java Beans Naming Conventions:


Java Beans are java classes that have properties.For every property
there should be getter and setter methods.
All the properties must be declared as the private (to get
security)
For every non – Boolean property will we should have public getXXX()
method.
i.e the getter method is no argument method only.
For the Boolean properties we can have setter method public setXXX()
Arrays Decleration Construction initialization
An array is a data structure that defines an indexed collection of
fixed number of homogeneous data elements. Once the size of
array is fixed there is no chance of increasing or decreasing its
size.Array show wonderful performance when compared with the
collections.
Declaration of array:
Become name is clearly saperated form the type,first one is the highly
recommended way.
At the time of declaration we are not allowed to specify the
size, violation leads to compail time error.

Array Example:int [] a; (valid)


int[6] a; (not valid)
For deceleration of 2/3 dimensional array
int [][] a; (valid)
int [][][]a; (valid)
int a[][]; (valid)
int a[][][]; (valid)
int [] a[][]; (valid)
int [] a[][]; (valid)
int [][]a; (valid)
int [][] a[]; (valid)
int[] a. b[]; (valid)
int[] a,[]b; (not valid)
int a,b[]; (valid)
int [][]a[]; (valid)

Example:
int []a[]; ------>2 di
int []a[];-------->2di
int []a[],b[]; ------->a is 2 di,b is 2 di
int []a[],[]b[]; --------> //not valid

Construction of arrays:
At the time of construction we should specify the size ,other
wise compail time error occures.
i.e int a =new int [6]; (not valid)
int [] a=new int []; (not valid)
int s[]=new int[0]; (valid)
It is legal to have an array with size zero.

Example: int [] a=new int [-6]; (not valid)


We are not allowed to specify the size of the array as nagative
number,violation leads to runtime exception saying negative
array size exception.
char/short /byte/int b=6;
int [] a=new int [b]; (valid)
long/double/float b=6;
int [] a=new int [b]; (not valid)
If we want to specify the size of the array by using some variable ,the
allowed data type for that variable are byte,short,char,int(i.e any data
type which can be implicitly promoted to the int type).
The maximum allowed size for java array is 2147483647.
Once an array is created, all the elements will assign with default
values (depends on data types)
Example:
int [] a=new int [6];
000000
Then a -------------------->For int default 0,for string it is null
int [][] a= new int [3][2];
Then a-----------------------> In java the 2 dimensional array is not
implemented as the matrix.it is simply an array of arrays.
int [][] a= new int [3][];
a[0] =new int[2];
a[1]=new int[3];
a[2]=new int[4];
so,no need to specify the second dimension in 2d,3d arrays.
Array Examples:
int [][] a=new int[3][2]; (valid)
int [][] a=new int[3][]; (valid)
int [][] a=new int[][2]; (not valid)
int [][] a=new int[][]; (not valid)
Base size should be specified mandatory.

int [][][] a new int [2][][]; (valid)


int [][][] a new int [2][3][]; (valid)
int [][][] a new int [][3][4]; (not valid)

Example:
int[] a=new int [6];
System.out.println(a[0]); -----------> output: 0
boolean[] b=new booleab[3];
System.out.println(b[0]); -------------> output: false
String s=new String [6];
System.out.println(s[0]); -------------->output: null

Example:
int [][] a=new int [2][3];
System.out.println(a[0]); -----------> output: Garbage value[I@add234]
System.out.println(a[0][0]); -----------> output: 0
int [][] a=new int [2];
System.out.println(a[0]); -----------> output: null
System.out.println(a[0][0]); -----------> output: Null Pointer Exception

Initializing an array:
int [] a=new int[3];
a[0]=20;
a[1]=30;
a[2]=40;
a[3]=50 ------> Leads to array index out of bound Exception
If you are accessing an array with invalid index or some -ve index we
will get a RTE saying array out of bound exception.
a[4.0]; ---------> leads to compail time error
Deceleration ,construction and initialization in single line:
int [] a;
a=new int [3];
Example:
char[] ch={‘l’,’a’,’x’,’m’,’a’,’n’};
String [] s= {“laxman”,”scjp”};
int [] a;
a ={10,20,30}; ----------------> Leads to compail time error illegal start
expression
so Declaration,contraction,initialization must in a single Line.

length Vs length():
length:This is a variable.applicable for only for array objects
represents the number of elements or the size of the array.
Ex1:
int a=new int[6];
System.out.println(a.length); ------------------> output: 6
Can’t apply to String
Ex2:
String s=”Laxman”;
System.out.println(s.length);
Given CTE because length variable applicable only for array objects.
length(): It is a final method applicable for string objects.
It represents the number of characters present in the String Object.
Ex:
String s=”Laxman”;
System.out.println(s.length()); ---------> 4
System.out.println(s.length); ---------->error
Anonymous Arrays: There are name less arrays.
Purpose of these anonymous arrays is just for instant use.
Example:
class Sample {
public static void main(String arg[]) {
System.out.println(sum(new int[]{10,20,30}));
}}
output: 60
While constructing anonymous arrays we are not allowed to
specify the size .violation leads to compile time error.
If we want, we can assign anonymous array for any reference
variable.
i.e int [] a=new int[] {10,20,30,40}; ----------> valid

Array Element Assignments:


As array elements we can take any values which can be implicitly
promoted to declared type.
int[] a =new int{3};
a[0]=10; -------> valid
a[0]=’a’; -------->valid because char can be implicitly promoted to int
type.
a[0]=b; ---------->valid because byte can implicitly promoted to int
type.
a[0]=10l; --------->CTE because long can’t be implicitly promoted to int
Here we can give only String objects.
Object[] o=new Object[b];
If an array is declared as object reference array we are allowed to
assign the objects of either declared type or its child classes.
Array variable Assignments:
Case 1: int [] a={10,20,30};
char [] ch={‘a’,’b’,’c’};
int [] b=ch; -------------->CTE Incompatible types reqired:int[]
found:char[]
A char element can be assigned in the place of int element .But we are
not allowed to give a char array in the place of int array.
But int [] b=a; ---------> valid
Case 2: int [] a={10,20,30,40};
int [] b={50,60,70};
In this case a=b and b=a, both are valid because while assigning one
array to another we have to consider only types irrespective of sizes.
Char ch={‘a’,’b’,’c’,’d’};
a=ch; --------->Incompatable not valid
case 3: int [][] a=new int[2][3];
a[0]=new int [6]; -------> valid
But a[0]=new int [2][3] -------> not valid
Int [][] a=new int[2][];
a[0]=new int[6]; -------> valid
a[0]=10; --------->CTE incompatable types reqired : int[] found : int
a[0]=new int [2][3]; -----------> CTE incompatable types reqired : int[]
found : int[][]
case 4: int [] a=new int[6];
System.out.println(a.length); -------------> 6
Int [][] a=new int [3][4];
System.out.println(a.length); -------------> 3
System.out.println(a[0].length); -----------> 4
Java operators
Operators&Assignments:
• increment/decrement
• shift
• arithmetic
• equality(==,!=)
• relational
• bit-wise
• short-circuit
• instanceof
• cast
• conditional(?)
• new
• []

Increment& decrement operators:


• Post Increment ------> y=x++;
• Pre Increment ------> y=++x;
• Post Decrement ------> y=x--;
• Pre Decrement ------> y=--x;

Example: int x=4;


int y=x++;
System.out.println(y); //4 .unexpecompile time errord type.
System.out.println(x); //5

Example: int y=++4;


System.out.println(y); //Compile time error
Increment or decrement operators, we can apply only for
variables not for constant expressions. Violation leads to
Compile time error saying unexpecompile time errord type
Required: variable but found=value.
Ex: int x=4;
int y=++(++x);
System.out.println(y); //COMPILE TIME ERROR
we can apply increment/decrement operators for variables only
one time. Ie . nesting of increment/decrement operators are
not allowed.
Ex: int x=y;
final int x=y;
x++;--- [x=x+1] x++;
System.out.println(x); //5
System.out.println(x); //COMPILE TIME ERROR
Increment/decrement operators, we can’t apply for the final
variables. Violation leads to compile time error saying can’t assign
values to final.
Ex: double d=10.5;
d++; System.out.println (d); //1.5
Increment/decrement operators, we can apply for floating point data
types.
Ex: byte b=10;
b=b+1;
System.out.println (b); //compile time error
Possible loss of precession
found: int , required :byte
Ex: byte b=10;
b=b++;
System.out.println (b); //11
i.e automatic typecasting takes place internaly

Ex: byte a=10;


byte b=20;
byte c=a+b;
System.out.println (c); //compile time error
if we can perform any arithmetic operation between any 2 variables a
and b the result is always max (int, type a, type b )
byte + short=int
char + char=int
int + char=int
int + long=long
doubles + byte=double

Arithmetic OPERATORS:-( + , - , * , / , % )
byte a=10
byte b=20
byte c=a+b; //compile time error plp req:byte
If we can perform arithmetic operators b/w any two operands a and b ,
the result type is, max(int, type a, type b)
Ex: int a=10+’a’ => 10+97=107
double b=10+12.5 => 10.0+12.5=>22.5;
For representing infinity, there are no constant; define in the integer
class. Hence 0/0 results is sum time exception saying arithmetic
exception
System.out.println(10/0); //Runtime Exception by zero .
System.out.println(10.0/0); //infinity
System.out.println(10.0f/0); //infinity
But in the float and double classes for representing infinity constants
are defined.
System.out.println (Float. POSITIVE_INFINITY); // infinity
System.out.println( Float NEGATIVE_ INFINITY); //-infinity

final float postive_ infinity ,


final float negative _ infinity are the constants contain in float class.
0/0 is undefined in the Integer class for representing undefined results
there is no constant available . Hence 0/0 results arithmetic exception.
0/0 → arithemetic exception but in float and double classes for
representing
undefined values there is a commands available. public static final
float NaN.
NaN→not a number and public static final double NaN
Ex:System.out.println(0.0 / 0) → NaN
System.out.println(Math.sqrt(4)); → 2.0
System.out.println(Math. Sqrt(-4)); → NaN.
System.out.println(10/0)→ Arithmatic exception
System.out.println(10.0 / 0)→ infinity
System.out.println(-10.0 /0→ - infinitz
System.out.println(0/0) → Arithematic Exception.
System.out.println(0.0/0 → NaN
System.out.println(-10/0) → arithmatic exception
System.out.println(-10.0/0)→ -infinity,
System.out.println(-0.0/0)→ NaN.
Float. POSITIVE_INFINITY = = Float. POSITIVE_INFINITY; // true
Float . POSITIVE_INFINITY = =Double. POSITIVE_INFINITY. // true
Float . NaN = =Float. NaN.
Float. NaN >double. NaN }false
Float. NaN !=Float. NaN →true.
if one are comparing NaN with any other , including NaN itself, the
result is always false, except for not equal(!=)operator.
Arithmetic exception:
1. runtime exception (unchecked)
2. only in the cone of integer arithmetic.
3. / and % only there two operators result in Arithmetic exception.
String concatenation operation:-
‘+’ is the only operator in java which in overloaded. We can one for
arithmetic addition and for string concatenation.
String a=”java”.
int b=30;
int c=20;
int d=10;
System.out.println (a+b+c+d);→java302010;
System.out.println(b+a+c+d);→ 30java2010
System.out.println(b+c+d+a); →60java
System.out.println(b+c+a+d);→50java10.

* If at least one operand is of string type then + acts as string


concatenation operator other wise + acts as arithematic operator.

SHIFT OPERATORS (1.4 ONLY):-


Left shift (<<)
Right shift ( >>)
Unsigned /zero filling right shift operator ( >>>)
In order to get high resolution of pictures
For compression of data also used these shift operators frequently use
in j2me edition.
Left Shift Operator:
a << b shift the bits of a ,b times to the left hand side.
Ex: 8 << 33 then 8 << 33 % 32 = 8 << 1 // result=16
Ex: 8 << - 31 then 8 << -31+32 = 8 << 1 // result= 16

Right Shift Operator:


a>>b shift the bits of a ,b times to the right hand side by filling the left
hand side bits with sign bit.
8 >> 1 --> 0000 …….100 = 4.
Filled with sign bit zero.
a >> b =a/2 power b for 8 >> 1 =8/2 power 1 =8/2=4.
If b < 31 then b=b+32
If b >31 then b= b% 32.
- 8 >> 1 ---> -8/2 power 1 = -8/2= -4.

Unsigned Right Shift Operator:


a>>> b , shift the bits of a, b times to the right hand side. By filling left
most bits with zero always.If a is +ve ,then there is no difference
between right shift and unsigned right shift operator.Except shift
distance zero ,the result of unsigned right shift operator is
always positive.
I few are applying shift operator between a and b the result type is
always max(int type of a)

Case1: byte b=8 >>1; // valid


Case2: int a=8;
byte b=a >> 1; // invalid
Case3: final int a=8;
byte b=a>>1; // valid
Case 4:long c=1;
byte b=8>>c; //invalid (as per max(int,type of a)
In a << ,>> ,>>> b ,If a and b ,both are compile time constants then
the compiler won’t go for formula for the result type.If at least one in
the variable ,either a or b then the compiler checks the type of the
result which is max(int,type of a) , the type b never participated in the
result .
Access modifiers
class Modifiers:
Once we are writing a class the access modifier describes the
properties of that class .(creation of child class is allowed or not
,creation of object is allowed or not ,we can access this class from
outside the package or not and so on).
Access specifiers or Access modifiers are same in case of java.java
compiler shows the error related to public,static,.......so on , it use the
word modifier not Specifier.
The allowed modifiers for the Top level classes are:
1.public 2.default 3. final 4.abstract 5. strictfp
If we are using other then these modifiers ,compile time error
saying modifier some not allowed here.
For the inner classes the following are allowed modifiers:
1.public 2. private 3.protected 4.default 5.final 6.abstract
7.static 8.strictfp

public class:
A public class can be accessed from any where with in the package
/outside the package.
package pack1;
public class B
{
System.out.println(“hai”);
}
package pack2
{
import pack1.B;
class A
{
public static void main(String arg[])
{
B b=new B(); // we can access
}

class:
If a class declared as the default ,we are allowed to access that class
only with in the current package.If you are trying to access from
outside package compilation fails.
package pack1;
class B
{
System.out.println(“hai”);
}
package pack2
{
import pack1.B;
class A
{
public static void main(String arg[])
{
B b=new B(); //we can't access
}
Here class B is is default ,but not public in pack1.So this class can’t be
accessed from outside package.
final class:
If a class declared as the final then we are not allowed to
create the child class.
Advantage: We can implement security.
Limitation: As we are not allowed to create the child class,we are
missing the key benefits of object oriented programming ,re usability
and flexibility.Its not a good programming practice to use final classes
in the real time unless security is required.
final method:
If a method declared as the final ,it indicates that this
implementation is final implementation.
ie. we are not allowed to override this implementation the
child class.
Observations:
If a class declared as the abstract, we should create the child class to
provide implementation for abstract methods.
If a class declared as the final, you are not allowed to create the child
class.Hence final and abstract combination is illegal for classes.
Example:
class Sample
{
void m1(); //error: missing method body or declaration missing.
public static void main(String arg[])
{
System.out.println(“hai”);
}
}
Abstract methods should be overridden in the child class to provide
implementation.But final methods are not allowed to override. Hence
abstract and final combination is illegal for methods also.
A final class never allowed to contain abstract methods. But a final
methods is allowed to keep inside abstract class.i,e final method in
abstract class is valid But abstract method in final class is not
valid.
Abstract is the keyword which can be applied for classes and methods
only.i.e we can’t use abstract keyword for a variable.
final is the keyword which can be applied for classes ,methods and
variables.

Strictfp: Strict floating point


This keyword we can apply for classes and methods .i.e we
can’t apply strictfp for the variables.
If a method declared as the strictfp all the floating point
calculations inside that method has to follow “IEEE 754”
standards so that we will get platform independent result.
If a class declared as the strictfp, all concrete methods in that
class has to follow IEE 754 standard for floating point
calculations.
Abstract and strictfp combination is not-valid for methods .But
it is valid combination for the classes.
Not-valid combinations
abstract and final .
abstract and strictfp
abstract and synchronized
abstract and static
abstract and native
abstract and private.
Method level Modifiers and Variable level Modifiers:
public members:
If a member is declared as public ,we are allowed to access that
member from any where with in the package or outside the package.
package pack1;
class A
{
public void m1()
{
System.out.println(“hai”):
}
}
package pack2;
import pack1.A;
class B
{
public static void main(String arg[])
{
A a=new A(); //error
a.m1();
}
}
The corresponding class must be visible.Before checking member
visibility, first we have to check class visibility.
If class A is declared as public then the class B compiles fine and prints
“Hai”. Default member:
If a member declared as the default ,that member is visible with in the
current package only.
package pack1;
public class A
{
void m1()
{
System.out.println(“hai”):
}
}
package pack2;
import pack1.A;
class B
{
public static void main(String arg[])
{
A a=new A();
a.m1(); //error
}
}
error:m1() is not public in pack1.A.
Hence default modifier is also known as package level
modifier.
private members:
If a member declared as the private we can access with in that class
only.i.e from outside the class, you are not allowed to access.
It is highly recommended to declare data members as private to
achieve security.
protected member:The most misunderstood modifier in java .If a
member declared as the protected with in the current package,every
where we are allowed to access,but outside the package ,we can
access only in the child classes.
protected= + child classes;
Example:
package pack1;
public class A
{
protected void m1()
{
System.out.println(“hai”);
}
}
case 1:
class B
{
public static void main(String arg[])
{
A a=new A();
a.m1(); // hai
}
}
Case 2:
class B extends A
{
public static void main(String arg[])
{
B b=new B();
b.m1(); // hai
}
}
case 3:
A a1=new B();
a1.m1(); //hai
case 4:
B a=new A();
a.m1(); // error
Example:
package pack2;
import pack1.A;
class B extends A
{
public static void main(String arg[])
{
A a=new A();
a.m1();
}
case 2:
B b=new B();
b.m1(); // valid
case 3:
a a1=new B();
a1.m1(); // in-valid
conclusions:
The protected members can be accessed with in the current package
any where either by using parent class reference or by using child
class reference.
But from outside package we can access protected member only by
using child class reference.
If we are using parent class reference to access protected member
from outside package we will get a compile time error.
Example:
case 1:
class Sample
{
public static void main(String arg[])
{
Object o=new Object();
o.finalize(); // error
System.out.println(“hai”);
}
}
error :finalize has protected access.
Case 2:
public static void main(String arg[])throws Throwable
{
Sample s=new Sample();
o.finalize(); // valid
System.out.println(“hai”);
}
case 3:
Object o=new Sample();
o.finalize(); //in valid

final variables:
final is the keyword which can be applied for methods classes
and variables.
Instance and static variables will get default values always
.There is no need to perform explicit initialization.
But the local variables never get any default values .Before accessing a
local variable ,we should perform initialization other wise compile time
error.
final instance variables :
For the final instance variables,we should perform initialization
other wise compile time error.
The final instance variable must be initialization before constructor
compiles. i.e at the time of declaration or inside instance initialization
block or inside constructor.
Example:
final int i;
public static void main(String arg[])
{
Sample s=new Sample()
System.out.println(s.i); // invalid
}

final-static variables:-
Final static variables must be initialized before class loaded
into memory. Otherwise compile time error. i.e we can perform
initialization for the final static variables at one of the
following places.
1. at the time of declaration
2. Inside the static initialization block
final static int I;
static
{
int i=30;
}

final-local variables:-
Local variables even though we can declared as the final must be
initialized before using.
class Sample
{
Public static void main(String args[])
{
final int I;
System.out.println(“hai”);
} // hai
For the local variables the only allowed modifier is final.
Example:
class test
{
public static void main(String arg[])
{
final int a; //instead of final we cant write int modifier
System.out.println(“hi”);
}
}
The variables which are declared as the method arguments are simply
acts as local variables of that method .hence the only applicable
modifier for the logical variables is final. If any formal parameter
declared as the final we are not allowed change its value with in the
method.
Example:
class test
{
public static void main(String arg[])
{
m1(100,200);
}
}
public static void m1(final int i, final int j)
{
i=200; //error
i=300; //error
}
}

Static Modifier:
The keyword static can be use for classes, methods, variables
We can not apply static keyword for the top level classes, but
we can apply inner classes.
For every object a separate copy of instance variables will be created
but in the case of static variables a single copy will be created at the
class level and shared by all the objects of that class.
Example:
class test
{
int i=10;
static int j=20;
public static void main(string arg[])
{
Test t1=new Test();
t1.i=100;
t1.j=200;
System.out.println(t1.i+’…”+t1.j); //100,200
Test t2=new Test();
System.out.println(t2.i+’…”+t2.j); // 10,200
t2.j=2000;
System.out.println(t1.i+’…”+t1.j); //100,2000
}
}
Most of the cases the keyword static associated with final modifier for
defining class level constants.
Non static variables can not be returning form static modifier/ content:
class test
{
int i=10;
public static void main(String arg[])
{
System.out.println(i);
}
}
error: Non static variable I cant be returning static content
example:
1) int i=10;
2) static int i=10;
3)public void m1()
{
System.out.println(i);
}
4) public static void m1()
{
System.out.println(i);
}
Which of the following are not allowed simultaneously in the same
class
1) & 3) instance variable can't be accessed from instance area,either
instance block, constructors or instance access block

1) & 2) compile time error.. non static variables are instance variables
can not be referenced from static constant

2) & 3) , 2) & 4)… static variables can be accessed from any where
either from instance area or static area

3)Usually static methods are utility methods and we should provide


complete implementation but for abstract methods we are not allowed
to provide implementation . Hence abstract and static
combination is illegal for the methods.

4) we can overload static methods.but we can not override

Synchronized Keyword:
Synchronized is the keyword which can be apply for method
and blocks. i.e we can not apply synchronized keyword for
classes and variables.
If a method declared as synchronized at a time only one thread
is allowed to execute that method on the given object.
Advantages:
1) We can provide thread safety
2) We can avoid data inconsistency problems
Disadvantages:
1)synchronized keyword increases waiting time of threads and hence
performance of the system goes down.hence unless and until there is
no specific requirement do not use synchronized keyword in the
coding.
Note: Synchronized is the keyword which is always talks about
implementation but abstract never talks about implementation.Hence
synchronized and abstract combination is illegal for the
methods.

Native Modifier:
Native is the keyword which can be apply only for methods. i.e
we can not apply native keyword for classes and variables.
1) A native method means. The method which is implemented in non-
java like c,c++;
2) Native methods are also known as foreign methods.
Advantages of Native method:
1) As the performance of java is low for improving the performance we
can depends on c or c++. This stage methods can be helped by native
keywords
2) We can communicate legacy systems by using native keyword
Demo:
class NativeEx
{
static
{
System.loadLibraries(“path of native methods library”);
}
native void m1();
}
class Client
{
public static void main(String arg[])
{
Native n=new NativeEx();
n.m1();
}
}
For the native methods already implementation is available but
abstract method means implementation is not available .hence
abstract and native combination is illegal for the methods
Native methods already implementation is available we are not
providing any implementation. Hence nativemethod declaration
should be ends with semicolon
Native and strictfp combination is illegal for methods because
old languages may not fallow IEEE 754 standerd for floating
point.
We can override a native method
We can overload a native method
Transient Keyword:
Transient is the keyword which can be applicable only for
variables i.e., we are not allowed to use transient keyword for
methods and classes.
Serialization:
The process of saving an object to a file is called serialization Strictly
serialization means “The process of converting java supported
format object to network supported format object (or) file
supported format object is called serialization.”
1) If a variable declared as a transient, at the time of
serialization JVM ignores the values of that the transient
variable. Instead of original values JVM saves default value.
2) Hence transient means not to serialize.
Example:- While saving account information permanently to a file we
are not allowed to save passwords for security reasons such type of
variables we have to declare by transient keyword
3)We can serialize only serializable objects violation leads to runtime
exception saying not serializable exception
4)An object is said to be serializable if an only if the corresponding
class implements serializable interface

Transient Example:
import java.io.*;
class TransientDemo implements Serializable
{
int i=10;
int j-20;
public static void main(string args[])throws exception
{
TransientDemo t1=new TransientDemo();
System.out.println(t1.i+”----“+t1.j);
file output stream fos=new file output stream(“abc.txt”);
object output stream oos=new object output stream(fos);
oos.writeobject(t1);
//t1.i=1000
//t1.j=2000
FileInputStream fis=new FileInputStream(“abc.txt”);
ObjectInputStream fis=new ObjectInputStream(fis);
Transient Demo t2=( Transient Demo)ois.writeObject(t1);
System.out.println(“t2.i+”…”+t2.j);
1).If we are not declaring implements serializable we will get a runtime
exception not serializable exception
2)if we are not keeping throws exception compile time error saying
unreported exception must be called or declared to be thrown

Note:- static variables never part of object state hence we are


not participating in the serialization process during a static
variables as the transient is useless and there is no impact.

Volatile
Volatile is the keyword which can be applicable only for
variables i.e we can not use for classes and methods. If the value of
the variable is changing frequently such tpe of variables we have to
declare with this volatile keyword.
1) For the volatile variables JVM will create a separate private
copy for every thread.After completing entire transaction but
that thread the final value will be updated in the master copy.
So that the value of the volatile variable is always stable
2) At variable level we can achieve synchronization by using volatile
keyword
3) For every thread maintaining a separate copy is always difficult
.hence performance of the system goes down
4) Volatile means the value keep on changing but final means the
value is not allowed to change. Hence volatile and final
combination is always illegal. We are not declaring a final variable
as volatile.
class:
In object-oriented programming, a class is a programming
language construct that is used as a blueprint to create
objects. This blueprint includes attributes and methods that the
created objects all share.
Usually, a class represents a person, place, or thing - it is an
abstraction of a concept within a computer program. Fundamentally, it
encapsulates the state and behavior of that which it conceptually
represents. It encapsulates state through data placeholders called
member variables; it encapsulates behavior through reusable code
called methods.
More technically, a class is a cohesive package that consists of a
particular kind of meta data. It describes the rules by which objects
behave; these objects are referred to as instances of that class. A class
has both an interface and a structure. The interface describes how the
class and its instances can be interacted with via methods, while the
structure describes how the data is partitioned into attributes within an
instance. A class may also have a representation (meta object) at run
time, which provides run time support for manipulating the class-
related meta data. In object-oriented design, a class is the most
specific type of an object in relation to a specific layer.
Programming languages that support classes all subtly differ in their
support for various class-related features. Most support various forms
of class inheritance. Many languages also support features providing
encapsulation, such as access specifiers.
class Example:
Class java
{
properties(variables);
Actions(methods);
}
object:
In its simplest embodiment, an object is an allocated region of
storage. Since programming languages use variables to access
objects, the terms object and variable are often used interchangeably.
However, until memory is allocated, an object does not exist.

Any language present objects and this should not be confounded with
the most powerful concept of object-orientation.

In procedural programming, an object may contain data or instructions,


but not both. (Instructions may take the form of a procedure or
function.) In object oriented programming, an object may be
associated with both the data and the instructions that operate on that
data.

How an object is created depends on the language. In a prototype-


based language (e.g.,JavaScript) an object can be created from
nothing, or can be based on an existing object. In a class-based
language (e.g- ,Java), an object is created as an instance (or
instantiation) of a class. The class forms a specification for the object.

To give a real world analogy, a house is constructed according to a


specification. Here, the specification is a blueprint that represents a
class, and the constructed house represents the object.
Object example:
class Sam

{
int i=10;
void mone()
{
System.out.println("java");
}
public static void main(String arg[])
{
Sam s=new Sam(); //Here is the Object
}}}
Abstraction
Hiding internal implementation is called Abstraction.
Advantages:
Security
Enhancement easy
we can enhance the internal implementation with out effecting outside
world.
Encapsulation
Encapsulation Advantages:
Security
Easy to enhance
Maintainability
Modularity
Example:
class Sample
{
public int i=10;
public int getId()
{
return i;
}
public void setId(int x)
{
this.i=x;
}
}
The major limitations od encapsulation is,it increases the code
(because we have to getter and setter methods for the data variables)
and hence slows down the execution.

Tightly encapsulated class:


A class is said to be tightly encapsulated if and only if data
members as the private
Check whether the fallowing classes are tightly encapsulated or not.
a)
class A {
private int x=10;
public void setX(int x)
{
this.x=x;
}
public int getX()
{
return x;
} ------------------//tightly encapsulated

b). class A{ private int y=10;} -----//tightly encapsulated

c). class A{ private int x=20;} ----// A is tightly encapsulated, B is not


class B extends A{ private int y=30;}

d). class A{ int y=20;}


class B extends A{ private int z=40;}
class C extends B { private int l=50; }

• If the parent class is not tightly encapsulated no child class is


tightly encapsulated.
Java Inheritance
IS-A relation:
• Also known as Inheritance
• By using extends keyword we can implement IS-A relationship.
• Re usability is the benefit of IS-A relationship
Inheritance is accepted up to certain level but after reaching problems.
Because for every child class object, internally all the parent objects
will be created in the inheritance tree.
In the real time it is recommended to have inheritance up to 8
to 10 levels only. Beyond that it is not suggestible.
is a relation Example:
class Superclass
{
void display()
{
System.out.println("Hi");
}
}
class InheritanceExample extends Superclass
{
public static void main(String arg[])
{
InheritanceExample ie=new InheritanceExample();
ie.display();
}
}
HAS-A relation:
• Also known as composition or Aggregation.
• By using new operator we can implement HAS-A relationship.
• Reusability (CBM->Component Based Model) is the benefit of HAS–A
relationship.
• The limitation of HAS-A relation ship is, we are increasing the
dependency between the classes. As a result, the maintenance of the
code becomes complex or costly.
has a relation Example:
class Car
{
Engine e= new Engine();
. …….
.......
}
class Engine
{
m1(){}
m2(){}
}

Car class has Engine reference. Hence Car allowed using all the
features of engine. But without Engine object we can’t create Car
object.
Method Signature
Method Signature :
Example:
public void m1(int a, int b)
{
m1(int,int); -----> signature of method m1
}

Example:
public void m1(int a, float b)
{
m1(int , float); //valid
m1(float , int);//invalid
}

• In java the method signature is compiled with method name and


argument list (the order of arguments also important).
• Return type is not part of the signature.
• Compiler uses the method signature to resolve method calls.
• With in a class two methods having same the signature is not
allowed, violation needs to CTE saying method is already
defined in class.

Example:
class Test
{
public int m1(int i){}//invalid, CTE: m1(int) is already defined in test
public void m1(int i){}
}
Method Overloading
Two methods having the same name are not allowed in the case of C-
language, for every data type even though the functionality in the
same; we should maintain different method names. It increases the
complexity of the programming. But in java, two methods having the
same name is allowed irrespective of parameters. We can maintain the
same method name for similar type of functionality. It simplifies the
programming. Such types of methods are called Overloaded methods.
• Two methods are said to be overloaded if and only of they
have the same method name, but different parameter list (at
least order).
• The signatures of the two overloaded methods must be different.
Example:
public void m1(){}
private int m1(int i){}

• Here m1() & m1(int i) are overloaded. We never consider return type,
access modifier and throws class in overloading.
Example:
class Sample
{
public void m1()
{
System.out.println(“no arg”);
}
public void m1(int i)
{
System.out.println(“ int arg”);
}
public void m1(double d)
{
System.out.println(“ double arg”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10.5);
}
}

• In the case of overloading which overloaded method must be


executed is decided method must be executed is decided by compiler
only based on reference type.
• Ie., Overloaded method resolution is the duty of compiler only. Hence
Overloading is the best
ex. of static polymorphism and some times also known as Early
Binding.

s.m1(10L);//double arg
s.m1(‘a’);//int arg

i.e., Automatic Promotion in Overloading:


• If we are calling a method m1() by passing char as arg on the sample
reference then the compiler will check in the Sample class for m1(),
which can take char as the arg.
• If it finds that method, it will execute at run time.If there is no such
method the compile promotes that char arg to the int arg and checks
for m1(int) method.
• If there is no such method, the compiler will check for m1(long),
fallowed by m1(float),fallowed by m1(double). Still if the compiler
won’t find any such method then only compiler will raised CTE saying
‘cannot resolve the symbol m1(char).
CASE 1:
class Sample
{
public void m1(int i,float f)
{
System.out.println(“int,float”);
}
public void m1(float i,int f)
{
System.out.println(“float,int”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1(10,10.0f);//int,float
s.m1(10.0f,10);//float,int
s.m1(10,10);//invalid-> CTE:reference m1 is ambiguous
}
}
CASE 2:
class Sample
{
public void m1(String s)
{
System.out.println(“String version”);
}

public void m1(Object o)


{
System.out.println(“Object version”);
}
public void m1(double d)
{
System.out.println(“double version”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1(“viswan”);// String version
s.m1(new Object());// Object version
s.m1(null);// String version
}
}
If there is Double (wrapper class) then CTE: reference to m1 is
ambiguous.
CASE 3:
class Animal
{
}
class Monkey extends Animal
{
}
public class OLStaticBinding {

public void m1(Animal a)


{
System.out.println("Animal version");
}
public void m1(Monkey m)
{
System.out.println("Monkey version");
}
public static void main(String a[])
{
OLStaticBinding s=new OLStaticBinding();
Animal a1 =new Animal();
s.m1(a1); // Animal version
Monkey m =new Monkey();
s.m1(m); // Monkey version
Animal a2 =new Monkey();
s.m1(a2); // Animal version

}
}
}
In the case of overloading the method resolution performed by the
compiler is based on the reference type.
Method Overriding
If you don’t want parent class implementation for any method we can
override in the child class based on our child class requirement. This
concept is called Overriding.
While overriding we have to fallow rules:
1. In the overriding, the method names and arg’s must be
same.
Ie. In the case of the overriding the signatures of the methods
must be same Until 1.4 version, the return types must be
same. But from 1.5 version onwards covariant return types are
also allowed.
Example:
class p { public Number getNumber(){} }
class c extends P{ public Number getNumber(){} }
(or)
class C extends P
{
public Byte/Short/Integer getNumber(){}
}
For Number class Byte/Short/Integer is co-variant return types or
classes.
Hence in case of overriding as the return type we can keep child class
objects also.
Example:
import java.io.*;
class P
{
public object m1(){ return new object; }
}
class C extends P
{
public Object m1(){ return new Object; }
}
class C extends P
{
public String m1(){ return “durga”; }
}//in 1.4 CTE saying m1() in C cannot override found:string, req:object:
in 1.5 ver no CTE
2. final methods can’t be overridden.
3. private methods never participate in the in the overriding
because these methods are not visible in the child classes.
4. While overriding decreasing access specifier is not allowed.
Violation leads to CTE.
class P { public int m1(){} }
class C extends P { public int m1(){} }
Parent class -------------------------------- Child class
public ----------------------------------------------- public
protected ---------------------------------------- protected, public
default ---------------------------------------- default, protected ,public
private ---------------------------------------- private, default, protected, public

* While implementing any interface method, we should declare that


method as public in the implemented class.(by default implements
interface method is public and abstract)
* An abstract method can be overridden as abstract. The child of the
original child class is responsible for the implementation.

class P{
public void m1()
{ } }//non abstract
abstract class C extends P{
public abstract m1(); }//valid abstract

5. While overriding the size of the CheckedException should not


increase. There is no rule for UnCheckedExceptions.
Example: Base or parent class :
public void m1()throws IOException
Derived or child class :

public void m1()throws FileNotfoundException //valid

public void m1()throws Exception -->CTE

public void m1()throws RunTimeException //valid


We can override a synchronized method to non-synchronized
and vice versa we can override native to native to non native
and vice versa.
We can override a non-final method to final method.
We can’t override a static method to non static and a non-
static method to static violation leads to CTE .
While overriding method has to execute will be decided by JVM based
on the Run Time Object. Hence Overriding is an example of
“dynamic polymorphism” or “LateBinding” (Dynamic Method
dispatch).
If the parent’s class reference can be used to hold child class object by
using that reference we are allowed to call only parent class methods.
Child class specific methods are not allowed to call by using parent
class reference.
Method Hiding:-
This is exactly same as overriding except both parent & child class
methods must be declared as static. In the method hiding the method
resolution take care by compiler only based on the reference type.
Ex:
class P
{
static int x=10;
int y=20;
}
class C extends P
{
static int x=100;
int y=200;
}
class Sample
{
public static void main(String[] a)
{
P p=new C();
System.out.println(p.x+”,”+p.y); //10,20
C c=new C();
System.out.println(c.x+”,”+c.y); //100,200
P p1=new P();
System.out.println(p1.x+”,”+p1.y); //10,20
}
}
We can’t override in the child class. But if define exactly same variable
in child class.
Variable resolutions take care by compiler only based on the reference
type.
Constructors
The purpose of Constructor is to perform of our creted object.
Whenever we are calling new operator for the creation of object, it
calls constructor automatically to provide initialization for the
object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}
Rules Of Constructor :
1. Constructor concept is applicable for every class including
abstract class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the constructor and the name of the class must be
same.
4. The allowed modifiers for the constructors are public,
private, protected, and default. If you are applying any other we
will get a CTE saying “modifier xxx not allowed her”.
5. We can’t give return type for the constructor even void also.

If we will give return type for the constructor that thing as a method
instead of constructor that thing as a method instead of constructor
(so, there is no CTE). Ie., it is legal (but stupid) to have a method
whose name same as classname.
Default Constructor:-
If the programmer is not writing any constructor, then only compiler
will generate a default constructor.
Ie., either programmer written constructor or compiler generated must
present in your class but not both at a time.
Prototype of default constructor shown below:
a).Programmer written code:- class Test{}
Compiler generated code:-
class Test
{
Test()
{
super();
}
}
The default constructor is always no argument constructor.
The access modifier of the default constructor is same as access
modifier of the class (public & default only).
The default constructor contains only one statement which is ‘no arg
call to super class Constructor ‘ (super();)
b) Programmer written code:-
class Test {
Test(int i)
{
System.out.println(“constructor”);
}}
Compiler generated code:-
class Test {
Test(int i)
{
super();
System.out.println(“constructor”);
}}

c). Programmer written code:-


class Test {
Test(int i)
{
super();
System.out.println(“Hai”);
}}
Compiler generated code:- no new code is going to generate.

d). Programmer written code:-


class Test {
void Test()
{
System.out.println(“hello”);
}
}
Compiler generated code:-
class Test {
void Test()
{
System.out.println(“hello”);
}
Test()
{
super();
}}
e). Programmer written code:-
class Test {
Test()
{
this(10);
System.out.println(“hai”);
}
Test(int i)
{
System.out.println(i);
}}
Compiler generated code:-
class Test {
Test() {
this(10);
System.out.println(“hai”);
}
Test(int i) {
super();
System.out.println(i);
}}
The first line inside a constructor must be a call to super class
constructor (by using super();) or a call to overload constructor
of the same class. ( by using ‘this’ keyword ).
If you are not writing the first line as either ‘super()’ or ‘this’
then compiler will always keep a no arg call to super class
constructor (super();).
1. Allowed only in Constructors.
2. Must be first statements.
3. Either super() or this, but not both.
We can invoke another constructor from constructor from a method
violation leads to CTE. i.e, super() or this must be used inside the
constructor only not anywhere else.
Overloaded Constructors:
We are allowed to keep more than one constructor inside a class ,
which are considered as overloaded constructors. We can’t override
the constructors, because they belong to the same Ex: class Test {
Test(int i){}
Test(){} ---->Overloaded Constructors
}
Constructors are not inherited and hence we are not allowed to
override a constructor.
while recursive method invocation we will get stackoverflowException
But in case of constructors we will get compile time error.
If we are writing any constructor in our class it is recommended to
place default constructor also. Otherwise we should take care while
writing the constructor child case.
If the parent class constructor throws some Checked Exception, while
writing child class constructors we should take care.In case of
unchecked exception no rule.
Recursive Constructor invocation:
class Sample {
Sample() // This is a compile time problem
{
this(10);
}
Sample(int i)
{
this(); // Invalid, CTE: recursive constructor invocation
}
public static void main(String a[])
{
System.out.println(“hai”);
}
}
Constructing the Child class constructors:
Example:
class P {
P()
{ super(); }
}
class C extends P
{
C() {
super();
} } //valid

Example:
class P {
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}

Example: class P
{
P() throws Exception ----> checked exception
{}
}
class C extends P
{
C() // compile time error unhandled exception type exception
{}
}
Date 3/11/2010.

abstract class
We can apply abstract keyword for the classes and methods .abstract
keyword is not possible for variables.If method declared as
abstract we don’t know implementation child class is responsible to
provide the implementation for the parent class abstract methods.

Abstract public void m1(); // here ; is mandatory.

Abstract method has declaration only and should not have any
implementation.
This is the way of decorating abstract method .we should not keep
curly braces at end.
If a class contain at least one abstract method we should have to
declare that class as abstract other wise compile time error.
An abstract class is not compulsory to have an abstract method.i.e
abstract class may contain zero number of abstract methods
also.this is for restricting object creation.
HttpServlet class doesn’t contain any abstract methods ,still the class
is declared as abstract because the methods present in HttpServlet
can’t provide any request ,response for the end user ,these methods
are just for sending error information.
It’s a good programming practice to use abstract methods ,abstract
classes and interfaces.
Example:
class Sam
{
abstract void m1(); //error
}

Example 2:
abstract class Xy
{
abstract void m1(); // valid
}

Example 3:
abstract class X
{
void m1() // valid
{
System.out.println(“valid”);
}
}
Example 4:
abstract class X
{
abstract void m2();
}

class Y extends X // error we must provide the implementation for m2


method .
{
}
interface
An interface defines the contract between service provider and the
client without highlighting internal implementation.
i.e Interface describes the services ,what service provider provides and
what client get.
The main advantage of interface are :
1. we never high lite our implementation to the outside world,we can
achieve security for our implementation.
2. With out effecting outside world,we can enhance our internal
implementation. Interface is considered as 100% pure abstract class
because we never keep implementation inside interface. And hence
all the methods present inside an interface are abstract
methods.
For the service provider point of view an interface defines the services
provided by that person.
From the client point of view an interface describes what services he
required.
Declaring an interface:
interface Interf
{
public void m1();
public void m2();
}
class Bea implements Interf
{
public void m1()
{
System.out.println(“implementation m1”);
}
public void m2()
{
System.out.println(“implementation m2”);
}
public static void main(String arg[])
{
Interf i=new Interf();
i.m1();
}
}
If you want to provide implementation for any interface
method, it must be declared as public .
The first concrete class which implements an interface must provide
implementation for all the interface methods other wise the class must
declared as abstract.
We can declare an interface (top level) with <default> and
public,abstract,strictfp modifiers.
interface methods Declarations:
All the interface methods by default abstract and public (either
we are specify or not specify) not concrete method.
Examples:
Void m1();
public void m1();
abstract void m1();
public abstract void m1();
All the above are same .
Hence the above four methods declaration are identical.
An interface method never be declared as native ,strictfp,private
,static, synchronized and protected.

interface variables Declarations:


All the interface variable are by default public ,static and final.
Hence the following variable declaration inside an interface are
identical.

interface interf
{
int x=10;
public int x=10;
public static final int x=10;
final int x=10;
static int x=0;
}
Hence an interface we never declared as private ,protected and
transient.

All the interface variables must perform initialization at the


time of declaration.
Hence the following code will not compile.
interface Interf
{
int x;
}
Inside implement classes we are not allowed to change the value of
interface variable violation leads to compile time error.
Class Sample implement Interf
{
public static void main(String arg[])
{
x=20; //compile time error
}
}
A class can extend only one class at a time .But can interface
can extend any number interfaces.
A class can implement any number of interfaces at a time.But
interface never implement another interface. It will extends
another interface.
Naming conflicts inside interface:
Case 1:
interface Left
{
public void m1();
}
interface Right
{
public void m1();
}
class Central implement Left,Right
{
public static void main(String arg[])
{
public void m1()
{
}
}
If two interfaces have the two are more same methods ,then only one
method implementation is enough from both interfaces.
Case 2:
The interface having same method name but different arguments.
Interface Inter
{
public void m1();
public void m1(int x);
}

case 3:
Same method name,same arguments but different written types.
Interface Left
{
public void m1();
}
Interface Right
{
public int m1();
}
class Central implement Left,Right
{
public static void main(String arg[])
{
public void m1() // error
{
}
public int m1() // error
{
}
}
}
In the above class same method signature m1 is not allow .violation
leads to compile time error.
Exceptional case:
We can’t provide implementation at a time for two or more interfaces
having methods with same signature but different return type .
Variable Naming conflicts:
interface Left
{
int x=10;
}
interface Right
{
int x=100;
}
class Central implement Left,Right
{
public static void Main(String arg[]
)
{
System.out.println(x); // reference to x is ambiguous both variables
System.out.println(Right.x);
System.out.println(Left.x);
}}
we can resolve variable naming conflicts using interface name.(i.e
instead of x we have to specify left.x or right.x).

Tag Interface Marker/Ability Interface:


If an interface is marked for some ability such type of
interfaces are called maker interfaces or tag interface or
ability interface.
Example: Comparable, Serializable, Clonable
If an interface doesn’t contain any method, it is usually marker
interface. Even though interface contains some methods still
we can use the term marker interface if this interface is
marked for some ability.
Example: Comparable (contains method compareTo())
Adapter classes doesn’t contain concrete methods ,contain
only empty implementation of the methods.
Difference between abstract class and interface:
Interfaces provides more security and high performance when
compare to abstract classes.
Abstract class may contain concrete methods but an interface
never contains any concrete method.
Collection-Interface
The 1.2 release of the Java platform includes a new collections
framework. A collection is an object that represents a group of
objects. A collections framework is a unified architecture for
representing and manipulating collections, allowing them to be
manipulated independently of the details of their representation. The
Collection interface is the root of the collection hierarchy. A Collection
represents a group of objects, known as its elements. Some
Collection implementations allow duplicate elements and others do
not. Some are ordered and others unordered. The JDK doesn't provide
any direct implementations of this interface: It provides
implementations of more specific subinterfaces like Set and List. This
interface is the least common denominator that all collections
implement.
Collection is used to pass collections around and manipulate them
when maximum generality is desired.Collection frame work define
a set classes and interfaces which can be used for
representing a group of objects as single entity. In the case of
c++ the corresponding collection frame work is known as
STL(Standered template library) and collection is known as container.
There are six collection interfaces. The most basic interface is
Collection. Three interfaces extend Collection: Set, List, and SortedSet.
The other two collection interfaces, Map and SortedMap, do not
extend Collection, as they represent mappings rather than true
collections. However, these interfaces contain collection-view
operations, which allow them to be manipulated as collections.
Collection Interface:
It defines general methods ,which can be used for a group of individual
objects. i.e a collection represents a group of individual ibjects.
Note:
Collection is an interface to represent a group of individual objects
where as collections is an utility class for defining utility methods like
sorting, searching.
Collection Interface Methods:
This Interface defines general methods which can be applied on any
collection object.
1.boolean add(Object obj)
2.boolean addAll(collection c)
3.boolean remove(Object o)
4.boolean removeAll(Collection c)
5.void clear()
6.boolean retainAll(Collection c)
removes all the elements in the collection except those present in c.
7.boolean contains(Object o)
8.boolean containsAll(Collection c)
9.boolean isEmpty()
10.int size() returns the number of objects present in the collection
11.Object[] toArray() mainly for improving the performance of the
system.
12. Iterator iterator() to return the objects one by one.

The primary advantages of a collections framework are that it:


• Reduces programming effort by providing useful data structures and
algorithms so you don't have to write them yourself.
• Increases performance by providing high-performance
implementations of useful data structures and algorithms. Because the
various implementations of each interface are interchangeable,
programs can be easily tuned by switching implementations.
• Provides interoperability between unrelated APIs by establishing a
common language to pass collections back and forth.
• Reduces the effort required to learn APIs by eliminating the need to
learn multiple ad hoc collection APIs.
• Reduces the effort required to design and implement APIs by
eliminating the need to produce ad hoc collections APIs.
• Fosters software reuse by providing a standard interface for
collections and algorithms to manipulate them.

SortedMap-TreeMap-Properties
SortedMap:
It is interface.If you want to store the elements based on some sorting
order of keys we should go for the SortedMap.A SortedMap is a Map
that maintains its mappings in ascending key order. It is the Map
analogue of SortedSet. The SortedMap interface is used for apps like
dictionaries and telephone directories.
SortedMap Methods:
1) Object firstKey() //Returns the firstkey of the sortedset
2) Object lasKey() // Returns the last key of the sortedset
3) SortedMap headMap( Object key) //Returns the SortedMap
whose keys are smaller than or equal to specified key
4) SortedMap tailMap( Object key) // Returns the SortedMap whose
keys are greater than or equal to specified key
5) SortedMap subMap( Object key1,Object key2) // Returns a
SortedMap whose keys are greater than or equal to the key1 but less
than key2
6) Comparator comparator(): //Returns Comparator Object that
defines the underlying sorting technique.If the natural sorting order is
used then returns null
TreeMap:
It implements the SortedMap interface.
The underlying datastructure for the TreeMap is Red-Black Tree
Insertion order is not preserved
Duplicate keys are not allowed but values may be duplicated
Heterogeneous objects are not allowed for the keys but values may be
heterogeneous.
As first entry null key insertion is possible to the empty treemap but
after if you try to add any other entry we will get the
NullPointerException
If you are trying to add an entry with the null key to an already exsting
treemap we will get the NullPointerException
There is no restriction for null values
If natural sorting order is used then the keys must be comparable
otherwise classCastException
TreeMap Constructors:
TreeMap map=new TreeMap():
TreeMap map=new TreeMap(Comparatror c):
TreeMap map=new TreeMap(Map m):
TreeMap map=new TreeMap(SortedMap m):

TreeMap Demo program:


package myutil;

import java.util.TreeMap;

public class TreeMapEx1 {


public static void main(String[] args)
{
TreeMap map=new TreeMap();
map.put(new Integer(100),"orange");
map.put(new Integer(200) ,"apple");
map.put(new Integer(300),"grapes");
System.out.println("The TreeeMap Is "+map);
// Try to place the null you will get NullPointerException
// map.put(null,"javasun");
}
}
output:
The TreeeMap Is {100=orange, 200=apple, 300=grapes}

TreeMap Example code with Comparator:


package myutil;

import java.util.Comparator;
import java.util.TreeMap;
class Mycompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
return -i1.compareTo(i2);
}
}

public class TreeMapCom {


public static void main(String[] args)
{
TreeMap map=new TreeMap(new Mycompare());
map.put(new Integer(100),"orange");
map.put(new Integer(300),"apple");
map.put(new Integer(200),"grapes");
map.put(new Integer(400),"grapes");
System.out.println("The TreeeMap Is "+map);
// Try to place the null you will get NullPointerException
//map.put(null,"javasun");
}
}
output:
The TreeeMap Is {400=grapes, 300=apple, 200=grapes, 100=orange}

Properties:It is the child class of Hashtable For Properties both


keys and values must be Strings
Propertes Constructors:
Properties props=new Properties();

Methods:
getProperty(String key);
setProperty(String key,String value);
propertyNames();
load(InputStream stream);
store(OutputStream stream,String comment);

Properties Demo Program:


import java.util.*;
public class PropertiesDemo {
public static void main(String[] args ){
Properties props=new Properties();
FileInputStream fis=new FileInputStream(“abc.properties”);
props.load(fis);//Load the file
System.out.println(props.getProperty(“orange”));
props.setProperty(“apple’,200);
FileOutputStream fos=new FileOutputStream(“abc.properties”));
}
}
Map-Hashtable-HashMap-WeakHashMap-IdentityHashMap
MAP Interface: A Map is an object that maps keys to values. Maps
cannot contain duplicate keys: Each key can map to at most one
value.
Map is not the child interface of Collection interface
If you want to store the values or objects as key value pairs we go for
the the Map interface
Both key and values are objects
Duplication of keys is not allowed but values may be duplicated
Key –Value Pair is called an Entry
Methods in Map Interface:
1)Object put(Object key,Object value) //Inserts a value into the map.if
the key is already exists it will replace the old values with new one
2)Object get(Object key) // Returns the value associated with the key
otherwise returns null
3)Object remove(Object key) // It removes the entry associated with
the key and returns the corresponding value otherwise returns null
4)boolean containsKey(Object key)
5)boolean containsValue(Object key)
6)int size()
7)boolean isEmpty()
8)void clean()
9)void putAll(Map m)
10)Set keySet()
11)Collection values()
12)Set emptySet()
// The following three methods collection view of Map
13)Object getKey();
14)Object getValue();
15)Object setValue(Object obj)
//Entry is an inner interface present inside the map.It contains
the following three methods which can be applied on the entry object.
16)Object getKey();
17)Object getValue();
18)Object setValue(Object obj)

Note:
interface Map{
Interface Entry{ // inner interface entry
Object getKey();
Object getValue();
Object setValue(Object obj)
}
}

Hashtable:
The underlying datastructure for the HashTable is the Hastable itself.
Heterogeneous values are allowed for both keys and values
null insertion is allowed for both keys and values for the first
element violation leads to NullPointerException
Almost all methods or Hashtable are synchronized hence it is
thread safe Insertion order is not preserved and the objects
are arranged based on hashcode
Duplicate objects for values but keys are not to be duplicated
Hashtable Constructors:
Hashtable table=new Hashtable();
Hashtable table=new Hashtable(int initialCapacity);
Hashtable table=new Hashtable(int initialCapacity,float fillRatio);
Hashtable table=new Hashtable(Map m);

Hashtable Demo:
import java.util.Hashtable;

public class HashtableEx1 {


public static void main(String[] args) {
Hashtable table=new Hashtable();
table.put(new Integer(1),"xxx");
table.put(new Integer(24),"yyy");
table.put(new Integer(3),"zzz");
table.put(new Integer(8),"aaa");
table.put(new Integer(9),"bbb");
table.put(new Integer(2),"sss");
System.out.println("The Hashtable is "+table);
}
}
output:
The Hashtable is {9=bbb, 8=aaa, 3=zzz, 2=sss, 24=yyy, 1=xxx}
HashMap:
The underlying datastructure for HashMap is Hashtable
Duplicate keys are not allowed but values may be duplicated
Insertion order is not preserved
Heterogeneous key and values are allowed
Null key is allowed only once but values are nulls for any
number of times
HashMap Constructors:
1) HashMap map=new HashMap();
it Create the empty hashmap with the default initial capacity 16 and
fillRatio 0.75
2) HashMap map=new HashMap(int initialCapacity);
it Create a HashMap with the specified nitialCapacity and default load
factor
3) HashMap map=new HashMap(int nitialCapacity,float loadFactor);
4) HashMap map=new HashMap(Map m);

HashMapDemo Program:
import java.util.*;
public class HashMapEx1 {
public static void main(String... args) {
HashMap map=new HashMap();
map.put("orange",new Integer(1000));
map.put("apple",new Integer(2000));
map.put("banana",new Integer(3000));
map.put("grapes",new Integer(4000));
System.out.println("The Map "+map);
System.out.println(map.put(("orange"),new Integer(1001)));
System.out.println("map "+map);
Set s=map.keySet();
System.out.println("The Key Set"+s);
Collection values=map.values();
System.out.println("The Values Are "+values);
Set s1=map.entrySet();
System.out.println("The Entry Set"+s1);
}
}

output:
The Map {orange=1000, grapes=4000, apple=2000, banana=3000}
1000
map {orange=1001, grapes=4000, apple=2000, banana=3000}
The Key Set[orange, grapes, apple, banana]
The Values Are [1001, 4000, 2000, 3000]
The Entry Set[orange=1001, grapes=4000, apple=2000,
banana=3000]

LinkedHashMap:
It is exactly similar to the HashMap except the following differences
HashMap:
Underlying datastructure is Hashtable
Insertion order is not preserved
While iterating we can not give guarantee for processing
order. Hence we can not use it for caching
LinedHashMap:
Underlying datastructures are hashtable and doubly linkedlist
Insertion order of elements is preserved
While iterating elements we can give guarantee for processing
order.Hence we can use for caching
IdentityHashMap:
In case of HashMap JVM uses the equals() method to identify
the duplicate keys
But if want to use the == operator to identify the duplicates
we go for the IdentityHashMap
Incase of IdentityHashMap two key reference i1 and i2 are
equal if and only if bot i1 and i2 are pointing to the same
object on the heap

IdentityHashMap Demo Program:


import java.util.IdentityHashMap;

public class IdentityHashMapEx1 {


public static void main(String... args) {
IdentityHashMap map=new IdentityHashMap ();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
map.put(i1,"orange");
map.put(i2,"apple");
System.out.println("The Map"+map);
}
}
WeakHashMap:
WeakHashMap is not a child class of HashMap
HashMap dominates the garbage collector.if any objects are associated
with the HashMap eventhough that object does not have any external
references .Garbage collector is not allowed to destroy that object
But garbage collector dominate the WeakHashMap that is in
case of hashmap if the key is not reachable garbage collector
is allowed to destroy whole entry associated with the key
WeakHashMap Demo Program:
import java.util.WeakHashMap;
class Temp {
public void finalize() {
System.out.println("finalize() Called");
}
public String toString() {
return "Temp";
}
}
public class WeakHashMapEx1 {
public static void main(String[] args) {
WeakHashMap map=new WeakHashMap();
Temp t=new Temp();
map.put(t,"orange");
t=null;
System.gc();
System.out.println("The Map"+map);
}
}
output:
finalize() Called
The Map{}

Collection-List-Vector-ArrayList-Stack-LinkedList
Collection Interface :
The Collection interface is the root of the collection hierarchy. A
Collection represents a group of objects, known as its elements. Some
Collection implementations allow duplicate elements and others do
not. Some are ordered and others unordered. The JDK doesn't provide
any direct implementations of this interface: It provides
implementations of more specific subinterfaces like Set and List. This
interface is the least common denominator that all collections
implement. Collection is used to pass collections around and
manipulate them when maximum generality is desired.

It defines general methods ,which can be used for a group of individual


objects.i.e a collection represents a group of individual ibjects.
Note: Collection is an interface to represent a group of individual
objects where as collections is an utility class for defining utility
methods like sorting,searching… etc.

List Interface:

It represents a group of individual objects where


Insertion order is preserved via indexes
Duplicate objects are allowed. .we can differentiate duplicate
objects by using indexes.
A list is also known as sequence ArrayList ,LinkedList ,Vector and Stack
implement List interface.
Following are the methods list interface :
1.boolean add(Object obj)
2.boolean add(int index,Object o)
3.boolean addAll(Collection c)
4.boolean addAll(int index,Collection c)
5.boolean remove(object o)
remove the first occurrence of this object
6.boolean removeAll(Collection c)
7.int indexOf(Object o)
return the index of first occurrence
returns -1 if there is no such object
8.int lastIndexOf(Objetc o)
9.Object get(int index)
there is no get method in the collection interface
10.Object set(int index , Object o)
11.ListIterator listIterator()
12.Object remove(int index)
Vector class:
The underlying datastructure for vector is growable array or resizable
array.
Insertion order is preserved.
Null insertion is possible.
Duplicate objects are allowed.
Hetrogeneous objects are allowed.
It implemented RandomAccess,Clonable and Serializable interfaces.
Best choice for retrieval operation.
Worst choice for insertion or deletion in the middle.
When compare with ArrayList,Vector is preferable when thread safety
is reqired because all the vector class methods are synchronized.

Vector methods:
For adding objects
1.add(Object o) ----> from collection
2.add(int index, Object o) ---------> from list
addElement(Object o) ---------> Vector
for removing objects
1.remove(Object o) ---------> from collection
2.remove(int index) -----------> from list
3.removeElement(Object o) ----------> Vector.
4.removeElementat(int index) -------------> Vector
5.removeAllElements()
6.clear() ------------> from collection
For accessing objects.
1.Object get(int index)
2.Object elementAt(int index)
3.Object firstElement()
4.Object lastElement();
5.int size()
6.int capacity();
Constructors of Vector:
1.Vector v=new Vector()
create an empty Vector with default initial capacity 10.
If the Vector reaches its maximum capacity a new Vector object will
create with a capacity = current capacity * 2 i.e doubles.
2.Vector v=new Vector(int initialcapacity)
Constructs an empty vector with the specified capacity.
3.Vector v=new Vector(Collection c)
4.Vector v=new Vector(int initialcapacity,int incrementalcapacity)

Vector Example:
import java.util.*;
class VectorDemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement(“a”);
for(int i=0;i<10;i++)
{
v.addElement(new Integer(i));
}
System.out.println(v);
System.out.println(v.capacity()); // 10
v.add(“b”);
System.out.println(v.capacity()); // 20
}}

Array List: The underlying datastructure for array List is growable array
or resizable array.
Insertion order is preserved.
Duplicate objects are allowed.
Hetrogeneous objects are allowed.
Null insertion is possible any number of times.
Constructors of ArrayList:
1.ArrayList a=new ArrayListA();
creates an empty arraylist with the default initial capacity 10.
If arraylist reaches its maximum capacity ,it creates a new
arraylist object with the new capacity as (Current capacity *
3/2 ) + 1;
2.arrayList a=new ArrayList(int initialcapacity)
creates an empty arraylist with the specified initial capacity.
3.ArrayList a=new ArrayList(Collection c)
Construct an equivalent arraylist for the given collection object.

ArrayList Example:
import java.util.*;
class ArraylistDemo
{
public static void main(String arg[])
{
ArrayList a=new ArrayList();
a.add(“aaa”);
a.add(“bbb”);
a.add(“new Integer(10)”);
a.add(null);
a.add(1,”ccc”);
System.out.println(a); // [aaa, ccc,bbb,10,null]
}
}
every collection class implemented clonable and serializable
interfaces.
System.out.println(a instanceOf java.io.Serializable); // true
System.out.println(a instanceOf java.io.Clonable); // true
ArrayList and Vector classes implemented Random Access
interface.Any element in ArrayList and Vector we can access with same
speed.Hence ArrayList is best suitable for retrivel operation.
ArrayList is a non-synchronised one introduced in 1.2 version.It is a
non-legacy class which has high performance.But we can’t achieve
security.Where as vector is a synchronized in 1.0 version .It is a
legacy class which has low performance But we can achive security.
In ArrayList ,there is a possibility for data corruption as it is thread
safe.ArrayList is the worrest choice,If your frequent operation is
insertion or deletion in the middle,because it reqires so many internal
shift operations .
LinkedList:
The underlying data structure for LinkedList is
DoublyLinkedList.
Insersion order is preserved.
Duplicate objects are allowed.
Null insertion is possible any number of times.
Hetrogeneous objects are also allowed.
It implemented serializable and clonable interfaces but not
RandomAccess interface.
LinkedList is the best choice if your frequent operation is insertion or
deletion in the middle.
LinkedList the worest choice if your frequent operation retrieval
operation.
LinkedList class contain the following methods for implementing Stacks
and Queues.
1.void addFirst(Object o)
2.void addLast(Object o)
3.Object removeFirst()
4.Object removeLast()
5.Object getFirst()
6.Object getLast()

Constructors of LinkedList:
1.LinkedList l=new LinkedList();
create an empty LinkedList (initial capacity is not applicable) size !=
capacity
2.LinkedList l=new LinkedList(Collection c)

LinkedList Example
import java.util.*;
class LinkedListDemo
{
public static void main(String arg[])

LinkedList l=new LinkedList();


l.add(“laxman”);
l.add(new Integer(10));
l.add(null);
l.add(“laxman”);
l.add(0,”scjp”);
l.add(“gorantla”);
l.removeLast();
l.addFirst(“ccc”);
System.out.println(l); // [ccc,gorantla,scjp,10,null]
}}

Stack Class: It is the child class of Vector


Contain only one constructor
Stack s=new Stack();
Methods of stack class:
1.Object push (Object obj)
It pushes an element into stack and that element also return.
2.Object pop()
removes the top of the stack and the object is returned.
3.Object peek()
returns the element present on the top of the stack.
4.boolean empty()
returns true if the stack isempty otherwise false.
5.int search(Object o)
returns the offset from the top of the stack if the Object present else
return -1.
Ex: s.search(“a”);
Stack example:
Import java.util.*;
Class StackDemo
{
public static void main(String arg[])
{
Stack s=new Stack();
s.push(“a”);
s.push(“b”);
s.push(“c”);
System.out.println(s); // [a,b,c]
System.out.println(s.search(“c”)); // 1
System.out.println(s.search(“a”)); // 3
}
}
insertion order should be preserved should be not LIFO.
treeset-Comparator
SortedSet Interface:
If you want to represent a group of individual,unique set of objects
,where all the objects are in some sorting order (either natural sorting
order or customized sorting order) then we should go for SortedSet.
SortedSet methods:
1.Object first()
returns the first element in sortedset
2.Object last()
return the last element in sortedset.
3.SortedSet headset(Object end)
returns the sorted set containing the elements which are lessthan end.
4.SortedSet tailSet(Object begain)
returns the sorted set that includes the elements which are greaaer
than or equal to begain.
5.SortedSet subset(Object begain,Object End)
return a sortedset that includes the elements which are greater than or
equal to begain but less than end.
6.Comparator comparator()
decribes underlying sorting technique if default sorting technique is
used then it simply returns null.

TreeSet class :
The underlying datastructure for the treeset is balancedtree.
Duplicate objects are not allowed.
Insertion order is not preserved, but all the elements are arranged in
some sorting order.
Null insersion is possible but only one.
Hetrogeous objects are not allowed, voialtion leads to runtime
exception saying classcast exception.
Constructors:
1. treeSet t=new TreeSet()
creates an empty TreeSet where the sorting technique is default
natural order.
2. TreeSet t=new TreeSet(Comparator c)
creates an empty TreeSet ,where the sorting technique is specified by
comparator object .( this is for customized sorting).
3. TreeSet t=new TreeSet(Collection c)
4. TreeSet t=new TreeSet(SortedSet s)
reserved for future purpose.

TreeSet Example:
import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t=new TreeSet();
t.add(“z”);
t.add(“k”);
t.add(“b”);
t.add(“f”);
System.out.println(t); // [b,f,k,z]
t.add(new Integer(10)); // class cast exception
}
}
In case of integers (10,15,20) it followes ascending order.
TreeSet t=new TreeSet()
t.add(null);
System.out.println(t);
t.add(“a”);
System.out.println(t); // nullpointer exception
Null acceptance:
For the empty TreeSet as the first element we are allowed to add null.
But after adding null if we are trying to add anyother ,we will get a RTE
saying NullPointerException”.If the treeset already contains some
elements,If we are trying to add null causes once again nullpointer
Exception.

In case of StringBuffer objects


t.add(new StringBuffer(‘a”));
t.add(new StringBuffer(“b”));
t.add(new StringBuffer(‘c”));
t.add(new StringBuffer(“l”));
System.out.println(t); // RTE saying classcast exception

i.e In the treeset we should add only.


Homogeneous and comparable objects violation leads classcast
Exception
An object is said to be comparable if an only if the corresponding class
implements comparable interface.
String and Wrapper classes already implemented comparable
interface.But StringBuffer doesn’t implemented comparable interface.
Comparator Interface:
If you want to define our own sorting we havwet to implement
comparator interface.
This interface present in java.util package.
This interface contain the following two methods.a
1.public int compare(Object o1,Object o2)
return –ve number if o1 comes before o2.
return +ve number If o1 comes after o2.
returns zero if o1 and o2 equal.
2.public Boolean equals(Object o)
by using comparator interface we can define our own
customized sorting.

Write a program to insert integer object in the TreeSet where the


Sorting technique is descending order.

import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new MyComparator());
t.add(new Integer(20));
t.add(new Integer(10));
t.add(new Integer(30));
t.add(new Integer(100));
System.out.println(t); // 10 ,20 ,30,100
}
}
class MyComparator implements Comparator
{
public int Compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
int i1=i1.intValue();
int i2=i2.intValue();
if(i1>i2)
return -1;
else
if(i1 > i2)
return +1;
else
return 0;
}
}

write a program to insert string objects into the TreeSet where the
sorting order is increasing order of String lengths.

import java.util.*;
class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new Mycomparator())
t.add(“aaaaaa”);
t.add(“bbbb”);
t.add(“ccc”);
System.out.println(t); // [ccc,bbbb,aaaaaa]
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
if(s1.length() < s2. length())
return -1;
else
if(s1.length() > s2.length())
return +1;
else
return 0;
}
}

program to insert StringBuffer Objects in the treeSet according to


dictionary order

import java.util.*;
class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new TreeSet(new MyComparator());
t.add(new StringBuffer(“aaa”);
t.add(new StringBuffer(“bbb”);
t.add(new StringBuffer(“ccc”);
t.add(new StringBuffer(‘ddd”);
System.out.println(t);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s1.compareTo(s2);
//return s2.compareTo(s1);
}
}

if we return always like this:


return 0; // aaa
return +100 // bbb,ccc,aaa,ddd
return -100 // ddd,aaa,ccc,bbb

collection-set-HashSet-LinkedHashSet
Collection Interface:
The Collection interface is the root of the collection hierarchy. A
Collection represents a group of objects, known as its elements. Some
Collection implementations allow duplicate elements and others do
not. Some are ordered and others unordered. The JDK doesn't provide
any direct implementations of this interface: It provides
implementations of more specific subinterfaces like Set and List. This
interface is the least common denominator that all collections
implement. Collection is used to pass collections around and
manipulate them when maximum generality is desired.

It defines general methods ,which can be used for a group of individual


objects.i.e a collection represents a group of individual ibjects.
Note:
Collection is an interface to represent a group of individual objects
where as collections is an utility class for defining utility methods like
sorting,searching… etc.

Set Interface:
A Set is a collection that cannot contain duplicate elements. As you
might expect, this interface models the mathematical set abstraction.
It is used to represent sets like the cards comprising a poker hand, the
courses making up a student's schedule, or the processes running on a
machine.

This interface doesn’t contain any new methods.we have to use


collection interface methods.

Hash Set:
The underlying data structure for the set is Hashtable.
Elements are inserted based on the hash code, hence insertion
order is not possible.
If we are trying to add a duplicate object no chance of getting RTE or
CTE add() just simply returns false.
Hetrogeneous objects are allowed.
Null insertion is possible but only once.
HashSet is the best choice for searching operations.
Hashset implemented serializable and clonable interface.
Constructors:
1.HashSet h=new HashSet();
Creates a new empty HashSet with default initial capacity 16
and load factor or fill ratio 0.75.
2.HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet with specified initial capacity and default fill
ratio is 0.75.
3.HashSet h=new HashSet(int int itialcapacity,float fillratio)
creates an empty HashSet with the specified initial capacity and
specified fill ratio.
4.HashSet h=new HashSet(Collection c)

HashSet Example:
import java.util.*;
class HashSetDemo
{
public static void main(String arg[])
{
HashSet h=new HashSet();
System.out.println(h.add(“b”); // true
h.add(“b”);
h.add(“c”);
h.add(“d”);
h.add(null);
h.add(new Integer(10));
System.out.println(h.add(“d”); // flase
System.out.println(h); // depends on hash code number insertion order.
}
}

Linked Hash Set:


The linked hash set is exactly similar to HashSet Except the following
differences.
Hashtable is the underlying data structure of
hashset.Hashtable and doubly linkedlist are the underlying
datastructures for linkedhashset.
In the above demo LinkedHashSet l=new LinkedHashSet();
Then the output: [b,c,d,null,10] preceding with true and flase.i.e
insertion order is preserved.
We can use LinkedHashSet for implementing caching memory.

Comparable Interface and clonable interface


Comparable Interface:
This is present in java.lang.package
Contains the following one method.
1.public int compareTo(Object o)
if returns –ve integer if o1 has to place before o2.
If returns +ve integer if o1 has to to place after o2.
If returns zero then o1 and o2 are equal.
All the wrapper classes and string class already implemented
comparable interface. But the StringBuffer doesn’t implement
comparable interface.
Comparable Interface Example:
Interface comparable
{
public int compareTo(Object o)
{
TreeSet t=new TreeSet(0;
t.add(“a”);
t.add(‘z”);
System.out.println(t); // a,z (:: z.compareTo(“a”);)
System.out.println((“a”).compareTo(“z”)); //-25
System.out.println((new Integer(10).compareTo(new Intege(1)); // +1
}
}|
Marker or Tag Interface:
If an interface is marked for some ability such type of interfaces are
called Marker interfaces.
Ex: clonable,serializable
If an interface with out any method obviously accept ass marker
interface.
Eventhough interface contains some methods,still we can consider as
marker interface .If it is marked for some ability.
Ex:Comparable interface.
Intreger i1=new Integer(10);
Integer i2=new Integer(20);
System.out.println(i2.compareTo i1); // -1
System.out.println(i1.compareTo i2); // +1
System.out.println(i1.compareTo i1); // 0
System.out.println(i1.compareTo(“a”)); // CTE nullpointer exception

Cloneable interface:
Cloning in programming uptaining bit wist exact copy of an
object is called cloning.
cloning Example:
Class sample() implements cloneable
{
Int i=10;
Public static void main(string args[])throwsClone
notSupportedEexception
{
Sample s1=new sample();
Sample s2=s1;
Sample s3=(sample)s1.clone();
S1.i=1000;
System.out.println(s3.i);
System.out.println(s1==s3);
we should type cast otherwise
CTE:in compatable types
Found: Object reqired=sample
The class must implements cloneable interface otherwise at runtime
clone() results cloneNotsupportException
Example:
Class sample implements clonable
{
Int i=10;
Public static void main(string[]args)throws cloneNot support Exception
{
Object o=new object();
Object o2=o.clone();
}
CTE:clone() has protected access in java.lang.object
The protected numbers we can access, from with in the same package
or from outside package but from outside package,the protected
number can be accessed b using child class reference only.ie we can’t
use parentclass reference to access protected number from outside
package,validation leadsto CTE.

clone() method:
Protected object clone() throws clone not supported exception.
This method can used to prouduced exactly duplicate copy of an
object..
All the objects can’t produce cloned object ,only clonable objects can
produce duplicate copies .
An object is said to be conable if and only if the corresponding
class implements clonable interface.
By using the folling object class clone() method we can produced
cloned objects
Protected object clone() throws clone supported exception
CheckedException so we should handle by using try catch or throws to
the caller by using throws clause.
Shallow cloning Example:
Class Student implements cloneable
{
String name;
String age;
Student(String name,String age)
{
This.name;
This.age=age;
]
Public Object clone()throws cloneNotSupportedException
{
Return this;
}
}
Class Student cloneDemo
{
Student s1= new Student(“hai”,”22”);
Student s2= (Student)s1.clone();
S2.name=”abc”;
System.out.println(s1.name);
Public static void main (String ar[])
{
StudentCloneDemo s1= new Student cloneDemo();
}
}
Deep cloning example:
Class Student implements cloneable
{
String name;
String age;
}
Student(String name ,String age)
{
This.name=name;
This.age=age;
}

Public Object clone(0throws CloneNotSuport Exception


{
try
{
ByteArrayOutputStream bas=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bas);
Oos.writeObject(this);
ByteArrayInputStream bias=new
ByteArrayInputStream(bas.toByteArray());
ObjectInputStream oos=new ObjectInputStream(bias);
Return ois.readObject();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
class DcloneDemo
{
DcloneDemo()throws CloneNotSuportException
{
Student s1=new Student(“hello”,”200”);
Student s2=(Student)s1.clone();
S2.name=”java”;
System.out.println(s1.name);
Public static void main(String[] arg)
{
new DcloneDemo();
}
}
Iterator,ListIterator,Enumeration
Enumeration:
This is cursor to retrive the objects one by one.
This interface contains the following two methods.
1.boolean hasMoreElements();
2.Object nextElement();
Enumeration Example:
Import java.util.*;
Class EnumDemo
{
public static void main(String arg[])
{
Vector v= new Vector();
For(int i=0;i<=10; i++)
{
v.addElement(new Integer(i);
}
System.out.println(v); // [0,1,2,3…….10]
Enumeration e=v.elements();
While(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
If(i.IntValue() % 2 ==0)
{
System.out.println(i);
}}}
Limitations:
1. We can get Enumeration Object only for legacy classes
(Vector,Stack,Hashtable,Properties,Dictionary,Enumeration)
2. While iterating the Objects of enumeration we can get only read-
access.
i.e while iterating we are not allowed to perform any remove or modify
operation.
Iterator:
This can be applied for any collection implemented class (legacy
and non-legacy)
While iterating the objects we are allowed to perform remove
operation also, in addition to read operation.
This interface contain the following there methods
Boolean hasNext()
Object next();
Void remove()

Iterator Example:
Import java.util.*;
Class IteratorDemo
{
public static void main(String arg[])
{
ArrayList l=new ArrayList();
for(int i=0;i<=10;i++)
{
l.add(new Integer(i);
}
System.out.println(i); // 0,1,2,3,……9
Iterator itr=l.iterator();
While(itr.hasNext())
{
Integer i=(Integer)itr.next();
If(i.intValue() % 2==0)
{
System.out.println(i);
}
else
{
itr.remove();
}
}
System.out.println(l); [0,2,4,6,8]
}
}
}

List Iterator:
List iterator is the child interface of iterator .this can be
applicable only for list implemented classes
(arraylist,linkedlist,vector and stack).
This is a bidirectional cursor .we can move either to forward or
backward direction
While iterating ,we are allowed to replace existing element with the
new element ,we are allowed to add new elements and still we can
perform remove operation also.
ListIterator defines the following methods.
1.boolean hasNext();
2.boolean hasPrevious();
3.Object next();
4.Object previous();
5.int nextIndex();
if there is no next element it just simply return the size of the list.
6.int previousIndex()
Return -1 if there is no previous index.
7.void remove()
8.void set()
9.void add()

ListIterator Example:
Import java.util.*;
Class ListIterDemo
{
public static void main(String arg[])
{
LikedList l=new LinkedList();
L.add(“laxman”);
l.add(“chandu”);
l.add(“ravi”);
l.add(“raju”);
System.out.println(l);
ListIterator lt=l.listIterator();
While(lt.hasNext())
{
String s=(String)lt.next();
If(s.equals(“laxman”))
{
lt.remove(); or lt.set(“scjp”);
}
}
System.out.println(l);
}
}
Thread creation
Multitasking:
* Executing several tasks simultaneously is the concept of Multitasking.
* The main objective of multitasking is to decrease response time of
the system, so that the performance of the system will increase.
Process Based Multitasking:-
* Executing several tasks simultaneously where each task is a
independent program.
* Example typing a java program in the Editor, playing MP3 player,
Downloading a file from the internet
* All the tasks are independent of each other and executes
simultaneously.
* This type of multitasking is useful at OS level.
* CGI fallows process based multitasking.
Thread Based Multitasking:-
* Executing several tasks simultaneously, where each task is a
separate inependent part of the same program. That independent part
is called the Thread.
* Servlets followThread Based MultiTasking.
* Java itself provide support for multithreading by introducing several
library classes.
* We can use in games/animation programme.
* Creating a thread in two ways.
1. By extending Thread
2. By implementing Runnable
Methods used to prevent a thread from execution:

* yield()
* join()
* sleep()
* Synchronization
* InterThread communication (wait, notify, notifyAll)

Defining, Instantiating and starting Thread by extending Thread class:


class MyThread extends Thread
{
public void run()
{
System.out.println("child job”);
}
}
Here run method is the heart of thread where you have to define the
job.
class Sample
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start(); //starting a thread
System.out.println(“Main thread job”);
}
}
The above program executes well.it gives the output mainthread
job,child job,.........
Difference between t.start() & t.run()?
• If we call t.start(), it will create a new Thread and that thread is
responsible for execution of run().
• If we call t.run(), mo new thread will create, the main thread only will
execute run(), just like a normal method.
• In case of t.start() output we can’t expect
• In case of t.run() output Child Thread 10 times fallowed by main
thread 10 times.

Thread class start():-


public void start()
{
1. Registering our thread with the thread scheduler then only thread
scheduler allocate CPU and memory type of resources for this new
thread also.
2. calls run()
}
If we over ride start method in the above example:
--->public void start()
{
System.out.println(“start method”);// start method 1 time, main thread
10 times
}
--->public void start()
{
super.start();
System.out.println(“start method”);// start method child & main thread
alternatively
}
class MyThread extends Thread
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
}
}
• Thread class run() has empty implementation that’s why we are
getting no output.
Defining, Instantiating and starting Thread by implementing Runnable
Ex: class MyRunnable implemts Runnable
{
public void run()
{
for(int i=0; i<=10 ;i++)
System.out.pritnln(“child thread”);
}
}
class ThreadDemo
{
public static void main(String a[])
{
MyRunnable r=new MyRunnable();
r.start(); // compile time errror
Thread t=new Thread(r); ---> Target Runnable
for(int i=0 ; i<=10 ; i++)
{
System.out.println(“main thread”);
}
}
} In the above example instead of r.start we place r.run();
//childThread (no new thread will create ) In the above example we
place the

* t.start(); //valid (new thread will create child thread)


* t.run(); // child thread (no new thead will create)

• Among the above two probabilities of creating thread it is highly


recommended to use implements Runnable mechanism.
• In the first case ( extends thread), our thread class extends
Java.Lang.Thread, hence no chance of extending any thing else. Hence
we are missing, the key benefit of oop’s concept ie., inheritance.
Lifecycle of Thread:

• Once the thread is started, there is no chance of starting the same


thread once again. // we can start thread onetime only.
Violation leads to RTE saying Illegal Thread State Exception”.
• Thread t= new Thread();
t.start(); //no o/p

Thread class Constructors:


1. Thread();
2. Thread(Runnable r);
3. Thread(String name);
4. Thread(Runnable r, String name);
5. Thread(ThreadGroup g, String name);
6. Thread(ThreadGroup g, Runnable r);
7. Thread(ThreadGroup g, Runnable r, String name);
Ex:- // Test king
class MyThread extends Thread
{
public void run()
{
System.out.println(“run”);
}
}
class ThreadDemo
{
public static void main(String a[])
{
MyThread t= new MyThread();
Thread t1=new Thread(t);
t1.start();
// t1.run(); ----> It is just like a method no new thread will create
}
}
Setting & getting the name of a thread:
Thread class contain the fallowing methods for setting & getting the
name of the Threads..

* public final String getName();


* public final void setName(String s);

Thread class yield , join , sleep.


Thread Priorities:
• Thread class contains the fallowing methods for setting and getting
priority of a thread.
public final int getPriority();
public final void setPriority(int i);
• The valid range for the thread priorities 1 to 10 (1 is atleast and 10 is
the highest)
• Thread class contains the fallowing predefined priority constraints.
MAX-PRIORITY ----> 10
NORM-PRIORITY ----> 5 (default)
MIN-PRIORITY ----> 10
• If you are trying to set the priority as greater than 10 or lessthan1,
then we will get a RTE saying “Illegal Argument Exception”
Example:
class MyThread extends Thread
{}
class Sample
{
public static void main(String a[])
{
Thread.currentThread().setPriority(10);
System.out.pritnln(Thread.currentThread().getPriority());
MyThread t= new MyThread();
System.out.pritnln(t.getPriority());//10 10
}
}
• The default priority for the maintained is 5. But we are allowed to
change the prority by using setPriority()
• The priority of any the thread is inherited from the parent thread.
• Thread scheduler uses these proroites to allocate CPU. The thread
which is having highest priority will get executes first.
t1.setPriority(10);
Yield() :
We can prevent a thread from execution by using one of the fallowing
methods.
1. yield()
2. join()
3. sleep()
• The thread which is executing yield() causes the current
thread temperarly pause and allow other waiting threads
of same or high priority to execute.
• If there is no waiting thread, the same thread will
execute immediately.
• If all the remaining threads are having low priority, then
the same thread once again will execute.
Method Signature:-
public static native yield();

• If the thread calls yield(), the thread going to ready


state.
yield method example:
Class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.pritnln(“child thread”);
Thread.yield();
}
}
}
class SampleDemo
{
public static void main (String a[])
{
MyThread t = new MyThread();
t.start();
for(int i=0;i<10;i++);
{
System.out.pritnln(“main thread”);
}
}
}
• The yield() depends upon underlying platform. Some platforms
may not support .Breaks java’s programme independency.
join:
• If any executing thread calls join method on any thread
t, the current thread will go to the blocked state until t
completes.
Method Signature:
public final void join() throws InterruptedException
public final void join(long ms)throws InterruptedException
public final void join(long ms, int nanosec)throws
InterruptedException

join Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“sita thread”);
try
{
Thred.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
class JoinDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
t.join(); //or t.join(3000);
for(int i=0;i<10;i++);
{
System.out.println(“Rama thread”);
}
}
}
sleep():-
• The thread which is executing sleep() will go to the
sleep for the specified amount of time.
MethodSignature:
public static void sleep(long ms) throws InterruptedException
public static void sleep(long ms, int nanoseconds)throws
InterruptedException

sleep example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“child thread”);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
class SleepDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
}
}
interrupt():
• The thread can interrupt any sleeping/waiting/blocked for
joining by the fallowing thread class method.
public void interrupt(); //this is instance method
interrupt example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“child thread”);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(“I got interrupted”);
}
}
}
}
class SleepDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
t.interrupt();
}
}

summsrization table:

Thread Synchronization
Synchronization:
The keyword synchronized can be apply only for methods and
blocks. Ie., We can’t apply synchronized keyword for the
classes and variables.
If a method (or block) declared as the synchronized at a time
only one thread is allowed to execute that synchronized area
on any given object.
Advantage: Prevent data corruption, achieve security.
Limitation: Because of synchronized keyword 2 threads are not allowed
to execute concurrently on any object, hence the waiting time of the
threads will increase, which results in low performance of the system.
A class can contain both synchronized and non synchronized methods.
If a thread calls synchronized method on any object, first this thread
got the lock, it is allowed to any synchronized method on that object.
If a thread executing any synchronized method on the given object at
that time no other thread is allowed to execute any synchronized
method on that object.
If a thread executing any synchronized method the remaining
threads are allowed simultaneously to execute nay non
synchronized method on that object.
Every Object in java has a lock. At the time of synchronization only the
lock concept will conme into the picture.
Synchronization example:-
class Display
{
public synchronized void show(String name)
{
for(int i=0;i<10;i++)
{
System.out.println(“Good Morning:”);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e){}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Display d;
String name;
MyThread(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.show(name);
}
}
class SynchronizedDemo
{
public static void main(String a[])
{
Display d=new Display();
MyThread t1=new MyThread(d,”java”);
MyThread t2=new MyThread(d,”Sun”);
t1.start();
t2.start();
}
}
output:
good morning : java ......10 times after good morning: sun ......10 times

If we are not putting synchronized keyword we will get some irregular


output like
goodmorning :good morning:java good morning:sun..........like that

Class Level lock:


• If you want to execute any static synchronized method, first the
thread should required a class level lock.
• If a thread has class level lock, it is allowed to execute any stock
synchronized method. During that time no other thread is allowed to
execute any static synchronized method. But the remaining threads
are allowed to execute any static non synchronized methods of the
same class.

thread communication wait , notify , notifyall


Two threads can communicate with each other by using wait(),
notify(), notifyall() methods Signatures.
Public final void wait() throw interepedException.
Public final native void wait(longms)throws InterruptedException.
Public final void wait(long ms,int ns)throws InterruptedException.
Public final native void notify();
Public final native void notifyAll();
Why this methods are in objclass instead of threadclass?
Wait(),notify();notifyAll() cantain in object class,not in the
thread class.because these methods can be applied on
common shared object,not on the thread.
Inorder to call wait(),notify(),notifyAll() on an object, we should be the
owener of that object.
We are allowed to call wait(),notify(),notifyAll() methods from
the synchronized context only(then only we will get the lock of that
object and we will beome owner of that object )
If we call wait(),notify(),notifeAll() from non synchronized context,we
will get a run time Exception saying”illegal monitar state Exception:
not a owner”

If the thread call wait()method,first it releases the lock and thenit will
go for waiting state, if the waiting thread gets ‘notification call’ or time
expired’ or’got interruption’ then it will go for another blocked state for
getting lock.
Once the thread got the lock, it will go to the ready state.
After calling wait method immedeatly releases the lock but after giving
notify call the thread may not the lock immediately.
The only method which causes the releasing of lock is wait()
method.
But in the case of sleep(),join() or yield() the thread never
releases the lock.
Method results release of lock:
Wait()
Join()
Sleep()
Yield()
Notify() // releases the lock, but may not immediatly
noifyAll()
A thread can acquire more then one lock at time .a thread releses the
lock of an object on which it calls the wait()method .it run releses all
the locks.
Example:
Class Thread A
{
Public static void main(string[]args)throws interrupted Exception
{
ThreadB b =new threadB();
b.start();
synchronized(b)//thread got lock
{
System.out.pritnln(“iam calling wait method”);
b.wait();
System.out.pritnlnpln(“I got notification);
}
System.out.pritnlnpln(b.total);
}
}
Class ThreadB extends Thread
{
Int total=0;
Public void run()
{
Synchronized (this).//.thread got lock
{
System.out.pritnln(“iam starting calculation”);
for(int i=0;i<=1000;i++)
{
Total=total+i;
}
System.out.pritnln(“iam giving notification call”);
notify();//thread releases lock again
}
}
} //500 500.
Flow -- > 0 -->1 --> 2 --> 3 --> 4 ---> 5

Daemon Thread
The threads which are executing in the background to provide
support for user defined threads are called daemon threads.
Ex: garbage callector
Thread class contain the following method for checking whether the
given thread is daemon or not
Public final Boolean isDaemon();
Daemon thread Example:
Class DaemonThread
{
Public static void main(string []args)
{
s.o.pln(thread .currentThread().isDaemon());
}
}
Usually daemon threads runnigg with low priority but based on our
requirement we can give high priority also,The daemon nature is
inherited from the parent..ie of the parent is the daemon thread then
the child also daemon thread and the parent n non-daemon by default
child also non-daemon. // Child and parents should daemon incase of
daemon
Based on our requirement we are allowed to change the daemon
nature of any thread b the following method.
Public final setDaemon(Boolean b);
if b is true the thread will become daemon otherwise non-Daemon
Example:class sample extends thread
{
{
Public static void main(String[] a)
{
MyThread t=new MyThread();
t.start();
t.setDaemon(true);
System.out.println(t.asDaemon());
we are not allowed to change Daemon nature after starting a
thread,validation leads to RTE saying “illegal thread state Exception”
ie we are not allowed to change Daemon nature of main method it is
already started at the beginning only.
Whenever the last non-Daemon thread dead all the Daemon threads
will be terminated automatically
Class MyThread extends Thread
{
Public void run()
{
For(int i=0;i<10;i++)
{
s.o.pln(“childmethod”);
try
{
Thread.sleep(2000);
}
Catch(InterruptedException e) {}
}
}
}
Class DaemonThreadExample
{
public static void main(string[]args)threads IE
{
MyThread t=new Thread();
System.out.println(t.isDaemon());
t.setDaemon(true);
t.start();
thread.sleep(5000);
System.out.println(“end of main thread”);
}
}
After starting the thread we are allowed to change the priority
of a thread but not allowed to change the Daemon nature.
Thread DeadLock
If two threads are waiting for each other forever, that situation is
considered as deadlock.(a lock without key is the deadlock)
We can present the dead lock occurrence but we const resolve.
Dead lock Example:
Class A
{
Public synchrozied void foo(B b)
{
System.out.println(“thread t1 entered into foo”);
try
{
Thread.sleep(2000);
}
catch(IE e){}
System.out.println(“thread t1 calling B’s last method”)
b.last();
}
Public synchronized void last()
{
System.out.println(“a class last method”);
}
}
Class B
{
Public synchronized void bar(A a)
{
System.out.println(“thread t2 entered into bar”);
try
{
Thread.sleep(2000);
{
Catch(intereped Exceptiom e){}
System.out.println(“thread t2 calling Ab last method);
a.last();
}
Public synchronized void last()
{
System.out.println(“B class last method”);
}
}
class DeadlockExample
{
A a=new A();
B b=new B();
DeadLock(){
Thread.currentThread().setName("main thread");
Thread t=new Thread(this);
t.start();
b.bar();
}
Public static void main(string[]args)
{
Deadlock d=new Deadlock();
}
Public void run()
{
a.foo(b);
}
}
thread group
Every Java thread is a member of a thread group. Thread groups
provide a mechanism for collecting multiple threads into a
single object and manipulating those threads all at once,
rather than individually. For example, you can start or suspend all
the threads within a group with a single method call. Java thread
groups are implemented by the thread group class in the java.lang
package.
The runtime system puts a thread into a thread group during thread
construction. When you create a thread, you can either allow the
runtime system to put the new thread in some reasonable default
group or you can explicitly set the new thread's group. The thread is a
permanent member of whatever thread group it joins upon its
creation--you cannot move a thread to a new group after the thread
has been created.
The Default Thread Group:
If you create a new Thread without specifying its group in the
constructor, the runtime system automatically places the new thread
in the same group as the thread that created it (known as the current
thread group and the current thread, respectively). So, if you leave the
thread group unspecified when you create your thread, what group
contains your thread?
When a Java application first starts up, the Java runtime system
creates a ThreadGroup named main. Unless specified otherwise, all
new threads that you create become members of the main thread
group.
Creating a Thread Explicitly in a Group
A thread is a permanent member of whatever thread group it joins
when its created--you cannot move a thread to a new group after the
thread has been created. Thus, if you wish to put your new thread in a
thread group other than the default, you must specify the thread group
explicitly when you create the thread. The Thread class has three
constructors that let you set a new thread's group:
public Thread(ThreadGroup group, Runnable target)
public Thread(ThreadGroup group, String name)
public Thread(ThreadGroup group, Runnable target, String
name)
Each of these constructors creates a new thread, initializes it based on
the Runnable and String parameters, and makes the new thread a
member of the specified group. For example, the following code
sample creates a thread group (myThreadGroup) and then creates a
thread (myThread) in that group.
ThreadGroup myThreadGroup = new ThreadGroup("My Group of
Threads");
Thread myThread = new Thread(myThreadGroup, "a thread for my
group");
The ThreadGroup passed into a Thread constructor does not
necessarily have to be a group that you create--it can be a group
created by the Java runtime system, or a group created by the
application in which your applet is running.
Thread group Example:
public class ThreadGroupDemo {

class MyThreadGroup extends ThreadGroup {


public void uncaughtException(Thread t, Throwable ex) {
System.err.println("I caught " + ex);
}
public MyThreadGroup(String name) {
super(name);
}
}

public static void main(String[] args) {


new ThreadGroupDemo().work();
}

protected void work() {


ThreadGroup g = new MyThreadGroup("bulk threads");
Runnable r = new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + " started");
for (int i=0; i<5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1776);
} catch (InterruptedException ex) {
System.out.println("Huh?");
}}}};

// Create and start all the Threads


for (int i = 0; i< 10; i++) {
new Thread(g, r).start();
}
// List them.
Thread[] list = new Thread[g.activeCount()];
g.enumerate(list);
for (int i=0; i) {
if (list[i] == null)
continue;
Thread t = list[i];
System.out.println(i + ": " + t);
}
}
}
object class
Java.lang.package contain several utility classes which are mandatory
for writing simple to complex programs.There is no need to import
java.lang.package as by default it is available to our program
Java.lang.object class: It is super class of any java class .all the
predefined classes are user defined classes either directly or indirectly
extends java.lang.objectclass
This class contain several utility methods which can be applied on any
java object.
.for every class parent class in object class
Class A extends B
{
// code
}
Means, Ie.for B,parent is object but for A parent is B only .so java
supports multilevel inheritance
The following are the 11 methods present in object class
1).public string to string()
For string representation of object.
2)public native int hashcode()
Returns the hashcode of an object
3)public Boolean equals(object obj)
For comparing the current object with the specified object
4)protected native object clone() throws clonesoft support Exception
To produced cloned object
5)protected void finalize()throws throwable
6)public final native class getclass()
7)public final viod wait()throws interrupted exception
8)public final void wait(longms)throws interrupted exception
9)public final void wait(long ms,int ns)throws interrupted exception
10)public final native void notify()
11)public final native void notifyAll()

1.tostring():
to String Example:
Class Sample
{
String name;int rollno;
Student(string name,int rollno)
{
This.name=name;
This.name=rollno;
}
Public static void main(string[]args)
{
Student s1=new student(“visvam”,101);
System.out.println(s1);
}
Public string tostring()
{
//return get class().getName()+’@’+
Integer.toHexstring(hashcode());
//return”this is student object”;
Returnname+”……”+rollno;
}
2.Hashcode():
HashCode Example:
String s1=new string(”visvam”);
String s2=new string(“visvam”);
System.out.println(s1.hashcode());
System.out.println(s2.hashcode());
hashcode()---when ever an object is created jvm allocates a number for
that object which is considered as hashcode().
Most of the cases the hashcode saving is unique for every object
Jvm uses this hashcode while saving objects to hashtable, hashmap or
hashset.
Hashcode never represents the address of an object.
Oppropriate way of overriding of hashCode method:
Ex: class Student
{
String name,int rollno;
Student(string name,int rollno)
{
This.name=name;
This.name=rollno;
}
Public int hashcode()
{
return rollno
}
Public string tostring()
{
return name+”-----“+rollno;
}
Public static void main(string[]args)
{
String s1=new string(“java”,101);
{
System.out.println(s1); // java ...... 101
}
Public int hashcode()
{
retuen rollno;
}
It is highly recomonded to override hashcode .In our classes.overriding
hashcode is appropriate if and only if every object we have to assign a
different hashcode.This is helpful for the jvm to save object in
hashcode,hashmap,hashset and serching also.
3.Equals()
Student s1=new student(“viswam”,101);
Student s1=new student(“surya”,102);
Student s1=new student(“surya”,102);
System.out.println(s1==s2); // false
System.out.println(s1.equal(s2)); // false
System.out.println(s2==s3); // false
System.out.println(s2.equals(s3)); // false
System.out.println(s2==s2); // true
System.out.println(s2.equals(s2)); // true
= = Operator:
This is meant for reference comparision always s1==s2 is true if and
only ig both s1 and s2 pointing to the same object on the heap.
Ex: string s1=”visvam”;
Thread t1=new Thread()
System.out.println(s1==t1);
we can’t apply==operator for incomparable types.validation leads to
CTE saying incomparable types.
S1==null is always “false”(no CTE&RTE)
equals()method :
The equals method available in object class meant for reference or
address comparision only(similar to==operator)but,we can override
equals() in our class for content comparision.
Overriding of .equals()
===> public Boolean equals(object o)
{
String name1=this.name;
Int rollno=this.rollno;
Student name2=s2.name;
Int rollno2=s2.rollno;
If(name1.equals(name2)&rollno1==rollno2)
Return true;
else
return false;
}
===>then System.out.println(s2.equals(s3)); //true
System.out.println(s1.equals(s2)); // false
====> in string class. .Equals() method is already overridden for
context comparision. Object class.equals method. Satisfy the following
two conditions.
1.this is always for address comparision
2.it never rise CTE&RTEs even the arguments are different types.
If the arguments are different types .equals() is simply return false.
public boolean equals(object o)
{
try
{
Name 0=this.name1;
Rollno1=this.rollno1;
Student s=(student)0;
Name2=this.name2;
Rollno2=this.rollno2;
If(name1.equals(name2)&rollno1=rollno2)
return true;
else
return false;
}
Catch(classcastException e)
{
return false;
}
}
Then==>s.o.pln(s1.equals(“visvam”));
Catch(nullpointerException e)
{
Return false;
}
Then==> s.o.pln(“null”));

Comparision between==Operator &.equal :


= = Operator :
1.we can apply for both primitation and object references
2. r1= =r2 is true if and only both r1,r2 pointingly to same object on
the heap. ie ==is always for reference comparision.
3.we cant’t override for context comparision.
4.we can’t apply = = operator for different tpes of objects
.incomparable types.
5.s1= =null is always false
.equals()
1.we can apply only for object references
2.by default ,.equals() present in the object class is meant for address
comparision onl
3.we can override .
4..equals()never release any CTE&RTEs even the arguments are
different types .in that situation it will just simply return false.
5.s1.equals(null) gives false when handle NPE through catch
Relationship between = =and .Equals
1. if r1==r2 is true then r1.equals(r2) is always true.
2. if r2 = = is false then r1.equals(r2) may returns true.
Contract between hashcode and .equals()
If r1=equals(r2) is true,then r1.hashcode() = = r2.hashcode();
Ie .equalent objects should alwas have same hashcode.
If r1.equals(r2) is false ,then their hashcode may be same.
If R1.hashcode() = = r2.hashcode() may returns true
If R1.hashcode() = = r2.hashcode() may returns true ,then
r1.equals(r2)may be true.
If R1.hashcode() = = r2.hashcode() may returns false,then
r1.equals(r2)alwas false.
In order to satisfy the above contract we have to override
hashcode() whenever we are overriding .equals()
4.clone()
Protected object clone() throws clone not supported exception.
This method can used to prouduced exactly duplicate copy of an
object..
All the objects can’t produce cloned object ,only clonable objects can
produce duplicate copies .
An object is said to be conable if and only if the corresponding
class implements clonable interface.
By using the folling object class clone() method we can
produced cloned objects
Protected object clone() throws clone supported exception
CheckedException so we should handle by using try catch or throws to
the caller by using throws clause.
String class
String class it is there in Java.lang package.
Immutability of the String object:
String s=”java”;
s.concat(“soft”);
System.out.println(s);
output:- jaVa
Muatability of StringBuffer object:
StringBuffer s=new StringBuffer(“java”);
s.append(“soft”);
System.out.println(s);
output:- javasoft
Once we created a string object we are not allowed to perform any
changes in the existing String object.
If you want to perform any changes (by using concat() or any other),
with the changes a new String object will create.
Hence String objects are considered as Immutable
In the case of StringBuffer, once we created a StringBuffer object, we
are allowed to perform any changes in the existing StringBuffer object
only.
Hence StringBuffer object is mutable
1. String s1=new String(“java”);
2. String s2=new String(“java”);
System.out.println(s1==s2); --> false
System.out.println(s1.equals(s2)); --> true
But
3. StringBuffer s3=new StringBuffer(“viswan”);
4. StringBuffer s4=new StringBuffer(“viswan”);
System.out.println(s1==s2); --> false
System.out.println(s1.equals(s2)); --> false
In the String class .equals() is overridden for content comparision. Here
the content of s1 and s2 are equal, that’s why s1.equals(s2) returns
true.
In the String class .equals() is not overridden for content comparision.
whenever we calling .equals()
Method on the StringBuffer object, Object class .eqauals() method will
execute, which is meant for address comparision only.
Hence s3.equals(s4) returns false eventhough the contents of s3 and
s4 are same.
Difference between the ways of creating String objects:-
1. String s1=”durga”;
2. String s2=new String(“durga”);
• In the first case, the JVM will check, is the any String object
with content durga in the “String Constant Pool”. If there is no
such object then only a new String object will create and s1
will pointed to that object.
• If the object already present then s1 will simply refers to that
object instead of creating a new object.
• In the second case, two String objects will create, one is on
the heap, for the other one in the “String Constant Pool” (If
the object is not already present) and s2 will pointing to heap
object.
Ex: String s=”viswan”;
s.concat(“sw”);

* In this content, three objects are created. One is on heap and another
two on “String Constant Pool”
• “String Constant Pool” never allows Garbage Collection.
• Heap durgasw String Constant Pool software
• I the object does not have any references in the “String
Constant Pool”, still this is not eligible for the Garbage
Collection.
• All the objects present in the “String Constant Pool” destroy,
whenever the JVM restarted.
What is the output and how many String objects are created.
String s1=”spring”;
String s2=s1+”summer”;
s1.concat(“fall”);
s2.covcat(“s1”);
s1+=”winter”;
System.out.println(s1+ “,”+s2);
output: spring , springsummer
string constant pool: spring, summer, fall, winter
Heap: springsummer, springfall, springwinter, springsummerspring
Advantage Of StringConstantPool:
String s1=”you can’t change me”;
String s2=”you can’t change me”;
System.out.println(s1==s2); // true
System.out.println(s1.equals(s2)); //true
String s3=new String(“you cannot change me”);
System.out.println(s1==s3);//false
System.out.println(s1.equals(s3)); //true
String s4=”you can’t” + “change me”;
System.out.println(s1==s4);
String s5=”you can’t”;
String s6=s5+”change me”;
System.out.println(s1==s6); //false
If final String s7=”you can’t”
System.out.println(s1==s7); //true
String s8= s7+”change me”;
s1==s8; //true.
• In our programme., if any String object is repeatedly going to use, we
can keep only one copy in the String Constant Pool and shared by
several required references. Instead of creating several same content
object, we are creating only one object, this is very efficient w.r.t to
memory point of view.
• As several refernces pointing to the same object in the
StringConstantPool, by using any references , if you allowed to use the
content of that object, the remaining references have to suffer.
• Hence once we created a string object we are not allowed to change
content.
• If you want to perform any changes, with those changes a new String
Object wil create . Hence the String Objects are declared as the
Immutable.
• StringConstantPool ---> Performance is improved. (advantages)
----> Immutability ( disadvantages)
Interning Of Strings:
String s1=new String(“viswan”);
String s2=s1;
String s3=s1.intern();
S1==s3; //false
String s4=”viswan”;
s4==s3; //true
• Intern() method used to point the String constant pool object
instead of heap object.
String Class Constructors:
1. String s=new String(String s);
2. String s=new String();
3. String s=new String(StringBuffer s1);
4. StringBuffer s1=new StringBuffer(“xxx”);
5. String s=new String(byte[]);
Ex: byte[] b={100,101,102,102}
String s=new String(b);
System.out.println(s); //”defg”
6. String s=new String(char[]);
Ex: Char[] ch={a,b,cd};
String s=new String(ch);
System.out.println(ch); // abcd
String Class Methods (only some imp):
1. public char charAt(int index):
This method returns the character located at the string’s specified
index. Remember that String indexes are zero based.
2. public String concat(String s):
This method returns a string with the value of the String passed into
the method appended to the end of the String used to invoke the
method.
The overloaded + and += operators perform the same function of
concat() method.
Ex: String s=”durga”;
s=s.concat(“sw”);
s=s+”sw”;
s+=”sw”;
System.out.println(s); //durgasw
3. public Boolean equals IgnoreCase(String s):
This method returns Boolean value ie., true or false depending on
whether the value of the string in the argument is the same as the
value of the String used to invoke the method.
Ex: String s=”DURGA”;
System.out.println(s.equalIgnoreCase(“Durga”); //true
s.equals(“Durga”); //false
4. public int length():
length() is the method in the case of String objects where as ‘length’ is
the variable in the case of Arrays.
Ex: String s= “durga”;
System.out.println(s.length); //CTE
System.out.println(s.length());// 5
5. public String replace(char old, char new):
String x=”ababab”;
System.out.println(x.replace(‘a’,’b’); //bbbbbb
6. a). public String substring(int begin):
String x=”0123456789”;
System.out.println(s.subString(6)); //6789
b). public String substring(int begin, int end):
System.out.println(s.subStrin(5,8)); //567

* End is not included in o/p.


* This is already overloaded method.
* It considers the index only.

String s=”abcdefgh”;
System.out.println(s.subString(3)); //defgh
System.out.println(s.subString(4,7)); //efg
7. public String toUpperCase():
String s= “ A New Moon”;
System.out.println(s.toUpperCase()); // A New Moon
8. public String toLowerCase()
String s= “ A New Moon”;
System.out.println(s.toLowerCase()); // A New Moon
9. public String trim()
String s=”viswan”;
System.out.println(s.trim()); //viswan
---> Leading or trailing blackspaces removed but not in the
middle.
10. public int indexOf(char ch)
---> Returns the index of the first occurance of the specified character.
---> Returns -1, if there is no such character.
String s=”durgascjp”;
s.indexOf(d); //0
11. public int lastIndexOf(char ch)
---> Returns the last occurrence index of the specified character.
String s=”durga”;
String y=s.toUpperCase();
String s=s.toLowerCase();
System.out.println(s==x);//true
System.out.println(s==y); // false

s,x ---> durga y---> durga

• After applying any method of the contest of the String has to change
then only a new String object will create with the corresponding
changes.

Ex1:
String s1=”abc”; s1 ---> abc
String s2=”def”; s2 ---> def <--- s3
String s3=”s2”; s2 ---> ghi
String s2=”ghi”;
S.o.p(s1+s2+s3); //abcghidef
Ex 2:
String x=new String(“xyz”);
y=”abc”;
x=x+y;
total objects are 4 ---> 2 on heap, 2 on string constant pool

* String objects as well as wrapper class objects are immutable.


* String, StringBuffer, wrapper, Math, StringBuilder classes are the final
classes. So, we are not allowed to create the child classes.

StringBuffer , StringBuilder
StringBuffer:
String objects are immutable where as StringBuffer objects are
mutable.
Ex: String s=”viswan”;
s.concat(“sw”); -----> Immutability
System.out.println(s);//viswan

But StringBuffer s=new StringBuffer(“viswan”);


s.append(“sw”); -----> Mutability
System.out.println(s); // viswansw
String s1=new String(“java”);
String s2=new String(“java”);
s1==s2; //false
s1.equals(s2); //false
Because in StringBuffer class .equals() method is not overridden for
content comparision. It is meant for address comparision only.
Constructors Of StringBuffer:
StringBuffer s= new StringBuffer();
Creates an empty StringBuffer object with default initial
capacity 16.
class SBDemo
{
public static void main(String a[])
{
StringBuffer s=new StringBuffer();
s.append(“abcdefghijklmnop”);
System.out.println(a.capacity());
}
}
---> If we add q then //34=(16+1)*2
• When ever StringBuffer reaches its max capacity a new
StringBuffer object is created with the new capacity is (current
capacity + 1)*2 ---> (16+1)*2=34
• First time only this can be valid. Afterwards the capacity
increases with the increase of characters only.
StringBuffer sb=new StringBuffer(int initialcapacity)
• Creates an empty StringBuffer object with the specified capacity.
StringBuffer sb=new StringBuffer(String s);
• Creates an equivalent StringBuffer object for the given String and
with a capacity equal to (length of String + 16).
Ex: StringBuffer s=new StringBuffer(“durga”);
System.out.println(s.capacity()); // 5+16=21
Length of the string “durga” =5

important methods of the StringBuffer :


1. public int length() ---> returns the length of the StringBuffer.
2. public int capacity() --->returns the capacity of the StringBuffer
3. public char charAt(int index)
Ex: StringBuffer s=new StringBuffer(“durga”);
char ch= s.charAt(3); //g
char ch=s.charAt(10); //invalid index
i.e., If the index is invalid we will get a RTE saying “String index of
bounds Exception”.
4. public void setCharAt(int index, char ch)
Constructing String from the given StringBuffer Object:
String s= bew String(StringBuffer s)
String s= StringBuffer.toString();
5. public synchronized StringBuffer append(String s); or (int i) or (char
ch) or (float f) or (double d) or (char[] ch) or (Boolean b) or (byte[] b)….
Ex: StringBuffer s= new StringBuffer(“PI”);
s.append(3.14 f);
System.out.println(s); //pi=3.14
6. public synchronized StringBuffer insert(int offset, String s) or
int/char/float/Boolean etc.,
Ex: StringBuffer s= new StringBuffer(“durga”);
s.insert(2,”012”);
System.out.println(s); //du012rga
7. public synchronized StringBuffer delete(int start, int end)

* delete the substring present in start to end – 1 position.


8. public synchronized stringBuffer delete charAt(int index)

* For deleting the character located at specified index.


9. public synchronized StringBuffer reverse()
Ex: StringBuffer sb= new StringBuffer(“madam”);
System.out.println(s.reverse()); //madam
10. public void setLength(int new length)

* This operation can result in the StringBuffer with the specified length.
The Extra characters will be removed.

If the StringBuffer is lessthan the specified length padded or appended


with space characters to the required length.
Ex: StringBuffer s=new StringBuffer(“viswan”);
s.length(3);
System.out.println(s); //vis
Chaining Of Methods :
• In the case of String and StringBuffer, the return type of most of the
methods are String or StringBuffer only, on that return type we are
allowed to call another method, as a result chaining of methods is
possible, in the case of String and StringBuffer.
Ex: StringBuffer sb= new StringBuffer(“durga”);
s1.m1().m2().m3().m4().m5().m6();

* All the method calls will execute left to right.


sb.append(“software”).insert(2,”xxx”).delete(4,7).reverse();
System.out.println(sb); // durgasw
--> duxxxrgasw ---> duxxasw
---> erawtfosaxxud
StringBuilder :
It is exactly similar to StringBuffer except all the methods are
nonsynchronized methods.
When compared with StringBuffer the following are the advantages of
StringBuilder.high performance and the operation are fast.
Data corruption is possible in the StringBuilder which is the major
drawback of StringBuilder, when compared with StringBuffer.
Example:
class Sample
{
public static void main(String a[])
{
StringBuilder sb=new StringBuilder(“surya”);
s.append(“software”);
s.reverse();
s.delete(3,5);
System.out.println(s);
}
}
//surya //suryasw
//erawtfosayrces //erafosayrces

Wrapper Class
The Wrapper classes have introduced for the fallowing two purposes by
SUN people.
1. To wrap primitives into object form so that we can handle
primitives also just like objects.
2. We can get several utility functions for primitives.
• The fallowing are the wrapper classes.
Type --------- Class
byte ---------> Byte
short ---------> Short
int ---------> Integer
long ----------> Long
float ----------> Float
double ----------> Double
char ----------> Character
boolean ----------> Boolean

Constructors of the Wrapper classes :


• Integer class contains the fallowing two constructors.
Integer i= new Integer(int i);
Integer i= new Integer(String s);
Ex: Integer i= new Integer(10);
Integer i= new Integer(“10”);
Integer i=new Integer(“ten”); x given
RTE: NumberFormatException
I.e., If the String is unable to convert into a number then we will get a
RTE saying “NumberFormantException”.
---> Byte b=new Byte(byte b);
---> Byte b=new Byte(String s);
Wrapper Class --------- Constructor Arguments
1. Byte --------------------> byte or String
2. Short --------------------> short or String
3. Integer ---------------------> int or String
4. Long ---------------------> long or String
5. Float ---------------------> float or String or double
Ex: float f= new Float(float f); //10.0f //valid
float f= new Float(String s); //”10.0f” //valid
float f= new Float(double d);//10.0 //valid
6. Double ----------------------> double
7. Character ------------------> char
Ex: Character c=new Character(char c);
Character c=new Character(‘d’); //valid
Character c=new Character(“d”); //invalid
8. Boolean ---------------------> Boolean or String
Ex: Boolean b=new Boolean(true); //valid
(false); //valid
(TRUE); //invalid
(FALSE); //invalid
Boolean b=new Boolean(“viswan”); //false
(“yes”); //false
(“no”); //false
Note: Other than “true” everything should return ‘false’.
Which of the fallowing are valid Boolean declarations?
1. boolean b=true; //valid
2. boolean b=false; //valid
3. boolean b=TRUE; //invalid
4. boolean b=FALSE; //invalid
5. Boolean b=new Boolean(“true”); //valid
6. Boolean b=new Boolean(“false”); //valid
7. Boolean b=new Boolean(“yes”); //valid //false
8. Boolean b=new Boolean(“NO”); //valid // false
9. boolean b=yes; //invalid //Compile time error
10. boolean b=NO; //invalid // Compiletime error
valueOf() method:
• Except character class every wrapper class contain a static valueOf()
which can be used for converting a String object to corresponding
wrapper object.
Ex: Integer i=Integer.valueOf(“10”); //valid
Integer i=Integer.valueOf(“ten”); //invalid // RTE
:NumberFormatException
Boolean b= Boolen.valueOf(“xxx”); //false
valueOf(String):
String object ----------to------------> Wrapper Object
• This is a static method.
• The argument is String only.
• Throws NumberFormatException, if we are unable to convert the
String to number.
Ex: Integer i= Integer.valueOf(10); //invalid
Argument is not String ,the Second version of valueOf() method:
• Byte. Short, Integer, Long classes contain second version of valueOf()
method which can take a String and radix as arguments.
• First the String converted into decimal form and then that decimal
value will be stored in the wrapper object.
Ex1: Integer i=Integer.valueOf(”101100”,2) ;
System.out.println(i);//44 base=radix
Signatures:
1. public static wrapper valueOf(String s)
object
2. public static wrapper valueOf(String s, int radix)
object
Ex2: Long l=Long.valueOf(“12”,5);
System.out.println(l); //7
* totally “36” bases or radixes are valid
xxxValue() methods:-
• All the numeric wrapper classes contains the fallowing methods for
“converting wrapperclass object to primitive”.
intVlaue(); byteVlaue(); shortVlaue(); longVlaue(); floatVlaue();
doubleVlaue();
• Each wrapper class contains the above six methods, in total 36
xxxValue() methods are possible.
• These xxxValue() methods are instance methods and no arg
methods.
Ex: Double d =new(150,263);
System.out.println(d.byteValue()); // -106
System.out.println(d.shortValue()); //150
System.out.println(d.intValue()); //150
System.out.println(d.longValue()); // 150
System.out.println(d.floatValue()); // 150.263
System.out.println(d.doubleValue()); // 150.263

• Character class contains charValue() method for converting character


object to primitive.
Ex: Character ch= new Character(‘a’) ;
Char c=ch.charValue();
System.out.println(c); // a
• Boolean class contain booleaValue() method for converting a Boolean
object to Boolean primitive.
Ex: Boolean B=new Boolen(“viswan”);
boolean b=B.charValue();
System.out.println(b); //false
parseXxx() methods:

• Every wrapper class except Character class contain parseXxx() for


converting a String object to corresponding primitive.
Ex: String s=”10”;
int i=Integer.parseInt(s);
double d=Double.parseDouble(s); //10.0
long l=Long.parseLong(s);
Wrapperclass--------- parseXxx()
Byte ------------> parseByte(String s)
Short -------------> parseShort(String s)
Integer -------------> parseInt(String s)
Long -------------> parseLong(String s)
Float -----------> parseFloat(String s)
Double ------------> parseDouble(String s)
• Boolean class contain a static method getBoolean() method for
converting a string to Boolean primitive.. -----> 1.4 version
String s=”123”;
int i=Integer.parseInt(s);
double d=Double.parseDouble(s);
System.out.println(i); //123
System.out.println(d); //123.0
Boolean b=getBoolean(“viswan”);
System.out.println(b); //false
Second version of parseXxx() :-
• All the integral wrapper classes (byte, short, integer, long) contains
second version of parseXxx().
public static primitive parseXxx(String s,int radix)
Ex: int i=Integer.parseInt(“10101100”,2);
System.out.println(i); //172
long l=Long.parseLong(“12”,8);
System.out.println(l); //10
• java support max – radix is 36(base)
System.out.println(Character.MAX-RADIX); //036
toString() method:
1st version:-
• All the wrapper classes contains an instance toString() method for
converting wrapper class object to corresponding String object.
• public String toString();
Integer i=new Integer(10);
String s= i.toString();
System.out.println(s); // 10
Boolen B=new Boolean(“surya”);
String s=B.toString();
System.out.println(s);//false

2nd Version:

• Every wrapper class contain a static toString() method for converting


a primitive to String object.
• This is available in all wrapper classes and object class also includes
Boolean and Character classes.
• public static String toString(10);
Ex: String s1=Integer.toString(10);
System.out.println(s);
String s1=Boolean.toString(true);
String s1=Integer.toString(‘a’);
System.out.println(s1);
System.out.println(s2);
3rd Version:

• Integer and Long classes contain the 3rd version of the toString()
method for converting given primitive to String of sprcified radix.
• public satic String toString(30,2);
Ex: String s= Integer.toString(30,2);
System.out.println(s); //”11110”
toString(primitive, int radix)
4th version:
• public static String to xxxString(primitive) //int/long
• The version of toString() is available in the Integer and Long classes
only. The possible to xxxString() methods are, toBinaryString,
toHexString and tooctalString for converting the given primitive to the
corresponding String form.
String s=Integr.toBinaryString(100); //1100100
String s=Integr.toOctalString(100); //144
String s=Integr.toHexString(100); //64
• All the wrapper class objects are immutable and all the wrapper
classes are final classes.
• ‘void’ is also one type of wrapper class.
• String class and all the wrapper classes are immutable.
• The fallowing are the final classes.
-->String
--> StrringBuffer
--->Math
AutoBoxing , AutoUnBoxing
AutoBoxing:
• Automatic conversion by the compiler from primitive type to the
corresponding object form is called AutoBoxing.
Ex: int i=10; //Compile time error in 1.4 but valid in 1.5
Integer I=i;
• Compiler first constructs the integer object and then assigned that
object to the variable.
AutoUnBoxing:
• Automatic conversion from wrapper class object to primitive type by
the compiler is called AutoUnBoxing.
Ex: Integer I= new Integer(10);
int i= I; //CTE :1.4
// valid in 1.5

* The compiler coverts Integer object to primitive and that primitive


value will assign to variable i.

* Because of these new autuboxing or auto unboxing features, the


importance of wrapper classes is not that much in the 1.5 version.
AutoBoxing in expressions:
Integer y=10;
Integer x=y;
Y++;
System.out.println(x); // 10
System.out.println(y); // 11
System.out.println(x==y); // flase
Wapper class objects are immutable .if you want to perform any
changes with those changes a new wrapper class object will create.
Special cases:
case1:
Integer i1=new Integer(10);
Integer i2=new Integer(10);
System.out.println(i1==i2); //false
Case2:
Integer i1=new Integer(10);
Integer i2=10;
System.out.println(i1==i2); //false
Case3:
Integer i1=100;
Integer i2=100;
System.out.println(i1==i2); //true
Case4:
Integer i1=1000;
Integer i2=1000;
System.out.println(i1==i2); //false
In the case of autoboxing compalier won’t create any new object If an
existing already created object mapped with the reqired one . the
existing object should be created bt the autoboxing only.
This poosibility will occur in the following cases.
1.By using autoboxing. If it is required to create a new wrapper object,
other wise compiler won’t create any new object, if already an object is
present in the fallowing cases. these Objects are Boolean and Byte.
2. Character object ranges from 0 to 127 ------> (‘\u0000’ to ‘\u0007f’).
3. For the integer and short if the value is less than or equal to 127.
4. For the long of the value is less than or equal to 127 L .
But Long l=10; //invalid
CTE: incompatable types
Found:int , req: java.lang.Long
Similarly Float f= 10; //invalid - CTE: incompatable types
Found: int, req: java.lang.Float
Case5:
Boolean b1=true;
Boolean b2=true;
System.out.println(b1==b2); // true
Case6:
Boolean b3=flase;
Boolean b4=flase;
System.out.println(b3==b4); // true
Special case:
Example:
class Sample
{
static Integer I1=10; ---->I1: Initialized
public static void main(String a[])
{
m1(I1); ---> I1 : auto unboxing
}
public static void m1(int i)
{
Integer I2=i; ----> I2: auto boxing
System.out.println(I2); //10
}
}
above example executes fine.
But
class Sample
{
static Integer I1; // not Initialized
public static void main(String a[])
{
m1(I1); // null pointer exception
}
public static void m1(int i)
{
Integer I2=i;
System.out.println(I2);
}
}
Static variables by default initialized with null, which can’t be
autoboxing/autounboxing.Hence Run time exception.

overloading when combining with widening and Autoboxing:


class Text
{
static void m1(Integer x)
{
System.out.println(“integer”);
}
static void m1(long l)
{
System.out.println(“long”);
}
public static void main(String arg[])
{
int i=5;
m1(i); //long
}
}
when comparing widening with autoboxing compiler always prefers
widening in order to provide the sport for legacy code.
Over loading in case of widening with var-arg method:
Class sample
{
static void m1(int I,int j)
{
System.out.println(“int, int”);
}
static void m1(byte… b)
{
System.out.println(“byte arg”);
}
public static void main(String arg[])
{
byte b=5;
m1(b,b);
}
} // in tint
widening dominates var-arg method .compiler will give the precedence
for widening over var-arg method.
Autoboxing vs var-args:
Class Sample
{
static void m1(Byte b)
{
System.out.println(“byte”);
}
static void m1(byte… b)
{
System.out.println(“byte arg”);
}
public static void main(String arg[])
{
byte b=5;
m1(b);
}
}
the compiler prefers autoboxing over var-args
If there is no other method matched,then only var-arg method always
seeks to least priority.
Conclusion:
The compiler always gives the precedence in the following order for
resolving over loading methods.
1.wid4ening
2.auto boxing & unboxing
3.var- args
Special cases:
Class Sampe
{
public static void m1(Long l)
{
System.out.println(“long”);
}
public static void main(String arg[])
{
byte b=5;
m1(b);
}
}

In java widening followed by autoboxing is not allowed.Hence the


above code raise a CTE saying m1(java.lang.long) in sample can not be
applied to (byte).
i.e Byte --------> Long is not possible.
But byte ----->long is possible.
Widening followed by autoboxing is not allowed. But the reverse is
allowed in java i.e autoboxing follwed by widening is possible.
Class Sample
{
static void m1(Object o)
{
System.out.println(“object”);
}
public static void main(String arg[])
{
byte b=5;
m1(b); // object
}
}
i.e byte -----> Byte -----> Object
i.e Here autoboxing is followed by widening .

class Samle
{
static void m1(byte… b)
{
System.out.println(“byte……”);
}
static void m1(byte b,byte… b1)
{
System.out.println(“byte, byte….”);
}
public static void main(String arg[])
{
byte b=5;
m1(b); // CTE saying reference to m1 is ambiguous.
}
}
Here both methods are matched because of var-args feature.Hence
compailer can’t give any precedence results in CTE
Static variable by default initialized with null,which can’t be autoboxing
/autounboxing
enum
It defines a list of named constants.This is interdused in 1.5
version.
Java enum is powerful than c,c++ enums because java enum
may contain methods ,constructors and instance variables in
addition to constants.But c,c++ enum contain only constants.
Example:
enum Month
{
Jan,Feb,Mar,Apr…….;
}
Example:
enum Beer
{
KF,RC,H5,H2,…….;
}
No variables in enum.At the end ( ; ) no need to specify (optional)
Use:we can reduce the number of bugs by using enumeration because
We are providing a set of predefined values for the variables.
Enum Example code:
enum Month
{
Jan,Feb,Mar,Apr;
}
class Sample
{
public static void main(String arg[])
{
Month m=Month.Mar;
System.out.println(m); // Mar
}
}
We can keep enum outside the class or inside the class.If we are
declaring enum outside the class,the allowed modifiers are public
,<default>.we can declare enum with in a class the allowed modifiers
are public ,<default>,protected,private.
We never allowed to declare enum inside a method,violation
leads to compile time error saying enum type must not be local.
Enum types is allowed to used as argument for the switch statement.
Example:
Enum Beer
{
KF,RC,H5;
}
class Sample
{
public static void main(String arg[])
{
Beer b= Beer.KF;
Switch(b)
{
case KF:
System.out.println(“too Bitter”);
break;
case RC:
System.out.println(“too Hot”);
break;
case H5:
System.out.println(“too strong”);
break;
}
}
}
until 1.4 version the allowed arguments for the switch statement are
byte,short,int,char.But 1.5 version onwords in addition to these
arguments Byte,Short,Character,Integer and enum also.
Values() method:
Enum contains a predefined method values to list the constants
available in that enum.
Example :
enum Month
{
Jan,Feb,Mar,Apr;
}
class Client
{
public static void main(String arg[])
{
Month[] m=Month.values();
for(Month m1:m)
{
System.out.println(m1); // Jan,Feb,Mar,Apr
}
}
enum never participated in inheritance hierarchy because every
enum class implicitly extends java.lang .enum .Thats why we never
allowed to create a child classfor the enum.As Month enum already
extends java.lang.enum hence it never allowed to extend any other.
Enum Month extends Some ---> not possible
If we are writing any enum it is extending java.lang.enum class.Hence
it never extends any thing else.So inheritance concept not applicable
for enums.
Example:
Enum Beer
{
KF(65),RC(50),H5(100),KO;
int price;
Beer(int price)
{
this.price=price;
}
public int getPrice()
{
return price;
}
Beer()
{
this.price=100;
}
}
class Sample
{
public static void main(String arg[])
{
Beer b=Beer.KF;
System.out.println(b); //KF
System.out.println(Beer.KF.ordinal());
System.out.println(b.price); //65
System.out.println(b.getPrice()); //65
Beer[] s=Beer.values();
for(Beer s1:s)
{
System.out.println(s1+”……….”+s1.getPrice());
}
}
}
• When ever enum is loaded into the memory, all the enum
constants will be assigned and JVM calls Constructor
automatically. The programmer is not allowed to call enum
constructor explicitly.
• The Constructors of enum can be overloaded if the enum
contain both enum constants, instance variables, the first line
should be enum constants and ends with semicolon.
i.e.
enum Beer
{
KF, RC //invalid ; missing
int price;
}
enum Beer
{
int price; //invalid because the 1st stmt should be enum constants.
KF, RC;
}
enum Beer
{
KF, RC;
int price; //valid
}

Ordinal Value
• The position of enum constant is important and indicated by their
ordinal values. We can ordinal value for any enum constant by the
fallowing method.

Public final int ordinal();


Ordinal value starts from zero(0).

Enum Month
{
JAN,FEB;
public static void main(String a[])
{
Month[] m=Month.values();
for(Month m1:m)
System.out.println(m1);//JAN,FEB
}
}//Save:Month.java, Run:Java Month
So just like a normal class, we can run enum also.
System.out.println(Month.JAN==Month.FEB); //false
So we can compare the constants declared in enum. Otherthan ‘=
=’operators, remaining <=, >=,<,> will gave CTE.
Duplicate constants can’t be declared. So, constants are unique.

enum Month
{
Jan,Feb,Jan; //invalid,CTE:Jan already defined
}

But

enum Month
{
Jan,Feb,JAN; //valid, due to case sensitive jan!=JAN
}
Comparable Interface and clonable interface
Comparable Interface:
This is present in java.lang.package
Contains the following one method.
1.public int compareTo(Object o)
if returns –ve integer if o1 has to place before o2.
If returns +ve integer if o1 has to to place after o2.
If returns zero then o1 and o2 are equal.
All the wrapper classes and string class already implemented
comparable interface. But the StringBuffer doesn’t implement
comparable interface.
Comparable Interface Example:
Interface comparable
{
public int compareTo(Object o)
{
TreeSet t=new TreeSet(0;
t.add(“a”);
t.add(‘z”);
System.out.println(t); // a,z (:: z.compareTo(“a”);)
System.out.println((“a”).compareTo(“z”)); //-25
System.out.println((new Integer(10).compareTo(new Intege(1)); // +1
}
}|
Marker or Tag Interface:
If an interface is marked for some ability such type of interfaces are
called Marker interfaces.
Ex: clonable,serializable
If an interface with out any method obviously accept ass marker
interface.
Eventhough interface contains some methods,still we can consider as
marker interface .If it is marked for some ability.
Ex:Comparable interface.
Intreger i1=new Integer(10);
Integer i2=new Integer(20);
System.out.println(i2.compareTo i1); // -1
System.out.println(i1.compareTo i2); // +1
System.out.println(i1.compareTo i1); // 0
System.out.println(i1.compareTo(“a”)); // CTE nullpointer exception

Cloneable interface:
Uptaining exact copy of a plant ,a bird,an animal or a human being is
called cloning.
Cloning in programming uptaining bit wist exact copy of an object is
called cloning.
cloning Example:

Class sample() implements cloneable


{
Int i=10;
Public static void main(string args[])throwsClone
notSupportedEexception
{
Sample s1=new sample();
Sample s2=s1;
Sample s3=(sample)s1.clone();
S1.i=1000;
System.out.println(s3.i);
System.out.println(s1==s3);
we should type cast otherwise
CTE:in compatable types
Found: Object reqired=sample
The class must implements cloneable interface otherwise at runtime
clone() results cloneNotsupportException
Example:
Class sample implements clonable
{
Int i=10;
Public static void main(string[]args)throws cloneNot support Exception
{
Object o=new object();
Object o2=o.clone();
}
CTE:clone() has protected access in java.lang.object
The protected numbers we can access, from with in the same package
or from outside package but from outside package,the protected
number can be accessed b using child class reference only.ie we can’t
use parentclass reference to access protected number from outside
package,validation leadsto CTE.

clone() method:
Protected object clone() throws clone not supported exception.
This method can used to prouduced exactly duplicate copy of an
object..
All the objects can’t produce cloned object ,only clonable objects can
produce duplicate copies .
An object is said to be conable if and only if the corresponding class
implements clonable interface.
By using the folling object class clone() method we can produced
cloned objects
Protected object clone() throws clone supported exception
CheckedException so we should handle by using try catch or throws to
the caller by using throws clause.
Shallow cloning Example:
Class Student implements cloneable
{
String name;
String age;
Student(String name,String age)
{
This.name;
This.age=age;
]
Public Object clone()throws cloneNotSupportedException
{
Return this;
}
}
Class Student cloneDemo
{
Student s1= new Student(“hai”,”22”);
Student s2= (Student)s1.clone();
S2.name=”abc”;
System.out.println(s1.name);
Public static void main (String ar[])
{
StudentCloneDemo s1= new Student cloneDemo();
}
}
Deep cloning example:
Class Student implements cloneable
{
String name;
String age;
}
Student(String name ,String age)
{
This.name=name;
This.age=age;
}

Public Object clone(0throws CloneNotSuport Exception


{
try
{
ByteArrayOutputStream bas=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bas);
Oos.writeObject(this);
ByteArrayInputStream bias=new
ByteArrayInputStream(bas.toByteArray());
ObjectInputStream oos=new ObjectInputStream(bias);
Return ois.readObject();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
class DcloneDemo
{
DcloneDemo()throws CloneNotSuportException
{
Student s1=new Student(“hello”,”200”);
Student s2=(Student)s1.clone();
S2.name=”java”;
System.out.println(s1.name);
Public static void main(String[] arg)
{
new DcloneDemo();
}
}

Java DefaultExceptionHandler
An Exception is an abnormal and unexpected and also unwanted event
that disturbs the normal flow of the program.
Ex: FileNotFoundExceptionArithmaticException etc..
Default Exception Handling Mechanism in JAVA:
class Sample
{
public static void main(String a[])
{
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
System.out.println(10/0);
}
}

RTE: Exception in thread “main” Java.Lang.Arithematic Exception: /by


zero
At Sample . doMoreStuff(Sample.java)
At Sample . doStuff(Sample.java:9)
At sample . main(Sample. java :5)
• If an exception is raised inside any method is r3esponsible for the
creation of exception object. (here doMoreStuff() is responsible )
• The Exception object must contain the fallowing information.
1. Name of the Exception(Java.Lang.ArithematicException)
2. Description of the Exception (/ by zero)
3. The position at which the exception raised. (stack trace).
• Now the method handover that exception object to the JVM. JVM will
come with that exception object and it will check, is there any
exception object and it will check is there any exception handler inside
that method abnormally and removes the corresponding entry from
the stack.
• Now the method handover that exception object to the JVM. JVM will
come with that exception object and it will check, is that any exception
handler inside that method. If there is no exception handler then JVM
blindly terminate that method abnormally and removes the
corresponding entry from the stack.
• JVM will check for the caller(doStuff()) containing any exception
handling code. If the caller also doesn’t contain any exception handling
code, then JVM simply terminate that method also and remove the
corresponding entry from the stack.
• This process will continue, until main() method. If the main() also
doesn’t have any exception handling code then JVM terminates main()
abnormally and handover the responsibility of the exception handling
to default exception handler.
• Now Default Exception handler print the exception
information to the end user
CommonExceptions and Errors:
Exceptions or errors may be thrown by either JVM(JVM Exceptions) or
thrown explicitly by application developers or API
programmers(programmatic exception).
1. NULLPOINTER EXCEPTION:
Class Sample
{
Static int[] a;
Static String name;
public static void main(String a[])
{
System.out.println(a.length);
}
}
System.out.println(a[o]); // null pointer exception (NPE)
System.out.println(name.length); //NPE
This is child class of RuntimeException. It is unchecked exception.
This is thrown by JVM when attempting to acess an object with a
reference variable whose current value is null.
Ie., on null if we are applying any operation we will get
NullPointerException.
2. STACK OVERFLOW ERROR:-
• This is child class of virtual machine error.
• It is unchecked
Throwable ----> Error ---> VMError ---> StackOverFlowError
Ex:class Sample
{
public static void m1()
{
m1();
}
public static void main(String a[]){ m1(); } // stack overflow error
}
StackOverflow error is thrown by JVM when a method recurses too
deeply.
class Sample
{
Sample() { new Sample(); }
public static void main(String a[]) { Sample s= new
Sample(); }//Exception in main thread stack overflow error
}
3. ARRAY INDEXOUTOF BOUNDS EXCEPTION:
• This is a child class of IndexOutOfBoundsExcption.
Throwable ---> Exception ---> RunTimeException ---->
IndexOutOfBoundsException---> ArrayIndexOutOfBoundsException,
StingIndexOutOfBoundsException
• It is an unchecked exception thrown by JVM when we are accessing
an array element with
Invalid index.
Ex:
class Sample
{
public static void main(String a[])
{
Int[] a=new int[6];
System.out.println(a[5]); //0
System.out.println(a[7]); //RTE: ArrayIndexOutOfException
System.out.println(a[-2]); //----do----
System.out.println(a[-2.5]); //CTE: PLP req: int found:double
}
}
4. CLASS CAST EXCEPTION:
Class Sample
{
public static void main(String a[]))
{
String s=”anu”;
Object o=(Object)s;
String s1=(String)O;
System.out.println(“hai”);
}
}
• It is the child class of RTE
• It is unchecked exception, thrown by JVM when attempting to cast a
reference variable to a type the fails to cast a reference variable to a
type the faith the IS- A test.
----> Object o=new Object();
String s=(String)o; // Class Cast Exception
----> StringBuffer s1= (StringBuffer)s;

5. NOCLASS DEF FOUND ERROR:


It is the child class of error and it is unchecked one and unreachable.
It is thrown by JVM. If the JVM or class loader tries to load the definition
of the class and no definition of the class could be found.
6. EXCEPTION IN INITIALIZER ERROR:
class Sample
{
Static String s;
String s1=new String(s);
public static void main(String a[])
{
System.out.println(“hai”);
}
}//Exception in initializer error caused by
java.lang.NullPointerException.
Thrown by the JVM to indicate that an exception is occur during
initialization of static variable or initialization block.
7. ILLEGAL ARGUMENT EXCEPTION:
It extends RTE and unchecked.
Thrown by aPI developer to indicate that a method has been passed an
illegal or inappropriate argument.
Ex: Thread class setPriority() and sleep() methods throw this exception.
class Sample
{
p s v m(String a[])
{
Thread.currentThread().setPriority(15);
}
}//CTE: Illegal Argument exception
8. NumberFormatException:
Integer i=new Integer(“10”);//valid
Integer i=new Integer(“ten”);//invalid
CTE: NumberFormateException
int i=Integer.parseInt(arg[0]);
In commandline if we give “10” is valid. But “ten” is invalid.
It is the direct child class of illegal argument exception and thrown
programmatically to indicate the application has attempted to convert
a string to the number, but the string doesn’t have appropriate format.
9. IllegalStateException:
It extends RTE and indicates that a method has been invoked at an
illegal or inappropriate time.
Ex: PrintWriter out=res.getWriter();
Out.println(…);
Out.close();
Out.println(“…”); ---> this is not appropriate time to call print() on out
object and hence throws IllegalStateException.
10. Assertion Error:
It is the child class of error throws programatically when assert
statement when Assert statement fails.
Summarization:
Exception or error --------------------- thrown by
1. NullPointerException ------------------ JVM
2. StackOverFlowErrorException --------------- JVM
3. ArrayIndexOutOfBoundsException ------------- JVM
4. ClassCastException ------------------------- JVM
5. NoClassDefFoundError -------------------- JVM
6. ExceptionInIntializerError -------------------- JVM

thrown by programmatically by programmer API developer:


7. IllegealArgumentException
8. NumberFormatException
9. IllegalStateException
10. Assertion Error
Checked , Unchecked Exceptions
Checked vs Unchecked Exceptions :
• The Exceptions which are checked by the compiler for
smooth execution of program at Runtime are called checked
Exceptions.
• The Exceptions which are unable to check by the compiler
are called Unchecked Exceptions.
• Runtime Exception and its child classes: Error and its child classes
are Unchecked Exceptions. While the remaining all are Unchecked
Exceptions.

P
artially Checked vs Fully Checked :
A Checked Exception is said to be Fully Checked Exception if
and only if all its child classes are also checked. Otherwise it is
Partially Checked Exception.
Ex: IOException is Fully Checked Exception
Exception is Partially Checked
Throwable is Partially Checked
try , catch , finally
finally block:
try
{
System.out.println(10/0);
}
catch(AE e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“catch”);
}
• The cleanup code, we have to keep inside finally block because
irrespective of exception occurred or not occurred or handled or not
handled, the finally block will always execute.

Q: Difference between final, finally and finalize?


• It is highly recommended to keep cleanup code inside finally block
instead of finalize().
• The finally block will always execute except the place where
the JVM got shutdown. We can shutdown the JVM by calling
/using System.exit(0).

Example:
try
{
System.out.println(“hai”);
}
catch( NULL pointer exception e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“finally”);
}
output:
hai
finally

Samples:
1. try{} catch(X e){} -->valid
2. try{}catch(X e){}finally{} -->valid
3. try{}finally{}catch(X e){} --> invalid
4. try{}finally{} -->valid
i.e , try --> catch --> finally is the only order.
Only try{} ---> invalid,
Only catch{} ----> invalid
Only finally{} ----> invalid
Note: try without catch & catch with out try invalid

Example:
catch(..){}
finally{}
CTE: catch with out try

Control Flow in try, catch, finally block :


try
{
Stmt1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
finally
{
Stmt 5;
}
Stmt 6;

See the below cases:


Case 1:- If there is no exception then 1,2,3,5,6 and normal termination.
Case 2:- If an exception raised at stmt2 and the corresponding catch
block found 1,4,5,6 and normal termination.
Case 3:- If an exception raised at stmt2 and the corresponding catch
block not matched 1,5 and abnormal termination.

Control Floe in the Nested try, catch, finally blocks:


try
{
Stmt1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
catch(XException e)
{
Stmt 7;
}
finally
{
Stmt 8;
}
Stmt 9;
}
catch(YException e)
{
Stmt 10;
}
finally
{
Stmt 11;
}
Stmt 12;

Case 1: If there is no exception 1,2,3,4,5,6,8,9,11,12 and normal


termination.
Case 2: If an exception raised at stmt 2 and the corresponding catch
block found then 1,10,11,12 and normal termination.
Case 3: If an exception raised at stmt2 and the corresponding catch
block has not matched then 1,11 and abnormal termination.
Case 4: If an exception raised at stmt5 and the corresponding catch
block has matched then 1,2,3,4,7,8,9,11,12 and normal termination.
Case 5: If an exception raised at stmt5 and the corresponding catch
block has not matched but the outer catch has matched then
1,2,3,4,8,10,11,12 and normal termination.
Case 6: If an exception raised at stmt5 but the inner and outer catch
blocks are not matched then 1,2,3,4,8,11 and abnormal termination.

‘Throw’ keyword:
public static void main(String a[])
{
try
{
Throw new AithmeticException()
}
}
By using ‘throw ‘ keyword, over created customized exception objects
are handed over to JVM.
Example:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any statement, violation leads
to CTE saying “unreachable statement”.

Example:
class Sample
{
static ArithmeticException e;
public static void main(String[] a)
{
throw e; //invalid
}
}
output: NullPointerException
‘e’(is in instance area) is not pointing “ArithmeticException’ here.
static ArithmeticException e=new ArithmeticException();

Example:
class Sample
{
public static void main(String a[])
{
Throw new Exception(); //invalid
}
}//CTE: “Unreported Exception Java.lang.Exception must be caught” or
declared to be thrown.
• Inside a program if there is any chance of throwing a checked
exception explicitly or implicitly we have to handle that checked
exception by using try - catch or we have to delegate the responsibility
or exception handling to the caller. Violation leads to CTE saying
Unreported Exception xxx; must be caught or declared to be thrown.

throws , throw
“throws” Keyword :We can ‘throws’ keyword for delegating
the responsibility of the Exception handling to the caller.
Ex:
class Sample
{
public static void main(String a[])throws InteruptedException
{
doStuff();
}
public static void doStuff()throws IE
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
Thread.sleep(1000);
}
}
without ‘throws’ CTE: Unreported Exception
java.lang.interuptedException ; must be caught or declared to be
thrown. To avoid CTE(compile time error) another way in using try --->
catch block.
Ex:
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(IOException e){} --->CTE (fullychecked exception)
}
}
CTE: exception java.io.IOException is never thrown in the body of the
corresponding try statement.
If we are keeping the catch block for fully checked exception there
should may be a chance of raising exception in the corresponding try
block otherwise CTE saying XXXException is never thrown in the body
of corresponding try statement.
Case 1:
try
{
System.out.println(“hai”);
}
catch(ArithematicException e) //valid no CTE(compile time error)
{ //unchecked exception }
Case 2: try
{
System.out.println(“hai”);
}
catch(Exception e) //valid no CTE
{
//Partially checked exception
}
Case 3:
try
{
System.out.println(“hello”);
}
catch(IOException e) //invalid CTE
{
// fully checked exception
}

Throw keyword:By using ‘throw ‘ keyword, over created


customized exception objects are handed over to JVM.

Example:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any statement, violation leads
to CTE saying “unreachable statement”.

Customized Exceptions :
Based on the programming required sometimes we have to design our
own Customized Exceptions.
Ex: Insufficient funds Exception
too young Exception
too old Exception
throw Example:
class TooYoungException extends RunTimeException
{
TooYoungException(String s)
{
super(s);
}
class Sample
{
public static void main(String a[])
{
int i=Integer.parseInt(arg[0]);
if(i>85)
throw new TooYoungException(“please wait some more time, you eill
get married”);
else if(i<10)
throw new TooYoungException(“ur age is already crossed”);
else
throw new TooYoungException(“very soon you will get match”);
}
}
java File
File:
A File Object is an abstract representstion of name of a file or
directory.

File f=new File(“abc.txt”);


Ststem.out.println(f.exits()); ------------>output: false
F represents a file abc.txt only
File f=new File(“Laxman”);
F represents a diretory ‘Laxman’.
.java file object represents both files and diretory(unix terminology).

Constructors of the File class:


--> File f=new File (String name)
create a file instance that represents the name of the file or directory.
--> File f =new File(String diretory,string name)
creates a file instance that represents a diretory or file name in the
specified directory.
---> File f=new File(File dir,String name)
create a new file instance that represents a file or diretory name in the
specified directory.
If the specified is not exists we will find an exception saying
IOException system can’t find the specified diretory.
Methods of the File class:
1.boolean exists()
return true if the file or diretory exists,otherwise false.
2.boolean createNewFile()
returns true if it will create a new file otherwise false.
3.boolean mkdir()
create the new diretory and returns true if the directory already
present returns false.
4.boolean isFile()
return true if the file object represents File
5.boolean isDirectory()
Inorder to check whether the file object represents,physical file name
or directory.
6.String[] list()
returns the files/directory name present in the directory.
7.boolean delete()
delete the file or directory represented by file object.
8.boolean renameTo(File destination)
1)Write a program(WAP) to create a file named with “xyz.txt” in the
current directory.
2)WAP for createing a directory laxman123 in the current working
directory and in that create a file named with file1.txt.
3.WAP a program to list all the files and directories present in directory
laxman123.
File Example :
1. Class Sample
{
public static void main(String add[])
{
File f=new File(“xyz.txt”);
If (!f.exists())

f.createNewFile();

System.out.println(f.exists());
}
}
2. class Sample
{
public static void main(String aff[])
{
File f=new File(“laxman.txt”);
If(!f.exists())
f.mkdir();
File f1=new File(“laxman”,”laxman txt”);
F1.createNewFile();
System.out.println(f1.exists());
}
}
3. Class Samle
{
public static void main(String ah[])
{
File f=new File (“laxman123”); ------------->already exists
String[] s=f.list();
for(String s1:s)
{
System.out.println(s1);
}
}
With the same name there may be a chance of a file or a directory
.From java code creating the file followed by creating the directory
with the same name allowed and File object represents a file only.
After creating the directory ,if we are creating file with tha same name
we will get RTE saying IOException:Access is denied
File f=new File(“dir1”,”file1.txt”);
This file object represents a file named with file1.txt which will present
in the directory
f.writeNewFile();
If the directory is not present then f.createNewFile() results a RTE
saying IOException:The system can not find the path specified.
If we call list() method on java file object which represents a physical
file instead of directory.it just simply return null.
If applied on directory it returns the content of the directory.
java All Reader classes
FileReader class:
If is the child class of abstract class reader this can be used for reading
charater data from a file.
FileReader Constructors:
1.FileReader fr=new FileReader(String fname)
2.FileReader fr=new FileReader (Filename f)
if the file is not found these constructors raise RTE saying FileNotFound
Exception
Methods:
1. int read()throws IOException
return the Unicode of the next charater if it is exists else---1.
2.int read(char[] ch)
returns the number of charaters from the file and populated in the
specified array.
3.void close()
the flushing is not reqired while reading data .so MISSING
File Reader Examples:
FileReader fr=new FileReader(“laxman.txt”);
System.out.println(“fr.read());
Char[] ch =new char[200];
Fr.read(ch);
For(char c1:ch)
System.out.println(c1);
Fr.close();

BufferedReader:
By using this we can improve the performance.It contain a separate
method readLine() to read single line at a time instead of
single charater.
So this is the more convenient class for reading charater data from a
file
Constructors:
1.BufferedReader br=new BufferedReader(Reader r)
2.BufferedReader br=new BufferedReader(Reader r,int size)
Methods:
1.int read()throws IOException
to read a single character
2.int read(char[] ch)throws IOException
to read an array of character
3.String readLine()
to read nextline a single line.
If there is no next line return null
BufferedReader Example:
FileReader fr=new FileReader(“laxman.txt”);
BufferedReader br=new BufferedReader(fr);
String s=br.readLine();
While(s!=null)
{
System.out.println(s);
S=br.readLine();
}
br.close();
}
java All writer classes
FileWriter:
This is a child class of writer .this class can be used for writing charater
data.
FileWriter constructors:
1.FileWriter fw=new FileWriter(Filename)
create a filewriter object to the given file if the file having this name
,doesn’t exists this constructor automatically creates the
corresponding file also.But this is not possible in the case of File
constructor.
2.FileWriter fw=new FileWriter(File f)
create FileWriter object for the specified File f .if the file is not already
present this constructor wilol create automatically the file also.
3.FileWriter fw=new FileWriter(String file name,Boolean
append)
If the second argument is true the data append to the existing
content .If it is false ,then the old data is over ridden by new data.
4.FileWriter fw =new FileWriter (File f, boolean append)
------>By default flase.
Methods of FileWriter:
1.void write(int ch)throws IOException
the Corresponding character can be written to the file.
2.void write(String s)throws IOException
writes a String to the file
3.void write(char[] ch)throws IOException
writes a charater array data ti the file
4.void flush()
to guarented that the last character of the data should be written to
the file
5.void close()
To the close file writer object
6.void write(int unicodevalue)throws IOException
File writer Example:
Import java.io.*;
Class Sample
{
public static void main(String aff[])
{
File f=new File(“file1.txt”);
System.out.println(f.exists());
FileWriter fw =new FileWriter(f);
System.out.println(f.exists());
Fw.write(100);
Fw.write(“laxman software”);
Char[] ch={‘L’,’a’,’x’,’m’,’a’,’n’};
Fw.write(ch);
Fw.close();
Fw.flush();
}
}
while inserting the data ,the programmer is responsible to insert
separately the line separator(\n).
When we are reading the data ,we have to put inside the char array.
we should know the size of the array in advance otherwise it will be a
probleam .
we have to read the data charater by charater which increase the
number of IO operations and decreses the performance of the system.
To overcome this ,SUN people has introduced buffered reader and
bufferwriter class
BufferedWriter:
we can create a bufferedwriter object over any writer object.
Construtors:
BufferedWriter bf=new BufferedWriter(Writer w);
BufferedWriter bw=new BufferedWriter(Writer w,int size);
Where size is the size of the buffer
Methods:
1.void write(int i)throws IOException
To write one charater
2.void write(String s)throws IOException
to write the given string
3.void write(char[] ch)throws IOException
4.void newLine()
to insert a new line character
5.void flush()
6.void close()
Q.when compare with java.io.BufferedWriter to java.io.FileWriter which
capability exists as a method in only one of .
a.closing system
2b.flushing the stream
c.writng to the stream
d.marking the location in the stream
e.writing the line separator to the string (valid)
Buffered Writer Example:
Class Sample
{
public static void main(String args[])
{
FileWriter fw=new FileWriter(“laxman.txt”);
BufferedWriter bw=new BufferedWriter(fw);
Bw.write(100);
Bw.write(“laxman”);
Bw..newLine();
Bw.write(“scjp”);
Bw.newLinw();
Bw.write(“srnagar”);
Bw.flush();
Bw.close();
Fw.close();
}
}

When ever we are closing the BufferedWriter autpmaticaly the stream


opened by fileWriter is also closed.
PrintWriter:
The most convenient class for writing any kind of text data .It has
enhanced in 1.5 version.
Constructors:
1.PrintWriter p=new PrintWriter(String name)
2.PrintWriter p=new PrintWriter(File name)
3.PrintWriter p=new PrintWriter(Writer w)
Methods:
1.void write(int ch)------> to write character
2.void write(String s)-----> to write String
3.void write(char[] ch)-----to write character
4.void print(int i) -----directory add the int
5.void print(String s)
6.void print(char[] ch)
7.void print(boolean b)
8.void print(char ch)
9.void print(long l)
10.void println(int i) -----directory add the int
11.void println(String s)
12.void println(char[] ch)
13.void println(boolean b)
14.void println(char ch)
15.void println(long l)
PrintWriter Example:
Import java.io.*;
Class Sample
{
public static void main(String add[])throws IOException
{
PrintWriter pw=new PrintWriter(“laxman.txt”);
Pw.write(100);
Pw.print(100);
Pw.print(true);
Pw.print(“laxman”);
Pw.print(“scjp”);
Pw.print(“Hyderabad”);
Pw.flush();
Pw.close();
}
}
Serialization
Java Serialization(serializable):
The process of saveing an object data to a file is called
serialization.
writeObject(o)
The process of retrieving an object data from the file is called
deserialization.
By using read object method of ObjectInputStream we can achieve
deserialization.
ObjectInputStream ----->FileInputStream------>abc.txt
serialization Example:
class Dog implements Serializable
{
int i=10;
int j=20;
transient int k=30;
}
public class Myser1 {
public static void main(String arg[])throws Exception

{
Dog d1=new Dog();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);

FileInputStream fis=new FileInputStream("laxman.txt");


ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println(d2.i+"......"+d2.j);
}
}

It is suggestable our java bean classes should implements


serialization.
Ois.readObject() method returns an object in the
java.lang.Object form .we should perform the type casting.
All the Objects doesn’t have the capability of saving to the file .Only
serializable Objects having this capability.
An object is said to be serializable if and only if the corresponding class
implements serializable interface(directly or indirectly).
The serializable interface doesn’t contain any method and it is an
example of marker interface.
If an object is non-serializable then we are not allow to save this object
to the file.vilation leads to RTE saying java.io.net.serializableException.
All the wrapper classes,collection classes and arrays of primitives
already implemented serializable interface.Hence these are serializable
objects.
If you don’t want to save ,the value of a particular instance variable
while performing serialization ,then we have to declare those variable
as transient.
If we are declearing a variable as the transient ,while saving an object
to the file JVM ignores ,the value of this variable ,instead of saving
original value ,JVM stores default value for the transient
variables.Hence transient means ‘not to serializable”.
Static variables are not part of object state hence they never
participated in the serialization process.A single copy of the static
variable will exist and all the objects will share that copy.
Final variable also never participated in the serialization.there is no
effect of declearing a final or a static variable as transient.
Object Graphs:
When ever we are saving an objects to the file all the objects
which are reachable from that object by default saving to the
file.This group of object is called ObjectGraph.
Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Dog1 implements Serializable


{
Cat c=new Cat();
}
class Cat implements Serializable
{
int i=10;
Rat r=new Rat();
}
class Rat implements Serializable
{
int j=20;
}

class SerDemo2
{
public static void main(String arg[])throws Exception
{
Dog1 d=new Dog1();
FileOutputStream fos=new FileOutputStream("abc1.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis=new FileInputStream("abc1.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog1 d1=(Dog1)ois.readObject();
System.out.println(d1.c.i);
System.out.println(d1. c.r.j);
}
}
When ever we are saving an object to the file.All the object present in
its objects graph by default will save to the file .Hence all the objects
present in the object graph also must be serializable .voilation leads to
RTE saying NotSerializable Exception”.
Example:
class Dog implements serializable
{
Cat c=new Cat();
}
Class Cat
{
Int j=20;
}
Class SerialDemo
{
public static void main(String arg[])
{
Dog d=new Dog();
FileOutputStream fos=new FileOutputStream(“abc.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
Oos.writeObject(d);
FileInputStream fis=new FileInputStream(“abc.txt’);
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d1=(Dog)ois.readObject();
System.out.println(d1.c.j);
System.out.println(d1. c.j);
}
}
Customized Serialization:
During default serialization there may be a chance of loss of
information .To over come these problems ,we can perform customized
serialization .
We can perform customized serialization by using the following two call
back methods.
1.private void writeObject(OutputStream os)
JVM calls this writeObject method at the time of serialization.
2.private void readObject(inputStream is)
the JVM calls this method at the time of deserialization
automatically.
The above two methods are called by JVM automatically at the time of
serialization and deserialization .Hence these methods are considered
as call back methods.
Customized Serialization Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Dog2 implements Serializable


{
transient Cat1 c=new Cat1();
private void writeObject(ObjectOutputStream os)throws Exception
{
os.defaultWriteObject();
int i=c.j;
os.writeInt(i);
}
private void readObject(ObjectInputStream is)throws Exception
{
is.defaultReadObject();
int i=is.readInt();
c=new Cat1();
c.j=i;
}
}
class Cat1
{
int j=20;
}
public class SerDemo3
{
public static void main(String arg[])throws Exception
{
Dog2 d=new Dog2();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis=new FileInputStream("abc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog2 d1=(Dog2)ois.readObject();
System.out.println(d1.c.j);
}
}

Date Format
Before going learn about Date Format We have to know the Locale
class.

DateFormat:
The representation of date is varied from location to location ,we can
format the date for a specific locale by using date format class.It is
available in java.text.package.It is an abstract class we are not allowed
to create an instance of date format by using constructor.
DateFormat d=new DateFormat() -------->not valid
Getting DateFormat object for the default locale:
public static DateFormat getInstance();
public static DateFormat getDateInstance();
public static DateFormat getDateinstance(int style);
the allowed styles are :
DateFormat.FULL(0);
DateFormat.LONG(1);
DateFormat.MEDIUM(2);
DateFormat.SHORT(3);
Getting DateFormat Object for the specific locale:
public static DateFormat getDateInstance(int style,Locale l)
Formating and parsing date:
Public String format(Date d) ----->from java date format to locale
specific date format
Public Date parse(String s) throws parseException //from locale specific
format to date format.

Example Date Format:


Import java.text.*;
Import java.util.*;
Class DateFormatDemo
{
public static void main(String arg[])
{
DateFormat d=DateFormat.getDateInstance(0);
System.out.println(“Full form is:”+d.format(new date());
System.out.println(“lond form;”+
(DateForamt.getDateInstance(1)).format(new Date());
System.otu.println(“medium is:”); //Feb 3, 2008
System.out.println(“short is”); // 2/3/08
System.otu.println(“Full is:”); //Sunday,febravary3, 2008
System.out.println(“Long is”); // Febravary 3 ,2008
}

Demo:
For India,italy
DateFormat in=DateFormat.getDateInstance(0,new Locale(‘pa”,”In”);
DateFormat us=DateFormat.getDateInstance(0);
DateForamt it=DateFormat.getDateInstance(0,new Locale.ITALY);
System.out.println(“India style:”+in.format(new Date()); //
Sunday,febravary 3,2008
System.out.println(“us style:”+us.format(new Date()); // Sunday
Febravary 3, 2008
System.out.println(“Italy style:”+it.format(new Date()); // dominica
3,febravary 2008.
Getting DateFormat object for representing both date and time.
Public static DateFormat getDateTimeInstance();
Public static DateFormat getDateTimeInstance(int date style, int time
style);
Public static DateForamt getDateTimeInstance(int date style, int time
style, locale l);
Demo:
DateFormat in=DateFormat.getDateTimeInstance(0,0,Locale.UK);
System.out.println(in); // 03 , febravary 2008 12:10:50 0’clock IST
Us: Sunday febravary 3,2008 12:10:50 pm IST
Number Format class
Before Going to learn about Number Format Batter know about Locale
Class

Number Format:
By using number format object we can represent the number specific
to a particular region (a particular locale).This class present in java
.text package.It is an abstract class we are not allowed to create object
by using constractor.
i.e NumberFormat nf=new NumberFormat() -----> not valid

Getting NumberFormat object for defaultLocale using factory method:


static NumberFormat getInstance();
static NumberFormat getNumberInstance();
static NumberFormat getCurrrencyInstance();
static NumberFormat getPercentInstance();
return NumberFormat object for representing currency and
percentage.

Getting NumberFormat object for a particular Locale:


static NumberFormat getInstance(Locale l);
static NumberFormat getNumberInstance(Locale l);
static NumberFormat getCurrencyInstance(Locale l);
static NumberFormat getPercentInstance(Locale l);

Methods of the NumberFormat class:


String format (long l);
String format(double d);
Number parse(String s)throws parseException ---->This method is for
converting locale specific to java number form.It throws a checked
exception parseException.

Example to Display the currency value 1234.343 for locations India


.Italy and us:
Import java.text.NumberFormat;
Import java.util.*;
Class NFDemo
{
Public staic void main(String arg[])
{
double d=123456.789;
Locale India=new Locale(“pa”,”IN”);
NumberFormat nf=NumberFormat.getCurrencyInstance(India);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
NumberFormat nf=NumberFormat.getCurrencyInstance(locale.ITALY);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
NumberFormat
nf=NumberFormat.getCurrencyInstance(locale.UNITEDSTATES);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
}}}
output:
INR123,456.789
C1 123.456.789
$123,456.789
we can set the maximam and minimum number of digits for integer
and fractional parts.For this we can use the following methods of
NumberFormat class.
public void setMaximumFractionalDigits(int n);
public void setMinimumFractionalDigits(int n);
public void setMaximumIntegerDigits(int n);
public void setMinimumIntegerDigits(int n);

Example:
Import java.text.*;
Import java.util.*;
Class NFDemo
{
public static vopid main(String arg[])
{
double d=123.456;
NumberFormat nf=NumberFormat.getInstance();

Systm.out.println(nf.format(d)); //123.456
nf. setMaximumFractionalDigits(2);
System.out.println(nf.format(d)); //123.46

nf.setMinimumFractionalDigits(5);
System.out.println(nf.format(d)); //123.45600
nf.setMaximumIntegerDigits(2);
System.out.println(nf.format(d)); //23.456
The most significant bits will be lost
nf.setMinimumIntegerDigits(6);
System.out.println(nf.format(d)); //000123.456
}
}
Constructors
The purpose of Constructor is to perform of our creted object.
Whenever we are calling new operator for the creation of object, it
calls constructor automatically to provide initialization for the object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}
Rules Of Constructor :
1. Constructor concept is applicable for every class including abstract
class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the const4ructor and the name of the class must be
same.
4. The allowed modifiers for the constructors are public, private,
protected, and default. If you are applying any other we will get a CTE
saying “modifier xxx not allowed her”.
5. We can’t give return type for the constructor even void also.

If we will give return type for the constructor that thing as a method
instead of constructor that thing as a method instead of constructor
(so,there is no CTE). Ie., it is legal (but stupid) to have a method whose
name same as classname.
Default Constructor:-
If the programmer is not writing any constructor, then only compiler
will generate a default constructor.
Ie., either programmer written constructor or compiler generated must
present in your class but not both at a time.
Prototype of default constructor shown below:
a).Programmer written code:- class Test{}
Compiler generated code:-
class Test
{
Test()
{
super();
}
}
The default constructor is always no argument constructor.
The access modifier of the default constructor is sane as access
modifier of the class (public & default only).
The default constructor contains only one statement which is ‘no arg
call to super class Constructor ‘ (super();)
b) Programmer written code:-
class Test {
Test(int i)
{
System.out.println(“constructor”);
}}
Compiler generated code:-
class Test {
Test(int i)
{
super();
System.out.println(“constructor”);
}}

c). Programmer written code:-


class Test {
Test(int i)
{
super();
System.out.println(“Hai”);
}}
Compiler generated code:- no new code is going to generate.

d). Programmer written code:-


class Test {
void Test()
{
System.out.println(“hello”);
}
}
Compiler generated code:-
class Test {
void Test()
{
System.out.println(“hello”);
}
Test()
{
super();
}}
e). Programmer written code:-
class Test {
Test()
{
this(10);
System.out.println(“hai”);
}
Test(int i)
{
System.out.println(i);
}}
Compiler generated code:-
class Test {
Test() {
this(10);
System.out.println(“hai”);
}
Test(int i) {
super();
System.out.println(i);
}}
The first line inside a constructor must be a call to super class
constructor ( by using super();) or a call to overload
constructor of the same class. (by using ‘this’ keyword).
If you are not writing the first line as either ‘super()’ or ‘this’
then compiler will always keep a no arg call to super class
constructor (super();).
1. Allowed only in Constructors.
2. Must be first statements.
3.Either super() or this, but not both.
We can invoke another constructor from constructor from a method
violation leads to CTE. i.e, super() or this must be used inside the
constructor only not anywhere else.
Overloaded Constructors:
We are allowed to keep more than one constructor inside a class ,
which are considered as overloaded constructors. We can’t override
the constructors, because they belong to the same Ex: class Test {
Test(int i){}
Test(){} ---->Overloaded Constructors
}
Constructors are not inherited and hence we are not allowed to
override a constructor.
while recursive method invocation we will get stackoverflowException
But in case of constructors we will get compile time error.
If we are writing any constructor in our class it is recommended to
place default constructor also. Otherwise we should take care while
writing the constructor child case.
If the parent class constructor throws some Checked Exception, while
writing child class constructors we should take care.In case of
unchecked exception no rule.
Recursive Constructor invocation:
class Sample {
Sample() // This is a compile time problem
{
this(10);
}
Sample(int i)
{
this(); // Invalid, CTE: recursive constructor invocation
}
public static void main(String a[])
{
System.out.println(“hai”);
}
}
Constructing the Child class constructors:
Example:
class P {
P()
{ super(); }
}
class C extends P
{
C() {
super();
} } //valid

Example:
class P {
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}

Example: class P
{
P() throws Exception ----> checked exception
{}
}
class C extends P
{
C() // compile time error unhandled exception type exception
{}
}
Java Generics
The problems of legacy collections:
There is no type safety for the collection objects.
Suppose we are constructing array list object to that we can add any
kind of object.
Suppose if our requirement is to add only String objects,by mistake if
we are adding any non string objects,still the compiler compiles the
code without raise any problem.
But at the time of retrieving these objects we may get class cast
exception.
Example:
ArrapList l=new ArrayList();
l.add(“laxman”);
l.add(new Integer(10));
String n1=(String)l.get(0);
String n2=(String)l.get(1);
Hence these is no type safety for the collection objects.
While retrieving the elements from the collection object we should
explicitly perform type casting even though we know the type of
elements present in the collection.
To resolve the above two problems Sun people provided generics
concept in the 1.5 version.
Hence by using generic we can provide type safely for the
collection objects and we can resolve explicit type casting
problems.
i.e no need to type cast at the time of retrieving elements from the
collection.

ArrayList <String > l= new ArrayList <String >();


This ArrayList can accept only string objects.This is declaring a generic
collection object .
By mistake of we are adding any non string object .it will results in the
compail time problem.Hence by using generics we can provide the
type safety for the collection objects.
At the time of retrieving we can directly assign to the String type no
need to problem explicit typecasting.
ArrayList <String> l=new ArrayList<String>();
l.add(“laxman”);
l.add(“scjp”);
l.add(10); // compile time error (CTE)
String n1=l.get(0);

i.e no need to perform explicit type casting so,generics are nothing but
parametrized collections because by using this we can define the type
parameter.

program to define ArrayList of String objects and display the contents


of ArrayList by using some method:
import java.util.*;
class GenericDemo
{
public static void main(String arg[])
{
ArrayList<String> l=NEW ArrayList <String >();
l.add(“a”);
l.add(“b”);
l.add(“c”);
show(l);
}
public static void show(ArrayList<String> l)
{
System.out.println(l);
}
}

To add any kind of objects to the ArrayList we can declare generic


arraylist as follows

ArrayList<Object> l=new ArrayList<Object>(); is equal to


List<Object> l=new ArrayList<Object>(); (valid)
List<Object> l=new ArrayList<String>(); (not valid)
Because polymorphism can be applicable for the base type not for the
parameter type.

ArrayList<Integer> l=new ArrayList<Integer>(); (valid)


Object<Integer> l=new ArrayList<Integer>(); (valid)
Object<number> l=new ArrayList<integer>(); (not valid)
ArrayList<int> l=new ArrayList<int>(); (not valid)
Since parameter must not be primitive type .
We can’t define primitive type as the parameter of collection
classes.violation leads to compail time error.
Saying unexpected type found:int required:reference
java net package
INTRODUCTION TO NETWORKING:
The Java execution environment is designed so that applications can
be easily written to efficiently communicate and share processing with
remote systems. Much of this functionality is provided with the
standard Java API within the java.net package.

TCP/IP Protocols:

Three protocols are most commonly used within the TCP/IP scheme
and a closer investigation of their properties is warranted.
Understanding how these three protocols (IP, TCP, and UDP) interact is
critical to developing network applications.

Internet Protocol (IP):

IP is the keystone of the TCP/IP suite. All data on the Internet flows
through IP packets, the basic unit of IP transmissions. IP is termed a
connectionless, unreliable protocol. As a connectionless protocol, IP
does not exchange control information before transmitting data to a
remote system—packets are merely sent to the destination with the
expectation that they will be treated properly. IP is unreliable because
it does not retransmit lost packets or detect corrupted data. These
tasks must be implemented by higher level protocols, such as TCP.

IP defines a universal-addressing scheme called IP addresses. An IP


address is a 32-bit number and each standard address is unique on the
Internet. Given an IP packet, the information can be routed to the
destination based upon the IP address defined in the packet header. IP
addresses are generally written as four numbers, between 0 and 255,
separated by period. (for example, 124.148.157.6)

While a 32-bit number is an appropriate way to address systems for


computers, humans understandably have difficulty remembering them.
Thus, a system called the Domain Name System (DNS) was developed
to map IP addresses to more intuitive identifiers and vice-versa. You
can use www.netspace.org instead of 128.148.157.6.

It is important to realize that these domain names are not used nor
understood by IP. When an application wants to transmit data to
another machine on the Internet, it must first translate the domain
name to an IP address using the DNS. A receiving application can
perform a reverse translation, using the DNS to return a domain name
given an IP address. There is not a one-to-one correspondence
between IP addresses and domain names: A domain name can map to
multiple IP addresses, and multiple IP addresses can map to the same
domain name.

Java provides a class to work with IP Addresses, InetAddress.

THE INETADDRESS CLASS:


This class represents an Internet Protocol (IP) address.
Applications should use the methods getLocalHost, getByName, or
getAllByName to create a new InetAddress instance. Transmission
Control Protocol (TCP)

Most Internet applications use TCP to implement the transport layer.


TCP provides a reliable, connection-oriented, continuous-stream
protocol. The implications of these characteristics are:
Reliable. When TCP segments, the smallest unit of TCP transmissions,
are lost or corrupted, the TCP implementation will detect this and
retransmit necessary segments.
Connection-oriented. TCP sets up a connection with a remote system
by transmitting control information, often known as a handshake,
before beginning a communication. At the end of the connect, a similar
closing handshake ends the transmission.
Continuous-stream. TCP provides a communications medium that
allows for an arbitrary number of bytes to be sent and received
smoothly; once a connection has been established, TCP segments
provide the application layer the appearance of a continuous flow of
data.

Because of these characteristics, it is easy to see why TCP would be


used by most Internet applications. TCP makes it very easy to create a
network application, freeing you from worrying how the data is broken
up or about coding error correction routines. However, TCP requires a
significant amount of overhead and perhaps you might wish to code
routines that more efficiently provide reliable transmissions given the
parameters of your application. Furthermore, retransmission of lost
data may be inappropriate for your application, because such
information's usefulness may have expired.

An important addressing scheme which TCP defines is the port. Ports


separate various TCP communications streams which are running
concurrently on the same system. For server applications, which wait
for TCP clients to initiate contact, a specific port can be established
from where communications will originate. These concepts come
together in a programming abstraction known as sockets.

User Datagram Protocol (UDP) :

UDP is a low-overhead alternative to TCP for host-to-host


communications. In contrast to TCP, UDP has the following features:
Unreliable. UDP has no mechanism for detecting errors nor
retransmitting lost or corrupted information.
Connectionless. UDP does not negotiate a connection before
transmitting data. Information is sent with the assumption that the
recipient will be listening.
Message-oriented. UDP allows applications to send self-contained
messages within UDP datagrams, the unit of UDP transmission. The
application must package all information within individual datagrams.
For some applications, UDP is more appropriate than TCP. For instance,
with the Network Time Protocol (NTP), lost data indicating the current
time would be invalid by the time it was retransmitted. In a LAN
environment, Network File System (NFS) can more efficiently provide
reliability at the application layer and thus uses UDP.

As with TCP, UDP provides the addressing scheme of ports, allowing for
many applications to simultaneously send and receive datagrams. UDP
ports are distinct from TCP ports. For example, one application can
respond to UDP port 512 while another unrelated service handles TCP
port 512.

Uniform Resource Locator (URL):


While IP addresses uniquely identify systems on the Internet, and ports
identify TCP or UDP services on a system, URLs provide a universal
identification scheme at the application level. Anyone who has used a
Web browser is familiar with seeing URLs, though their complete
syntax may not be self-evident. URLs were developed to create a
common format of identifying resources on the Web, but they were
designed to be general enough so as to encompass applications that
predated the Web by decades. Similarly, the URL syntax is flexible
enough so as to accommodate future protocols.
URL Syntax :
The primary classification of URLs is the scheme, which usually
corresponds to an application protocol. Schemes include http, ftp,
telnet, and gopher. The rest of the URL syntax is in a format that
depends upon the scheme. These two portions of information are
separated by a colon to give us:
scheme-name:scheme-info

Thus, while mailto:dwb@netspace.org indicates "send mail to user dwb


at the machine netspace.org," ftp://dwb@netspace.org/ means "open
an FTP connection to netspace.org and log in as user dwb."

General URL Format:


Most URLs used conform to a general format that follows the following
pattern:
scheme-name://host:port/file-info#internal-reference

Scheme-name is a URL scheme such as HTTP, FTP, or Gopher. Host is


the domain name or IP address of the remote system. Port is the port
number on which the service is listening; since most application
protocols define a standard port, unless a non-standard port is being
used, the port and the colon which delimits it from the host is omitted.
File-info is the resource requested on the remote system, which often
times is a file. However, the file portion may actually execute a server
program and it usually includes a path to a specific file on the system.
The internal-reference is usually the identifier of a named anchor
within an HTML page. A named anchor allows a link to target a
particular location within an HTML page. Usually this is not used, and
this token with the # character that delimits it is omitted.

Java and URLs:


Java provides a very powerful and elegant mechanism for creating
network client applications allowing you to use relatively few
statements to obtain resources from the Internet. The java.net
package contains the sources of this power, the URL and
URLConnection classes.

THE URL CLASS :

Class URL represents a Uniform Resource Locator, a pointer to a


"resource" on the World Wide Web. A resource can be something as
simple as a file or a directory, or it can be a reference to a more
complicated object, such as a query to a database or to a search
engine.

In general, a URL can be broken into several parts. The previous


example of a URL indicates that the protocol to use is http (HyperText
Transport Protocol) and that the information resides on a host machine
named www.ncsa.uiuc.edu. The information on that host machine is
named demoweb/url-primer.html. The exact meaning of this name on
the host machine is both protocol dependent and host dependent. The
information normally resides in a file, but it could be generated on the
fly. This component of the URL is called the file component, even
though the information is not necessarily in a file.

A URL can optionally specify a "port", which is the port number to


which the TCP connection is made on the remote host machine. If the
port is not specified, the default port for the protocol is used instead.
For example, the default port for http is 80. An alternative port could
be specified as:
http://www.ncsa.uiuc.edu:8080/demoweb/url-primer.html

A URL may have appended to it an "anchor", also known as a "ref" or a


"reference". The anchor is indicated by the sharp sign character "#"
followed by more characters. For example,

http://java.sun.com/index.html#chapter1

This anchor is not technically part of the URL. Rather, it indicates that
after the specified resource is retrieved, the application is specifically
interested in that part of the document that has the tag chapter1
attached to it. The meaning of a tag is resource specific.

An application can also specify a "relative URL", which contains only


enough information to reach the resource relative to another URL.
Relative URLs are frequently used within HTML pages.

For example, if the contents of the URL:


http://java.sun.com/index.html

contained within it the relative URL:


FAQ.html

it would be a shorthand for:


http://java.sun.com/FAQ.html

The relative URL need not specify all the components of a URL. If the
protocol, host name, or port number is missing, the value is inherited
from the fully specified URL. The file component must be specified. The
optional anchor is not inherited.

Example for URL :

GetURLApp.java

import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;

public class GetURLApp


{
public static void main(String args[])
{
try
{
if(args.length!=1) error("Usage: java GetURLApp URL");
System.out.println("Fetching URL: "+args[0]);
URL url = new URL(args[0]);
BufferedReader inStream = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = inStream.readLine())!= null)
{
System.out.println(line);
}
inStream.close();
}
catch (MalformedURLException ex)
{
error("Bad URL");
}
catch (IOException ex)
{
error("IOException occurred.");
}
}

public static void error(String s){


System.out.println(s);
System.exit(1);
}
}

THE URLCONNECTION CLASS :


The abstract class URLConnection is the superclass of all classes that
represent a communications link between the application and a URL.
Instances of this class can be used both to read from and to write to
the resource referenced by the URL. In general, creating a connection
to a URL is a multistep process:
openConnection()
connect()

Manipulate parameters that affect the connection to the remote


resource.
Interact with the resource; query header fields and contents.

1. The connection object is created by invoking the openConnection


method on a URL.
2. The setup parameters and general request properties are
manipulated.
3. The actual connection to the remote object is made, using the
connect method.
4. The remote object becomes available. The header fields and the
contents of the remote object can be accessed.
The setup parameters are modified using the following methods:
• setAllowUserInteraction
• setDoInput
• setDoOutput
• setIfModifiedSince
• setUseCaches
and the general request properties are modified using the method:
setRequestProperty
Default values for the AllowUserInteraction and UseCaches parameters
can be set using the methods setDefaultAllowUserInteraction and
setDefaultUseCaches. Default values for general request properties
can be set using the setDefaultRequestProperty method.

Each of the above set methods has a corresponding get method to


retrieve the value of the parameter or general request property. The
specific parameters and general request properties that are applicable
are protocol specific.

The following methods are used to access the header fields and the
contents after the connection is made to the remote object:
getContent
getHeaderField
getInputStream
getOutputStream
Certain header fields are accessed frequently. The methods:
getContentEncoding
getContentLength
getContentType
getDate
getExpiration
getLastModified
provide convenient access to these fields. The getContentType method
is used by the getContent method to determine the type of the remote
object; subclasses may find it convenient to override the
getContentType method.

In the common case, all of the pre-connection parameters and general


request properties can be ignored: the pre-connection parameters and
request properties default to sensible values. For most clients of this
interface, there are only two interesting methods: getInputStream and
getObject, which are mirrored in the URL class by convenience
methods.
More information on the request properties and header fields of an http
connection can be found at:
http://www.w3.org/hypertext/WWW/Protocols/HTTP1.0/draft-ietf-http-
spec.html

TCP Socket Basics:

Sockets were originally developed at the University of California at


Berkeley as a tool to easily accomplish network programming.
Originally part of UNIX operating systems, the concept of sockets has
been incorporated into a wide variety of operating environments,
including Java.
What is a Socket?
A socket is a handle to a communications link over the network with
another application. A TCP socket is one that utilizes the TCP protocol,
inheriting the behavior of that transport protocol. Four pieces of
information are needed to create a TCP socket:

• The local system's IP address


• The TCP port number which the local application is using
• The remote system's IP address
• The TCP port number to which the remote application is responding

Sockets are often used in client-server applications: A centralized


service waits for various remote machines to request specific
resources, handling each request as it arrives. In order for clients to
know how to communicate with the server, standard application
protocols are assigned well-known ports. On UNIX operating systems,
ports below 1024 can only be bound by applications with super-user
(for example, root) privileges, and thus for control, these well-known
ports lie within this range, by convention. Some well known ports are
shown in the following table.

Well-known TCP ports and services

Port
Service
21 FTP
23 Telnet
25 SMTP (Internet Mail Transfer)
79 Finger
80 HTTP
For many application protocols, you can merely use the Telnet
application to connect to the service port and then manually emulate a
client. This may help you understand how client-server
communications work.

Client applications must also obtain, or bind, a port to establish a


socket connection. Because the client initiates the communication with
the server, such a port number could conveniently be assigned at
runtime. Client applications are usually run by normal, unprivileged
users on UNIX systems, and thus these ports are allocated from the
range above 1024. This convention has held when migrated to other
operating systems, and client applications are generally given a
dynamically-allocated port above 1024.

Because no two applications can bind the same port on the same
machine simultaneously, a socket uniquely identifies a
communications link. Realize that a server may respond to two clients
on the same port, since the clients will be on different systems and/or
different ports; the uniqueness of the link's characteristics are
preserved.

JAVA TCP SOCKET CLASSES :

Java has a number of classes, which allow you to create socket-based


network applications. The two classes you use include java.net.Socket
and java.net.ServerSocket.

THE SERVERSOCKET CLASS

public class ServerSocket extends Object

This class implements server sockets. A server socket waits for


requests to come in over the network. It performs some operation
based on that request, and then possibly returns a result to the
requester.

The actual work of the server socket is performed by an instance of the


SocketImpl class. An application can change the socket factory that
creates the socket implementation to configure itself to create sockets
appropriate to the local firewall.

Example for ServerSocket:

ServerExample.java

import java.io.*;
import java.net.*;
import java.util.Date;

public class ServerExample


{
public static void main(String args[])
{
ServerSocket server = null;
Socket socket = null;
BufferedOutputStream send = null;
try
{
server = new ServerSocket(3000);
System.out.println("server started");
while(true)
{
socket = server.accept();
send = new BufferedOutputStream(socket.getOutputStream());
String date = (new Date()).toString();
byte data[] = new byte[date.length()];
data = date.getBytes();
send.write(data,0,data.length);
send.flush();
System.out.println("data flushed");
send.close();
socket.close();
}
}
catch(Exception err) {
System.out.println("Exception in transferring data to client");
}
}
}
THE SOCKET CLASS :

This class implements client sockets (also called just "sockets"). A


socket is an endpoint for communication between two machines. The
actual work of the socket is performed by an instance of the
SocketImpl class. An application, by changing the socket factory that
creates the socket implementation, can configure itself to create
sockets appropriate to the local firewall.

Example for Socket :

import java.io.*;
import java.net.*;
public class ClientExample {
public static void main(String args[]) {
Socket socket = null;
BufferedInputStream receive = null;
if(args.length == 0){
System.out.println("Usage : java ClientExample

My own ConnectionPool implementation


By seeing this example we can get the two things

1- how to implement our own connection


2- why sun gives wait, notify methods in object class.

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;
public class MyConnectionPool {
Vector connections= null;
static MyConnectionPool instance=null;
public static final int MAX_CONNECTIONS=10;

//removeAllConnections objects
public synchronized void removeAllConnections() {
if (connections==null) {
return;
}
try {
int sz= connections.size();
for (int i=0; i < sz/2; i++) {
Connection c= (Connection) connections.elementAt(i);
c= null;
connections.remove(i);
}
if (connections!= null && connections.size() > 0) {
connections.removeAllElements();
}
connections= null;
}catch (Exception e) {
System.out.println( "Error "+ e);
}
instance =null;
}

//getInstance...
public static MyConnectionPool getInstance() {
if (instance ==null)
instance= new MyConnectionPool();
return instance;
}

//initializing all connections upto max limit i.e upto 10 connections...


public synchronized void initialize() {
if (connections ==null) {
try {
Class.forName(" com.mysql.jdbc.Driver ");
connections= new Vector();
int count =0;
while (count < MAX_CONNECTIONS) {
Connection
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost
:1521:xe","scott","tiger");
connections.addElement(connection);
count++;
}
System.out.println( "total connections created r:" + count);
} catch (Exception e) {
System.out.println( "initialise:Exception ");
e.printStackTrace();
instance.removeAllConnections();
initialize();
}
}
}
//getting connection....
public synchronized Connection getConnection() {
System.out.println( "getConnection ");
Connection c =null;
System.out.println("connections"+connections.size());
if (connections== null)
return null;
if (connections.size() > 0) {
System.out.println("i am in if");
c =(Connection) connections.elementAt(0);
connections.removeElementAt(0);
}else
{
System.out.println("i am in else");
try {
wait();
c =(Connection) connections.elementAt(0);
connections.removeElementAt(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return c;
}
//put connection obj into vector.
public synchronized void putConnection(Connection c) {
if (c != null) {
connections.addElement(c);
notifyAll();
}}}}
}

Struts Flow
When we deploy our application in the server, at first the container
reads the information from web.xml file.Here ActionServlet object will
be created and init() of ActionServlet will be called.Here ActionServlet
is the backbone to the whole application.
When client send a rewuest using .jsp extension , getters() and reset()
of FormBean will be called. When client fill the form and press on
submit button, then setters() and validate() will be called.
If the data is not valid ,then the form redirects to another page which is
specified in struts-config.xml file. If the data is valid , then only Action
class object will be created.
In Action class , have execute() which have return type of
ActionForward. We can specify the business logic in Model and provide
that object in execute().
After completion of business logic execution , then it forwards to
another page ( either success or failure) , whichis specified in struts-
config.xml file.

You might also like