Core Java Book
Core Java Book
1. Identifiers
2. Reserved words
3. Data types
4. Literals
5. Arrays
6. Types of variabless
7. Var arg method
8. Main method
9. Command line arguments
10. Java coding standards
Identifier: A name in java program is called identifier. It may be class name,
method name, variable name and label name.
Example:
Example:
class Test{
int number=10;
1
int Number=20;
int NUMBER=20; we can differentiate with case.
int NuMbEr=30;
}]
Rule 5: There is no length limit for java identifiers but it is not recommended
to take more than 15 lengths.
Rule 6: We cant use reserved words as identifiers.
Example: int if=10; --------------invalid
Rule 7: All predefined java class names and interface names we use as
identifiers.
Example 1:
class Test
{
public static void main(String[] args){
int String=10;
System.out.println(String);
}}
Output:
10
Example 2:
class Test
{
public static void main(String[] args){
int Runnable=10;
System.out.println(Runnable);
}}
Output:
10
Even though it is legal to use class names and interface names as identifiers
but it is not a good programming practice.
Which of the following are valid java identifiers?
Reserved words:
In java some identifiers are reserved to associate some functionality or
meaning such type of reserved identifiers are called reserved words.
Diagram:
1) public
2) private
3) protected
4) static
5) final
6) abstract
7) synchronized
8) native
9) strictfp(1.2 version)
10) transient
11) volatile
Keywords for exception handling:
1) try
2) catch
3) finally
4) throw
5) throws
6) assert(1.4 version)
Class related keywords:
1) class
2) package
3) import
4) extends
5) implements
6) interface
Object related keywords:
1) new
2) instanceof
3) super
4) this
Void return type keyword:
If a method wont return anything compulsory that method should be
declared with the void return type in java but it is optional in C++.
1) void
Unused keywords:
goto: Create several problems in old languages and hence it is banned in
java.
Const: Use final instead of this.
By mistake if we are using these keywords in our program we will get
compile time error.
Reserved literals:
1) true values for boolean data type.
2) false
4
Except Boolean and char all remaining data types are considered as
signed data types because we can represent both +ve and-ve
numbers.
Byte:
Size: 1byte (8bits)
Maxvalue: +127
Minvalue:-128
Range:-128to 127[-27 to 27-1]
The most significant bit acts as sign bit. 0 means +ve number and
1 means ve number.
+ve numbers will be represented directly in the memory whereas
ve numbers will be represented in 2s complement form.
Example:
byte b=10;
byte b2=130;//C.E:possible loss of precision
byte b=10.5;//C.E:possible loss of precision
byte b=true;//C.E:incompatible types
byte b="durga";//C.E:incompatible types
byte data type is best suitable if we are handling data in terms of
streams either from the file or from the network.
6
Short:
The most rarely used data type in java is short.
Size: 2 bytes
Range: -32768 to 32767(-215 to 215-1)
Example:
short s=130;
short s=32768;//C.E:possible loss of precision
short s=true;//C.E:incompatible types
Short data type is best suitable for 16 bit processors like 8086 but
these processors are completely outdated and hence the
corresponding short data type is also out data type.
Int:
This is most commonly used data type in java.
Size: 4 bytes
Range:-2147483648 to 2147483647 (-231 to 231-1)
Example:
int i=130;
int i=10.5;//C.E:possible loss of precision
int i=true;//C.E:incompatible types
long:
Whenever int is not enough to hold big values then we should go for
long data type.
Example:
To hold the no. Of characters present in a big file int may not enough
hence the return type of length() method is long.
long l=f.length();//f is a file
Size: 8 bytes
Range:-263 to 263-1
Note: All the above data types (byte, short, int and long) can be used to
represent whole numbers. If we want to represent real numbers then we
should go for floating point data types.
Floating Point Data types:
float
double
1) If we want to 5 to 6 decimal
1) If we want to 14 to 15 decimal
places of accuracy then we
places of accuracy then we
should go for float.
should go for double.
2) Size:4 bytes.
3) Range:-3.4e38 to 3.4e38.
4) float follows single precision.
2) Size:8 bytes.
3) -1.7e308 to1.7e308.
4) double
follows
precision.
double
Example 1:
boolean b=true;
boolean b=True;//C.E:cannot find symbol
boolean b="True";//C.E:incompatible types
boolean b=0;//C.E:incompatible types
Example 2:
boolean
Not
applicable
char
2 bytes
Not
applicable(bu
t allowed
values true|
false)
0 to 65535
Boolean
false
Character
0(represents
blank space)
Integral Literals: For the integral data types (byte, short, int and long) we
can specify literal value in the following ways.
1) Decimal literals: Allowed digits are 0 to 9.
Example: int x=10;
2) Octal literals: Allowed digits are 0 to 7. Literal value should be
prefixed with zero.
Example: int x=010;
3) Hexa Decimal literals: The allowed digits are 0 to 9, A to Z. For the
extra digits we can use both upper case and lower case characters.
This is one of very few areas where java is not case sensitive. Literal
value should be prefixed with ox(or)oX.
Example: int x=0x10;
These are the only possible ways to specify integral literal.
Which of the following are valid declarations?
1) int x=0786;//C.E:integer number too large: 0786(invalid)
2) int x=0xFACE;(valid)
3) int x=0xbeef;(valid)
4) int x=0xBeer;//C.E:';' expected(invalid)
//:int x=0xBeer;
^
// ^
5) int x=0xabb2cd;(valid)
Example:
int x=10;
int y=010;
int z=0x10;
System.out.println(x+"----"+y+"----"+z); //10----8----16
By default every integral literal is int type but we can specify explicitly
as long type by suffixing with small l (or) capital L.
9
Example:
int x=10;(valid)
long l=10L;(valid)
long l=10;(valid)
int x=10l;//C.E:possible loss of precision(invalid)
There is no direct way to specify byte and short literals explicitly. But
whenever we are assigning integral literal to the byte variables and its
value within the range of byte compiler automatically treats as byte
literal. Similarly short literal also.
Example:
byte b=10;(valid)
byte b=130;//C.E:possible loss of precision(invalid)
short s=32767;(valid)
short s=32768;//C.E:possible loss of precision(invalid)
Floating Point Literals: Floating point literal is by default double type but
we can specify explicitly as float type by suffixing with f or F.
Example:
float f=123.456;//C.E:possible loss of precision(invalid)
float f=123.456f;(valid)
double d=123.456;(valid)
We can specify explicitly floating point literal as double type by
suffixing with d or D.
Example:
double d=123.456D;
We can specify floating point literal only in decimal form and we cant
specify in octal and hexadecimal forms.
Example:
double d=123.456;(valid)
double d=0123.456;(valid)
double d=0x123.456;//C.E:malformed floating point literal(invalid)
Which of the following floating point declarations are valid?
1) float f=123.456;//C.E:possible loss of precision(invalid)
2) float f=123.456D;//C.E:possible loss of precision(invalid)
3) double d=0x123.456;//C.E:malformed floating point literal(invalid)
4) double d=0xFace;(valid)
5) double d=0xBeef;(valid)
We can assign integral literal directly to the floating point data types
and that integral literal can be specified in octal and Hexa decimal
form also.
Example:
double d=0xBeef;
System.out.println(d);//48879.0
But we cant assign floating point literal directly to the integral types.
Example:
10
\r
Carriage return
\f
Form feed
\b
Back space character
\
Single quote
\
Double quote
\\
Back space
Which of the following char declarations are valid?
1) char ch=a;//C.E:cannot find symbol(invalid)
2) char ch='ab';//C.E:unclosed character literal(invalid)
3) char ch=65536;//C.E:possible loss of precision(invalid)
4) char ch=\uface;//C.E:illegal character: \64206(invalid)
5) char ch='/n';//C.E:unclosed character literal(invalid)
6) none of the above.(valid)
String literals:
Any sequence of characters with in double quotes is treated as String
literal.
Example:
String s="bhaskar";(valid)
Diagram:
Arrays
1)
2)
3)
4)
5)
6)
7)
8)
9)
Introduction
Array declaration
Array construction
Array initialization
Array declaration, construction, initialization in a single line.
length Vs length() method
Anonymous arrays
Array element assignments
Array variable assignments.
An array is an indexed collection of fixed number of homogeneous data
elements.
The main advantage of arrays is we can represent multiple values with
the same name so that readability of the code will be improved.
But the main disadvantage of arrays is:
Fixed in size that is once we created an array there is no chance of
increasing or decreasing the size based on our requirement that is to
use arrays concept compulsory we should know the size in advance
which may not possible always.
We can resolve this problem by using collections.
12
Array declarations:
Single dimensional array declaration:
Example:
int[] a;//recommended to use because name is clearly separated from the
type
int []a;
int a[];
At the time of declaration we cant specify the size otherwise we will
get compile time error.
Example:
int[] a;//valid
int[5] a;//invalid
Two dimensional array declaration:
Example:
int[][] a;
int [][]a;
int a[][];
All are valid.
int[] []a;
int[] a[];
int []a[];
Three dimensional array declaration:
Example:
int[][][] a;
int [][][]a;
int a[][][];
int[] [][]a;
int[] a[][];
All are valid.
int[] []a[];
int[][] []a;
int[][] a[];
int []a[][];
int [][]a[];
Which of the following declarations are valid?
1) int[] a1,b1;//a-1,b-1(valid)
2) int[] a2[],b2;//a-2,b-1(valid)
3) int[] []a3,b3;//a-2,b-2(valid)
4) int[] a,[]b;//C.E:<identifier> expected(invalid)
13
Example:
For every array type corresponding classes are available but these
classes are part of java language and not available to the programmer
level.
Array Type
corresponding class name
int[]
[I
int[][]
[[I
double[]
[D
.
.
.
.
Rule 1:
At the time of array creation compulsory we should specify the size
otherwise we will get compile time error.
Example:
int[] a=new int[3];
int[] a=new int[];//C.E:array dimension missing
Rule 2:
It is legal to have an array with size zero in java.
Example:
int[] a=new int[0];
System.out.println(a.length);//0
Rule 3:
If we are taking array size with -ve int value then we will get runtime
exception saying NegativeArraySizeException.
Example:
14
Example 2:
int[][][] a=new int[2][][];
a[0]=new int[3][];
a[0][0]=new int[1];
a[0][1]=new int[2];
a[0][2]=new int[3];
15
a[1]=new int[2][2];
Diagram:
16
System.out.println(a);//[[I@3e25a5
System.out.println(a[0]);//[I@19821f
System.out.println(a[0][0]);//0
Diagram:
Example 3:
int[][] a=new int[2][];
System.out.println(a);//[[I@3e25a5
System.out.println(a[0]);//null
System.out.println(a[0][0]);//R.E:NullPointerException
Diagram:
Note: if we are trying to access array element with out of range index we
will get Runtime Exception saying ArrayIndexOutOfBoundsException.
Declaration construction and initialization of an array in a single
line:
We can perform declaration construction and initialization of an array
in a single line.
Example:
17
char[] ch={'a','e','i','o','u'};(valid)
String[] s={"balayya","venki","nag","chiru"};(valid)
We can extend this short cut even for multi dimensional arrays also.
Example:
int[][] a={{10,20,30},{40,50}};`
Diagram:
Example:
int[][][] a={{{10,20,30},{40,50}},{{60},{70,80},{90,100,110}}};
Diagram:
int[][][] a={{{10,20,30},{40,50}},{{60},{70,80},{90,100,110}}};
System.out.println(a[0][1][1]);//50(valid)
System.out.println(a[1][0][2]);//R.E:ArrayIndexOutOfBoundsException:
2(invalid)
System.out.println(a[1][2][1]);//100(valid)
System.out.println(a[1][2][2]);//110(valid)
System.out.println(a[2][1][0]);//R.E:ArrayIndexOutOfBoundsException:
2(invalid)
System.out.println(a[1][1][1]);//80(valid)
If we want to use this short cut compulsory we should perform
declaration, construction and initialization in a single line. If we are
trying to divide into multiple lines then we will get compile time error.
Example:
length Vs length():
length:
1) It is the final variable applicable only for arrays.
18
find
length() method:
1) It is a final method applicable for String objects.
2) It returns the no of characters present in the String.
Example:
String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7
In multidimensional arrays length variable represents only base size
but not total size.
Example:
int[][] a=new int[6][3];
System.out.println(a.length);//6
System.out.println(a[0].length);//3
Diagram:
Example:
int[] a=new int[]{10,20,30,40};(valid)
Example:
class Test
{
public static void main(String[] args)
{
System.out.println(sum(new int[]{10,20,30,40}));//100
}
public static int sum(int[] x)
{
int total=0;
for(int x1:x)
{
total=total+x1;
}
return total;
}
}
Array element assignments:
Case 1: In the case of primitive array as array element any type is allowed
which can be promoted to declared type.
Example 1: For the int type arrays the allowed array element types are
byte, short, char int.
int[] a=new int[10];
a[0]=97;//(valid)
a[1]='a';//(valid)
byte b=10;
a[2]=b;//(valid)
short s=20;
a[3]=s;//(valid)
a[4]=10l;//C.E:possible loss of precision
Example 2: For float type arrays the allowed element types are byte, short,
char, int, long, float.
Case 2: In the case of Object type arrays as array elements we can provide
either declared type objects or its child class objects.
Example 1:
Object[] a=new Object[10];
a[0]=new Integer(10);//(valid)
a[1]=new Object();//(valid)
20
a[2]=new String("bhaskar");//(valid)
Example 2:
Number[] n=new Number[10];
n[0]=new Integer(10);//(valid)
n[1]=new Double(10.5);//(valid)
n[2]=new String("bhaskar");//C.E:incompatible types//(invalid)
Diagram:
21
Note: In the case of object type arrays child type array can be assign to
parent type array variable.
Example:
String[] s={"A","B"};
Object[] o=s;
Case 2: Whenever we are assigning one array to another array internal
elements wont be copy just reference variables will be reassigned hence
sizes are not important but types must be matched.
Example:
int[] a={10,20,30,40,50,60,70};
int[] b={80,90};
a=b;//(valid)
b=a;//(valid)
Diagram:
a[1]=new int[4];
a=new int[4][3];
Diagram:
Types of Variables
Based the type of value represented by the variable all variables are
divided into 2 types. They are:
1) Primitive variables
2) Reference variables
Primitive variables: Primitive variables can be used to represent primitive
values.
Example: int x=10;
Reference variables: Reference variables can be used to refer objects.
Example: Student s=new Student();
Diagram:
24
Static variables:
If the value of a variable is not varied from object to object such type
of variables is not recommended to declare as instance variables. We
have to declare such type of variables at class level by using static
modifier.
In the case of instance variables for every object a separate copy will
be created but in the case of static variables for entire class only one
copy will be created and shared by every object of that class.
Static variables will be crated at the time of class loading and
destroyed at the time of class unloading hence the scope of the static
variable is exactly same as the scope of the .class file.
Static variables will be stored in method area. Static variables should
be declared with in the class directly but outside of any method or
block or constructor.
Static variables can be accessed from both instance and static areas
directly.
We can access static variables either by class name or by object
reference but usage of class name is recommended.
But within the same class it is not required to use class name we can
access directly.
1) Start JVM.
2) Create and start Main Thread by JVM.
3) Locate(find) Test.class by main Thread.
4) Load Test.class by main Thread.
5) Execution of main() method.
6) Unload Test.class
7) Terminate main Thread.
8) Shutdown JVM.
Example:
class Test
{
static int i=10;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.i);//10
System.out.println(Test.i);//10
System.out.println(i);//10
}
}
26
}
}
Example 2:
class Test
{
public static void main(String[] args)
{
try
{
int i=Integer.parseInt("ten");
}
catch(NullPointerException e)
{
}
}
}
Example:
Example:
class Test
{
public static void main(String[] args)
{
int x;
if(args.length>0)
{
x=10;
}
System.out.println(x);//C.E:variable x might not have been
initialized
}
}
Example:
class Test
{
public static void main(String[] args)
{
int x;
if(args.length>0)
{
x=10;
}
else
{
x=20;
}
System.out.println(x);
}
}
Output:
java Test x
29
10
java Test x y
10
java Test
20
It is never recommended to perform initialization for the local variables
inside logical blocks because there is no guarantee of executing that
block always at runtime.
It is highly recommended to perform initialization for the local variables
at the time of declaration at least with default values.
Note: The only applicable modifier for local variables is final. If we are
using any other modifier we will get compile time error.
Example:
class Test
{
public static void main(String[] args)
{
public int x=10;
private int x=10;
protected int x=10;
C.E: illegal start of expression
static int x=10;
volatile int x=10;
transient int x=10;
final int x=10;//(valid)
}
}
Conclusions:
1) For the static and instance variables it is not required to perform
initialization explicitly JVM will provide default values. But for the local
variables JVM wont provide any default values compulsory we should
perform initialization explicitly before using that variable.
2) For every object a separate copy of instance variable will be created
whereas for entire class a single copy of static variable will be created.
For every Thread a separate copy of local variable will be created.
3) Instance and static variables can be accessed by multiple Threads
simultaneously and hence these are not Thread safe but local variables
can be accessed by only one Thread at a time and hence local
variables are Thread safe.
UN initialized arrays
30
Example:
class Test
{
int[] a;
public static void main(String[] args)
{
Test t1=new Test();
System.out.println(t1.a);//null
System.out.println(t1.a[0]);//R.E:NullPointerException
}
}
Instance level:
Example 1:
int[] a;
System.out.println(obj.a);//null
System.out.println(obj.a[0]);//R.E:NullPointerException
Example 2:
int[] a=new int[3];
System.out.println(obj.a);//[I@3e25a5
System.out.println(obj.a[0]);//0
Static level:
Example 1:
static int[] a;
System.out.println(a);//null
System.out.println(a[0]);//R.E:NullPointerException
Example 2:
static int[] a=new int[3];
System.out.println(a);//[I@3e25a5
System.out.println(a[0]);//0
Local level:
Example 1:
int[] a;
System.out.println(a);
C.E: variable a might not have been
initialized
System.out.println(a[0]);
Example 2:
int[] a=new int[3];
System.out.println(a);//[I@3e25a5
System.out.println(a[0]);//0
31
We can call or invoke this method by passing any no. Of int values
including zero number.
Example:
class Test
{
public static void methodOne(int... x)
{
System.out.println("var-arg method");
}
public static void main(String[] args)
{
methodOne();
methodOne(10);
methodOne(10,20,30);
}
}
Output:
var-arg method
var-arg method
var-arg method
Internally var-arg parameter implemented by using single dimensional
array hence within the var-arg method we can different arguments by
using index.
Example:
class Test
{
32
Case 5:
class Test
{
public static void methodOne(int i)
{
System.out.println("general method");
}
public static void methodOne(int... i)
{
System.out.println("var-arg method");
}
public static void main(String[] args)
{
methodOne();//var-arg method
methodOne(10,20);//var-arg method
methodOne(10);//general method
}
}
In general var-arg method will get least priority that is if no other
method matched then only var-arg method will get the chance this is
exactly same as default case inside a switch.
Case 6: For the var-arg methods we can provide the corresponding type
array as argument.
Example:
class Test
{
{
System.out.println("var-arg method");
}
public static void main(String[] args)
{
methodOne(new int[]{10,20,30});//var-arg method
}
}
Case 7:
class Test
{
public void methodOne(int[] i){}
34
Example:
class Test
{
public static void main(String... args)
{
System.out.println("var-arg main method");//var-arg main
method
}
}
Case 2: Wherever var-arg parameter present we cant replace with single
dimensional array.
Example:
class Test
{
public static void methodOne(int[]... x)
{
for(int[] a:x)
{
System.out.println(a[0]);
}
}
public static void main(String[] args)
{
int[] l={10,20,30};
int[] m={40,50};
methodOne(l,m);
}
35
}
Output:
10
40
Analysis:
Main Method
Whether the class contains main() method or not and whether it is
properly declared or not these checkings are not responsibilities of the
compiler, at runtime JVM is responsible for this. If jvm unable to find
the required main() method then we will get runtime exception saying
NoSuchMethodError: main.
Example:
class Test
{}
Output:
javac Test.java
java Test R.E: NoSuchMethodError: main
JVM always searches for the main() method with the following
signature.
If we are performing any changes to the above signature then the code
wont run and will get Runtime exception saying NoSuchMethodError.
Anyway the following changes are acceptable to main() method.
1) The order of modifiers is not important that is instead of public static
we can take static public.
2) We can declare string[] in any acceptable form
1) String[] args
2) String []args
36
3) String args[]
3) Instead of args we can use any valid java identifier.
4) We can replace string[] with var-arg parameter.
Example:
main(String... args)
5) main() method can be declared with the following modifiers.
final, synchronized, strictfp.
Which of the following main() method declarations are valid?
1) public static void main(String args){}(invalid)
2) public synchronized final strictfp void main(String[] args){} (invalid)
3) public static void Main(String... args){} (invalid)
4) public static int main(String[] args){}//int return type we can't take//
(invalid)
5) public static synchronized final strictfp void main(String... args){}
(valid)
In which of the above cases we will get compile time error?
No case, in all the cases we will get runtime exception.
Overloading of the main() method is possible but JVM always calls
string[] argument main() method only.
Example:
class Test
{
public static void main(String[] args)
{
System.out.println("String[] array main method"); overloaded
methods
}
public static void main(int[] args)
{
System.out.println("int[] array main method");
}
}
Output:
String[] array main method
The other overloaded method we have to call explicitly then only it will
be executed.
Inheritance concept is applicable for static methods including main()
method hence while executing child class if the child class doesnt
contain main() method then the parent class main() method will be
executed.
Example 1:
37
class Parent
{
public static void main(String[] args)
{
System.out.println("parent main");
}
}
class Child extends Parent
{}
Analysis:
Example 2:
class Parent
{
public static void main(String[] args)
{
System.out.println("parent main");
}
}
class Child extends Parent
{
public static void main(String[] args)
{
System.out.println("Child main");
}
}
Analysis:
38
Parent.java
Parent.java
Example 1:
class Test
{
public static void main(String[] args)
{
for(int i=0;i<=args.length;i++)
{
System.out.println(args[i]);
}
}
}
Output:
java Test x y z
ArrayIndexOutOfBoundsException: 3
Example 2:
Replace i<=args.length with i<args.length then it will run successfully.
Within the main() method command line arguments are available in
the form of String hence + operator acts as string concatenation but
not arithmetic addition.
Example:
class Test
39
{
public static void main(String[] args)
{
System.out.println(args[0]+args[1]);
}
}
Output:
E:\SCJP>javac Test.java
E:\SCJP>java Test 10 20
1020
Space is the separator between 2 command line arguments and if our
command line argument itself contains space then we should enclose
with in double quotes.
Example:
class Test
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}
Output:
E:\SCJP>javac Test.java
E:\SCJP>java Test "vijaya bhaskar"
Vijaya bhaskar
Java coding standards
It is highly recommended to follow coding standards.
Whenever we are writing any component the name of the component
should reflect the purpose or functionality.
Example:
41
Example:
42
43
Case1:
If there is no public class then we can use any name for java source file
there are no restrictions.
Example:
A.java
B.java
C.java
Bhaskar.java
case2:
44
Cae3:
If both B and C classes are declared as public and name of the file is
B.java then we will get compile time error saying class C is public,
should be declared in a file named C.java.
It is highly recommended to take only one class for source file and
name of the program (file) must be same as class name. This approach
improves readability and understandability of the code.
Example:
class A
{
public static void main(String args[]){
System.out.println("A class main method is executed");
}
}
class B
{
public static void main(String args[]){
System.out.println("B class main method is executed");
}
}
class C
{
public static void main(String args[]){
System.out.println("C class main method is executed");
}
}
class D
{
}
Output:
D:\Java>java A
A class main method is executed
45
D:\Java>java B
B class main method is executed
D:\Java>java C
C class main method is executed
D:\Java>java D
Exception in thread "main" java.lang.NoSuchMethodError: main
D:\Java>java Bhaskar
Exception in thread "main" java.lang.NoClassDefFoundError: Bhaskar
We can compile a java program but not java class in that program for
every class one dot class file will be created.
We can run a java class but not java source file whenever we are trying
to run a class the corresponding class main method will be executed.
If the class wont contain main method then we will get runtime
exception saying NoSuchMethodError: main.
If we are trying to execute a java class and if the corresponding .class
file is not available then we will get runtime execution saying
NoClassDefFoundError: Bhaskar.
Import statement:
class Test{
public static void main(String args[]){
ArrayList l=new ArrayList();
}
}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:3: cannot find symbol
symbol : class ArrayList
location: class Test
ArrayList l=new ArrayList();
Test.java:3: cannot find symbol
symbol : class ArrayList
location: class Test
ArrayList l=new ArrayList();
We can resolve this problem by using fully qualified name
java.util.ArrayList l=new java.util.ArrayList();. But problem with using
fully qualified name every time is it increases length of the code and
reduces readability.
We can resolve this problem by using import statements.
Example:
46
import java.util.ArrayList;
class Test{
public static void main(String args[]){
ArrayList l=new ArrayList();
}
}
Output:
D:\Java>javac Test.java
Hence whenever we are using import statement it is not require to use
fully qualified names we can use short names directly. This approach
decreases length of the code and improves readability.
Case 1: Types of Import Statements:
There are 2 types of import statements.
1) Explicit class import
2) Implicit class import.
Explicit class import:
Example: Import java.util.ArrayList
This type of import is highly recommended to use because it improves
readability of the code.
Best suitable for Hi-Tech city where readability is important.
Implicit class import:
Example: import java.util.*;
It is never recommended to use because it reduces readability of the
code.
Bet suitable for Ameerpet where typing is important.
Case2:
Which of the following import statements are valid?
Case3:
consider the following code.
class MyArrayList extends java.util.ArrayList
{
}
The code compiles fine even though we are not using import
statements because we used fully qualified name.
47
48
Case7:
In any java program the following 2 packages are not require to import
because these are available by default to every java program.
1. java.lang package
2. default package(current working directory)
Case8:
Import statement is totally compile time concept if more no of
imports are there then more will be the compile time but there is no
change in execution time.
Difference between C language #include and java language import.
In the case of C language #include all the header files will be loaded at
the time of include statement hence it follows static loading.
But in java import statement no .class will be loaded at the time of
import statements in the next lines of the code whenever we are using
a particular class then only corresponding .class file will be loaded.
Hence it follows dynamic loading or load-on demand or load-onfly.
Static import:
This concept introduced in 1.5 versions. According to sun static import
improves readability of the code but according to worldwide
programming exports (like us) static imports creates confusion and
49
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.4302853847363891
Explain about System.out.println statement?
Example 1 and example 2:
Example 3:
import static java.lang.System.out;
class Test
{
public static void main(String args[]){
out.println("hello");
out.println("hi");
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
hi
Example 4:
import static java.lang.Integer.*;
import static java.lang.Byte.*;
class Test
{
51
52
Diagram:
System.out.println("package demo");
}
}
Javac HydJobs.java generated class file will be placed in current
working directory.
Diagram:
Javac d . HydJobs.java
-d means destination to place generated class files . means current
working directory.
Generated class file will be placed into corresponding package
structure.
Diagram:
Example:
private class Test
{
public static void main(String args[]){
int i=0;
for(int j=0;j<3;j++)
{
i=i+j;
}
System.out.println(i);
}}
OUTPUT:
Compile time error.
D:\Java>javac Test.java
Test.java:1: modifier private not allowed here
private class Test
But For the inner classes the following modifiers are allowed.
Diagram:
What is the difference between access specifier and access
modifier?
56
In
EXAMPLE:
Program1:
package pack1;
public class Test
{
public void methodOne(){
System.out.println("test class methodone is executed");
}}
Compile the above program:
D:\Java>javac -d . Test.java
Program2:
package pack2;
import pack1.Test;
class Test1
{
public static void main(String args[]){
Test t=new Test();
t.methodOne();
}}
OUTPUT:
D:\Java>javac -d . Test1.java
D:\Java>java pack2.Test1
Test class methodone is executed.
If class Test is not public then while compiling Test1 class we will get
compile time error saying pack1.Test is not public in pack1;
cannot be accessed from outside package.
Default Classes:
If a class declared as the default then we can access that class only
within the current package hence default access is also known as
package level access.
57
Example:
Program 1:
package pack1;
class Test
{
public void methodOne(){
System.out.println("test class methodone is executed");
}}
Program 2:
package pack1;
import pack1.Test;
class Test1
{
public static void main(String args[]){
Test t=new Test();
t.methodOne();
}}
OUTPUT:
D:\Java>javac -d . Test.java
D:\Java>javac -d . Test1.java
D:\Java>java pack1.Test1
Test class methodone is executed
Final Modifier:
Final Methods:
Program 2:
class child extends Parent
{
public void marriage(){
System.out.println("Thamanna");
}}
OUTPUT:
Compile time error.
D:\Java>javac Parent.java
D:\Java>javac child.java
child.java:3: marriage() in child cannot override marriage() in
Parent; overridden method is final
public void marriage(){
Final Class:
If a class declared as the final then we cannt creates the child class
that is inheritance concept is not applicable for final classes.
EXAMPLE:
Program 1:
final class Parent
{
}
Program 2:
class child extends Parent
{
}
OUTPUT:
Compile time error.
D:\Java>javac Parent.java
D:\Java>javac child.java
child.java:1: cannot inherit from final Parent
class child extends Parent
Note: Every method present inside a final class is always final by
default whether we are declaring or not. But every variable present
inside a final class need not be final.
Example:
final class parent
{
static int x=10;
static
{
59
x=999;
}}
The main advantage of final keyword is we can achieve security.
Whereas the main disadvantage is we are missing the key benefits of
oops: polymorsim (because of final methods), inheritance (because of
final classes) hence if there is no specific requirement never
recommended to use final keyboard.
Abstract Modifier:
Abstract is the modifier applicable only for methods and classes but
not for variables.
Abstract Methods:
Even though we dont have implementation still we can declare a
method with abstract modifier. That is abstract methods have only
declaration but not implementation. Hence abstract method
declaration should compulsory ends with semicolon.
EXAMPLE:
60
Abstract class:
For any java class if we are not allow to create an object such type of
class we have to declare with abstract modifier that is for abstract
class instantiation is not possible.
Example:
abstract class Test
{
public static void main(String args[]){
Test t=new Test();
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: Test is abstract; cannot be instantiated
Test t=new Test();
What is the difference between abstract class and abstract method?
If a class contain at least on abstract method then compulsory the
corresponding class should be declare with abstract modifier. Because
implementation is not complete and hence we cant create object of
that class.
Even though class doesnt contain any abstract methods still we can
declare the class as abstract that is an abstract class can contain zero
no of abstract methods also.
Example1: HttpServlet class is abstract but it doesnt contain any abstract
method.
61
}
class child extends Parent
{
public void methodOne(){}
}
Output:
Compile time error.
D:\Java>javac Parent.java
Parent.java:6: child is not abstract and does not override abstract method
methodTwo() in Parent
class child extends Parent
If we declare class child as abstract then the code compiles fine but
child of child is responsible to provide implementation for methodTwo().
What is the difference between final and abstract?
For abstract methods compulsory we should override in the child class
to provide implementation. Whereas for final methods we cant
override hence abstract final combination is illegal for methods.
For abstract classes we should compulsory create child class to provide
implementation whereas for final class we cant create child class.
Hence final abstract combination is illegal for classes.
Final class cannot contain abstract methods whereas abstract class can
contain final method.
Example:
Note:
Usage of abstract methods, abstract classes and interfaces is always
good programming practice.
Strictfp:
strictfp is the modifier applicable for methods and classes but not for
variables.
Strictfp modifier introduced in 1.2 versions.
63
Member modifiers:
Public members:
If a member declared as the public then we can access that member
from anywhere but the corresponding class must be visible hence
before checking member visibility we have to check class visibility.
Example:
Program 1:
package pack1;
class A
{
public void methodOne(){
System.out.println("a class method");
}}
D:\Java>javac -d . A.java
Program 2:
package pack2;
64
import pack1.A;
class B
{
public static void main(String args[]){
A a=new A();
a.methodOne();
}}
Output:
Compile time error.
D:\Java>javac -d . B.java
B.java:2: pack1.A is not public in pack1; cannot be accessed from outside
package
import pack1.A;
In the above program even though methodOne() method is public we
cant access from class B because the corresponding class A is not
public that is both classes and methods are public then only we can
access.
Default member:
If a member declared as the default then we can access that member
only within the current package hence default member is also known
as package level access.
Example 1:
Program 1:
package pack1;
class A
{
void methodOne(){
System.out.println("methodOne is executed");
}}
Program 2:
package pack1;
import pack1.A;
class B
{
public static void main(String args[]){
A a=new A();
a.methodOne();
}}
Output:
D:\Java>javac -d . A.java
65
D:\Java>javac -d . B.java
D:\Java>java pack1.B
methodOne is executed
Example 2:
Program 1:
package pack1;
class A
{
void methodOne(){
System.out.println("methodOne is executed");
}}
Program 2:
package pack2;
import pack1.A;
class B
{
public static void main(String args[]){
A a=new A();
a.methodOne();
}}
Output:
Compile time error.
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
B.java:2: pack1.A is not public in pack1; cannot be accessed from outside
package
import pack1.A;
Private members:
If a member declared as the private then we can access that member
only with in the current class.
Private methods are not visible in child classes where as abstract
methods should be visible in child classes to provide implementation
hence private, abstract combination is illegal for methods.
Protected members:
If a member declared as the protected then we can access that
member within the current package anywhere but outside package
only in child classes.
Protected=default+kids.
We can access protected members within the current package
anywhere either by child reference or by parent reference but from
66
67
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:1: variable i might not have been initialized
class Test
Rule:
For the final instance variables we should perform initialization before
constructor completion. That is the following are various possible
places for this.
1) At the time of declaration:
Example:
class Test
{
final int i=10;
}
Output:
D:\Java>javac Test.java
D:\Java>
2) Inside instance block:
Example:
class Test
{
final int i;
{
i=10;
}}
Output:
D:\Java>javac Test.java
D:\Java>
3) Inside constructor:
Example:
class Test
{
final int i;
Test()
{
i=10;
}}
Output:
D:\Java>javac Test.java
70
D:\Java>
If we are performing initialization anywhere else we will get compile
time error.
Example:
class Test
{
final int i;
public void methodOne(){
i=10;
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to final variable i
i=10;
Final static variables:
If the value of a variable is not varied from object to object such type
of variables is not recommended to declare as the instance variables.
We have to declare those variables at class level by using
static modifier.
For the static variables it is not required to perform initialization
explicitly jvm will always provide default values.
Example:
class Test
{
static int i;
public static void main(String args[]){
System.out.println("value of i is :"+i);
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
Value of i is: 0
If the static variable declare as final then compulsory we should
perform initialization explicitly whether we are using or not otherwise
we will get compile time error.
Example:
71
Rule:
For the final static variables we should perform initialization before
class loading completion otherwise we will get compile time error. That
is the following are possible places.
1) At the time of declaration:
Example:
class Test
{
final static int i=10;
}
Output:
D:\Java>javac Test.java
D:\Java>
2) Inside static block:
Example:
class Test
{
final static int i;
static
{
i=10;
}}
Output:
Compile successfully.
If we are performing initialization anywhere else we will get compile
time error.
Example:
class Test
{
final static int i;
public static void main(String args[]){
i=10;
}}
72
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to final variable i
i=10;
Final local variables:
To meet temporary requirement of the programmer sometime we can
declare the variable inside a method or block or constructor such type
of variables are called local variables.
For the local variables jvm wont provide any default value compulsory
we should perform initialization explicitly before using that variable.
Example:
class Test
{
public static void main(String args[]){
int i;
System.out.println("hello");
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
Hello
Example:
class Test
{
public static void main(String args[]){
int i;
System.out.println(i);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: variable i might not have been initialized
System.out.println(i);
Even though local variable declared as the final before using only we
should perform initialization.
Example:
class Test
{
73
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: illegal start of expression
private int x=10;
Formal parameters:
The formal parameters of a method are simply access local variables of
that method hence it is possible to declare formal parameters as final.
If we declare formal parameters as final then we cant change its value
within the method.
Example:
74
Static modifier:
Static is the modifier applicable for methods, variables and blocks.
We cant declare a class with static but inner classes can be
declaring as the static.
In the case of instance variables for every object a separate copy will
be created but in the case of static variables a single copy will be
created at class level and shared by all objects of that class.
Example:
Output:
D:\Java>javac Test.java
D:\Java>java Test
888.....20
Instance variables can be accessed only from instance area directly
and we cant access from static area directly.
But static variables can be accessed from both instance and static
areas directly.
1) Int x=10;
2) Static int x=10;
3) Public void methodOne(){
75
System.out.println(x);
}
4) Public static void methodOne(){
System.out.println(x);
}
Which are the following declarations are allow within the same class
simultaneously?
a) 1 and 3
Example:
class Test
{
int x=10;
public void methodOne(){
System.out.println(x);
}}
Output:
Compile successfully.
b) 1 and 4
Example:
class Test
{
int x=10;
public static void methodOne(){
System.out.println(x);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: non-static variable x cannot be referenced from a static context
System.out.println(x);
c) 2 and 3
Example:
class Test
{
static int x=10;
public void methodOne(){
System.out.println(x);
}}
Output:
Compile successfully.
d) 2 and 4
Example:
class Test
76
{
static int x=10;
public static void methodOne(){
System.out.println(x);
}}
Output:
Compile successfully.
e) 1 and 2
Example:
class Test
{
int x=10;
static int x=10;
}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: x is already defined in Test
static int x=10;
f) 3 and 4
Example:
class Test{
public void methodOne(){
System.out.println(x);
}
public static void methodOne(){
System.out.println(x);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: methodOne() is already defined in Test
public static void methodOne(){
Overloading concept is applicable for static method including main method
also.
Example:
77
Example:
Output:
Native modifier:
Native is a modifier applicable only for methods but not for variables and
classes.
The methods which are implemented in non java are called native methods or
foreign methods.
The main objectives of native keyword are:
To improve performance of the system.
To use already existing legacy non java code.
To use native keyword:
Pseudo code:
Synchronized is the modifier applicable for methods and blocks but not
for variables and classes.
If a method or block declared with synchronized keyword then at a
time only one thread is allow to execute that method or block on the
given object.
The main advantage of synchronized keyword is we can resolve data
inconsistency problems, but the main disadvantage is it increases
waiting time of the threads and effects performance of the system.
Hence if there is no specific requirement never recommended to use
synchronized keyword.
Transient modifier:
Transient is the modifier applicable only for variables but not for
methods and classes.
At the time of serialization if we dont want to serialize the value of a
particular variable to meet the security constraints then we should
declare that variable with transient modifier.
At the time of serialization jvm ignores the original value of the
transient variable and save default value that is transient means not
to serialize.
Static variables are not part of object state hence serialization concept
is not applicable for static variables duo to this declaring a static
variable as transient there is no use.
Final variables will be participated into serialization directly by their
values due to this declaring a final variable as transient there is no
impact.
Volatile modifier:
Volatile is the modifier applicable only for variables but not for classes
and methods.
If the value of variable keeps on changing such type of variables we
have to declare with volatile modifier.
If a variable declared as volatile then for every thread a separate local
copy will be created by the jvm, all intermediate modifications
performed by the thread will takes place in the local copy instead of
master copy.
Once the value got finalized before terminating the thread that final
value will be updated in master copy.
The main advantage of volatile modifier is we can resolve data
inconsistency problems, but creating and maintaining a separate copy
for every thread increases complexity of the programming and effects
80
Modifier
Classes
Outer
Inner
Metho
ds
Variabl
es
Blocks
Interfac
es
Enum
Construct
ors
Public
Private
Protected
Default
Final
Abstract
Strictfp
Static
Synchroni
zed
Native
Transient
Volatile
Summary of modifier:
The modifiers which are applicable for inner classes but not for outer
classes are private, protected, static.
The modifiers which are applicable only for methods native.
The modifiers which are applicable only for variables transient and
volatile.
The modifiers which are applicable for constructor public, private,
protected, default.
The only applicable modifier for local variables is final.
Interfaces:
1) Introduction
2) Interface declarations and implementations.
81
3)
4)
5)
6)
Extends vs implements
Interface methods
Interface variables
Interface naming conflicts
a) Method naming conflicts
b) Variable naming conflicts
7) Marker interface
8) Adapter class
9) Interface vs abstract class vs concrete class.
10)
Difference between interface and abstract class?
11)
Conclusions
Def1: Any service requirement specification (srs) is called an interface.
Example1: Sun people responsible to define JDBC API and database vendor
will provide implementation for that.
Diagram:
Example2: Sun people define SERVLET API to develop web applications web
server vendor is responsible to provide implementation.
Diagram:
Def2: From the client point of view an interface define the set of services
what his excepting. From the service provider point of view an interface
defines the set of services what is offering. Hence an interface is considered
as a contract between client and service provider.
Example: ATM GUI screen describes the set of services what bank people
offering, at the same time the same GUI screen the set of services what
82
customer his excepting hence this GUI screen acts as a contract between
bank and customer.
Def3: Inside interface every method is always abstract whether we are
declaring or not hence interface is considered as 100% pure abstract class.
Summery def: Any service requirement specification (SRS) or any contract
between client and service provider or 100% pure abstract classes is
considered as an interface.
Declaration and implementation of an interface:
Note1: Whenever we are implementing an interface compulsory for every
method of that interface we should provide implementation
otherwise we have to declare class as abstract in that case child class
is responsible to provide implementation for remaining methods.
Note2: Whenever we are implementing an interface method compulsory it
should be declared as public otherwise we will get compile time
error.
Example:
interface Interf
{
void methodOne();
void methodTwo();
}
}
interface Three extends One,Two
{
}
1) Which of the following is true?
1. A class can extend any no. Of classes at a time.
2. An interface can extend only one interface at a time.
3. A class can implement only one interface at a time.
4. A class can extend a class and can implement an interface but
not both simultaneously.
5. None of the above.
Ans: 5
2) Consider the expression X extends Y for which of the possibility of X
and Y this expression is true?
1. Both x and y should be classes.
2. Both x and y should be interfaces.
3. Both x and y can be classes or can be interfaces.
4. No restriction.
Ans: 3
3) X extends Y, Z?
X, Y, Z should be interfaces.
4) X extends Y implements Z?
X, Y should be classes.
Z should be interface.
5) X implements Y, Z?
X should be class.
Y, Z should be interfaces.
6) X implements Y extend Z?
Example:
interface One{
}
class Two {
}
class Three implements One extends Two{
}
Output:
Compile time error.
D:\Java>javac Three.java
Three.java:5: '{' expected
class Three implements One extends Two{
85
86
87
Example 2:
class Test implements Interf
{
public static void main(String args[]){
int x=20;
//here we declaring the variable x.
System.out.println(x);
}
}
Output:
D:\Java>javac Test.java
D:\Java>java Test
20
Interface naming conflicts:
Method naming conflicts:
Case 1:
If two interfaces contain a method with same signature and same
return type in the implementation class only one method
implementation is enough.
Example 1:
interface Left
{
public void methodOne();
}
Example 2:
interface Right
{
public void methodOne();
}
Example 3:
88
89
}
}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
D:\Java>java Test
888
999
Marker interface: if an interface doesnt contain any methods and by
implementing that interface if our object gets some ability such type of
interfaces are called Marker interface (or) Tag interface (or) Ability interface.
Example:
Serilizable
cloneable
RandomAccess
These are marked for some ability
SingleThreadModel
.
.
.
.
Example 1: By implementing Serilizable interface we can send that object
across the network and we can save state of an object into a file.
Example 2: By implementing SingleThreadModel interface Servlet can
process only one client request at a time so that we can get Thread Safety.
Example 3: By implementing Cloneable interface our object is in a position
to provide exactly duplicate cloned object.
Without having any methods in marker interface how objects will
get ability?
Internally JVM will provide required ability.
Why JVM is providing the required ability?
To reduce complexity of the programming.
Is it possible to create our own marker interface?
Yes, but customization of JVM is required.
Adapter class:
Adapter class is a simple java class that implements an interface only
with empty implementation for every method.
If we implement an interface directly for each and every method
compulsory we should provide implementation whether it is required or
91
}
Example 2:
public class Test extend AdapterX{{
public void m3(){
}}
Example:
about
not
completely
(partial
implementation)
then
we
should go for abstract class.
}
class child extends Parent{
child(){
System.out.println(this.hashCode());
}
}
class Test{
public static void main(String args[]){
child c=new child();
System.out.println(c.hashCode());
}
}
Every method present inside interface is abstract but in abstract
class also we can take only abstract methods then what is the need
of interface concept?
We can replace interface concept with abstract class. But it is not a
good programming practice. We are misusing the roll of abstract class.
95
Diagram 2:
Example:
Expression
Initial value of
Final value of x Final value of y
x
Y=++x;
10
11
11
Y=x++;
10
11
10
Y=--x;
10
9
9
Y=x--;
10
9
10
We can apply increment or decrement operator only for variables but
not for constant values.
96
Example:
Example:
Example 2:
In the case of increment or decrement operator the required typecasting will be performed automatically by the compiler.
Example:
byte b=10;
b++;
System.out.println(b);//11
Arithmetic operators: (+,-,*, /, %)
98
Example:
System.out.println('a'+1);//98
System.out.println('a'+'b');//195
System.out.println(10+0.5);//10.5
System.out.println('a'+3.5);//100.5
Infinity:
In the case of integral arithmetic (byte, short, int, long) there is no way
to represent infinity.
Hence if infinity is the result then we will get ArithmeticException.
Example:
Example 3:
101
Diagram:
For any object reference of, r==null is always false. But null==null is
true.
== Vs .equals():
==operator is always meant for reference comparison whereas
.equals() method mostly meant for content comparison.
Example:
String s1=new String("bhaskar");
String s2=new String("bhaskar");
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//true
Diagram:
Instanceof operator:
We can use this operator to check whether the given object is of
particular type (or) not.
Syntax:
Example:
Thread t=new Thread();
System.out.println(t instanceof Thread);//true
System.out.println(t instanceof Object);//true
System.out.println(t instanceof Runnable);//true
Diagram:
103
Note:
To use instanceof operator compulsory there should be some
relationship between argument types (either parent-child (or) childparent (or) same type) otherwise we will get compile time error saying
inconvertible types.
Example:
We can apply this operator only for integral types but not for boolean
types.
Example 1:
Example 2:
System.out.println(~4);//5
Diagram:
System.out.println(!true);//false
System.out.println(!false);//true
Summary:
&
|
Applicable for both boolean and integral types.
^
~-------Applicable for integral types only.
! --------Applicable for boolean types only.
Short circuit (&&, ||) operators:
These operators are exactly same as normal bitwise operators &, |
except the following differences.
&,|
&&,||
1) Both arguments should be
1) Second argument evaluation is
evaluated always.
optional.
2) Relatively performance is low.
2) Relatively performance is high.
3) Applicable for both integral and
3) Applicable only for boolean
105
boolean types.
types but not for integral types.
1) r1&&r2
r2 will be evaluated if and only if r1 is true.
2) r1||r2
r2 will be evaluated if and only if r1 is false.
Example 1:
class OperatorsDemo
{
public static void main(String[] args)
{
int x=10, y=15;
if(++x>10(operator)++y<15)
{
++x;
}
else
{
++y;
}
System.out.println(x+"------------"+y);
}
}
Output:
operator
x
y
&
11
17
|
12
16
&&
11
17
||
12
15
Example 2:
class OperatorsDemo
{
public static void main(String[] args)
{
int x=10;
if(++x<10(operator)x/0>10)
{
System.out.println("hello");
}
else
{
System.out.println("hi");
106
}
}
}
&&
&
Output: Hi
Output: R.E: Exception in thread
"main"
java.lang.ArithmeticException: / by
zero
Type-cast operator (primitive type casting):
There are two types of primitive type casting.
1) Implicit type casting.
2) Explicit type casting.
Implicit type casting:
Compiler is the responsible for this typecasting.
Whenever we are assigning smaller data type value to the bigger data
type variable this type casting will be performed.
Also known as widening or up casting.
There is no lose of information in this type casting.
The following are various possible implicit type casting.
Diagram:
Example 1:
int x='a';
System.out.println(x);//97
Note: Compiler converts char to int type automatically by implicit
casting.
Example 2:
double d=10;
System.out.println(d);//10.0
Note: Compiler converts int to double type automatically by implicit
casting.
Explicit type casting:
Programmer is responsible for this type casting.
Whenever we are assigning bigger data type value to the smaller
type variable then explicit type casting is required.
Also known as Narrowing or down casting.
There may be a chance of lose of information in this type casting.
The following are various possible conversions where explicit
casting is required.
107
type
type
data
type
Diagram:
Example 1:
Example 2:
int x=130;
byte b=(byte)x;
System.out.println(b);//-126
Analysis:
Whenever we are assigning bigger data type value to the smaller data
type variable by explicit type casting the most significant bit(MSB)will
be lost.
Example:
int x=150;
short s=(short)x;
System.out.println(s);//150
byte b=(byte)x;
System.out.println(b);//-106
Whenever we are assigning floating point data types to the integer
data type by explicit type casting the digits after the decimal point will
be loosed.
Example:
108
Assignment operators:
They are three types of assignment operators.
Simple assignment:
Example: int x=10;
Chained assignment:
Example:
int a,b,c,d;
a=b=c=d=20;
System.out.println(a+"---"+b+"---"+c+"---"+d);//20---20---20---20
We cant perform chained assignment directly at the time of
declaration.
Example 1:
Example 2:
int a,b,c,d;
a=b=c=d=30;
Compound assignment:
Sometimes we can mix assignment operator with some other operator
to form compound assignment operator.
The following is the list of all possible compound assignment operators
in java.
Example 1:
109
Example 3:
Conditional operator:
The only ternary operator which is available in java is conditional
operator.
Example 1:
int x=(10>20)?30:40;
System.out.println(x);//40
We can perform nesting of conditional operator also.
Example 2:
Example 5:
Example 6:
final int a=10,b=20;
byte c1=(a>b)?30:40;
byte c2=(a<b)?30:40;
System.out.println(c1);//40
System.out.println(c2);//30
new operator:
110
return i;
}
}
Example 1:
Example 2:
int i=1;
i+=++i + i++ + ++i + i++;
System.out.println(i);//13Analysis:
i=i+ ++i + i++ + ++i + i++;
i=1+2+2+4+4;
i=13;
112
Flow Control
Flow control describes the order in which all the statements will be
executed at run time.
Diagram:
Selection statements:
1. if-else:
Syntax:
int x=10;
if(x=20)
{
System.out.println("hello");
}else{
System.out.println("hi");
}}}
OUTPUT:
Compile time error
D:\Java>javac ExampleIf.java
ExampleIf.java:4: incompatible types
found : int
required: boolean
if(x=20)
EXAMPLE 3:
public class ExampleIf{
public static void main(String args[]){
int x=10;
if(x==20)
{
System.out.println("hello");
}else{
System.out.println("hi");
}}}
OUTPUT:
Hi
EXAMPLE 4:
public class ExampleIf{
public static void main(String args[]){
boolean b=false;
if(b=true)
{
System.out.println("hello");
}else{
System.out.println("hi");
}}}
OUTPUT:
Hello
EXAMPLE 5:
public class ExampleIf{
public static void main(String args[]){
boolean b=false;
if(b==true)
{
System.out.println("hello");
}else{
114
System.out.println("hi");
}}}
OUTPUT:
Hi
Both else and curly braces are optional.
Without curly braces we can take only one statement under if, but it
should not be declarative statement.
EXAMPLE 6:
public class ExampleIf{
public static void main(String args[]){
if(true)
System.out.println("hello");
}}
OUTPUT:
Hello
EXAMPLE 7:
public class ExampleIf{
public static void main(String args[]){
if(true);
}}
OUTPUT:
No output
EXAMPLE 8:
public class ExampleIf{
public static void main(String args[]){
if(true)
int x=10;
}}
OUTPUT:
Compile time error
D:\Java>javac ExampleIf.java
ExampleIf.java:4: '.class' expected
int x=10;
ExampleIf.java:4: not a statement
int x=10;
EXAMPLE 9:
public class ExampleIf{
public static void main(String args[]){
if(true){
int x=10;
}}}
OUTPUT:
D:\Java>javac ExampleIf.java
D:\Java>java ExampleIf
EXAMPLE 10:
115
OUTPUT:
Hello
Hi
Semicolon is a valid java statement which is call empty statement and
it wont produce any output.
If several options are available then it is not recommended to use ifelse we should go for switch statement.
Switch:
Syntax:
switch(x)
{
case 1:
action1
case 2:
action2
.
.
.
default:
default action
}
Curly braces are mandatory.
Both case and default are optional.
Every statement inside switch must be under some case (or) default.
Independent statements are not allowed.
EXAMPLE 1:
public class ExampleSwitch{
public static void main(String args[]){
switch(x)
{
System.out.println("hello");
}}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleSwitch.java
ExampleSwitch.java:5: case, default, or '}' expected
System.out.println("hello");
116
Until 1.4 version the allow types for the switch argument are byte,
short, char, int but from 1.5 version on wards the corresponding
wrapper classes (Byte, Short, Character, Integer) and enum types
are allowed.
DIAGRAM:
System.out.println("20");
}}}
OUTPUT:
10
20
Switch argument and case label can be expressions also, but case
should be constant expression.
EXAMPLE 4:
public class ExampleSwitch{
public static void main(String args[]){
int x=10;
switch(x+1)
{
case 10:
case 10+20:
case 10+20+30:
}}}
OUTPUT:
No output.
Every case label should be within the range of switch argument type.
EXAMPLE 5:
public class ExampleSwitch{
public static void main(String args[]){
byte b=10;
switch(b)
{
case 10:
System.out.println("10");
case 100:
System.out.println("100");
case 1000:
System.out.println("1000");
}}}
OUTPUT:
Compile time error
D:\Java>javac ExampleSwitch.java
ExampleSwitch.java:10: possible loss of precision
found : int
required: byte
case 1000:
Duplicate case labels are not allowed.
EXAMPLE 6:
public class ExampleSwitch{
public static void main(String args[]){
int x=10;
118
switch(x)
{
case 97:
System.out.println("97");
case 99:
System.out.println("99");
case 'a':
System.out.println("100");
}}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleSwitch.java
ExampleSwitch.java:10: duplicate case label
case 'a':
CASE SUMMARY:
DIAGRAM:
}}}
OUTPUT:
X=0
x=1
x=2
x=3
0
1
2
default
1
default
DEFAULT CASE:
Within the switch we can take the default anywhere, but at most once
it is convention to take default as last case.
EXAMPLE 8:
public class ExampleSwitch{
public static void main(String args[]){
int x=0;
switch(x)
{
default:
System.out.println("default");
case 0:
System.out.println("0");
break;
case 1:
System.out.println("1");
case 2:
System.out.println("2");
}}}
OUTPUT:
X=0
x=1
x=2
x=3
0
1
2
default
2
ITERATIVE STATEMENTS:
While loop: if we dont know the no of iterations in advance then best loop
is while loop:
EXAMPLE 1:
while(rs.next())
{
}
EXAMPLE 2:
while(e.hasMoreelEments())
{
---------------------------}
EXAMPLE 3:
while(itr.hasNext())
120
{
---------------------------}
The argument to the while statement should be Boolean type. If we are
using any other type we will get compile time error.
EXAMPLE 1:
public class ExampleWhile{
public static void main(String args[]){
while(1)
{
System.out.println("hello");
}}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleWhile.java
ExampleWhile.java:3: incompatible types
found : int
required: boolean
while(1)
Curly braces are optional and without curly braces we can take only
one statement which should not be declarative statement.
EXAMPLE 2:
public class ExampleWhile{
public static void main(String args[]){
while(true)
System.out.println("hello");
}}
OUTPUT:
Hello (infinite times).
EXAMPLE 3:
public class ExampleWhile{
public static void main(String args[]){
while(true);
}}
OUTPUT:
No output.
EXAMPLE 4:
public class ExampleWhile{
121
System.out.println("hello");
}
System.out.println("hi");
}}
OUTPUT:
D:\Java>javac ExampleWhile.java
ExampleWhile.java:4: unreachable statement
{
EXAMPLE 8:
public class ExampleWhile{
public static void main(String args[]){
int a=10,b=20;
while(a<b)
{
System.out.println("hello");
}
System.out.println("hi");
}}
OUTPUT:
Hello (infinite times).
EXAMPLE 9:
public class ExampleWhile{
public static void main(String args[]){
final int a=10,b=20;
while(a<b)
{
System.out.println("hello");
}
System.out.println("hi");
}}
OUTPUT:
Compile time error.
D:\Java>javac ExampleWhile.java
ExampleWhile.java:8: unreachable statement
System.out.println("hi");
EXAMPLE 10:
public class ExampleWhile{
public static void main(String args[]){
final int a=10;
while(a<20)
123
{
System.out.println("hello");
}
System.out.println("hi");
}}
OUTPUT:
D:\Java>javac ExampleWhile.java
ExampleWhile.java:8: unreachable statement
System.out.println("hi");
Note:
Every final variable will be replaced with the corresponding value by
compiler.
If any operation involves only constants then compiler is responsible to
perform that operation.
If any operation involves at least one variable compiler wont perform
that operation. At runtime jvm is responsible to perform that operation.
EXAMPLE 11:
public class ExampleWhile{
public static void main(String args[]){
int a=10;
while(a<20)
{
System.out.println("hello");
}
System.out.println("hi");
}}
OUTPUT:
Hello (infinite times).
Do-while:
If we want to execute loop body at least once then we should go for dowhile.
Syntax:
124
Without curly braces we can take only one statement between do and
while and it should not be declarative statement.
Example 1:
public class ExampleDoWhile{
public static void main(String args[]){
do
System.out.println("hello");
while(true);
}}
Output:
Hello (infinite times).
Example 2:
public class ExampleDoWhile{
public static void main(String args[]){
do;
while(true);
}}
Output:
Compile successful.
Example 3:
public class ExampleDoWhile{
public static void main(String args[]){
do
int x=10;
while(true);
}}
Output:
D:\Java>javac ExampleDoWhile.java
ExampleDoWhile.java:4: '.class' expected
int x=10;
ExampleDoWhile.java:4: not a statement
int x=10;
ExampleDoWhile.java:4: ')' expected
int x=10;
Example 4:
public class ExampleDoWhile{
public static void main(String args[]){
do
{
125
int x=10;
}while(true);
}}
Output:
Compile successful.
Example 5:
public class ExampleDoWhile{
public static void main(String args[]){
do while(true)
System.out.println("hello");
while(true);
}}
Output:
Hello (infinite times).
Rearrange the above example:
public class ExampleDoWhile{
public static void main(String args[]){
do
while(true)
System.out.println("hello");
while(true);
}}
Output:
Hello (infinite times).
Example 6:
public class ExampleDoWhile{
public static void main(String args[]){
do
while(true);
}}
Output:
Compile time error.
D:\Java>javac ExampleDoWhile.java
ExampleDoWhile.java:4: while expected
while(true);
ExampleDoWhile.java:5: illegal start of expression
}
Unreachable statement in do while:
Example 7:
126
Example 10:
public class ExampleDoWhile{
public static void main(String args[]){
int a=10,b=20;
do
{
System.out.println("hello");
}
while(a>b);
System.out.println("hi");
}}
Output:
Hello
Hi
Example 11:
public class ExampleDoWhile{
public static void main(String args[]){
final int a=10,b=20;
do
{
System.out.println("hello");
}
while(a<b);
System.out.println("hi");
}}
Output:
Compile time error.
D:\Java>javac ExampleDoWhile.java
ExampleDoWhile.java:9: unreachable statement
System.out.println("hi");
Example 12:
public class ExampleDoWhile{
public static void main(String args[]){
final int a=10,b=20;
do
{
System.out.println("hello");
}
while(a>b);
System.out.println("hi");
128
}}
Output:
D:\Java>javac ExampleDoWhile.java
D:\Java>java ExampleDoWhile
Hello
Hi
For Loop:
This is the most commonly used loop and best suitable if we know the
no of iterations in advance.
Syntax:
1) Initilizationsection:
This section will be executed only once.
Here usually we can declare loop variables and we will perform
initialization.
We can declare multiple variables but should be of the same type and
we cant declare different type of variables.
Example:
1) Int i=0,j=0; valid
2) Int i=0,Boolean b=true; invalid
3) Int i=0,int j=0; invalid
In initialization section we can take any valid java statement including
s.o.p also.
Example 1:
public class ExampleFor{
public static void main(String args[]){
int i=0;
for(System.out.println("hello u r sleeping");i<3;i++){
System.out.println("no boss, u only sleeping");
}}}
Output:
D:\Java>javac ExampleFor.java
D:\Java>java ExampleFor
Hello u r sleeping
No boss, u only sleeping
129
System.out.println("hi");
}}
Output:
Compile time error.
D:\Java>javac ExampleFor.java
ExampleFor.java:6: unreachable statement
System.out.println("hi");
Example 2:
public class ExampleFor{
public static void main(String args[]){
for(int i=0;false;i++){
System.out.println("hello");
}
System.out.println("hi");
}}
Output:
Compile time error.
D:\Java>javac ExampleFor.java
ExampleFor.java:3: unreachable statement
for(int i=0;false;i++){
Example 3:
public class ExampleFor{
public static void main(String args[]){
for(int i=0;;i++){
System.out.println("hello");
}
System.out.println("hi");
}}
Output:
Compile time error.
D:\Java>javac ExampleFor.java
ExampleFor.java:6: unreachable statement
System.out.println("hi");
Example 4:
public class ExampleFor{
public static void main(String args[]){
int a=10,b=20;
for(int i=0;a<b;i++){
System.out.println("hello");
}
131
System.out.println("hi");
}}
Output:
Hello (infinite times).
Example 5:
public class ExampleFor{
public static void main(String args[]){
final int a=10,b=20;
for(int i=0;a<b;i++){
System.out.println("hello");
}
System.out.println("hi");
}}
Output:
D:\Java>javac ExampleFor.java
ExampleFor.java:7: unreachable statement
System.out.println("hi");
For each:
For each Introduced in 1.5version.
Best suitable to retrieve the elements of arrays and collections.
Example 1: Write code to print the elements of single dimensional array by normal
for loop and enhanced for loop.
Example:
Output:
D:\Java>javac ExampleFor.java
D:\Java>java ExampleFor
10
20
30
40
50
132
Example 3: Write equivalent code by For Each loop for the following for loop.
public class ExampleFor{
public static void main(String args[]){
for(int i=0;i<10;i++)
{
System.out.println("hello");
}}}
Output:
D:\Java>javac ExampleFor1.java
D:\Java>java ExampleFor1
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
We cant write equivalent for each loop.
For each loop is the more convenient loop to retrieve the elements of arrays
and collections, but its main limitation is it is not a general purpose loop.
Transfer statements:
Break statement:
We can use break statement in the following cases.
1) Inside switch to stop fall-through.
2) Inside loops to break the loop based on some condition.
3) Inside label blocks to break block execution based on some condition.
Example 1:
class Test{
133
134
Output:
D:\Java>javac Test.java
D:\Java>java Test
1
3
5
7
9
We can use continue only inside loops if we are using anywhere else
we will get compile time error saying continue outside of loop.
Example:
class Test
{
public static void main(String args[]){
int x=10;
if(x==10);
continue;
System.out.println("hello");
}
}
Output:
Compile time error.
D:\Enum>javac Test.java
Test.java:6: continue outside of loop
continue;
Labeled break and continue statements:
In the nested loops to break (or) continue a particular loop we should
go for labeled break and continue statements.
Syntax:
135
Example:
class Test
{
public static void main(String args[]){
l1:
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i==j)
break;
System.out.println(i+"........."+j);
}}}}
Break:
1.........0
2.........0
2.........1
Break l1:
No output.
Continue:
0.........1
0.........2
1.........0
1.........2
2.........0
136
2.........1
Continue l1:
1.........0
2.........0
2.........1
Do-while vs continue (The most dangerous combination):
Output:
1
4
6
8
10
Compiler wont check unreachability in the case of if-else it will check
only in loops.
Example 1:
class Test
{
public static void main(String args[]){
while(true)
{
System.out.println("hello");
}
System.out.println("hi");
}
}
Output:
Compile time error.
D:\Enum>javac Test.java
Test.java:8: unreachable statement
137
System.out.println("hi");
Example 2:
class Test
{
public static void main(String args[]){
if(true)
{
System.out.println("hello");
}
else
{
System.out.println("hi");
}}}
Output:
Hello
Exception Handling
1. Introduction
2. Runtime stack mechanism
3. Default exception handling in java
4. Exception hierarchy
5. Customized exception handling by try catch
6. Control flow in try catch
7. Methods to print exception information
8. Try with multiple catch blocks
9. Finally
10.
Difference between final, finally, finalize
11.
Control flow in try catch finally
12.
Control flow in nested try catch finally
13.
Various possible combinations of try catch finally
14.
throw keyword
15.
throws keyword
16.
Exception handling keywords summary
17.
Various possible compile time errors in exception handling
18.
Customized exceptions
19.
Top-10 exceptions
Exception: An unwanted unexpected event that disturbs normal flow of the
program is called exception.
Example:
SleepingException
TyrePunchuredException
FileNotFoundException..etc
138
class Test
{
public static void main(String[] args){
doStuff();
}
public static void doStuff(){
doMoreStuff();
}
public static void doMoreStuff(){
System.out.println(10/0);
}}
Output:
Runtime error
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.doMoreStuff(Test.java:10)
at Test.doStuff(Test.java:7)
at Test.main(Test.java:4)
Diagram:
Exception hierarchy:
Exception: Most of the cases exceptions are caused by our program and
these are recoverable.
Error: Most of the cases errors are not caused by our program these are due
to lack of system resources and these are non recoverable.
Checked Vs Unchecked Exceptions:
141
142
143
System.out.println("statement3");
}
}
Abnormal termination.
}
catch(ArithmeticException e){
System.out.println(10/2);
}
System.out.println("statement3");
}}
Output:
statement1
5
statement3
Normal termination.
Description.
Example:
145
to
is
a
is
default handler
}
This
approach
is
highly
}}}
Output:
Try block executed
Finally block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.main(Test.java:8)
Return Vs Finally:
Even though return present in try or catch blocks first finally will be
executed and after that only return statement will be considered that is
finally block dominates return statement.
Example:
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try block executed");
return;
}
catch(ArithmeticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}}}
Output:
Try block executed
Finally block executed
If return statement present try catch and finally blocks then finally
block return statement will be considered.
Example:
class Test
{
public static void main(String[] args)
{
System.out.println(methodOne());
}
149
If a class declared as the final then child class creation is not possible.
If a method declared as the final then overriding of that method is not
possible.
If a variable declared as the final then reassignment is not possible.
Finally:
It is the block always associated with try catch to maintain clean up
code which should be executed always irrespective of whether
exception raised or not raised and whether handled or not handled.
Finalize:
It is a method which should be called by garbage collector always just
before destroying an object to perform cleanup activities.
Note:
To maintain clean up code faunally block is recommended over
finalize() method because we cant expert exact behavior of GC.
Control flow in try catch finally:
Example:
class Test
{
public static void main(String[] args){
try{
System.out.println("statement1");
System.out.println("statement2");
System.out.println("statement3");
}
catch(Exception e){
System.out.println("statement4");
}
finally
{
System.out.println("statement5");
}
System.out.println("statement6");
}
}
Case 1: If there is no exception. 1, 2, 3, 5, 6 normal termination.
Case 2: if an exception raised at statement 2 and corresponding catch block
matched. 1,4,5,6 normal terminations.
Case 3: if an exception raised at statement 2 and corresponding catch block
is not matched. 1,5 abnormal termination.
151
}
finally{
String s=null;
System.out.println(s.length());
}}}
Note: Default exception handler can handle only one exception at a time
and that is the most recently raised exception.
Various possible combinations of try catch finally:
Example 1:
class Test1{
public static void main(String[] args){
try
{}
catch(ArithmeticException e)
{}
}}
Output:
Compile and running successfully.
Example 2:
class Test1{
public static void main(String[] args){
try
{}
catch(ArithmeticException e)
{}
catch(NullPointerException e)
{}
}
}
Output:
Compile and running successfully.
Example 3:
class Test1{
public static void main(String[] args){
try
{}
catch(ArithmeticException e)
{}
catch(ArithmeticException e)
{}
154
}
}
Output:
Compile time error.
Test1.java:7: exception java.lang.ArithmeticException has already been
caught
catch(ArithmeticException e)
Example 4:
class Test1{
public static void main(String[] args){
try
{}
}
}
Output:
Compile time error
Test1.java:3: 'try' without 'catch' or 'finally'
try
Example 5:
class Test1{
public static void main(String[] args){
catch(Exception e)
{}
}
}
Output:
Compile time error.
Test1.java:3: 'catch' without 'try'
catch(Exception e)
Example 6:
class Test1{
public static void main(String[] args){
try
{}
System.out.println("hello");
catch(Exception e)
{}
}
}
Output:
155
Output:
Test1.java:3: 'finally' without 'try'
Finally
Example 13:
class Test1{
public static void main(String[] args){
try
{ try{}
catch(Exception e){}
}
catch(Exception e)
{}
}
}
Output:
Compile and running successfully.
Example 14:
class Test1{
public static void main(String[] args){
try
{}
catch(Exception e)
{
try{}
finally{}
}
}
}
Output:
Compile and running successfully.
Example 15:
class Test1{
public static void main(String[] args){
try
{}
catch(Exception e)
{
try{}
catch(Exception e){}
}
158
finally{
finally{}
}
}
}
Output:
Compile time error.
Test1.java:11: 'finally' without 'try'
finally{}
Example 16:
class Test1{
public static void main(String[] args){
finally{}
try{ }
catch(Exception e){}
}
}
Output:
Compile time error.
Test1.java:3: 'finally' without 'try'
finally{}
Example 17:
class Test1{
public static void main(String[] args){
try{ }
catch(Exception e){}
finally
{
try{}
catch(Exception e){}
finally{}
}
}
}
Output:
Compile and running successfully.
Throw statement: Sometime we can create exception object explicitly and
we can hand over to the JVM manually by using throw keyword.
Example:
159
160
public static void main(String[] args){ public static void main(String[] args){
System.out.println(10/0);
throw new ArithmeticException("/ by
System.out.println("hello");
zero");
}
System.out.println("hello");
}
}
Output:
}
Runtime error: Exception in thread Output:
"main"
Compile time error.
java.lang.ArithmeticException: / by Test3.java:5: unreachable statement
zero
System.out.println("hello");
at Test3.main(Test3.java:4)
Case 3: We can use throw keyword only for Throwable types otherwise we
will get compile time error saying incomputable types.
Example:
class Test3
class Test3 extends
{
RuntimeException
public static void main(String[] args){ {
throw new Test3();
public static void main(String[] args){
}
throw new Test3();
}Output:
}
Compile time error.
}
Test3.java:4: incompatible types
Output:
found : Test3
Runtime error: Exception in thread
required: java.lang.Throwable
"main" Test3
throw new Test3();
at Test3.main(Test3.java:4)
Throws statement: in our program if there is any chance of raising
checked exception compulsory we should handle either by try catch or by
throws keyword otherwise the code wont compile.
Example:
class Test3
{
public static void main(String[] args){
Thread.sleep(5000);
}
}
Unreported exception java.lang.InterruptedException; must be caught
or declared to be thrown. We can handle this compile time error by
using the following 2 ways.
Example:
By using try catch
By using throws keyword
161
class Test3
{
public static void main(String[] args){
try{
Thread.sleep(5000);
}
catch(InterruptedException e){}
}
}
Output:
Compile and running successfully
Example:
class Test
{
public static void main(String[] args)throws InterruptedException{
doStuff();
}
public static void doStuff()throws InterruptedException{
doMoreStuff();
}
public static void doMoreStuff()throws InterruptedException{
Thread.sleep(5000);
}
}
Output:
Compile and running successfully.
In the above program if we are removing at least one throws keyword
then the program wont compile.
162
Case 1: we can use throws keyword only for Throwable types otherwise we
will get compile time error saying incompatible types.
Example:
class Test3{
class Test3 extends
public static void main(String[]
RuntimeException{
args)throws Test3
public static void main(String[]
{}
args)throws Test3
}
{}
Output:
}
Compile time error
Output:
Test3.java:2: incompatible types
Compile and running successfully.
found : Test3
required: java.lang.Throwable
public static void main(String[]
args)throws Test3
Case 2:
Example:
class Test3{
class Test3{
public static void main(String[] args){ public static void main(String[] args){
throw new Exception();
throw new Error();
}
}
}
}
Output:
Output:
Compile time error.
Runtime error
Test3.java:3: unreported exception
Exception in thread "main"
java.lang.Exception; must be caught
java.lang.Error
or declared to be thrown
at Test3.main(Test3.java:3)
Case 3:
In our program if there is no chance of rising an exception then we
cant right catch block for that exception otherwise we will get compile
time error saying exception XXX is never thrown in body of
corresponding try statement. But this rule is applicable only for fully
checked exception.
Example:
163
3) TooOldException
Program:
class TooYoungException extends RuntimeException
{
TooYoungException(String s)
{
super(s);
}
}
class TooOldException extends RuntimeException
{
TooOldException(String s)
{
super(s);
}
}
class CustomizedExceptionDemo
{
public static void main(String[] args){
int age=Integer.parseInt(args[0]);
if(age>60)
{
throw new TooYoungException("please wait some more time.... u will get best
match");
}
else if(age<18)
{
throw new TooOldException("u r age already crossed....no chance of getting
married");
}
else
{
System.out.println("you will get match details soon by e-mail");
}}}
Output:
1) E:\scjp>java CustomizedExceptionDemo 61
Exception in thread "main" TooYoungException: please wait some more
time.... u will get best match
at
CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21)
165
2) E:\scjp>java CustomizedExceptionDemo 27
You will get match details soon by e-mail
3) E:\scjp>java CustomizedExceptionDemo 9
Exception in thread "main" TooOldException: u r age already crossed....no
chance of getting married
at
CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:25)
Note: It is highly recommended to maintain our customized exceptions as
unchecked by extending RuntimeException.
We can catch any Throwable type including Errors also.
Example:
Top-10 Exceptions:
Exceptions are divided into two types. They are:
1) JVM Exceptions:
2) Programatic exceptions:
JVM Exceptions:
The exceptions which are raised automatically by the jvm whenever a
particular event occurs.
Example:
1) ArrayIndexOutOfBoundsException(AIOOBE)
2) NullPointerException (NPE).
Programatic Exceptions:
The exceptions which are raised explicitly by the programmer (or) by
the API developer are called programatic exceptions.
Example:
1) IllegalArgumentException(IAE).
1) ArrayIndexOutOfBoundsException:
It is the child class of RuntimeException and hence it is unchecked.
Raised automatically by the JVM whenever we are trying to access
array element with out of range index.
Example:
class Test{
public static void main(String[] args){
int[] x=new int[10];
System.out.println(x[0]);//valid
System.out.println(x[100]);//AIOOBE
166
System.out.println(x[-100]);//AIOOBE
}
}
2) NullPointerException:
It is the child class of RuntimeException and hence it is unchecked.
Raised automatically by the JVM, whenever we are trying to call any
method on null.
Example:
class Test{
public static void main(String[] args){
String s=null;
System.out.println(s.length());R.E: NullPointerException
}
}
3) StackOverFlowError:
It is the child class of Error and hence it is unchecked. Whenever we
are trying to invoke recursive method call JVM will raise
StackOverFloeError automatically.
Example:
class Test
{
public static void methodOne()
{
methodTwo();
}
public static void methodTwo()
{
methodOne();
}
public static void main(String[] args)
{
methodOne();
}
}
Output:
Run time error: StackOverFloeError
4) NoClassDefFound:
It is the child class of Error and hence it is unchecked. JVM will raise
this error automatically whenever it is unable to find required .class
file.
167
6) ExceptionInInitializerError:
It is the child class of Error and it is unchecked. Raised automatically by
the JVM, if any exception occurs while performing static variable
initialization and static block execution.
Example 1:
class Test{
static int i=10/0;
}
Output:
Runtime exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
Example 2:
class Test{
static {
String s=null;
System.out.println(s.length());
}}
Output:
Runtime
exception:
Exception
in
thread
"main"
java.lang.ExceptionInInitializerError
7) IllegalArgumentException:
It is the child class of RuntimeException and hence it is unchecked.
Raised explicitly by the programmer (or) by the API developer to
indicate that a method has been invoked with inappropriate argument.
Example:
168
class Test{
public static void main(String[] args){
Thread t=new Thread();
t.setPriority(10);valid
t.setPriority(100);invalid
}}
Output:
Runtime exception
Exception in thread "main" java.lang.IllegalArgumentException.
8) NumberFormatException:
It is the child class of IllegalArgumentException and hence is
unchecked. Raised explicitly by the programmer or by the API
developer to indicate that we are attempting to convert string to the
number. But the string is not properly formatted.
Example:
class Test{
public static void main(String[] args){
int i=Integer.parseInt("10");
int j=Integer.parseInt("ten");
}}
Output:
Runtime Exception
Exception in thread "main" java.lang.NumberFormatException: For
input string: "ten"
9) IllegalStateException:
It is the child class of RuntimeException and hence it is unchecked.
Raised explicitly by the programmer or by the API developer to indicate
that a method has been invoked at inappropriate time.
Example:
Once session expires we cant call any method on the session object
otherwise we will get IllegalStateException
HttpSession session=req.getSession();
System.out.println(session.getId());
session.invalidate();
System.out.println(session.getId());illgalstateException
10)
AssertionError:
It is the child class of Error and hence it is unchecked. Raised explicitly
by the programmer or by API developer to indicate that Assert
statement fails.
Example:
169
assert(false);
Exception/Error
1) AIOOBE
2) NPE(NullPointerException)
3) StackOverFlowError
4) NoClassDefFoundError
5) CCE(ClassCastException)
6) ExceptionInInitializerError
7) IAE(IllegalArgumentException)
8) NFE(NumberFormatException)
9) ISE(IllegalStateException)
10)
AE(AssertionError)
Raised by
Raised automatically
Exceptions)
JVM(JVM
Raised
explicitly
either
by
programmer or by API developer
(Programatic Exceptions).
OOPS
1)
2)
3)
4)
5)
6)
by
Data Hiding
Abstraction
Encapsulation
Tightly Encapsulated Class
IS-A Relationship
HAS-A Relationship
170
7) Method Signature
8) Overloading
9) Overriding
10)
Method Hiding
11)
Static Control Flow
12)
Instance Control Flow
13)
Constructors
14)
Coupling
15)
Cohesion
16)
Object Type Casting
Data Hiding:
Our internal data should not go out directly that is outside person cant
access our internal data directly.
By using private modifier we can implement data hiding.
Example:
class Account
{
private double balance;
......................;
......................;
}
The main advantage of data hiding is security.
Note: recommended modifier for data members is private.
Abstraction:
Hide internal implementation and just highlight the set of services, is
called abstraction.
By using abstract classes and interfaces we can implement
abstraction.
Example:
By using ATM GUI screen bank people are highlighting the set of
services what they are offering without highlighting internal
implementation.
The main advantages of Abstraction are:
1) We can achieve security as we are not highlighting our internal
implementation.
2) Enhancement will become very easy because without effecting end
user we can able to perform any type of changes in our internal
system.
3) It provides more flexibility to the end user to use system very easily.
4) It improves maintainability of the application.
Encapsulation:
171
Conclusion:
1) Whatever the parent has by default available to the child but whatever
the child has by default not available to the parent. Hence on the child
reference we can call both parent and child class methods. But on the
parent reference we can call only methods available in the parent class
and we cant call child specific methods.
2) Parent class reference can be used to hold child class object but by
using that reference we can call only methods available in parent class
and child specific methods we cant call.
3) Child class reference cannot be used to hold parent class object.
Example:
The common methods which are required for housing loan, vehicle
loan, personal loan and education loan we can define into a separate
class in parent class loan. So that automatically these methods are
available to every child loan class.
Example:
class Loan
{
//common methods which are required for any type of loan.
}
class HousingLoan extends Loan
{
//Housing loan specific methods.
}
class EducationLoan extends Loan
{
//Education Loan specific methods.
174
For all java classes the most commonly required functionality is define
inside object class hence object class acts as a root for all java classes.
For all java exceptions and errors the most common required
functionality defines inside Throwable class hence Throwable class acts
as a root for exception hierarchy.
Diagram:
Multiple inheritance:
Having more than one Parent class at the same level is called multiple
inheritance.
Example:
Any class can extends only one class at a time and cant extends more
than one class simultaneously hence java wont provide support for
multiple inheritance.
Example:
But an interface can extends any no. Of interfaces at a time hence java
provides support for multiple inheritance through interfaces.
Example:
175
If our class doesnt extends any other class then only our class is the
If our class extends any other class then our class is not direct child
class of object.
Example 1:
Example 2:
176
wont
have
Cyclic inheritance:
Cyclic inheritance is not allowed in java.
Example 1:
Example 2:
HAS-A relationship:
1) HAS-A relationship is also known as composition (or) aggregation.
2) There is no specific keyword to implement hAS-A relationship but
mostly we can use new operator.
3) The main advantage of HAS-A relationship is reusability.
Example:
class Engine
{
//engine specific functionality
}
class Car
{
Engine e=new Engine();
//........................;
//........................;
//........................;
}
Class Car HAS-A engine reference.
177
Aggregation:
Without existing container object if there is a chance of existing
contained objects such type of relationship is called aggregation. In
aggregation objects have weak association.
Example:
Within a department there may be a chance of several professors will
work whenever we are closing department still there may be a chance
of existing professor object without existing department object the
relationship between department and professor is called aggregation
where the objects having weak association.
Example:
178
179
Example:
Having the same name and different argument types is called method
overloading.
All these methods are considered as overloaded methods.
Having overloading concept in java reduces complexity of the
programming.
Example:
class Test
{
public void methodOne()
{
System.out.println("no-arg method");
}
public void methodOne(int i)
{
System.out.println("int-arg method");
overloaded
methods
}
public void methodOne(double d)
{
System.out.println("double-arg method");
}
public static void main(String[] args)
{
Test t=new Test();
t.methodOne();//no-arg method
t.methodOne(10);//int-arg method
t.methodOne(10.5);//double-arg method
}
}
180
Example:
class Test
{
public void methodOne(int i)
{
System.out.println("int-arg method");
}
public void methodOne(float f)
overloaded methods
{
System.out.println("float-arg method");
}
public static void main(String[] args)
{
Test t=new Test();
//t.methodOne('a');//int-arg method
//t.methodOne(10l);//float-arg method
t.methodOne(10.5);//C.E:cannot find symbol
}
}
Case 2:
181
class Test
{
public void methodOne(String s)
{
System.out.println("String version");
}
public void methodOne(Object o)
Both methods are said
to
be overloaded methods.
{
System.out.println("Object version");
}
public static void main(String[] args)
{
Test t=new Test();
t.methodOne("bhaskar");//String version
t.methodOne(new Object());//Object version
t.methodOne(null);//String version
}
}
In overloading Child will always get high priority then Parent.
Case 3:
class Test
{
public void methodOne(String s)
{
System.out.println("String version");
}
public void methodOne(StringBuffer s)
{
System.out.println("StringBuffer version");
}
public static void main(String[] args)
{
Test t=new Test();
t.methodOne("durga");//String version
t.methodOne(new StringBuffer("bhaskar"));//StringBuffer version
}
}
Output:
182
Case 4:
class Test
{
public void methodOne(int i,float f)
{
System.out.println("int-float method");
}
public void methodOne(float f,int i)
{
System.out.println("float-int method");
}
public static void main(String[] args)
{
Test t=new Test();
t.methodOne(10,10.5f);//int-float method
t.methodOne(10.5f,10);//float-int method
t.methodOne(10,10);//C.E:reference to methodOne is ambiguous,
both method methodOne(int,float) in Test and method methodOne(float,int)
in Test match
t.methodOne(10.5f,10.5f);//C.E:cannot find symbol
}
}
Case 5:
class Test
{
public void methodOne(int i)
{
System.out.println("general method");
}
public void methodOne(int...i)
{
System.out.println("var-arg method");
}
public static void main(String[] args)
183
{
Test t=new Test();
t.methodOne();//var-arg method
t.methodOne(10,20);//var-arg method
t.methodOne(10);//general method
}
}
185
186
Co-variant return type concept is applicable only for object types but
not for primitives.
Private methods are not visible in the Child classes hence overriding
concept is not applicable for private methods. Based on own
requirement we can declare the same Parent class private method in
child class also. It is valid but not overriding.
Example:
Example:
abstract class Parent
{
public abstract void methodOne();
}
class Child extends Parent
{
public void methodOne()
{}
}
Diagram:
189
Rule: While overriding if the child class method throws any checked
exception compulsory the parent class method should throw the
same checked exception or its parent otherwise we will get compile
time error.
But there are no restrictions for un-checked exceptions.
Example:
class Parent
{
public void methodOne()
{}
}
class Child extends Parent
{
public void methodOne()throws Exception
{}
}
Output:
Compile time error
methodOne() in Child cannot override methodOne() in Parent; overridden
method does not throw java.lang.Exception
Examples:
190
{
public static void methodOne()
{}
}
class Child extends Parent
{
public static void methodOne()
{}
}
It is valid. It seems to be overriding concept is applicable for static
methods but it is not overriding it is met1hod hiding.
METHOD HIDING
All rules of method hiding are exactly same as overriding except the
following differences.
Overriding
Method hiding
1. Both Parent and Child class 1. Both Parent and Child class
methods should be non static.
methods should be static.
2. Method resolution is always takes 2. Method resolution is always takes
care by JVM based on runtime object. care by compiler based on reference
type.
3. Overriding is also considered as 3. Method hiding is also considered
runtime polymorphism (or) dynamic as compile time polymorphism (or)
polymorphism (or) late binding.
static polymorphism (or) early biding.
Example:
class Parent
{
public static void methodOne()
{
System.out.println("parent class");
}
}
class Child extends Parent
{
public static void methodOne()
{
System.out.println("child class");
}
}
class Test
192
{
public static void main(String[] args)
{
Parent p=new Parent();
p.methodOne();//parent class
Child c=new Child();
c.methodOne();//child class
Parent p1=new Child();
p1.methodOne();//parent class
}
}
Note: If both Parent and Child class methods are non static then it will
become overriding and method resolution is based on runtime object. In this
case the output is
Parent class
Child class
Child class
Overriding with respect to Var arg methods:
A var arg method should be overridden with var-arg method only. If we
are trying to override with normal method then it will become
overloading but not overriding.
Example:
class Parent
{
public void methodOne(int... i)
{
System.out.println("parent class");
}
}
class Child extends Parent
overloading but not
overriding.
{
public void methodOne(int i)
{
System.out.println("child class");
}
}
class Test
{
public static void main(String[] args)
193
{
Parent p=new Parent();
p.methodOne(10);//parent class
Child c=new Child();
c.methodOne(10);//child class
Parent p1=new Child();
p1.methodOne(10);//parent class
}
}
In the above program if we replace child class method with var arg
then it will become overriding. In this case the output is
Parent class
Child class
Child class
Overriding with respect to variables:
Overriding concept is not applicable for variables.
Variable resolution is always takes care by compiler based on reference
type.
Example:
class Parent
{
int x=888;
}
class Child extends Parent
{
int x=999;
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
System.out.println(p.x);//888
Child c=new Child();
System.out.println(c.x);//999
Parent p1=new Child();
System.out.println(p1.x);//888
}
}
194
Note: In the above program Parent and Child class variables, whether both
are static or non static whether one is static and the other one is non static
there is no change in the answer.
Differences between overloading and overriding?
Property
Overloading
Overriding
1) Method names
1) Must be same.
1) Must be same.
2) Argument type
2) Must
be
2) Must
be
same
different(at
including order.
least order)
3) Method signature
3) Must
be
3) Must be same.
different.
4) Return types
4) No restrictions.
4) Must be same until
1.4v but from 1.5v
onwards we can take
co-variant
return
types also.
5) private,static,fina
5) Can
be
5) Can
not
be
l methods
overloaded.
overridden.
6) Access modifiers
6) No restrictions.
6) Weakering/reducing
is not allowed.
7) Throws clause
7) No restrictions.
7) If child class method
throws any checked
exception compulsory
parent class method
should
throw
the
same
checked
exceptions
or
its
parent
but
no
restrictions for unchecked exceptions.
8) Method
8) Is always takes
8) Is always takes care
resolution
care
by
by JVM based on
compiler based
runtime object.
on
referenced
type.
9) Also known as
9) Compile
time
polymorphism
(or)
static(or)early
binding.
195
9) Runtime
polymorphism
dynamic
(or)
binding.
(or)
late
Note:
1) In overloading we have to check only method names (must be same)
and arguments (must be different) the remaining things like return
type extra not required to check.
2) But In overriding we should compulsory check everything like method
names, arguments, return types, throws keyword, modifiers etc.
Consider the method in parent class
Parent: public void methodOne(int i)throws IOException
In the child class which of the following methods we can take.
1) public void methodOne(int i)//valid(overriding)
2) private void methodOne()throws Exception//valid(overloading)
3) public native void methodOne(int i);//valid(overriding)
4) public static void methodOne(double d)//valid(overloading)
5) public static void methodOne(int i)
Compile time error
1) methodOne(int) in Child cannot override methodOne(int) in Parent;
overriding method is static
6) public static abstract void methodOne(float f)
Compile time error
1) illegal combination of modifiers: abstract and static
2) Child is not abstract and does not override abstract method
methodOne(float) in Child
Polymorphism: Same name with different forms is the concept of
polymorphism.
Example 1: We can use same abs() method for int type, long type, float
type etc.
Example:
1) abs(int)
2) abs(long)
3) abs(float)
Example 2: We can use the same List reference to hold ArrayList object,
LinkedList object, Vector object, or Stack object.
Example:
1) List l=new ArrayList();
2) List l=new LinkedList();
3) List l=new Vector();
4) List l=new Stack();
Diagram:
196
Diagram:
this.rollno=rollno;
}
public static void main(String[] args)
{
Student s1=new Student("vijayabhaskar",101);
Student s2=new Student("bhaskar",102);
}
}
Diagram:
}
}
class Test
{
Test(int i)
{
this();
}
Test()
{}
}
}
}
class Test
{
Test(int i)
{
this();
}
Test()
{
super();
}
}
super() vs this():
The 1st line inside every constructor should be either super() or this() if
we are not writing anything compiler will always generate super().
Case 1: We have to take super() (or) this() only in the 1 st line of constructor.
If we are taking anywhere else we will get compile time error.
Example:
class Test
{
Test()
{
System.out.println("constructor");
super();
}
}
Output:
Compile time error.
Call to super must be first statement in constructor
Case 2: We can use either super() (or) this() but not both simultaneously.
Example:
class Test
{
Test()
{
super();
this();
}
}
201
Output:
Compile time error.
Call to this must be first statement in constructor
Case 3: We can use super() (or) this() only inside constructor. If we are using
anywhere else we will get compile time error.
Example:
class Test
{
public void methodOne()
{
super();
}
}
Output:
Compile time error.
Call to super must be first statement in constructor
That is we can call a constructor directly from another constructor only.
Diagram:
Example:
super(),this()
1. These are constructors calls.
super, this
1. These are keywords which can be
used to call parent class and current
class instance members.
inside 2. We can use anywhere except static
area.
Overloaded constructors:
A class can contain more than one constructor and all these
constructors having the same name but different arguments and hence
these constructors are considered as overloaded constructors.
Example:
class Test
{
Test(double d)
{
this(10);
System.out.println("double-argument constructor");
}
Test(int i)
{
this();
System.out.println("int-argument constructor");
}
Test()
{
System.out.println("no-argument constructor");
}
public static void main(String[] args)
{
Test t1=new Test(10.5);//no-argument constructor/int-argument
constructor/double-argument constructor
Test t2=new Test(10);//no-argument constructor/int-argument
constructor
Test t3=new Test();//no-argument constructor
}
}
Inheritance concept is not applicable for constructors and hence
overriding concept also not applicable to the constructors. But
constructors can be overloaded.
We can take constructor in any java class including abstract class also
but we cant take constructor inside inheritance.
203
Example:
We cant create object for abstract class but abstract class can
contain constructor what is the need?
Abstract class constructor will be executed to perform initialization of
child class object.
Which of the following statement is true?
1) Whenever we are creating child class object then automatically parent
class object will be created.(false)
2) Whenever we are creating child class object then parent class
constructor will be executed.(true)
Example:
abstract class Parent
{
Parent()
{
System.out.println(this.hashCode());//11394033//here this means
child class object
}
}
class Child extends Parent
{
Child()
{
System.out.println(this.hashCode());//11394033
}
}
class Test
{
public static void main(String[] args)
{
Child c=new Child();
System.out.println(c.hashCode());//11394033
204
}
}
Case 1: recursive method call is always runtime exception where as
recursive constructor invocation is a compile time error.
Note:
Recursive functions:
A function is called using two methods (types).
1) Nested call
2) Recursive call
Nested call:
Calling a function inside another function is called nested call.
In nested call there is a calling function which calls another
function(called function).
Example:
public static void methodOne()
{
methodTwo();
}
public static void methodTwo()
{
methodOne();
}
Recursive call:
Calling a function within same function is called recursive call.
In recursive call called and calling function is same.
Example:
public void methodOne()
{
methodOne();
}
205
Example:
Case 3:
class Parent
{
Parent()throws java.io.IOException
{}
}
class Child extends Parent
{}
Output:
Compile time error
Unreported exception java.io.IOException in default constructor.
Example:
class Parent
{
Parent()throws java.io.IOException
{}
}
class Child extends Parent
{
Child()throws Exception
{
super();
}
}
If Parent class constructor throws some checked exception compulsory
Child class constructor should throw the same checked exception (or)
its Parent.
Singleton classes:
For any java class if we are allow to create only one object such type of
class is said to be singleton class.
Example:
1) Runtime class
2) ActionServlet
3) ServiceLocator
Runtime r1=Runtime.getRuntime();//getRuntime() method is a factory
method
.................................................
.................................................
Runtime r2=Runtime.getRuntime();
.................................................
207
.................................................
Runtime r3=Runtime.getRuntime();
System.out.println(r1==r2);//true
System.out.println(r1==r3);//true
Diagram:
}
Diagram:
Note:
We can create any xxxton classes like(double ton,trible ton.etc)
Example:
class Test
{
private static Test t1=null;
private static Test t2=null;
private Test()
{}
public static Test getTest()//getTest() method is a factory method
{
if(t1==null)
{
t1=new Test();
return t1;
}
else if(t2==null)
{
t2=new Test();
return t2;
}
else
{
if(Math.random()<0.5)
return t1;
else
return t2;
}
}
}
class Client
{
public static void main(String[] args)
{
System.out.println(Test.getTest().hashCode());//1671711
209
System.out.println(Test.getTest().hashCode());//11394033
System.out.println(Test.getTest().hashCode());//11394033
System.out.println(Test.getTest().hashCode());//1671711
}
}
Which of the following is true?
1) The name of the constructor and name of the class need not be same.
(false)
2) We can declare return type for the constructor but it should be void.
(false)
3) We can use any modifier for the constructor. (false)
4) Compiler will always generate default constructor. (false)
5) The modifier of the default constructor is always default. (false)
6) The 1st line inside every constructor should be super always. (false)
7) The 1st line inside every constructor should be either super or this and
if we are not writing anything compiler will always place this().(false)
8) Overloading concept is not applicable for constructor. (false)
9) Inheritance and overriding concepts are applicable for constructors.
(false)
10)
Concrete class can contain constructor but abstract class cannot.
(false)
11)
Interface can contain constructor. (false)
12)
Recursive constructor call is always runtime exception. (false)
13)
If Parent class constructor throws some un-checked exception
compulsory Child class constructor should throw the same un-checked
exception or its Parent. (false)
14)
Without using private constructor we can create singleton class.
(false)
15)
None of the above.(true)
Factory method:
By using class name if we are calling a method and that method
returns the same class object such type of method is called factory
method.
Example:
Runtime r=Runtime.getRuntime();//getRuntime is a factory
method.
DateFormat df=DateFormat.getInstance();
If object creation required under some constraints then we can
implement by using factory method.
210
Analysis:
Output:
E:\scjp>javac Base.java
E:\scjp>java Base
0
First static block
Second static block
211
20
Main method
Read indirectly write only state (or) RIWO:
If a variable is in RIWO state then we cant perform read operation
directly otherwise we will get compile time error saying illegal forward
reference.
Example:
212
Example:
213
Analysis:
Output:
E:\scjp>java Derived
0
Base static block
0
Derived first static block
Derived second static block
200
Derived main
Whenever we are executing Child class the following sequence of events
will be performed automatically.
1) Identification of static members from Parent to Child. [1 to 11]
2) Execution of static variable assignments and static blocks from Parent
to Child.[12 to 22]
3) Execution of Child class main() method.[23 to 25].
Static block:
Static blocks will be executed at the time of class loading hence if we
want to perform any activity at the time of class loading we have to
define that activity inside static block.
With in a class we can take any no. Of static blocks and all these static
blocks will be executed from top to bottom.
Example:
The native libraries should be loaded at the time of class loading hence
we have to define that activity inside static block.
Example:
class Test
{
static
{
System.loadLibrary("native library path");
214
}
}
Every JDBC driver class internally contains a static block to register the
driver with DriverManager hence programmer is not responsible to
define this explicitly.
Example:
class Driver
{
static
{
Register this driver with DriverManager
}
}
Without using main() method is it possible to print some statements
to the console?
Ans: Yes, by using static block.
Example:
class Google
{
static
{
System.out.println("hello i can print");
System.exit(0);
}
}
Output:
Hello i can print
Without using main() method and static block is it possible to print
some statements to the console?
Example 1:
class Test
{
static int i=methodOne();
public static int methodOne()
{
System.out.println("hello i can print");
System.exit(0);
return 10;
}
}
215
Output:
Hello i can print
Example 2:
class Test
{
static Test t=new Test();
Test()
{
System.out.println("hello i can print");
System.exit(0);
}
}
Output:
Hello i can print
Example 3:
class Test
{
static Test t=new Test();
{
System.out.println("hello i can print");
System.exit(0);
}
}
Output:
Hello i can print
Without using System.out.println() statement is it possible to print
some statement to the console?
Example:
class Test
{
public static void main(String[] args)
{
System.err.println("hello");
}
}
216
Analysis:
i=0[RIWO]
j=0[RIWO]
i=10[R&W]
j=20[R&W]
Output:
217
}
Child()
{
System.out.println("Child class constructor");
}
public static void main(String[] args)
{
Child c=new Child();
System.out.println("Child class main method");
}
public void methodTwo()
{
System.out.println(j);
}
{
System.out.println("Child second instance block");
}
int j=200;
}
Output:
E:\scjp>javac Child.java
E:\scjp>java Child
0
Parent first instance block
Parent class constructor
0
Child first instance block
Child second instance block
Child class constructor
Child class main method
Whenever we are creating child class object the following sequence of
events will be executed automatically.
1) Identification of instance members from Parent to Child.
2) Execution of instance variable assignments and instance block only in
Parent class.
3) Execution of Parent class constructor.
4) Execution of instance variable assignments and instance blocks in
Child class.
5) Execution of Child class constructor.
219
Note: Object creation is the most costly operation in java and hence if there
is no specific requirement never recommended to crate objects.
Example 1:
public class Initilization
{
private static String methodOne(String msg)
{
System.out.println(msg);
return msg;
}
public Initilization()
{
m=methodOne("1");
}
{
m=methodOne("2");
}
String m=methodOne("3");
public static void main(String[] args)
{
Object obj=new Initilization();
}
}
Analysis:
220
Output:
2
3
1
Example 2:
public class Initilization
{
private static String methodOne(String msg)
{
System.out.println(msg);
return msg;
}
static String m=methodOne("1");
{
m=methodOne("2");
}
static
{
m=methodOne("3");
}
public static void main(String[] args)
{
Object obj=new Initilization();
}
}
Output:
1
3
2
We cant access instance variables directly from static area because at
the time of execution of static area JVM may not identify those
members.
Example:
221
But from the instance area we can access instance members directly.
Static members we can access from anywhere directly because these
are identified already at the time of class loading only.
Type casting:
Parent class reference can be used to hold Child class object but by
using that reference we cant call Child specific methods.
Example:
Object o=new String("bhaskar");//valid
System.out.println(o.hashCode());//valid
System.out.println(o.length());//C.E:cannot find symbol,symbol : method
length(),location: class java.lang.Object
Similarly we can use interface reference to hold implemented class
object.
Example:
Runnable r=new Thread();
Type casting syntax:
222
Example 2:
Example 2:
Runtime checking:
The underlying object type of d must be either same (or) derived
type of C otherwise we will get runtime exception saying
ClassCastException.
Example:
223
Diagram:
Example 1:
224
Example 2:
((B)c).methodOne();//c
((A)((B)c)).methodOne();//c
Example 3:
C c=new C();
System.out.println(c.x);//999
System.out.println(((B)c).x);//888
System.out.println(((A)((B)c)).x);//777
Variable resolution is always based on reference type only.
If we are changing variable as static then also we will get the same
output.
Coupling:
The degree of dependency between the components is called coupling.
Example:
class A
226
{
static int i=B.j;
}
class B extends A
{
static int j=C.methodOne();
}
class C extends B
{
public static int methodOne()
{
return D.k;
}
}
class D extends C
{
static int k=10;
public static void main(String[] args)
{
D d=new D();
}
}
The above components are said to be tightly coupled to each other
because the dependency between the components is more.
Tightly coupling is not a good programming practice because it has
several serious disadvantages.
1) Without effecting remaining components we cant modify any
component hence enhancement(development) will become difficult.
2) It reduces maintainability of the application.
3) It doesnt promote reusability of the code.
It is always recommended to maintain loosely coupling between the
components.
Cohesion:
For every component we have to maintain a clear well defined
functionality such type of component is said to be follow high cohesion.
Diagram:
227
Multi Threading
228
Agenda
1) Introduction.
2) The ways to define instantiate and start a new Thread.
3) Getting and setting name of a Thread.
4) Thread priorities.
5) The methods to prevent(stop) Thread execution.
1. yield()
2. join()
3. sleep()
6) Synchronization.
7) Inter Thread communication.
8) Deadlock
9) Daemon Threads.
Multitasking: Executing several tasks simultaneously is the concept of
multitasking. There are two types of multitaskings.
1) Process based multitasking.
2) Thread based multitasking.
Diagram:
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();//Instantiation of a Thread
t.start();//starting of a Thread
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}
Case 1: Thread Scheduler:
If multiple Threads are waiting to execute then which Thread will
execute 1st is decided by Thread Scheduler which is part of JVM.
230
main thread
Entire output produced by only main Thread.
Case 3: importance of Thread class start() method.
For every Thread the required mandatory activities like registering the
Thread with Thread Scheduler will takes care by Thread class start()
method and programmer is responsible just to define the job of the
Thread inside run() method. That is start() method acts as best
assistant to the programmer.
Example:
start()
{
1. Register Thread with Thread Scheduler
2. All other mandatory low level activities.
3. Invoke or calling run() method.
}
We can conclude that without executing Thread class start() method
there is no chance of starting a new Thread in java.
Case 4: If we are not overriding run() method:
If we are not overriding run() method then Thread class run() method
will be executed which has empty implementation and hence we wont
get any output.
Example:
class MyThread extends Thread
{}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
}
}
It is highly recommended to override run() method. Otherwise dont go
for multithreading concept.
232
We can overload run() method but Thread class start() method always
invokes no argument run() method the other overload run() methods
we have to call explicitly then only it will be executed just like normal
method.
Example:
class MyThread extends Thread
{
public void run()
{
System.out.println("no arg method");
}
public void run(int i)
{
System.out.println("int arg method");
}
}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
}
}
Output:
No arg method
Case 6: overriding of start() method:
If we override start() method then our start() method will be executed
just like a normal method call and no new Thread will be started.
Example:
class MyThread extends Thread
{
public void start()
{
System.out.println("start method");
}
public void run()
{
System.out.println("run method");
}
233
}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
System.out.println("main method");
}
}
Output:
start method
main method
Entire output produced by only main Thread.
Case 7:
Example 1:
Example 2:
234
Output:
Example:
class ThreadDemo
{
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);//here r is a Target Runnable
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
236
Output:
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
We cant expect exact output but there are several possible outputs.
Case study:
MyRunnable r=new MyRunnable();
Thread t1=new Thread();
Thread t2=new Thread(r);
Case 1:
t1.start():
A new Thread will be created which is responsible for the execution of
Thread class run()method.
Output:
main thread
main thread
main thread
main thread
main thread
Case 2: t1.run():
No new Thread will be created but Thread class run() method will be
executed just like a normal method call.
Output:
237
main thread
main thread
main thread
main thread
main thread
Case 3: t2.start():
New Thread will be created which is responsible for the execution of
MyRunnable run() method.
Output:
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
Case 4: t2.run():
No new Thread will be created and MyRunnable run() method will be
executed just like a normal method call.
Output:
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread
Case 5:
r.start():
We will get compile time error saying start()method is not available in
MyRunnable class.
Output:
Compile time error
E:\SCJP>javac ThreadDemo.java
238
239
Diagram:
Output:
main method
run method
Getting and setting name of a Thread:
Every Thread in java has some name it may be provided explicitly by
the programmer or automatically generated by JVM.
Thread class defines the following methods to get and set name of a
Thread.
Methods:
1) public final String getName()
2) public final void setName(String name)
Example:
class MyThread extends Thread
{}
class ThreadDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());//main
MyThread t=new MyThread();
System.out.println(t.getName());//Thread-0
Thread.currentThread().setName("Bhaskar Thread");
System.out.println(Thread.currentThread().getName());//Bhaskar
Thread
}
}
240
Thread Priorities
Thread.currentThread().setPriority(9);
MyThread t=new MyThread();
System.out.println(t.getPriority());//9
}
}
Example 2:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child thread");
}
}
}
class ThreadPriorityDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
//t.setPriority(10);
1
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
If we are commenting line 1 then both main and child Threads will have
the same priority and hence we cant expect exact execution order.
If we are not commenting line 1 then child Thread has the priority 10
and main Thread has the priority 5 hence child Thread will get chance
for execution and after completing child Thread main Thread will get
the chance in this the output is:
Output:
child thread
child thread
child thread
child thread
242
child thread
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
Some operating systems(like windowsXP) may not provide proper
support for Thread priorities. We have to install separate bats provided
by vendor to provide support for priorities.
The Methods to Prevent a Thread from Execution:
We can prevent(stop) a Thread execution by using the following
methods.
1) yield();
2) join();
3) sleep();
yield():
yield() method causes to pause current executing Thread for giving
the chance of remaining waiting Threads of same priority.
If all waiting Threads have the low priority or if there is no waiting
Threads then the same Thread will be continued its execution.
If several waiting Threads with same priority available then we cant
expect exact which Thread will get chance for execution.
The Thread which is yielded when it get chance once again for
execution is depends on mercy of the Thread scheduler.
public static native void yield();
Diagram:
243
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
Thread.yield();
System.out.println("child thread");
}
}
}
class ThreadYieldDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}
Output:
main thread
main thread
main thread
main thread
main thread
child thread
child thread
244
child
child
child
thread
thread
thread
In the above example the chance of completing main Thread 1 st is high
because child Thread always calling yield() method.
Join():
If a Thread wants to wait until completing some other Thread then we
should go for join() method.
Example:
If a Thread t1 executes t2.join() then t1 should go for waiting state until
completing t2.
Diagram:
Diagram:
Example:
class ThreadJoinDemo
{
public static void main(String[] args)throws InterruptedException
{
System.out.println("M");
Thread.sleep(3000);
System.out.println("E");
Thread.sleep(3000);
System.out.println("G");
Thread.sleep(3000);
System.out.println("A");
}
}
Output:
M
E
G
A
Interrupting a Thread:
247
Whenever we are calling interrupt() method we may not see the effect
immediately, if the target Thread is in sleeping or waiting state it will
be interrupted immediately.
If the target Thread is not in sleeping or waiting state then interrupt
call will wait until target Thread will enter into sleeping or waiting
state. Once target Thread entered into sleeping or waiting state it will
effect immediately.
In its lifetime if the target Thread never entered into sleeping or
waiting state then there is no impact of interrupt call simply interrupt
call will be wasted.
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("iamlazy thread");
}
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
System.out.println("i got interrupted");
}
}
}
class ThreadInterruptDemo1
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
t.interrupt();
System.out.println("end of main thread");
}
}
249
Synchronization
Synchronized is the keyword applicable for methods and blocks but not
for classes and variables.
If a method or block declared as the synchronized then at a time only one
Thread is allow to execute that method or block on the given object.
The main advantage of synchronized keyword is we can resolve date
inconsistency problems.
But the main disadvantage of synchronized keyword is it increases
waiting time of the Thread and effects performance of the system.
Hence if there is no specific requirement then never recommended to use
synchronized keyword.
Internally synchronization concept is implemented by using lock concept.
Every object in java has a unique lock. Whenever we are using
synchronized keyword then only lock concept will come into the picture.
250
}
}
class SynchronizedDemo
{
public static void main(String[] args)
{
Display d1=new Display();
MyThread t1=new MyThread(d1,"dhoni");
MyThread t2=new MyThread(d1,"yuvaraj");
t1.start();
t2.start();
}
}
If we are not declaring wish() method as synchronized then both
Threads will be executed simultaneously and we will get irregular
output.
Output:
good morning:good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
dhoni
If we declare wish()method as synchronized then the Threads will be
executed one by one that is until completing the 1 st Thread the 2nd
Thread will wait in this case we will get regular output which is nothing
but
Output:
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:yuvaraj
good morning:yuvaraj
good morning:yuvaraj
252
good morning:yuvaraj
good morning:yuvaraj
Case study:
Case 1:
Display d1=new Display();
Display d2=new Display();
MyThread t1=new MyThread(d1,"dhoni");
MyThread t2=new MyThread(d2,"yuvaraj");
t1.start();
t2.start();
Diagram:
Example:
Int x=b;
Synchronized(x){}
Output:
Compile time error.
Unexpected type.
Found: int
Required: reference
Questions:
1) Explain about synchronized keyword and its advantages and
disadvantages?
2) What is object lock and when a Thread required?
3) What is class level lock and when a Thread required?
4) What is the difference between object lock and class level lock?
5) While a Thread executing a synchronized method on the given object is
the remaining Threads are allowed to execute other synchronized
methods simultaneously on the same object?
Ans: No.
6) What is synchronized block and explain its declaration?
7) What is the advantage of synchronized block over synchronized
method?
8) Is a Thread can hold more than one lock at a time?
254
Diagram:
Two Threads can communicate with each other by using wait(), notify()
and notifyAll() methods.
The Thread which is excepting updation it has to call wait() method
and the Thread which is performing updation it has to call notify()
method. After getting notification the waiting Thread will get those
updations.
Diagram:
255
wait(), notify() and notifyAll() methods are available in Object class but
not in Thread class because Thread can call these methods on any
common object.
To call wait(), notify() and notifyAll() methods compulsory the current
Thread should be owner of that object that is current Thread should
has lock of that object that is current Thread should be in synchronized
area. Hence we can call wait(), notify() and notifyAll() methods only
from synchronized area otherwise we will get runtime exception saying
IllegalMonitorStateException.
Once a Thread calls wait() method on the given object 1st it releases
the lock of that object immediately and entered into waiting state.
Once a Thread calls notify() (or) notifyAll() methods it releases the lock
of that object but may not immediately.
Except these (wait(),notify(),notifyAll()) methods there is no other
place(method) where the lock release will be happen.
Method
yield()
join()
sleep()
wait()
notify()
notifyAll()
Example 1:
class ThreadA
{
public static void main(String[] args)throws InterruptedException
{
ThreadB b=new ThreadB();
b.start();
synchronized(b)
{
System.out.println("main
Thread
calling
wait()
method");//step-1
b.wait();
System.out.println("main
Thread
got
notification
call");//step-4
System.out.println(b.total);
}
}
}
class ThreadB extends Thread
257
{
int total=0;
public void run()
{
synchronized(this)
{
System.out.println("child thread starts calcuation");//step-2
for(int i=0;i<=100;i++)
{
total=total+i;
}
System.out.println("child
thread
giving
notification
call");//step-3
this.notify();
}
}
}
Output:
main Thread calling wait() method
child thread starts calculation
child thread giving notification call
main Thread got notification call
5050
Example 2:
Producer consumer problem:
Producer(producer Thread) will produce the items to the queue and
consumer(consumer thread) will consume the items from the queue. If
the queue is empty then consumer has to call wait() method on the
queue object then it will entered into waiting state.
After producing the items producer Thread call notify() method on the
queue to give notification so that consumer Thread will get that
notification and consume items.
Diagram:
Example:
258
Notify vs notifyAll():
We can use notify() method to give notification for only one Thread.
If multiple Threads are waiting then only one Thread will get the
chance and remaining Threads has to wait for further notification.
But which Thread will be notify(inform) we cant expect exactly it
depends on JVM.
We can use notifyAll() method to give the notification for all waiting
Threads. All waiting Threads will be notified and will be executed
one by one.
Note: On which object we are calling wait(), notify() and notifyAll() methods
that corresponding object lock we have to get but not other object locks.
Example:
Dead lock:
If 2 Threads are waiting for each other forever(without end) such type
of situation(infinite waiting) is called dead lock.
There are no resolution techniques for dead lock but several
prevention(avoidance) techniques are possible.
259
}
class DeadLock implements Runnable
{
A a=new A();
B b=new B();
DeadLock()
{
Thread t=new Thread(this);
t.start();
a.foo(b);//main thread
}
public void run()
{
b.bar(a);//child thread
}
public static void main(String[] args)
{
new DeadLock();//main thread
}
}
Output:
Thread1 starts execution of foo() method
Thread2 starts execution of bar() method
Thread2 trying to call a.last()
Thread1 trying to call b.last()
//here cursor always waiting.
Daemon Threads:
The Threads which are executing in the background are called daemon
Threads. The main objective of daemon Threads is to provide support
for non daemon Threads.
Example:
Garbage collector
We can check whether the Thread is daemon or not by using
isDaemon() method.
public final boolean isDaemon();
We can change daemon nature of a Thread by using setDaemon ()
method.
public final void setDaemon(boolean b);
261
But we can change daemon nature before starting Thread only. That is
after starting the Thread if we are trying to change the daemon nature
we will get R.E saying IllegalThreadStateException.
Main Thread is always non daemon and we cant change its daemon
nature because its already started at the beginning only.
Main Thread is always non daemon and for the remaining Threads
daemon nature will be inheriting from parent to child that is if the
parent is daemon child is also daemon and if the parent is non daemon
then child is also non daemon.
Whenever the last non daemon Thread terminates automatically all
daemon Threads will be terminated.
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("lazy thread");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{}
}
}
}
class DaemonThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.setDaemon(true);
1
t.start();
System.out.println("end of main Thread");
}
}
Output:
262
263
boolean stop=false;
Step 2:
If the variable becomes true return from the run() method.
If(stop) return;
Step 3:
Whenever to stop the Thread store true into the variable.
System.in.read();//press enter
Obj.stop=true;
Questions:
1) What is a Thread?
2) Which Thread by default runs in every java program?
Ans: By default main Thread runs in every java program.
3) What is the default priority of the Thread?
4) How can you change the priority number of the Thread?
5) Which method is executed by any Thread?
Ans: A Thread executes only public void run() method.
6) How can you stop a Thread which is running?
7) Explain the two types of multitasking?
8) What is the difference between a process and a Thread?
9) What is Thread scheduler?
10)
Explain the synchronization of Threads?
11)
What is the difference between synchronized block and
synchronized keyword?
12)
What is Thread deadlock? How can you resolve deadlock
situation?
13)
Which methods are used in Thread communication?
14)
What is the difference between notify() and notifyAll()
methods?
15)
What is the difference between sleep() and wait()
methods?
16)
Explain the life cycle of a Thread?
17)
What is daemon Thread?
265
Java.lang Package
1)
2)
3)
4)
5)
6)
Object
String
StringBuffer
StringBuilder
Wrapper Classes
Autoboxing and Autounboxing
For writing any java program the most commonly required classes and
interfaces are encapsulated in the separate package which is nothing
but java.lang package.
It is not required to import java.lang package in our program because it
is available by default to every java program.
The following are some of important classes present in java.lang
package.
1. Object
2. String
3. StringBuffer
4. StringBuilder
5. All wrapper classes
6. Execption API
7. Thread API.etc
What is your favorite package?
Why java.lang is your favorite package?
It is not required to import lang package explicitly but the remaining
packages we have to import.
Java.lang.Object class: For any java object whether it is predefine or
customized the most commonly required methods are encapsulated into a
separate class which is nothing but object class.
As object class acts as a root (or) parent (or) super for all java classes,
by default its methods are available to every java class.
The following is the list of all methods present in java.lang Object class.
1) public String toString();
2) public native int hashCode();
3) public boolean equals(Object o);
4) protected native Object clone()throws
CloneNotSupportedException;
5) public final Class<?> getClass();
6) protected void finalize()throws Throwable;
266
return name+"........"+rollno;
}
In String class, StringBuffer, StringBuilder, wrapper classes and in all
collection classes toString() method is overridden for meaningful string
representation. Hence in our classes also highly recommended to
override toString() method.
Example 2:
class Test
{
public String toString()
{
return "Test";
}
public static void main(String[] args){
Integer i=new Integer(10);
String s=new String("bhaskar");
Test t=new Test();
System.out.println(i);
System.out.println(s);
System.out.println(t);
}}
Output:
10
Bhaskar
Test
hashCode() method:
For every object jvm will generate a unique number which is nothing
but hashCode.
hashCode of an object will be used by jvm while saving objects into
HashSet, HashMap, and Hashtable etc.
If the objects are stored according to hashCode searching will become
very efficient (The most powerful search algorithm is hashing which
will work based on hashCode).
If we didnt override hashCode() method then Object class hashCode()
method will be executed which generates hashCode based on address
of the object but it doesnt mean hashCode represents address of the
object.
Based on our programming requirement we can override hashCode()
method in our class.
Overriding hashCode() method is said to be proper if and only if for
every object we have to generate a unique number.
Example 3:
class Student
class Student
{
{
public int hashCode()
int rollno;
268
{
return 100;
}}
It is improper way of overriding
hashCode() method because
for every object we are
generating same hashcode.
if(name1.equals(name2)&&rollno1==rollno2)
{
return true;
}
else return false;
}
catch(ClassCastException e)
{
return false;
}
catch(NullPointerException e)
{
return false;
}
}
public static void main(String[] args){
Student s1=new Student("vijayabhaskar",101);
Student s2=new Student("bhaskar",102);
Student s3=new Student("vijayabhaskar",101);
Student s4=s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
System.out.println(s1.equals("vijayabhaskar"));
System.out.println(s1.equals("null"));
}
}
Output:
False
True
True
False
False
Simplified version of .equals() method:
public boolean equals(Object o){
try{
Student s2=(Student)o;
if(name.equals(s2.name)&&rollno==s2.rollno){
return true;}
else return false;
}
catch(ClassCastException e)
{
return false;
}
catch(NullPointerException e)
272
{
return false;
}}
More simplified version of .equals() method:
public boolean equals(Object o)
{
if(this==o)
return true;
if(o instanceof Student)
{
Student s2=(Student)o;
if(name.equals(s2.name)&&rollno==s2.rollno)
return true;
else
return false;
}
return false;
}
Example 7:
class Student
{
String name;
int rollno;
Student(String name,int rollno)
{
this.name=name;
this.rollno=rollno;
}
public boolean equals(Object o)
{
if(this==o)
return true;
if(o instanceof Student)
{
Student s2=(Student)o;
if(name.equals(s2.name)&&rollno==s2.rollno)
return true;
else
return false;
}
return false;
}
public static void main(String[] args){
Student s=new Student("vijayabhaskar",101);
Integer i=new Integer(10);
273
System.out.println(s.equals(i));
}
}
Output:
False
To make .equals() method more efficient we have to place the following
code at the top inside .equals() method.
if(this==o)
return true;
Diagram:
return i;
}
public String toString()
{
return i+"";
}
public static void main(String[] args)
{
Test t1=new Test(10);
Test t2=new Test(20);
System.out.println(t1.hashCode());//10
System.out.println(t2.hashCode());//20
System.out.println(t1.hashCode()==t2.hashCode());//false
System.out.println(t1.equals(t2));//false
}
}
4) If hashcodes of 2 objects are equal then these objects are always equal
by == operator also.(invalid)
Clone () method:
The process of creating exactly duplicate object is called cloning.
The main objective of cloning is to maintain backup.
That is if something goes wrong we can recover the situation by using
backup copy.
We can perform cloning by using clone() method of Object class.
protected native object clone() throws
CloneNotSupportedException;
Example:
class Test implements Cloneable
{
int i=10;
int j=20;
public
static
void
main(String[]
args)throws
CloneNotSupportedException
278
{
Test t1=new Test();
Test t2=(Test)t1.clone();
t2.i=888;
t2.j=999;
System.out.println(t1.i+"---------------"+t1.j);
System.out.println(t2.i+"---------------"+t2.j);
}
}
Output:
10---------------20
888---------------999
Diagram:
279
String
Case 1:
String s=new String("bhaskar");
s.concat("software");
System.out.println(s);//bhaskar
Once we create a String object
we cant perform any changes
in the existing object. If we are
try to perform any changes
with those changes a new
object will be created. This
behavior is called immutability
of the String object.
Diagram:
StringBuffer sb=new
StringBuffer("bhaskar");
sb.append("software");
System.out.println(sb);
Once we created a StringBuffer
object we can perform any
changes in the existing object.
This
behavior
is
called
mutability of the StringBuffer
object.
Diagram:
Case 2:
String s1=new String("bhaskar");
String s2=new String("bhaskar");
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//tr
StringBuffer sb1=new
StringBuffer("bhaskar");
StringBuffer sb2=new
StringBuffer("bhaskar");
280
ue
System.out.println(sb1==sb2);//false
System.out.println(sb1.equals(sb2));//
false
In StringBuffer class .equals()
method is not overridden for
content compression hence
Object class .equals() method
got executed which is always
meant
for
reference
compression. Hence if objects
are different .equals() method
returns false even though
content is same.
Case 3:
String s=new String("bhaskar");
String s="bhaskar";
In this case two objects will be
In this case only one object will
created one is on the heap the
be created in SCP and s is
other
one
is
SCP(String
always referring that object.
constant pool) and s is always Diagram:
pointing to heap object.
Diagram:
Note:
1) Object creation in SCP is always optional 1 st JVM will check is any object
already created with required content or not. If it is already available
then it will reuse existing object instead of creating new object. If it is
not already there then only a new object will be created. Hence there is
no chance of existing 2 objects with same content on SCP that is
duplicate objects are not allowed in SCP.
2) Garbage collector cant access SCP area hence even though object
doesnt have any reference still that object is not eligible for GC if it is
present in SCP.
3) All SCP objects will be destroyed at the time of JVM shutdown
automatically.
Example 1:
String s1=new String("bhaskar");
String s2=new String("bhaskar");
281
String s3="bhaskar";
String s4="bhaskar";
Diagram:
Example 2:
String s=new String("bhaskar");
s.concat("software");
s=s.concat("solutions");
s="bhaskarsoft";
Diagram:
For every String Constant one object will be created in SCP. Because of
runtime operation if an object is required to create compulsory that
object should be placed on the heap but not SCP.
Example 3:
String s1=new String("spring");
s1.concat("fall");
s1=s1+"winter";
String s2=s1.concat("summer");
System.out.println(s1);
System.out.println(s2);
Diagram:
282
Example:
class StringDemo
{
public static void main(String[] args)
{
String s1=new String("you cannot change me!");
String s2=new String("you cannot change me!");
System.out.println(s1==s2);//false
String s3="you cannot change me!";
System.out.println(s1==s3);//false
String s4="you cannot change me!";
System.out.println(s3==s4);//true
String s5="you cannot "+"change me!";
System.out.println(s3==s5);//true
String s6="you cannot ";
String s7=s6+"change me!";
System.out.println(s3==s7);//false
final String s8="you cannot ";
String s9=s8+"change me!";
System.out.println(s3==s9);//true
System.out.println(s6==s8);//true
}
}
Diagram:
283
1)
2)
3)
4)
5)
284
{
public static void main(String[] args)
{
String s1=new String("bhaskar");
String s2=s1.intern();
String s3="bhaskar";
System.out.println(s2==s3);//true
}
}
Diagram:
Diagram 2:
286
{
String s="ababab";
System.out.println(s.replace('a','b'));//bbbbbb
}
}
9) public String toLowerCase();
Converts the all characters of the string to lowercase.
Example:
class StringInternDemo
{
public static void main(String[] args)
{
String s="BHASKAR";
System.out.println(s.toLowerCase());//bhaskar
}
}
10) public String toUpperCase();
Converts the all characters of the string to uppercase.
Example:
class StringInternDemo
{
public static void main(String[] args)
{
String s="bhaskar";
System.out.println(s.toUpperCase());//BHASKAR
}
}
11) public String trim()
We can use this method to remove blank spaces present at beginning
and end of the string but not blank spaces present at middle of the
String.
Example:
class StringInternDemo
{
public static void main(String[] args)
{
String s=" bha skar ";
System.out.println(s.trim());//bha skar
}
}
12) public int indexOf(char ch);
It returns index of 1st occurrence of the specified character if the
specified character is not available then return -1.
Example:
class StringInternDemo
290
{
public static void main(String[] args)
{
String s="vijayabhaskarreddy";
System.out.println(s.indexOf('a'));//3
System.out.println(s.indexOf('z'));-1
}
}
13) public int lastIndexOf(Char ch);
It returns index of last occurrence of the specified character if the
specified character is not available then return -1.
Example:
class StringInternDemo
{
public static void main(String[] args)
{
String s="vijayabhaskarreddy";
System.out.println(s.lastIndexOf('a'));//11
System.out.println(s.indexOf('z'));//-1
}
}
Note:
Because runtime operation if there is a change in content with those
changes a new object will be created only on the heap but not in SCP.
If there is no change in content no new object will be created the same
object will be reused.
Example 1:
class StringInternDemo
{
public static void main(String[] args)
{
String s1="bhaskar";
String s2=s1.toUpperCase();
String s3=s1.toLowerCase();
System.out.println(s1==s2);//false
System.out.println(s1==s3);//true
}
}
Diagram:
291
Example 2:
class StringInternDemo
{
public static void main(String[] args)
{
String s1="bhaskar";
String s2=s1.toString();
System.out.println(s1==s2);//true
}
}
Diagram:
Immutable program:
final class CreateImmutable
{
private int i;
CreateImmutable(int i)
{
this.i=i;
}
public CreateImmutable modify(int i)
{
if(this.i==i)
return this;
else
return (new CreateImmutable(i));
}
public static void main(String[] args)
{
CreateImmutable c1=new CreateImmutable(10);
CreateImmutable c2=c1.modify(100);
CreateImmutable c3=c1.modify(10);
System.out.println(c1==c2);//false
System.out.println(c1==c3);//true
CreateImmutable c4=c1.modify(100);
System.out.println(c2==c4);//false
}
}
Diagram:
Final vs immutability:
If we declare a variable as final then we cant perform reassignment for
that variable. It doesnt mean in the corresponding object we cant
perform any changes. That is through final keyword we wont get any
immutability that is final and immutability concepts are different.
Example:
class Test
293
{
public static void main(String[] args)
{
final StringBuffer sb=new StringBuffer("bhaskar");
sb.append("software");
System.out.println(sb);//bhaskarsoftware
sb=new StringBuffer("solutions");//C.E: cannot assign a value
to final variable sb
}
}
In the above example even though sb is final we can perform any
type of change in the corresponding object. That is through final
keyword we are not getting any immutability nature.
StringBuffer
StringBuffer
object
will
be
Newcapacity=(currentcapacity+1)*2.
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//16
sb.append("abcdefghijklmnop");
System.out.println(sb.capacity());//16
sb.append("q");
System.out.println(sb.capacity());//34
}
294
created
with
}
2) StringBuffer sb=new StringBuffer(int initialcapacity);
Creates an empty StringBuffer object with the specified initial capacity.
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer(19);
System.out.println(sb.capacity());//19
}
}
3) StringBuffer sb=new StringBuffer(String s);
Creates an equivalent StringBuffer object for the given String with
capacity=s.length()+16;
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("bhaskar");
System.out.println(sb.capacity());//23
}
}
Important methods of StringBuffer:
1) public int length();
Return the no of characters present in the StringBuffer.
2) public int capacity();
Returns the total no of characters but a StringBuffer can
accommodate(hold).
3) public char charAt(int index);
It returns the character located at specified index.
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("vijayabhaskarreddy");
System.out.println(sb.length());//18
System.out.println(sb.capacity());//34
295
System.out.println(sb.charAt(14));//e
}
}
4) public void setCharAt(int index,char ch);
To replace the character locating at specified index with the provided
character.
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("vijayabhaskarreddy");
sb.setCharAt(6,'A');
System.out.println(sb);
}
}
5) public StringBuffer append(String s);
public StringBuffer append(int i);
public StringBuffer append(long l);
public StringBuffer append(boolean b);
All these are overloaded methods.
public StringBuffer append(double d);
public StringBuffer append(float f);
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
sb.append("PI value is :");
sb.append(3.14);
sb.append(" this is exactly ");
sb.append(true);
System.out.println(sb);//PI value is :3.14 this is exactly true
}
}
6) public StringBuffer insert(int index,String s);
public StringBuffer insert(int index,int i);
public StringBuffer insert(int index,long l);
public StringBuffer insert(int index,double d);
All are overloaded methods
public StringBuffer insert(int index,boolean b);
296
}
10)
public void setLength(int length);
Consider only specified no of characters and remove all the remaining
characters.
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("vijayabhaskar");
sb.setLength(6);
System.out.println(sb);//vijaya
}
}
11)
public void trimToSize();
To deallocate the extra free memory such that capacity and size are
equal.
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer(1000);
System.out.println(sb.capacity());//1000
sb.append("bhaskar");
System.out.println(sb.capacity());//1000
sb.trimToSize();
System.out.println(sb.capacity());//7
}
}
12)
public void ensureCapacity(int initialcapacity);
To increase the capacity dynamically based on our requirement.
Example:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//16
sb.ensureCapacity(1000);
298
System.out.println(sb.capacity());//1000
}
}
StringBuilder (1.5)
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
sb.append("vijaya").insert(6,"bhaskarreddy").delete(13,17).reverse().append
("solutions").insert(22,"abcdf").reverse();
System.out.println(sb);//sfdcbanoitulosvijayabhaskary
}
}
Wrapper classes
Character class defines only one constructor which can take char
primitive as argument there is no String argument constructor.
Character ch=new Character(a);//valid
Character ch=new Character(a);//invalid
Boolean class defines 2 constructors with boolean primitive and String
arguments.
If we want to pass boolean primitive the only allowed values are true,
false where case should be lower case.
Example:
Boolean b=new Boolean(true);
//Boolean b1=new Boolean(True);//C.E
//Boolean b=new Boolean(False);//C.E
If we are passing String argument then case is not important and
content is not important. If the content is case insensitive String of true
then it is treated as true in all other cases it is treated as false.
Example 1:
class WrapperClassDemo
{
public static void main(String[] args)throws Exception
{
Boolean b1=new Boolean("true");
Boolean b2=new Boolean("True");
Boolean b3=new Boolean("false");
Boolean b4=new Boolean("False");
Boolean b5=new Boolean("bhaskar");
System.out.println(b1);//true
System.out.println(b2);//true
System.out.println(b3);//false
System.out.println(b4);//false
System.out.println(b5);//false
}
}
Example 2(for exam purpose):
class WrapperClassDemo
{
public static void main(String[] args)throws Exception
{
Boolean b1=new Boolean("yes");
Boolean b2=new Boolean("no");
System.out.println(b1);//false
301
System.out.println(b2);//false
System.out.println(b1.equals(b2));//true
System.out.println(b1==b2);//false
}
}
Wrapper class
Byte
Short
Integer
Long
Float
Double
Character
Constructor summery
byte, String
short, String
Int, String
long, String
float, String, double
double, String
Boolean
boolean, String
Note:
1) In all wrapper classes toString() method is overridden to return its
content.
2) In all wrapper classes .equals() method is overridden for content
compression.
Utility methods:
1) valueOf() method.
2) XXXValue() method.
3) parseXxx() method.
4) toString() method.
valueOf() method: We can use valueOf() method to create wrapper object
for the given primitive or String this method is alternative to constructor.
Form 1: Every wrapper class except Character class contains a static
valueOf() method to create wrapper object for the given String.
public static wrapper valueOf(String s);
Example:
class WrapperClassDemo
{
public static void main(String[] args)throws Exception
{
Integer i=Integer.valueOf("10");
Double d=Double.valueOf("10.5");
Boolean b=Boolean.valueOf("bhaskar");
System.out.println(i);//10
System.out.println(d);//10.5
System.out.println(b);//false
}
}
302
Form 2: Every integral type wrapper class (Byte, Short, Integer, and Long)
contains the following valueOf() method to convert specified radix string to
wrapper object.
Example:
class WrapperClassDemo
{
public static void main(String[] args)
{
Integer i=Integer.valueOf("100",2);
System.out.println(i);//4
}
}
Analysis:
}
}
Diagram:
}
}
booleanValue() method: Boolean class contains booleanValue() method to
convert Boolean object to boolean primitive.
public boolean booleanValue();
Example:
class WrapperClassDemo
{
public static void main(String[] args)
{
Boolean b=new Boolean("bhaskar");
boolean b1=b.booleanValue();
System.out.println(b1);//false
}
}
Diagram:
305
Example:
class WrapperClassDemo
{
public static void main(String[] args)
{
String s1=Integer.toString(10);
String s2=Boolean.toString(true);
System.out.println(s1);//10
System.out.println(s2);//true
}
}
Form 3:
Integer and long classes contains the following static toString() method
to convert the primitive to specified radix String form.
public static String toString(primitive p,int radix);
Example:
class WrapperClassDemo
{
public static void main(String[] args)
{
String s1=Integer.toString(7,2);
String s2=Integer.toString(17,2);
System.out.println(s1);//111
System.out.println(s2);//10001
}
}
Form 4: Integer and Long classes contains the following toXxxString()
methods.
public static String toBinaryString(primitive p);
public static String toOctalString(primitive p);
public static String toHexString(primitive p);
Example:
class WrapperClassDemo
{
public static void main(String[] args)
{
String s1=Integer.toBinaryString(7);
String s2=Integer.toOctalString(10);
String s3=Integer.toHexString(20);
System.out.println(s1);//111
System.out.println(s2);//12
System.out.println(s3);//14
307
}
}
Diagram:
Program 2:
308
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
Boolean b=new Boolean(true);
if(b)
{
System.out.println("hello");
}}}
Output:
Hello
Example 2:
Program 1:
Program 2:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
ArrayList l=new ArrayList();
Integer i=new Integer(10);
l.add(i);
}
}
But from 1.5 version onwards we can provide primitive value in the
place of wrapper and wrapper object in the place of primitive all
required conversions will be performed automatically by compiler.
These automatic conversions are called Autoboxing and Autounboxing.
Autoboxing: Automatic conversion of primitive to wrapper object by
compiler is called Autoboxing.
Example:
309
Example:
Note: From 1.5 version onwards we can use primitives and wrapper objects
interchangly the required conversions will be performed automatically by
compiler.
Example 1:
import java.util.*;
class AutoBoxingAndUnboxingDemo
310
{
static Integer I=0;
public static void main(String[] args)
{
int i=I;
System.out.println(i);//0
}
}
Example 2:
Example 3:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
Integer x=10;
Integer y=x;
++x;
System.out.println(x);//11
System.out.println(y);//10
System.out.println(x==y);//false
}
}
Diagram:
311
Note: All wrapper objects are immutable that is once we created a wrapper
object we cant perform any changes in the existing object. If we are trying
to perform any changes with those changes a new object will be created.
Example 4:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
Integer x=new Integer(10);
Integer y=new Integer(10);
System.out.println(x==y);//false
}
}
Diagram:
Example 5:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
Integer x=new Integer(10);
Integer y=10;
System.out.println(x==y);//false
}
}
Diagram:
Example 6:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
312
Example 7:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
Integer x=10;
Integer y=10;
System.out.println(x==y);//true
}
}
Diagram:
Example 8:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void main(String[] args)
{
Integer x=100;
Integer y=100;
System.out.println(x==y);//true
}
}
Diagram:
Example 9:
import java.util.*;
class AutoBoxingAndUnboxingDemo
313
{
public static void main(String[] args)
{
Integer x=1000;
Integer y=1000;
System.out.println(x==y);//false
}
}
Diagram:
Diagram:
Conclusions:
To implement the Autoboxing concept in every wrapper class a buffer
of objects will be created at the time of class loading.
By Autoboxing if an object is required to create 1 st JVM will check
whether that object is available in the buffer or not. If it is available
then JVM will reuse that buffered object instead of creating new object.
If the object is not available in the buffer then only a new object will be
created. This approach improves performance and memory utilization.
But this buffer concept is available only in the following cases.
Byte
Always
Short
-128 To 127
Integer
-128 To 127
Long
-128 To 127
Character
0 To 127
Boolean
Always
In all the remaining cases compulsory a new object will be created.
Examples:
314
}
}
Output:
Widening
Widening dominates Autoboxing.
Case 2: Widening vs var-arg method.
Example:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void methodOne(long l)
{
System.out.println("widening");
}
public static void methodOne(int... i)
{
System.out.println("var-arg method");
}
public static void main(String[] args)
{
int x=10;
methodOne(x);
}
}
Output:
Widening
Widening dominates var-arg method.
Case 3: Autoboxing vs var-arg method.
Example:
import java.util.*;
class AutoBoxingAndUnboxingDemo
{
public static void methodOne(Integer i)
{
System.out.println("Autoboxing");
}
public static void methodOne(int... i)
{
System.out.println("var-arg method");
}
316
Diagram:
317
Java.IO Package
318
Agenda:
1) File
2) FileWriter
3) FileReader
4) BufferedWriter
5) BufferedReader
6) PrintWriter
File:
File f=new File("abc.txt");
This line 1 checks whether abc.txt file is already available (or) not if it
is already available then f simply refers that file. If it is not already
available then it wont create any physical file just creates a java File
object represents name of the file.
Example:
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
File f=new File("cricket.txt");
System.out.println(f.exists());//false
f.createNewFile();
System.out.println(f.exists());//true
}
}
A java File object can represent a directory also.
Example:
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
File f=new File("cricket123");
System.out.println(f.exists());//false
f.mkdir();
System.out.println(f.exists());//true
}
}
st
319
320
Program:
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
File f=new File("c:\\bhaskar","demo.txt");
f.createNewFile();
}
}
Import methods of file class:
1) boolean exists();
Returns true if the physical file or directory available.
2) boolean createNewFile();
This method 1st checks whether the physical file is already available or
not if it is already available then this method simply returns false. If
this file is not already available then it will create a new file and returns
true
3) boolean mkdir();
4) boolean isFile();
Returns true if the File object represents a physical file.
5) boolean isDirectory();
6) String[] list();
It returns the names of all files and subdirectories present in the
specified directory.
7) long length();
Returns the no of characters present in the file.
8) boolean delete();
To delete a file or directory.
FileWriter:
By using FileWriter we can write character data to the file.
Constructors:
FileWriter fw=new FileWriter(String name);
FileWriter fw=new FileWriter(File f);
The above 2 constructors meant for overriding.
Instead of overriding if we want append operation then we should go
for the following 2 constructors.
FileWriter fw=new FileWriter(String name,boolean append);
FileWriter fw=new FileWriter(File f,boolean append);
321
1) int read();
It attempts to read next character from the file and return its Unicode
value. If the next character is not available then we will get -1.
2) int read(char[] ch);
It attempts to read enough characters from the file into char[] array
and returns the no of characters copied from the file into char[] array.
3) void close();
Approach 1:
import java.io.*;
class FileReaderDemo
{
public static void main(String[] args)throws IOException
{
FileReader fr=new FileReader("cricket.txt");
int i=fr.read();
while(i!=-1)
{
System.out.print((char)i);
i=fr.read();
}
}
}
Output:
Bhaskar
Software solutions
ABC
Approach 2:
import java.io.*;
class FileReaderDemo
{
public static void main(String[] args)throws IOException
{
File f=new File("cricket.txt");
FileReader fr=new FileReader(f);
char[] ch=new char[(int)f.length()];
fr.read(ch);
for(char ch1:ch)
{
System.out.print(ch1);
}
323
}
}
Output:
VBR
Software solutions.
Usage of FileWriter and FileReader is not recommended because:
1) While writing data by FileWriter compulsory we should insert line
separator(\n) manually which is a bigger headache to the programmer.
2) While reading data by FileReader we have to read character by
character which is not convent to the programmer.
3) To overcome these limitations we should go for BufferedWriter and
BufferedReader concepts.
BufferedWriter:
By using BufferedWriter object we can write character data to the file.
Constructors:
BufferedWriter bw=new BufferedWriter(writer w);
BufferedWriter
bw=new
BufferedWriter(writer
w,int
buffersize);
Note:
BufferedWriter never communicates directly with the file it should
communicates via some writer object.
Which of the following declarations are valid?
1) BufferedWriter bw=new BufferedWriter(cricket.txt); (invalid)
2) BufferedWriter
bw=new
BufferedWriter
(new
File(cricket.txt)); (invalid)
3) BufferedWriter
bw=new
BufferedWriter
(new
FileWriter(cricket.txt)); (valid)
Methods:
1) write(int ch);
2) write(char[] ch);
3) write(String s);
4) flush();
5) close();
6) newline();
Inserting a new line character to the file.
When
compared
with
FileWriter
which
of
the
capability(facility) is available as method in BufferedWriter.
1) Writing data to the file.(x)
2) Closing the writer.(x)
324
following
Note:
BufferedReader can not communicate directly with the File it should
communicate via some Reader object. The main advantage of
325
Methods:
write(int ch);
write (char[] ch);
write(String s);
flush();
close();
print(char ch);
print (int i);
print (double d);
print (boolean b);
print (String s);
println(char ch);
println (int i);
println(double d);
println(boolean b);
println(String s);
Example:
import java.io.*;
class PrintWriterDemo
{
public static void main(String[] args)throws IOException
{
FileWriter fw=new FileWriter("cricket.txt");
PrintWriter out=new PrintWriter(fw);
out.write(100);
out.println(100);
out.println(true);
out.println('c');
out.println("bhaskar");
out.flush();
out.close();
}
}
Output:
d100
327
true
c
bhaskar
What is the difference between write(100) and print(100)?
In the case of write(100) the corresponding character d will be added
to the File but in the case of print(100) 100 value will be added
directly to the File.
Note 1:
1) The most enhanced Reader to read character data from the File is
BufferedReader.
2) The most enhanced Writer to write character data to the File is
PrintWriter.
Note 2:
1) In general we can use Readers and Writers to handle character data.
Where as we can use InputStreams and OutputStreams to handle
binary data(like images, audio files, video files etc).
2) We can use OutputStream to write binary data to the File and we can
use InputStream to read binary data from the File.
Diagram:
328
Program:
import java.io.*;
class FileWriterDemo1
{
public static void main(String[] args)throws IOException
{
PrintWriter pw=new PrintWriter("file3.txt");
BufferedReader
br=new
BufferedReader(new
FileReader("file1.txt"));
String line=br.readLine();
while(line!=null)
{
pw.println(line);
line=br.readLine();
}
br=new BufferedReader(new FileReader("file2.txt")); reuse
line=br.readLine();
while(line!=null)
{
pw.println(line);
line=br.readLine();
}
pw.flush();
br.close();
pw.close();
}
}
Requirement: Write a program to perform file merge operation where
merging should be performed line by line alternatively.
Diagram:
329
Program:
import java.io.*;
class FileWriterDemo1
{
public static void main(String[] args)throws IOException
{
PrintWriter pw=new PrintWriter("file3.txt");
BufferedReader
br1=new
BufferedReader(new
FileReader("file1.txt"));
BufferedReader
br2=new
BufferedReader(new
FileReader("file2.txt"));
String line1=br1.readLine();
String line2=br2.readLine();
while(line1!=null||line2!=null)
{
if(line1!=null)
{
pw.println(line1);
line1=br1.readLine();
}
if(line2!=null)
{
pw.println(line2);
line2=br2.readLine();
}
}
pw.flush();
br1.close();
br2.close();
pw.close();
}
330
}
Requirement: Write a program to delete duplicate numbers from the file.
Diagram:
Program:
import java.io.*;
class FileWriterDemo1
{
public static void main(String[] args)throws IOException
{
BufferedReader
br1=new
BufferedReader(new
FileReader("input.txt"));
PrintWriter out=new PrintWriter("output.txt");
String target=br1.readLine();
while(target!=null)
{
boolean available=false;
BufferedReader
br2=new
BufferedReader(new
FileReader("output.txt"));
String line=br2.readLine();
while(line!=null)
{
if(target.equals(line))
{
available=true;
break;
}
line=br2.readLine();
}
if(available==false)
{
out.println(target);
out.flush();
}
target=br1.readLine();
331
}
}
}
Requirement: write a program to perform file extraction operation.
Diagram:
Program:
import java.io.*;
class FileWriterDemo1
{
public static void main(String[] args)throws IOException
{
BufferedReader
br1=new
BufferedReader(new
FileReader("input.txt"));
PrintWriter pw=new PrintWriter("output.txt");
String line=br1.readLine();
while(line!=null)
{
boolean available=false;
BufferedReader
br2=new
BufferedReader(new
FileReader("delete.txt"));
String target=br2.readLine();
while(target!=null)
{
if(line.equals(target))
{
available=true;
break;
}
target=br2.readLine();
}
if(available==false)
{
332
pw.println(line);
}
line=br1.readLine();
}
pw.flush();
}
}
SERIALIZATION
333
1. Introduction.
2. Object graph in serialization.
3. customized serialization.
4. Serialization with respect inheritance.
Serialization: The process of saving (or) writing state of an object to a file is
called serialization but strictly speaking it is the process of converting an
object from java supported form to either network supported form (or) file
supported form.
By using FileOutputStream and ObjectOutputStream classes we can
achieve serialization process.
Diagram:
Example 1:
import java.io.*;
class Dog implements Serializable
{
int i=10;
int j=20;
334
}
class SerializableDemo
{
public static void main(String args[])throws Exception{
Dog d1=new Dog();
System.out.println("Serialization started");
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);
System.out.println("Serialization ended");
System.out.println("Deserialization started");
FileInputStream fis=new FileInputStream("abc.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println("Deserialization ended");
System.out.println(d2.i+"................"+d2.j);
}
}
Output:
Serialization started
Serialization ended
Deserialization started
Deserialization ended
10................20
Diagram:
335
Serialization started
Serialization ended
Deserialization started
Deserialization ended
10................20
30................40
Transient keyword:
While performing serialization if we dont want to serialize the value of
a particular variable then we should declare that variable with
transient keyword.
At the time of serialization JVM ignores the original value of transient
variable and save default value.
That is transient means not to serialize.
Static Vs Transient:
static variable is not part of object state hence they wont participate
in serialization because of this declaring a static variable as transient
these is no use.
Transient Vs Final:
final variables will be participated into serialization directly by their
values. Hence declaring a final variable as transient there is no use.
Example 3:
import java.io.*;
class Dog implements Serializable
{
static transient int i=10;
final transient int j=20;
}
class SerializableDemo
{
public static void main(String args[])throws Exception{
Dog d1=new Dog();
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);
FileInputStream fis=new FileInputStream("abc.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println(d2.i+"................"+d2.j);
}
}
337
Output:
10................20
Diagram:
Table:
declaration
output
10................20
int i=10;
int j=20;
transient int i=10;
0................20
int j=20;
transient int i=10;
0................20
transient static int j=20;
transient final int i=10;
10................0
transient int j=20;
transient final int i=10;
10................20
transient static int j=20;
Object graph in serialization:
Whenever we are serializing an object the set of all objects which are
reachable from that object will be serialized automatically. This group
of objects is nothing but object graph in serialization.
In object graph every object should be Serializable otherwise we will
get runtime exception saying NotSerializableException.
Example 4:
import java.io.*;
class Dog implements Serializable
{
Cat c=new Cat();
}
class Cat implements Serializable
{
338
Customized serialization:
Example 5:
import java.io.*;
class Account implements Serializable
{
String userName="Bhaskar";
transient String pwd="kajal";
}
class CustomizedSerializeDemo
{
public static void main(String[] args)throws Exception{
Account a1=new Account();
System.out.println(a1.userName+"........."+a1.pwd);
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(a1);
FileInputStream fis=new FileInputStream("abc.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
Account a2=(Account)ois.readObject();
System.out.println(a2.userName+"........."+a2.pwd);
}
}
Output:
Bhaskar.........kajal
Bhaskar.........null
Diagram:
At the time of Account object serialization JVM will check is there any
writeObject() method in Account class or not. If it is not available then
JVM is responsible to perform serialization(default serialization). If
Account class contains writeObject() method then JVM feels very happy
and executes that Account class writeObject() method. The same rule
is applicable for readObject() method also.
int j=20;
}
class SerializableWRTInheritance
{
public static void main(String[] args)throws Exception{
Dog d1=new Dog();
System.out.println(d1.i+"........"+d1.j);
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);
FileInputStream fis=new FileInputStream("abc.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println(d2.i+"........"+d2.j);
}
}
Output:
10........20
10........20
Even though Dog class does not implements Serializable interface
explicitly but we can Serialize Dog object because its parent class
animal already implements Serializable interface.
Case 2:
Even though parent class does not implements Serializable we can
serialize child object if child class implements Serializable interface.
At the time of serialization JVM ignores the values of instance variables
which are coming from non Serializable parent JVM saves default
values for those variables.
At the time of Deserialization JVM checks whether any parent class is
non Serializable or not. If any parent class is non Serializable JVM
creates a separate object for every non Serializable parent and shares
its instance variables to the current object.
For this JVM always calls no arg constructor(default constructor) of that
non Serializable parent hence every non Serializable parent should
compulsory contain no arg constructor otherwise we will get runtime
exception.
Example 8:
import java.io.*;
class Animal
{
343
int i=10;
Animal(){
System.out.println("Animal constructor called");
}
}
class Dog extends Animal implements Serializable
{
int j=20;
Dog(){
System.out.println("Dog constructor called");
}
}
class SerializableWRTInheritance
{
public static void main(String[] args)throws Exception{
Dog d1=new Dog();
d1.i=888;
d1.j=999;
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);
System.out.println("Deserialization started");
FileInputStream fis=new FileInputStream("abc.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println(d2.i+"........."+d2.j);
}
}
Output:
Animal constructor called
Dog constructor called
Deserialization started
Animal constructor called
10.........999
Diagram:
344
Collections
345
s[0]=new Student();//valid
s[1]=new Customer();//invalid(compile time error)
Compile time error:
Test.java:7: cannot find symbol
Symbol: class Customer
Location: class Test
s[1]=new Customer();
3) But we can resolve this problem by using object type array(Object[]).
Example:
Object[] o=new Object[10000];
o[0]=new Student();
o[1]=new Customer();
4) Arrays concept is not implemented based on some data structure
hence ready-made methods support we cant expert. For every
requirement we have to write the code explicitly.
To overcome the above limitations we should go for collections
concept.
1) Collections are growable in nature that is based on our requirement we
can increase (or) decrease the size hence memory point of view
collections concept is recommended to use.
2) Collections can hold both homogeneous and heterogeneous objects.
3) Every collection class is implemented based on some standard data
structure hence for every requirement ready-made method support is
available being a programmer we can use these methods directly
without writing the functionality on our own.
346
347
Diagram:
Set:
1) It is the child interface of Collection.
2) If we want to represent a group of individual objects as single entity
where duplicates are not allow and insertion order is not preserved
then we should go for Set interface.
Diagram:
SortedSet:
1) It is the child interface of Set.
2) If we want to represent a group of unique objects according to some
sorting order then we should go for SortedSet.
NavigableSet:
1) It is the child interface of SortedSet.
2) It provides several methods for navigation purposes.
Queue:
1) It is the child interface of Collection.
348
Diagram:
Note: All the above interfaces (Collection, List, Set, SortedSet, NavigableSet,
and Queue) meant for representing a group of individual objects.
If we want to represent a group of objects as key-value pairs then we
should go for Map.
Map:
1) Map is not child interface of Collection.
2) If we want to represent a group of objects as key-value pairs then we
should go for Map interface.
3) Duplicate keys are not allowed but values can be duplicated.
Diagram:
SortedMap:
349
Diagram:
350
Collection interface:
If we want to represent a group of individual objects then we should go
for Collection interface. This interface defines the most common
general methods which can be applicable for any Collection object.
The following is the list of methods present in Collection interface.
1) boolean add(Object o);
2) boolean addAll(Collection c);
3) boolean remove(Object o);
4) boolean removeAll(Object o);
5) boolean retainAll(Collection c);
To remove all objects except those present in c.
6) Void clear();
7) boolean contains(Object o);
8) boolean containsAll(Collection c);
9) boolean isEmpty();
10)
Int size();
11)
Object[] toArray();
12)
Iterator iterator();
There is no concrete class which implements Collection interface
directly.
List interface:
It is the child interface of Collection.
If we want to represent a group of individual objects where duplicates
are allow and insertion order is preserved. Then we should go for List.
We can differentiate duplicate objects and we can maintain insertion
order by means of index hence index play very important role in List.
List interface defines the following specific methods.
1) boolean add(int index,Object o);
2) boolean addAll(int index,Collectio c);
3) Object get(int index);
4) Object remove(int index);
5) Object set(int index,Object new);//to replace
6) Int indexOf(Object o);
Returns index of first occurrence of o.
351
352
Diagram:
LinkedList:
1) The underlying data structure is double LinkedList
2) If our frequent operation is insertion (or) deletion in the middle then
LinkedList is the best choice.
3) If our frequent operation is retrieval operation then LinkedList is worst
choice.
4) Duplicate objects are allowed.
5) Insertion order is preserved.
6) Heterogeneous objects are allowed.
7) Null insertion is possible.
8) Implements
Serializable
and
Cloneable
interfaces
but
not
RandomAccess.
Diagram:
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("bhaskar");
l.add(30);
l.add(null);
l.add("bhaskar");
System.out.println(l);//[bhaskar, 30, null, bhaskar]
l.set(0,"software");
System.out.println(l);//[software, 30, null, bhaskar]
l.set(0,"venky");
System.out.println(l);//[venky, 30, null, bhaskar]
l.removeLast();
System.out.println(l);//[venky, 30, null]
l.addFirst("vvv");
System.out.println(l);//[vvv, venky, 30, null]
}
}
Vector:
1) The underlying data structure is resizable array (or) growable array.
2) Duplicate objects are allowed.
3) Insertion order is preserved.
4) Heterogeneous objects are allowed.
5) Null insertion is possible.
6) Implements Serializable, Cloneable and RandomAccess interfaces.
Every method present in Vector is synchronized and hence Vector is
Thread safe.
Vector specific methods:
To add objects:
1) add(Object o);-----Collection
2) add(int index,Object o);-----List
3) addElement(Object o);-----Vector
To remove elements:
1) remove(Object o);--------Collection
2) remove(int index);--------------List
3) removeElement(Object o);----Vector
4) removeElementAt(int index);-----Vector
5) removeAllElements();-----Vector
6) clear();-------Collection
To get objects:
355
Enumeration e=v.elements();
Vector Object
Enumeration interface defines the following two methods
1) public boolean hasMoreElements();
2) public Object nextElement();
Example:
import java.util.*;
class EnumerationDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=0;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
if(i%2==0)
System.out.println(i);//0 2 4 6 8 10
}
System.out.print(v);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}
Limitations of Enumeration:
1) We can apply Enumeration concept only for legacy classes and it is not
a universal cursor.
2) By using Enumeration we can get only read access and we cant
perform remove operations.
3) To overcome these limitations sun people introduced Iterator concept
in 1.2v.
Iterator:
1) We can use Iterator to get objects one by one from any collection
object.
2) We can apply Iterator concept for any collection object and it is a
universal cursor.
3) While iterating the objects by Iterator we can perform both read and
remove operations.
We can get Iterator object by using iterator() method of Collection
interface.
Iterator itr=c.iterator();
Iterator interface defines the following 3 methods.
358
2)
3)
4)
5)
6)
7)
8)
9)
public
public
public
public
public
public
public
public
Object next();
int nextIndex();
boolean hasPrevious();
Object previous();
int previousIndex();
void remove();
void set(Object o);
void add(Object new);
forward
backward
Example:
import java.util.*;
class ListIteratorDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("balakrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
System.out.println(l);//[balakrishna, venki, chiru, nag]
ListIterator itr=l.listIterator();
while(itr.hasNext())
{
String s=(String)itr.next();
if(s.equals("venki"))
{
itr.remove();
}
}
System.out.println(l);//[balakrishna, chiru, nag]
}
}
Case 1:
if(s.equals("chiru"))
{
itr.set("chran");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chran, nag]
Case 2:
if(s.equals("nag"))
{
itr.add("chitu");
}
Output:
360
Set interface does not contain any new method we have to use only
Collection interface methods.
HashSet:
1) The underlying data structure is Hashtable.
361
is Hashtable.
is a combination of LinkedList
and Hashtable.
2) Insertion order is preserved.
2) Insertion
order
is
not
preserved.
3) Introduced in 1.2 v.
3) Introduced in 1.4v.
In the above program if we are replacing HashSet with LinkedHashSet
the output is [B, C, D, Z, null, 10].That is insertion order is preserved.
Example:
import java.util.*;
class LinkedHashSetDemo
{
public static void main(String[] args)
{
LinkedHashSet h=new LinkedHashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z"));//false
System.out.println(h);//[B, C, D, Z, null, 10]
}
}
Note: LinkedHashSet and LinkedHashMap commonly used for implementing
cache applications where insertion order must be preserved and duplicates
are not allowed.
SortedSet:
1) It is child interface of Set.
2) If we want to represent a group of unique objects according to some
sorting order then we should go for SortedSet interface.
3) That sorting order can be either default natural sorting (or) customized
sorting order.
SortedSet interface define the following 6 specific methods.
1) Object first();
2) Object last();
3) SortedSet headSet(Object o);
Returns the SortedSet whose elements are <=o.
4) SortedSet tailSet(Object o);
5)
6)
TreeSet:
1) The underlying data structure is balanced tree.
2) Duplicate objects are not allowed.
3) Insertion order is not preserved and it is based on some sorting order
of objects.
4) Heterogeneous objects are not allowed if we are trying to insert
heterogeneous objects then we will get ClassCastException.
5) Null insertion is possible(only once).
Constructors:
1) TreeSet t=new TreeSet();
Creates an empty TreeSet object where all elements will be inserted
according to default natural sorting order.
2) TreeSet t=new TreeSet(Comparator c);
Creates an empty TreeSet object where all objects will be inserted
according to customized sorting order specified by Comparator object.
3) TreeSet t=new TreeSet(SortedSet s);
4) TreeSet t=new TreeSet(Collection c);
Example 1:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
364
Example 3:
class Test
{
public static void main(String[] args)
{
System.out.println("A".compareTo("Z"));//-25
System.out.println("Z".compareTo("K"));//15
System.out.println("A".compareTo("A"));//0
//System.out.println("A".compareTo(new
Integer(10)));//Test.java:8: compareTo(java.lang.String) in java.lang.String
cannot be applied to (java.lang.Integer)
//System.out.println("A".compareTo(null));//NullPointerException
}
}
If we are depending on default natural sorting order then internally JVM
will use compareTo() method to arrange objects in sorting order.
Example 4:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
366
t.add(10);
t.add(0);
t.add(15);
t.add(10);
System.out.println(t);//[0, 10, 15]
}
}
If we are not satisfying with default natural sorting order (or) if default
natural sorting order is not available then we can define our own
customized sorting by Comparator object.
Comparable meant for default natural sorting order.
Comparator meant for customized sorting order.
Comparator interface:
Comparator interface present in java.util package this interface defines
the following 2 methods.
1) public int compare(Object obj1,Object Obj2);
Diagram:
367
369
System.out.println(t);//[ShobaRani,
Roja,
Ramulamma,
RajaKumari, GangaBhavani]
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String s1=obj1.toString();
String s2=(String)obj2;
//return s2.compareTo(s1);
return -s1.compareTo(s2);
}
}
Requirement: Write a program to insert StringBuffer objects into the
TreeSet where the sorting order is alphabetical order.
Program:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet(new MyComparator());
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("K"));
t.add(new StringBuffer("L"));
System.out.println(t);// [A, K, L, Z]
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s1.compareTo(s2);
}
}
370
return 1;
}
else return 0;
}
}
class CompComp
{
public static void main(String[] args)
{
Employee e1=new Employee("nag",100);
Employee e2=new Employee("balaiah",200);
Employee e3=new Employee("chiru",50);
Employee e4=new Employee("venki",150);
Employee e5=new Employee("nag",100);
TreeSet t1=new TreeSet();
t1.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t1);//[chiru----50,
nag----100,
venki----150,
balaiah----200]
TreeSet t2=new TreeSet(new MyComparator());
t2.add(e1);
t2.add(e2);
t2.add(e3);
t2.add(e4);
t2.add(e5);
System.out.println(t2);//[balaiah----200, chiru----50, nag----100,
venki----150]
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Employee e1=(Employee)obj1;
Employee e2=(Employee)obj2;
String s1=e1.name;
String s2=e2.name;
373
return s1.compareTo(s2);
}
}
Compression of Comparable and Comparator?
Comparable
Comparator
1) Comparable meant for default
1) Comparator
meant
for
natural sorting order.
customized sorting order.
2) Present in java.lang package.
2) Present in java.util package.
3) Contains only one method.
3) Contains 2 methods.
compareTo() method.
Compare() method.
Equals() method.
4) String class and all wrapper
4) No
predefined
class
Classes
implements
implements Comparator.
Comparable interface.
Compression of Set implemented class objects:
Property
HashSet
LinkedHashSet
TreeSet
1) Underlying
Hashtable.
LinkedList
Balanced Tree.
Data structure.
+Hashtable.
2) Insertion order. Not preserved.
Preserved.
Not
preserved
(by default).
3) Duplicate
Not allowed.
Not allowed.
Not allowed.
objects.
4) Sorting order.
Not applicable.
Not applicable.
Applicable.
5) Heterogeneous Allowed.
Allowed.
Not allowed.
objects.
6) Null insertion.
Allowed.
Allowed.
For the empty
TreeSet as the
1st element null
insertion
is
possible in all
other cases we
will get NPE.
Map:
1) If we want to represent a group of objects as key-value pair then we
should go for Map interface.
2) Both key and value are objects only.
3) Duplicate keys are not allowed but values can be duplicated.
4) Each key-value pair is called one entry.
Diagram:
374
Diagram:
1) No method is synchronized.
2) Multiple Threads can operate
simultaneously on HashMap
object and hence it is not
Thread safe.
3) Relatively performance is high.
4) Null is allowed for both key and
value.
5) It is non legacy and introduced
in 1.2v.
Example:
import java.util.*;
class HashMapDemo
{
public static void main(String[] args)
{
HashMap m=new HashMap();
m.put("chiranjeevi",700);
m.put("balaiah",800);
m.put("venkatesh",200);
m.put("nagarjuna",500);
System.out.println(m);//{nagarjuna=500, venkatesh=200,
balaiah=800, chiranjeevi=700}
System.out.println(m.put("chiranjeevi",100));//700
Set s=m.keySet();
377
380
Example 1:
import java.util.*;
class TreeMapDemo
{
public static void main(String[] args)
{
TreeMap t=new TreeMap();
t.put(100,"ZZZ");
t.put(103,"YYY");
t.put(101,"XXX");
t.put(104,106);
t.put(107,null);
//t.put("FFF","XXX");//ClassCastException
//t.put(null,"xxx");//NullPointerException
System.out.println(t);//{100=ZZZ, 101=XXX, 103=YYY,
104=106, 107=null}
}
}
Example 2:
import java.util.*;
class TreeMapDemo
{
public static void main(String[] args)
{
TreeMap t=new TreeMap(new MyComparator());
t.put("XXX",10);
t.put("AAA",20);
t.put("ZZZ",30);
t.put("LLL",40);
System.out.println(t);//{ZZZ=30, XXX=10, LLL=40, AAA=20}
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s2.compareTo(s1);
}
382
}
Hashtable:
1) The underlying data structure is Hashtable.
2) Insertion order is not preserved and it is based on hash code of the
keys.
3) Heterogeneous objects are allowed for both keys and values.
4) Null key (or) null value is not allowed otherwise we will get
NullPointerException.
5) Duplicate keys are allowed but values can be duplicated.
Constructors:
1) Hashtable h=new Hashtable();
Creates an empty Hashtable object with default initialcapacity 11 and
default fill ratio 0.75.
2) Hashtable h=new Hashtable(int initialcapacity);
3) Hashtable h=new Hashtable(int initialcapacity,float fillratio);
4) Hashtable h=new Hashtable (Map m);
Example:
import java.util.*;
class HashtableDemo
{
public static void main(String[] args)
{
Hashtable h=new Hashtable();
h.put(new Temp(5),"A");
h.put(new Temp(2),"B");
h.put(new Temp(6),"C");
h.put(new Temp(15),"D");
h.put(new Temp(23),"E");
h.put(new Temp(16),"F");
System.out.println(h);//{6=C, 16=F, 5=A, 15=D, 2=B, 23=E}
}
}
class Temp
{
int i;
Temp(int i)
{
this.i=i;
}
public int hashCode()
{
383
return i;
}
public String toString()
{
return i+"";
}
}
Diagram:
Properties:
1) Properties class is the child class of Hashtable.
2) If anything which changes frequently such type of values not
recommended to hardcode in java application because for every
change we have to recompile, rebuild and redeployed the application
and even server restart also required sometimes it creates a big
business impact to the client.
3) Such type of variable things we have to hardcode in property files and
we have to read the values from the property files.
4) The main advantage in this approach is if there is any change in
property files automatically those changes will be available to java
application just redeployment is enough.
5) By using Properties object we can read and hold properties from
property files into java application.
Constructor:
Properties p=new Properties();
In properties both key and value should be String type only.
Methods:
1) String getPrperty(String propertyname) ;
Returns the value associated with specified property.
2) String setproperty(String propertyname,String propertyvalue);
To set a new property.
3) Enumeration propertyNames();
385
Example:
import java.util.*;
import java.io.*;
class PropertiesDemo
{
public static void main(String[] args)throws Exception
{
Properties p=new Properties();
FileInputStream fis=new FileInputStream("abc.properties");
p.load(fis);
System.out.println(p);//{user=scott,
password=tiger,
venki=8888}
String s=p.getProperty("venki");
System.out.println(s);//8888
p.setProperty("nag","9999999");
Enumeration e=p.propertyNames();
while(e.hasMoreElements())
{
String s1=(String)e.nextElement();
System.out.println(s1);//nag
//user
//password
//venki
}
FileOutputStream fos=new FileOutputStream("abc.properties");
p.store(fos,"updated by bhaskar for scjp demo class");
}
}
386
Property file:
2) Usually Queue follows first in first out order but based on our
requirement we can implement our own order also.
3) From 1.5v onwards LinkedList also implements Queue interface.
4) LinkedList based implementation of Queue always follows first in first
out order.
Queue interface methods:
1) boolean after(Object o);
To add an object to the Queue.
2) Object poll() ;
To remove and return head element of the Queue, if Queue is empty
then we will get null.
3) Object remove();
To remove and return head element of the Queue. If Queue is empty
then
this
method
raises
Runtime
Exception
saying
NoSuchElementException.
4) Object peek();
To return head element of the Queue without removal, if Queue is
empty this method returns null.
5) Object element();
It returns head element of the Queue and if Queue is empty then it will
raise Runtime Exception saying NoSuchElementException.
PriorityQueue:
387
388
Note: Some platforms may not provide proper supports for PriorityQueue
[windowsXP].
Example 2:
import java.util.*;
class PriorityQueueDemo
{
public static void main(String[] args)
{
PriorityQueue q=new PriorityQueue(15,new MyComparator());
q.offer("A");
q.offer("Z");
q.offer("L");
q.offer("B");
System.out.println(q);//[Z, B, L, A]
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String s1=(String)obj1;
String s2=obj2.toString();
return s2.compareTo(s1);
}
}
1.6v Enhancements (NavigableSet and NavigableMap)
NavigableSet:
1) It is the child interface of SortedSet.
2) It provides several methods for navigation purposes.
Diagram:
389
1)
2)
3)
4)
5)
6)
7)
Diagram:
Example:
import java.util.*;
class NavigableSetDemo
{
public static void main(String[] args)
{
TreeSet<Integer> t=new TreeSet<Integer>();
t.add(1000);
t.add(2000);
t.add(3000);
t.add(4000);
t.add(5000);
System.out.println(t);//[1000, 2000, 3000, 4000, 5000]
390
System.out.println(t.ceiling(2000));//2000
System.out.println(t.higher(2000));//3000
System.out.println(t.floor(3000));//3000
System.out.println(t.lower(3000));//2000
System.out.println(t.pollFirst());//1000
System.out.println(t.pollLast());//5000
System.out.println(t.descendingSet());//[4000, 3000, 2000]
System.out.println(t);//[2000, 3000, 4000]
}
}
NavigableMap:
It is the child interface of SortedMap and it defines several methods for
navigation purpose.
Diagram:
{
TreeMap<String,String> t=new TreeMap<String,String>();
t.put("b","banana");
t.put("c","cat");
t.put("a","apple");
t.put("d","dog");
t.put("g","gun");
System.out.println(t);//{a=apple, b=banana, c=cat, d=dog,
g=gun}
System.out.println(t.ceilingKey("c"));//c
System.out.println(t.higherKey("e"));//g
System.out.println(t.floorKey("e"));//d
System.out.println(t.lowerKey("e"));//d
System.out.println(t.pollFirstEntry());//a=apple
System.out.println(t.pollLastEntry());//g=gun
System.out.println(t.descendingMap());//{d=dog,
c=cat,
b=banana}
System.out.println(t);//{b=banana, c=cat, d=dog}
}
}
Diagram:
Collections class:
Collections class defines several utility methods for collection objects.
Sorting the elements of a List:
Collections class defines the following methods to perform sorting the
elements of a List.
public static void sort(List l);
To sort the elements of List according to default natural sorting order in
this case the elements should be homogeneous and comparable
otherwise we will get ClassCastException.
The List should not contain null otherwise we will get
NullPointerException.
public static void sort(List l,Comparator c);
392
{
String s1=(String)obj1;
String s2=obj2.toString();
return s2.compareTo(s1);
}
}
Searching the elements of a List:
Collections class defines the following methods to search the elements
of a List.
public static int binarySearch(List l,Object obj);
If the List is sorted according to default natural sorting order then we
have to use this method.
public static int binarySearch(List l,Object obj,Comparator c);
If the List is sorted according to Comparator then we have to use this
method.
394
Program 2:
import java.util.*;
class CollectionsSearchDemo
{
public static void main(String[] args)
{
ArrayList l=new ArrayList();
l.add(15);
l.add(0);
l.add(20);
l.add(10);
l.add(5);
System.out.println(l);//[15, 0, 20, 10, 5]
Collections.sort(l,new MyComparator());
System.out.println(l);//[20, 15, 10, 5, 0]
System.out.println(Collections.binarySearch(l,10,new
MyComparator()));//2
System.out.println(Collections.binarySearch(l,13,new
MyComparator()));//-3
System.out.println(Collections.binarySearch(l,17));//-6
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
return i2.compareTo(i1);
}
}
Diagram:
Conclusions:
395
Example:
396
{
int[] a={10,5,20,11,6};
System.out.println("primitive array before sorting");
for(int a1:a)
{
System.out.println(a1);
}
Arrays.sort(a);
System.out.println("primitive array after sorting");
for(int a1: a)
{
System.out.println(a1);
}
String[] s={"A","Z","B"};
System.out.println("Object array before sorting");
for(String s1: s)
{
System.out.println(s1);
}
Arrays.sort(s);
System.out.println("Object array after sorting");
for(String s1:s)
{
System.out.println(s1);
}
Arrays.sort(s,new MyComparator());
System.out.println("Object array after sorting by Comparator:");
for(String s1: s)
{
System.out.println(s1);
}
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s2.compareTo(s1);
398
}
}
Searching the elements of array:
Arrays class defines the following methods to search elements of array.
1) public static int binarySearch(primitive[] p,primitive key);
2) public static int binarySearch(Object[] p, object key);
3) public
static
int
binarySearch(Object[]
p,Object
key,Comparator c);
All rules of Arrays class binarySearch() method are exactly same as
Collections class binarySearch() method.
Program: To search elements of array.
import java.util.*;
class ArraysSearchDemo
{
public static void main(String[] args)
{
int[] a={10,5,20,11,6};
Arrays.sort(a);
System.out.println(Arrays.binarySearch(a,6));//1
System.out.println(Arrays.binarySearch(a,14));//-5
String[] s={"A","Z","B"};
Arrays.sort(s);
System.out.println(Arrays.binarySearch(s,"Z"));//2
System.out.println(Arrays.binarySearch(s,"S"));//-3
Arrays.sort(s,new MyComparator());
System.out.println(Arrays.binarySearch(s,"Z",new
MyComparator()));//0
System.out.println(Arrays.binarySearch(s,"S",new
MyComparator()));//-2
System.out.println(Arrays.binarySearch(s,"N"));//-4(unpredictable
result)
}
}
Converting array to List:
Arrays class defines the following method to view array as List.
public static List asList (Object[] o);
Strictly speaking we are not creating an independent List object just we
are viewing array in List form.
By using List reference if we are performing any change automatically
these changes will be reflected to array reference similarly by using
399
400
Generics
Agenda:
1) Introduction
2) Generic Classes
3) Bounded Types
4) Generic methods and wild card character
5) Communication with non generic code
6) Conclusions
Introduction:
Case 1:
Arrays are always type safe that is we can provide the guarantee for
the type of elements present inside array.
For example if our programming requirement is to hold String type of
objects it is recommended to use String array. In the case of string
array we can add only string type of objects by mistake if we are trying
to add any other type we will get compile time error.
401
Example:
Example:
402
For this ArrayList we can add only string type of objects by mistake if
we are trying to add any other type we will get compile time error that
is through generics we are getting type safety.
403
Concluson2:
For the parameter type we can use any class or interface but not
primitive value(type).
Example:
Generic classes:
Until1.4v ArrayList class is declared as follows.
Example:
class ArrayList
{
add(Object o);
Object get(int index);
404
add() method can take object as the argument and hence we can add
any type of object to the ArrayList. Due to this we are not getting type
safety.
The return type of get() method is object hence at the time of retrieval
compulsory we should perform type casting.
But in 1.5v a generic version of ArrayList class is declared as follows.
Example:
Example:
ArrayList<String> l=new ArrayList<String>();
For this requirement compiler considered ArrayList class is
Example:
class ArrayList<String>
{
add(String s);
String get(int index);
}
add() method can take only string type as argument hence we can add
only string type of objects to the List. By mistake if we are trying to add
any other type we will get compile time error.
Example:
405
Based on our requirement we can create our own generic classes also.
Example:
class Account<T>
{}
Account<Gold> g1=new Account<Gold>();
Account<Silver> g2=new Account<Silver>();
Example:
class UDGenerics<T>
{
T obj;
UDGenerics(T obj)
{
this.obj=obj;
}
406
Here as the type parameter we can pass any type and there are no
restrictions hence it is unbounded type.
Example 2:
class Test<T extends X>
{}
If x is a class then as the type parameter we can pass either x or its
child classes.
If x is an interface then as the type parameter we can pass either x or
its implementation classes.
Example 1:
Example 2:
409
Output:
Test.java:12: unexpected type
Found :?
Required: class or interface without bounds
ArrayList<?> l7=new ArrayList<?>();
We can declare the type parameter either at class level or method
level.
Declaring type parameter at class level:
class Test<T>
{
We can use anywhere this 'T'.
}
Declaring type parameter at method level:
We have to declare just before return type.
Example:
public <T> void methodOne1(T t){}//valid
public <T extends Number> void methodOne2(T t){}//valid
public <T extends Number&Comparable> void methodOne3(T t){}//valid
public <T extends Number&Comparable&Runnable> void methodOne4(T t)
{}//valid
public <T extends Number&Thread> void methodOne(T t){}//invalid
Output:
Compile time error.
Test.java:7: interface expected here
public <T extends Number&Thread> void methodOne(T t){}//valid
public <T extends Runnable&Number> void methodOne(T t){}//invalid
Output:
Compile time error.
Test.java:8: interface expected here
public <T extends Runnable&Number> void methodOne(T t){}//valid
Communication with non generic code:
To provide compatibility with old version sun people compramized the
concept of generics in very few areas the following is one such area.
Example:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> l=new ArrayList<String>();
411
l.add("A");
//l.add(10);//C.E:cannot find symbol,method add(int)
methodOne(l);
l.add(10.5);//C.E:cannot find symbol,method add(double)
System.out.println(l);//[A, 10, 10.5, true]
}
public static void methodOne(ArrayList l)
{
l.add(10);
l.add(10.5);
l.add(true);
}
}
Note:
Generics concept is applicable only at compile time, at runtime there is
no such type of concept. Hence the following declarations are equal.
ArrayList l=new ArrayList<String>();
ArrayList l=new ArrayList<Integer>();
All are equal.
ArrayList l=new ArrayList();
Example 1:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList l=new ArrayList<String>();
l.add(10);
l.add(10.5);
l.add(true);
System.out.println(l);// [10, 10.5, true]
}
}
Example 2:
import java.util.*;
class Test
{
public void methodOne(ArrayList<String> l){}
public void methodOne(ArrayList<Integer> l){}
}
Output:
412
Inner Classes
Example:
414
Diagram:
Note: The relationship between outer class and inner class is not IS-A
relationship and it is Has-A relationship.
Based on the purpose and position of declaration all inner classes are
divided into 4 types. They are:
1) Normal or Regular inner classes
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes.
1. Normal (or) Regular inner class: If we are declaring any named class
inside another class directly without static modifier such type of inner classes
are called normal or regular inner classes.
Example:
class Outer
{
class Inner
{
}
}
Output:
415
Example:
class Outer
{
class Inner
{
}
public static void main(String[] args)
{
System.out.println("outer class main method");
}
}
Output:
E:\scjp>javac Outer.java
Outer.java:5: inner classes cannot have static declarations
public static void main(String[] args)
Accessing inner class code from static area of outer class:
Example:
class Outer
{
class Inner
{
public void methodOne(){
System.out.println("inner class method");
}
}
public static void main(String[] args)
{
}
}
Accessing inner class code from instance area of outer class:
Example:
class Outer
{
class Inner
{
public void methodOne()
{
System.out.println("inner class method");
}
}
public void methodTwo()
{
Inner i=new Inner();
i.methodOne();
}
417
418
From inner class we can access all members of outer class (both static
and non-static, private and non private methods and variables) directly.
Example:
class Outer
{
int x=10;
static int y=20;
class Inner{
public void methodOne()
{
System.out.println(x);//10
System.out.println(y);//20
}
}
public static void main(String[] args)
{
new Outer().new Inner().methodOne();
}
}
Within the inner class this always refers current inner class object. To
refer current outer class object we have to use outer class
name.this.
Example:
class Outer
{
int x=10;
class Inner
{
int x=100;
public void methodOne()
419
{
int x=1000;
System.out.println(x);//1000
System.out.println(this.x);//100
System.out.println(Outer.this.x);//10
}
}
public static void main(String[] args)
{
new Outer().new Inner().methodOne();
}
}
class Inner
{
public void sum(int i,int j)
{
System.out.println("The sum:"+(i+j));
}
}
Inner i=new Inner();
i.sum(10,20);
;;;;;;;;;;;;;
i.sum(100,200);
;;;;;;;;;;;;;;;
i.sum(1000,2000);
;;;;;;;;;;;;;;;;;
}
public static void main(String[] args)
{
new Test().methodOne();
}
}
Output:
The sum: 30
The sum: 300
The sum: 3000
If we are declaring inner class inside instance method then we can
access both static and non static members of outer class directly.
But if we are declaring inner class inside static method then we can
access only static members of outer class directly and we cant access
instance members directly.
Example:
class Test
{
int x=10;
static int y=20;
public void methodOne()
{
class Inner
{
public void methodTwo()
{
421
System.out.println(x);//10
System.out.println(y);//20
}
}
Inner i=new Inner();
i.methodTwo();
}
public static void main(String[] args)
{
new Test().methodOne();
}
}
}
}
If we declared y as final then we wont get any compile time error.
Consider the following declaration.
class Test
{
int i=10;
static int j=20;
public void methodOne()
{
int k=30;
final int l=40;
class Inner
{
public void methodTwo()
{
System.out.println(i);
System.out.println(j);
line 1
System.out.println(k);
System.out.println(l);
}
}
Inner i=new Inner();
i.methodTwo();
}
public static void main(String[] args)
{
new Test().methodOne();
}
}
At line 1 which of the following variables we can access?
423
2) abstract
3) strictfp
By mistake if we are declaring any other modifier we will get compile
time error.
Anonymous inner classes:
Sometimes we can declare inner class without name such type of inner
classes are called anonymous inner classes.
The main objective of anonymous inner classes is just for instant
use.
There are 3 types of anonymous inner classes
1) Anonymous inner class that extends a class.
2) Anonymous inner class that implements an interface.
3) Anonymous inner class that defined inside method arguments.
Anonymous inner class that extends a class:
class PopCorn
{
public void taste()
{
System.out.println("spicy");
}
}
class Test
{
public static void main(String[] args)
{
PopCorn p=new PopCorn()
{
public void taste()
{
System.out.println("salty");
}
};
p.taste();//salty
PopCorn p1=new PopCorn();
p1.taste();//spicy
}
}
Analysis:
1) PopCorn p=new PopCorn();
We are just creating a PopCorn object.
2) PopCorn p=new PopCorn()
424
{
};
We are creating child class without name for the PopCorn class and for
that child class we are creating an object with Parent PopCorn
reference.
3) PopCorn p=new PopCorn()
{
public void taste()
{
System.out.println("salty");
}
};
1) We are creating child class for PopCorn without name.
2) We are overriding taste() method.
3) We are creating object for that child class with parent reference.
Note: Inside Anonymous inner classes we can take or declare new methods
but outside of anonymous inner classes we cant call these methods directly
because we are depending on parent reference.[parent reference can be
used to hold child class object but by using that reference we cant call child
specific methods]. These methods just for internal purpose only.
Example 1:
class PopCorn
{
public void taste()
{
System.out.println("spicy");
}
}
class Test
{
public static void main(String[] args)
{
PopCorn p=new PopCorn()
{
public void taste()
{
methodOne();//valid call(internal purpose)
System.out.println("salty");
}
public void methodOne()
425
{
System.out.println("child specific method");
}
};
//p.methodOne();//here we can not call(outside inner class)
p.taste();//salty
PopCorn p1=new PopCorn();
p1.taste();//spicy
}
}
Output:
Child specific method
Salty
Spicy
Example 2:
class Test
{
public static void main(String[] args)
{
Thread t=new Thread()
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child thread");
}
}
};
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
Anonymous Inner Class that implements an interface:
Example:
class InnerClassesDemo
{
426
System.out.println("main thread");
}
}
}
Output:
This output belongs to example 2, anonymous inner class that
implements an interface example and anonymous inner class that
define inside method arguments example.
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread
Child thread
Difference between general class and anonymous inner classes:
General Class
Anonymous Inner Class
1) A general class can extends
1) Ofcource
anonymous
inner
only one class at a time.
class also can extends only one
class at a time.
2) A general class can implement
2) But anonymous inner class can
any no. Of interfaces at a time.
implement only one interface
at a time.
3) A general class can extends a
3) But anonymous inner class can
class and can implement an
extends
a
class
or
can
interface simultaneously.
implements an interface but
not both simultaneously.
428
Example:
class Test
{
static class Nested
{
public static void main(String[] args)
{
System.out.println("nested class main method");
}
}
public static void main(String[] args)
{
429
Internationalization
3) DateFormat
1. Locale: A Locale object can be used to represent a geographic (country)
location (or) language.
Locale class present in java.util package.
It is a final class and direct child class of Object implements Cloneable
and Serializable Interfaces.
How to create a Locale object:
We can create a Locale object by using the following constructors of
Locale class.
1) Locale l=new Locale(String language);
2) Locale l=new Locale(String language,String country);
Locale class already defines some predefined Locale constants. We can
use these constants directly.
Example:
Locale. UK
Locale. US
Locale. ITALY
Locale. CHINA
Important methods of Locale class:
1) public static Locale getDefault()
2) public static void setDefault(Locale l)
3) public String getLanguage()
4) public String getDisplayLanguage(Locale l)
5) public String getCountry()
6) public String getDisplayCountry(Locale l)
7) public static String[] getISOLanguages()
8) public static String[] getISOCountries()
9) public static Locale[] getAvailableLocales()
Example for Locale:
import java.util.*;
class LocaleDemo{
public static void main(String args[]){
Locale l1=Locale.getDefault();
//System.out.println(l1.getCountry()+"....."+l1.getLanguage());
//System.out.println(l1.getDisplayCountry()+"....."+l1.getDisplayLanguage());
Locale l2=new Locale("pa","IN");
Locale.setDefault(l2);
String[] s3=Locale.getISOLanguages();
for(String s4:s3)
{
//System.out.print("ISO language is :");
//System.out.println(s4);
}
String[] s4=Locale.getISOCountries();
432
for(String s5:s4)
{
System.out.print("ISO Country is:");
System.out.println(s5);
}
Locale[] s=Locale.getAvailableLocales();
for(Locale s1:s)
{
//System.out.print("Available locales is:");
//System.out.println(s1.getDisplayCountry()
+"......"+s1.getDisplayLanguage());
}}}
NumberFormat:
Various countries follow various styles to represent number.
Example:
1,23,456.789------------INDIA
123,456.789-------------US
123.456,789-------------ITALY
By using NumberFormat class we can format a number according to a
particular Locale.
NumberFormat class present in java.Text package and it is an abstract
class.
Hence we cant create an object by using constructor.
NumberFormat nf=new NumberFormat(); --------invalid
Getting NumberFormat object for the default Locale:
NumberFormat class defines the following methods for this.
import java.util.*;
import java.text.*;
class NumberFormatDemo
{
public static void main(String args[]){
double d=123456.789;
NumberFormat nf=NumberFormat.getInstance(Locale.ITALY);
System.out.println("ITALY form is :"+nf.format(d));
}
}
Output:
ITALY form is :123.456,789
Requirement: Write a program to print a java number in INDIA, UK, US and
ITALY currency formats.
Program:
import java.util.*;
import java.text.*;
class NumberFormatDemo
{
public static void main(String args[]){
double d=123456.789;
Locale INDIA=new Locale("pa","IN");
NumberFormat nf=NumberFormat.getCurrencyInstance(INDIA);
System.out.println("INDIA notation is :"+nf.format(d));
NumberFormat nf1=NumberFormat.getCurrencyInstance(Locale.UK);
System.out.println("UK notation is :"+nf1.format(d));
NumberFormat nf2=NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("US notation is :"+nf2.format(d));
NumberFormat nf3=NumberFormat.getCurrencyInstance(Locale.ITALY);
System.out.println("ITALY notation is :"+nf3.format(d));
}}
Output:
INDIA notation is: INR 123,456.79
UK notation is: 123,456.79
US notation is: $123,456.79
ITALY notation is: 123.456,79
Setting Maximum, Minimum, Fraction and Integer digits:
NumberFormat class defines the following methods for this purpose.
1) public void setMaximumFractionDigits(int n);
2) public void setMinimumFractionDigits(int n);
3) public void setMaximumIntegerDigits(int n);
4) public void setMinimumIntegerDigits(int n);
Example:
import java.text.*;
public class NumberFormatExample
{
434
435
Example:
import java.text.*;
import java.util.*;
public class DateFormatDemo
{
public static void main(String args[]){
DateFormat ITALY=DateFormat.getDateTimeInstance(0,0,Locale.ITALY);
System.out.println("ITALY style is:"+ITALY.format(new Date()));
}
}
Output:
ITALY style is: mercoled 20 luglio 2011 23.21.30 IST
Development
Javac: we can use Javac to compile a single or group of .java files.
Syntax:
437
Classpath: Class path describes the location where the required .class
files are available. We can set the class path in the following 3 ways.
1) Permanently by using environment variable classpath. This class
path will be preserved after system restart also.
2) Temporary for a particular command prompt level by using set
command.
Example:
Once if you close the command prompt automatically this class path
will be lost.
3) We can set the class path for a particular command level by using
cp (or) class path. This class path is applicable only for that
command execution. After executing the command this classpath will
be lost.
Among the 3 ways of setting the class path the most common way is
setting class path at command level by using cp.
Example 1:
class Rain
{
public static void main(String args[]){
System.out.println("Raining of jobs these days");
}
}
438
Analysis:
Example 2:
Analysis:
Example 3:
439
Analysis:
Analysis:
Note: Whenever we are placing jar file in the classpath compulsory we have
to specify the name of the jar file also and just location is not enough.
System properties:
For every system some persistence information is available in the form
of system properties. These may include name of the os, java version,
vendor of jvm etc.
We can get system properties by using getProperties() method of
system class. The following program displays all the system properties.
Example 7:
import java.util.*;
class Test{
public static void main(String args[]){
//Properties is a class in util package.
//here getPropertes() method returns the Properties object.
Properties p=System.getProperties();
p.list(System.out);
}
}
How to set system property from the command prompt:
442
JDK=JRE+Development Tools.
JRE=JVM+Libraries.
JRE is the part of JDK.
Jvm is the part of JRE.
Note: At client side JRE is required and at developers side JDK is required.
Shortcut way to place a jar files:
If we are placing jar file in the following location then it is not required
to set classpath explicitly.
443
Diagram:
ENUM
444
Diagram:
}
Output:
D:\Enum>java Test
KF
Note: Every enum constant internally static hence we can access by using
enum name.
Enum vs switch statement:
Until 1.4 versions the allowed types for the switch statement are byte,
short, char int. But from 1.5 version onwards in addition to this the
corresponding wrapper classes and enum type also allowed. That is
from 1.5 version onwards we can use enum type as argument to switch
statement.
Diagram:
Example:
enum Beer
{
KF,KO,RC,FO;
}
class Test{
public static void main(String args[]){
Beer b1=Beer.RC;
switch(b1){
case KF:
System.out.println("it is childrens brand");
break;
case KO:
System.out.println("it is too lite");
break;
case RC:
System.out.println("it is too hot");
break;
446
case FO:
System.out.println("buy one get one");
break;
default:
System.out.println("other brands are not good");
}
}}
Output:
D:\Enum>java Test
It is too hot
If we are passing enum type as argument to switch statement then
every case label should be a valid enum constant otherwise we will get
compile time error.
Example:
enum Beer
{
KF,KO,RC,FO;
}
class Test{
public static void main(String args[]){
Beer b1=Beer.RC;
switch(b1){
case KF:
case RC:
case KALYANI:
}}}
Output:
Compile time error.
D:\Enum>javac Test.java
Test.java:11: unqualified enumeration constant name required
case KALYANI:
We can declare enum either outside the class or within the class but
not inside a method. If we declare enum outside the class the allowed
modifiers are:
1) public
2) default
3) strictfp.
If we declare enum inside a class then the allowed modifiers are:
1) public
private
2) default + protected
447
3) strictfp
static
Example:
Enum vs inheritance:
Every enum in java is the direct child class of java.lang.Enum class
hence it is not possible to extends any other enum.
Every enum is implicitly final hence we cant create child enum.
Because of above reasons we can conclude inheritance concept is not
applicable for enums explicitly.
But enum can implement any no. Of interfaces simultaneously.
Example:
Example:
enum Beer
{
KF(100),KO(70),RC(65),Fo(90),KALYANI;
int price;
Beer(int price){
this.price=price;
}
Beer()
{
this.price=125;
}
public int getPrice()
{
return price;
}
}
class Test{
public static void main(String args[]){
451
Beer[] b=Beer.values();
for(Beer b1:b)
{
System.out.println(b1+"......."+b1.getPrice());
}}}
Inside enum we can take both instance and static methods but it is not
possible to take abstract methods.
Case 1:
Every enum constant represents an object hence whatever the
methods we can apply on the normal objects we can apply the same
methods on enum constants also.
Which of the following expressions are valid?
1) Beer.KF==Beer.RC----------------------------> false
2) Beer.KF.equals(Beer.RC) ------------------->false
3) Beer.KF<Beer.RC------------------------------>invalid
4) Beer.KF.ordinal()<Beer.RC.ordinal()------>valid
Case 2:
Example 1:
package pack1;
public enum Fish
{
STAR,GUPPY;
}
Example 2:
package pack2;
//import static pack1.Fish.*;
import static pack1.Fish.STAR;
class A
{
public static void main(String args[]){
System.out.println(STAR);
}
}
1) Import pack1.*; ---------------------------->invalid
2) Import pack1.Fish; ------------------------->invalid
3) import static pack1.Fish.*; --------------->valid
4) import static pack1.Fish.STAR; ---------->valid
Example 3:
package pack3;
//import pack1.Fish;
452
import pack1.*;
//import static pack1.Fish.GUPPY;
import static pack1.Fish.*;
class B
{
public static void main(String args[]){
Fish f=Fish.STAR;
System.out.println(GUPPY);
}
}
Case 3:
enum Color
{
BLUE,RED
{
public void info(){
System.out.println("Dangerous color");
}
},GREEN;
public void info()
{
System.out.println("Universal color");
}}
class Test{
public static void main(String args[]){
Color[] c=Color.values();
for(Color c1:c)
{
c1.info();
}}}
Output:
Universal color
Dangerous color
Universal color
Regular expression
Quantifiers:
Quantifiers can be used to specify no of characters to match.
a-----------------------Exactly one a
a+----------------------At least one a
a*----------------------Any no of as including zero number
a? ----------------------At most one a
Example:
456
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("abaabaaab");
while(m.find())
{
System.out.println(m.start()+"-------"+m.group());
}
}
}
Output:
//solutions
}
}
}
Example 2:
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("\\."); (or)[.]
String[] s=p.split("www.dugrajobs.com");
for(String s1:s)
{
System.out.println(s1);//www
//dugrajobs
//com
}
}
}
String class split() method:
String class also contains split() method to split the given string
against a regular expression.
Example:
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
String s="www.durgajobs.com";
String[] s1=s.split("\\.");
for(String s2:s1)
{
System.out.println(s2);//www
//durgajobs
//com
}
}
}
Note:
458
}
}
Requirement: Write a regular expression to represent all valid identifiers in
yava language.
Rules:
The allowed characters are:
1) a to z, A to Z, 0 to 9, -,#
2) The 1st character should be alphabet symbol only.
3) The length of the identifier should be at least 2.
Program:
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("[a-zA-Z][a-zA-Z0-9-#]+"); (or)
Pattern p=Pattern.compile("[a-zA-Z][a-zA-Z0-9-#][a-zA-Z0-9#]*");
Matcher m=p.matcher(args[0]);
if(m.find()&&m.group().equals(args[0]))
{
System.out.println("valid identifier");
}
else
{
System.out.println("invalid identifier");
}
}
}
Output:
E:\scjp>javac RegularExpressionDemo.java
E:\scjp>java RegularExpressionDemo bhaskar
Valid identifier
E:\scjp>java RegularExpressionDemo ?bhaskar
Invalid identifier
Requirement: Write a regular expression to represent all mobile numbers.
Rules:
1) Should contain exactly 10 digits.
2) The 1st digit should be 7 to 9.
460
Program:
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("[7-9][0-9][0-9][0-9][0-9][0-9][0-9][09][0-9][0-9]");
//Pattern p=Pattern.compile("[7-9][0-9]{9}");
Matcher m=p.matcher(args[0]);
if(m.find()&&m.group().equals(args[0]))
{
System.out.println("valid number");
}
else
{
System.out.println("invalid number");
}
}
}
Analysis:
10 digits mobile:
[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] (or)
[7-9][0-9]{9}
Output:
E:\scjp>javac RegularExpressionDemo.java
E:\scjp>java RegularExpressionDemo 9989308279
Valid number
E:\scjp>java RegularExpressionDemo 6989308279
Invalid number
10 digits (or) 11 digits:
(0?[7-9][0-9]{9})
Output:
E:\scjp>javac RegularExpressionDemo.java
E:\scjp>java RegularExpressionDemo 9989308279
Valid number
E:\scjp>java RegularExpressionDemo 09989308279
Valid number
E:\scjp>java RegularExpressionDemo 919989308279
Invalid number
461
Program:
import java.util.regex.*;
import java.io.*;
class RegularExpressionDemo
{
public static void main(String[] args)throws IOException
{
PrintWriter out=new PrintWriter("output.txt");
BufferedReader
br=new
BufferedReader(new
FileReader("input.txt"));
Pattern p=Pattern.compile("[7-9][0-9]{9}");
String line=br.readLine();
while(line!=null)
{
Matcher m=p.matcher(line);
while(m.find())
{
out.println(m.group());
}
line=br.readLine();
}
out.flush();
}
}
Requirement: Write a program to extract all Mail IDS from the File.
Note: In the above program replace mobile number regular expression with
MAIL ID regular expression.
Requirement: Write a program to display all .txt file names present in
E:\scjp folder.
Program:
463
import java.util.regex.*;
import java.io.*;
class RegularExpressionDemo
{
public static void main(String[] args)throws IOException
{
int count=0;
Pattern p=Pattern.compile("[a-zA-Z0-9-$.]+[.]txt");
File f=new File("E:\\scjp");
String[] s=f.list();
for(String s1:s)
{
Matcher m=p.matcher(s1);
if(m.find()&&m.group().equals(s1))
{
count++;
System.out.println(s1);
}
}
System.out.println(count);
}
}
Output:
input.txt
output.txt
outut.txt
3
464