Java SE 8 Programmer 1 (IZO-808) Study Material - Cleaned
Java SE 8 Programmer 1 (IZO-808) Study Material - Cleaned
Java SE 8 Programmer 1 (IZO-808) Study Material - Cleaned
1 https://www.youtube.com/durgasoftware
OCJA
Table of Contents
1) The Features of Java ……………………………………………………………………………… 3
3) Arrays …………………………………………………………………………………………………. 24
15) Date And Time API (Joda - Time API) ………………………………………………… 390
2 https://www.youtube.com/durgasoftware
OCJA
1) Simple
2) Platform Independent
3) Architecture Neutral
4) Portable
5) Secure
6) Object-Oriented
7) Multithreaded
8) Robust
9) Distributed
10) Interpreted
11) High Performance
12) Dynamic
1) Simple:
Java is very simple and easy to learn (Nursery Level) programming language.
We can write Java programs very easily.
To learn Java no prior knowledge is required.
Most of the complex or confusing features of other languages C,C++ like Pointers etc .. are
removed in Java.
2) Platform Independent:
If we write Java program once, we can run on any platform. i.e Java follows Write Once Run
and Anywhere(WORA) principle.
3) Architecture-Neutral:
Java program never communicates with the platform directly. Changes and upgrades in
operating systems, processors and system resources will not force any changes in Java
Programs.
4) Portable:
We can carry the java byte code to any platform without making any changes.
(Mobile Number Portability in India)
3 https://www.youtube.com/durgasoftware
OCJA
5) Secure:
Java programs never communicate directly with the machine. First converted into byte code
and then converted into machine code by the JVM
If the byte code contains any problem, then JVM won't allow that code to run and will raise
VerifyError. Intenally inside JVM, ByteCode verifier is responsible to verify the byte code.
Hence Java programs won't cause any problem to the System.
7) Multithreaded:
In the case of multithreading, multiple threads can run simultaneously and can perform
specified tasks simultaneously, so that performance of the application will be improved.
Java provides inbuilt support for multi threading by providing a rich API.
8) Robust:
Java is strongly typed language. Compiler will check each and every declaration and
assignments at compile time only for type compatibility. If any problem wrt types, then at
compile time only we can identify the problem.
Java provides Garbage Collector for automatic memory management. Hence there is no
chance of memory related problems.
Java provides inbuilt Exception hanlding, which prevents abnormal termination of the
program at runtime.
Java is platform independent and it can run on any platform.
Because of all these facilities, the chance of failing the program at runtime is very very less and
Hence Java is Robust.
4 https://www.youtube.com/durgasoftware
OCJA
9) Distributed:
If the application is distributed across multiple machines (JVMs), such type of application is
called Distributed Application. Java provides inbuilt support for Distributed programming with
RMI and EJB.
12) Dynamic:
In the case of Java programs, all .class files won't be loaded at the beginning. At runtime if JVM
required any class then only the corresponding .class file will be loaded(Dynamic Loading).The
main advantage is program will always get latest version of .class file and memory utilization
will be improved.
First Java Source File will be compiled into ByteCode. Bytecode is an intermediate and machine
independent code. JVM will interpret byte code into the corresponding machine dependent code
and executes that machine code.
5 https://www.youtube.com/durgasoftware
OCJA
Java Source File Test.java
Note:
JVM (Java Virtual Machine) is an interpreter which is responsible to run java applications line by
line.
Note:
6 https://www.youtube.com/durgasoftware
OCJA
JVM
+ Library
Classes + Development
Tools
JRE
JDK
Note:
On the Developer's Machine we have to install JDK, where as on the client machine we have to
install JRE.
Answer: B and D
Answer: C
7 https://www.youtube.com/durgasoftware
OCJA
Data Types
Every variable has a type, every expression has a type and all types are strictly define more over
every assignment should be checked by the compiler by the type compatibility hence java
language is considered as strongly typed programming language.
Except Boolean and char all remaining data types are considered as signed data types because we
can represent both "+ve" and"-ve" numbers.
8 https://www.youtube.com/durgasoftware
OCJA
Integral Data Types:
byte Data Type:
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 2's complement form.
Example:
byte b=10;
byte b2=130;//C.E:possible loss of precision
found : int
required : byte
byte b=10.5;//C.E:possible loss of precision
byte b=true;//C.E:incompatible types
byte b="ashok";//C.E:incompatible types
found : java.lang.String
required : byte
Note:
byte data type is best suitable if we are handling data in terms of streams either from the file or
from the network.
9 https://www.youtube.com/durgasoftware
OCJA
short Data Type:
The most rarely used data type in java is short.
Size: 2 bytes
Range: s-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
Note:
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.
Example:
int i=130;
int i=10.5;//C.E:possible loss of precision
int i=true;//C.E:incompatible types
Eg 1:
To hold the distance travelled by light in 1000 days , int may not enough, compulsory we should go
for long data type.
Eg 2:
To hold the number of characters present in a big file, int may not enough, compulsory we should
go for long data type. Hence the return type of length() method is long.
10 https://www.youtube.com/durgasoftware
OCJA
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.
Float double
If we want to 5 to 6 decimal places of If we want to 14 to 15 decimal places of
accuracy then we should go for float. accuracy then we should go for double.
Size:4 bytes. Size:8 bytes.
Range:-3.4e38 to 3.4e38. -1.7e308 to1.7e308.
float follows single precision. double follows double precision.
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:
11 https://www.youtube.com/durgasoftware
OCJA
char data type:
Old languages like C & C++ are ASCII code based and the number of ASCII characters are
< 256. To represent these 256 characters, 8 – bits are enough and hence char size in old
languages 1 byte.
But, in java we are allowed to use worldwide any alphabet character and java is Unicode
based. The number of unicode characters are > 256 and <= 65536. To represent all these
characters one byte is not enough compulsory we should go for 2 bytes.
Size: 2 bytes
Range: 0 to 65535
Example:
char ch1=97;
char ch2=65536;//C.E:possible loss of precision
12 https://www.youtube.com/durgasoftware
OCJA
Note:
Literals
Any constant value which can be assigned to the variable is called literal.
Example:
Integral Literals:
For the integral data types (byte, short, int and long) we can specify literal value in the
following ways.
2) Octal literals(base-8):
13 https://www.youtube.com/durgasoftware
OCJA
Example: int x=0x10;
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 of int type but we can specify explicitly as long type by
suffixing with small "l" (or) capital "L".
Example:
int x=10;(valid)
long l=10L;(valid)
long l=10;(valid)
int x=10l;//C.E:possible loss of precision(invalid)
found : long
required : int
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=127;(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)
14 https://www.youtube.com/durgasoftware
OCJA
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:
Example:
double d=123.456D;
We can specify floating point literal only in decimal form and we can't specify in octal and
hexadecimal forms.
Example:
double d=123.456;(valid)
double d=0123.456;(valid) //it is treated as decimal value but not octal
double d=0x123.456;//C.E:malformed floating point literal(invalid)
Which of the following floating point declarations are valid?
float f=123.456; //C.E:possible loss of precision(invalid)
float f=123.456D; //C.E:possible loss of precision(invalid)
double d=0x123.456; //C.E:malformed floating point literal(invalid)
double d=0xFace; (valid)
double d=0xBeef; (valid)
We can assign integral literal directly to the floating point data types and that integral literal can
be specified in decimal , octal and Hexa decimal form also.
Example:
double d=0xBeef;
System.out.println(d);//48879.0
float f = 100f:
System.out.println(f); //100.0
But we can't assign floating point literal directly to the integral types.
Example:
int x=10.0;//C.E:possible loss of precision
We can specify floating point literal even in exponential form also (significant notation).
15 https://www.youtube.com/durgasoftware
OCJA
Example:
double d=10e2;//==>10*102(valid)
System.out.println(d);//1000.0
Boolean literals:
The only allowed values for the boolean type are true (or) false where case is important.
i.e., lower case
Example:
boolean b=true;(valid)
boolean b=0;//C.E:incompatible types(invalid)
boolean b=True;//C.E:cannot find symbol(invalid)
boolean b="true";//C.E:incompatible types(invalid)
Char literals:
1) A char literal can be represented as single character within single quotes .
Example:
char ch='a';(valid)
char ch=a;//C.E:cannot find symbol(invalid)
char ch="a";//C.E:incompatible types(invalid)
char ch='ab';//C.E:unclosed character literal(invalid)
16 https://www.youtube.com/durgasoftware
OCJA
2) We can specify a char literal as integral literal which represents Unicode of that character.
We can specify that integral literal either in decimal or octal or hexadecimal form but allowed
values range is 0 to 65535.
Example:
Example:
char ch='\ubeef';
char ch1='\u0061';
System.out.println(ch1); //a
char ch2=\u0062; //C.E:cannot find symbol
char ch3='\iface'; //C.E:illegal escape character
Every escape character in java acts as a char literal.
Example:
\n New line
\t Horizontal tab
\r Carriage return
\f Form feed
\\ Back slash
17 https://www.youtube.com/durgasoftware
OCJA
Which of the following char declarations are valid?
char ch=a; //C.E:cannot find symbol(invalid)
char ch='ab'; //C.E:unclosed character literal(invalid)
char ch=65536; //C.E:possible loss of precision(invalid)
char ch=\uface; //C.E:illegal character: \64206(invalid)
char ch='/n'; //C.E:unclosed character literal(invalid)
none of the above. (valid)
String literals:
Any sequence of characters with in double quotes is treated as String literal.
Example:
String s="Durga"; (valid)
Binary Literals
Usage of '_' in Numeric Literals
Binary Literals:
For the integral data types until 1.6v we can specified literal value in the following ways
Decimal
Octal
Hexa decimal
But from 1.7v onwards we can specify literal value in binary form also.
The allowed digits are 0 to 1.
Literal value should be prefixed with Ob or OB .
int x = 0b111;
System.out.println(x); // 7
18 https://www.youtube.com/durgasoftware
OCJA
The main advantage of this approach is readability of the code will be improved At the time of
compilation ' _ ' symbols will be removed automatically , hence after compilation the above lines
will become double d = 123456.789
We can use more than one underscore symbol also between the digits.
Example 1:
int x='a';
System.out.println(x);//97
Note: Compiler converts char to int type automatically by implicit type casting.
19 https://www.youtube.com/durgasoftware
OCJA
Example 2:
double d=10;
System.out.println(d);//10.0
Note: Compiler converts int to double type automatically by implicit type casting.
Example:
int x=130;
byte b=(byte)x;
System.out.println(b); //-126
20 https://www.youtube.com/durgasoftware
OCJA
Example 2:
int x=130;
byte b=x;
System.out.println(b); //CE : possible loss of precision
Whenever we are assigning higher datatype value to lower datatype value variable by explicit type
casting ,the most significant bits will be lost i.e., we have considered least significant bits .
Example 3 :
int x=150;
short s=(short)x;
byte b=(byte)x;
System.out.println(s); //150
System.out.println(b); //-106
Whenever we are assigning floating point value to the integral types by explicit type casting, the
digits of after decimal point will be lost .
21 https://www.youtube.com/durgasoftware
OCJA
Example 4:
double d=130.456 ;
int x=(int)d ;
System.out.println(x); //130
byte b=(byte)d ;
System.out.println(b); //-206
A) int to byte
B) byte to int
C) float to double
D) double to float
E) None of the above
Answer: B, C
A) int to byte
B) byte to int
C) float to double
D) double to float
E) None of the above
Answer: A, D
int i =100;
float f = 100.100f;
double d = 123;
22 https://www.youtube.com/durgasoftware
OCJA
Which of the following assignments won't compile?
A) i=f;
B) f=i;
C) d=f;
D) f=d;
E) d=i;
F) i=d;
Answer: A,D,F
Q4. In which of the following cases we will get Compile time error?
A) float f =100F;
B) float f =(float)1_11.00;
C) float f =100;
D) double d = 203.22;
float f = d;
E) int i =100;
float f=(float)i;
Answer: D
Answer: A
23 https://www.youtube.com/durgasoftware
OCJA
Arrays
1) Introduction
2) Array declaration
3) Array construction
4) Array initialization
5) Array declaration, construction, initialization in a single line
6) length variable Vs length() method
7) Anonymous arrays
8) Array element assignments
9) Array variable assignments
1) Introduction
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.
2) 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 can't specify the size otherwise we will get compile time error.
Example:
int[] a;//valid
int[5] a;//invalid
24 https://www.youtube.com/durgasoftware
OCJA
Two dimensional array declaration:
Example:
int[][] a;
int [][]a;
int a[][]; All are valid.(6 ways)
int[] []a;
int[] a[];
int []a[];
Example:
int[][][] a;
int [][][]a;
int a[][][];
int[] [][]a;
int[] a[][]; All are valid.(10 ways)
int[] []a[];
int[][] []a;
int[][] a[];
int []a[][];
int [][]a[];
Note:
If we want to specify the dimension before the variable, then it is allowed only for the first
variable. By mistake if we are trying to declare for any other variable in the same declaration then
we will get compile time error.
25 https://www.youtube.com/durgasoftware
OCJA
Example:
3) Array construction:
Every array in java is an object hence we can create by using new operator.
For every array type corresponding classes are available but these classes are part of java
language and not available to the programmer level.
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.
26 https://www.youtube.com/durgasoftware
OCJA
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:
int[] a=new int[-3];//R.E:NegativeArraySizeException
Rule 4:
The allowed data types to specify array size are byte, short, char, int.
By mistake if we are using any other type we will get compile time error.
Example:
int[] a=new int['a'];//(valid)
byte b=10;
int[] a=new int[b];//(valid)
short s=20;
int[] a=new int[s];//(valid)
int[] a=new int[10l];//C.E:possible loss of precision//(invalid)
int[] a=new int[10.5];//C.E:possible loss of precision//(invalid)
Rule 5:
The maximum allowed array size in java is maximum value of int size [2147483647].
Example:
int[] a1=new int[2147483647];(valid)
int[] a2=new int[2147483648];
//C.E:integer number too large: 2147483648(invalid)
In the first case we may get RE : OutOfMemoryError.
27 https://www.youtube.com/durgasoftware
OCJA
Which code fragment required to insert at Line-1 to produce output 10:20
Answer: A
Example 1:
int[][] a=new int[2][];
a[0]=new int[3];
a[1]=new int[2];
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];
a[1]=new int[2][2];
28 https://www.youtube.com/durgasoftware
OCJA
4) Array Initialization:
Whenever we are creating an array every element is initialized with default value automatically.
Example 1:
int[] a=new int[3];
System.out.println(a);//[I@3e25a5
System.out.println(a[0]);//0
Note: Whenever we are trying to print any object reference internally toString() method will be
executed which is implemented by default to return the following.
classname@hexadecimalstringrepresentationofhashcode.
29 https://www.youtube.com/durgasoftware
OCJA
Example 2:
System.out.println(a);//[[I@3e25a5
System.out.println(a[0]);//[I@19821f
System.out.println(a[0][0]);//0
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
Once we created an array all its elements by default initialized with default values.
If we are not satisfied with those default values then we can replace with our customized values.
Example:
int[] a=new int[4];
a[0]=10;
a[1]=20;
30 https://www.youtube.com/durgasoftware
OCJA
a[2]=30;
a[3]=40;
a[4]=50;//R.E:ArrayIndexOutOfBoundsException: 4
a[-4]=60;//R.E:ArrayIndexOutOfBoundsException: -4
Note: if we are trying to access array element with out of range index we will get Runtime
Exception saying ArrayIndexOutOfBoundsException.
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) String[] s = new String[2];
6) int i =0;
7) for(String s1 : s)
8) {
9) s[i].concat("Element "+i);
10) i++;
11) }
12) for(i=0;i<s.length;i++)
13) {
14) System.out.println(s[i]);
15) }
16) }
17) }
B) null Element 0
null Element 1
C) null
null
D) NullPointerException
31 https://www.youtube.com/durgasoftware
OCJA
Answer: D
Note: On null,if we are tryint to apply any operation then we will get NullPoinerException
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) int[][] n = new int[1][3];
6) for(int i =0; i< n.length; i++)
7) {
8) for (int j=0;j>n[i].length ;j++ )
9) {
10) num[i][j]=10;
11) }
12) }
13) }
14) }
Which option represents the state of the array after successful completion of outer for loop?
A) n[0][0]=10;
n[0][1]=10;
n[0][2]=10;
B) n[0][0]=10;
n[1][0]=10;
n[2][0]=10;
C) n[0][0]=10;
n[0][1]=0;
n[0][2]=0;
D) n[0][0]=10;
n[0][1]=10;
n[0][2]=10;
n[1][0]=0;
n[1][1]=0;
n[1][2]=0;
n[1][3]=0;
Answer: A
32 https://www.youtube.com/durgasoftware
OCJA
Q. Consider the code
1) class Student
2) {
3) String name;
4) public Student(String name)
5) {
6) this.name=name;
7) }
8) }
9) public class Test
10) {
11) public static void main(String[] args)
12) {
13) Student[] students = new Student[3];
14) students[1]= new Student("Durga");
15) students[2]= new Student("Ravi");
16) for(Student s : students)
17) {
18) System.out.println(s.name);
19) }
20) }
21) }
B) null
Durga
Ravi
C) Compilation Fails
D) ArrayIndexOutOFBoundsException
E) NullPointerException
Answer: E
33 https://www.youtube.com/durgasoftware
OCJA
5) 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:
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}};
Example:
int[][][] a={{{10,20,30},{40,50}},{{60},{70,80},{90,100,110}}};
34 https://www.youtube.com/durgasoftware
OCJA
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:
int[] x= {10,20,30,40,50};
x[2]=x[4];
x[4]=60;
A) 10,20,30,40,50
B) 10,20,50,40,50
C) 10,20,50,40,60
D) 10,20,30,40,50
Answer: C
35 https://www.youtube.com/durgasoftware
OCJA
Q. Given Student class as
1) class Student
2) {
3) int rollno;
4) String name;
5) public Student(int rollno,String name)
6) {
7) this.rollno=rollno;
8) this.name=name;
9) }
10) }
11) public class Test
12) {
13) public static void main(String[] args)
14) {
15) Student[] students ={
16) new Student(101,"Durga"),
17) new Student(102,"Ravi"),
18) new Student(103,"Shiva"),
19) new Student(104,"Pavan")
20) };
21) System.out.println(students);
22) System.out.println(students[2]);
23) System.out.println(students[2].rollno);
24) }
25) }
A) students
Shiva
103
B) [LStudent;@61baa894
Shiva
103
C) [LStudent;@61baa894
Student@66133adc
103
D) [LStudent;@61baa894
Pavan
103
Answer: C
36 https://www.youtube.com/durgasoftware
OCJA
6) length Vs length():
length:
It is the final variable applicable only for arrays.
It represents the size of the array.
Example:
length() method:
It is a final method applicable for String objects.
It returns the no of characters present in the String.
Example:
String s="durga";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//5
In multidimensional arrays length variable represents only base size but not total size.
Example:
length variable applicable only for arrays where as length()method is applicable for String objects.
There is no direct way to find total size of multi dimentional array but indirectly we can find as
follows
x[o].length +x[1].length + x[2].length + .......
37 https://www.youtube.com/durgasoftware
OCJA
Q. Consider the following code
A) 4
6
B) 4
4
C) 6
4
D) 6
6
Answer: A
38 https://www.youtube.com/durgasoftware
OCJA
7) Anonymous Arrays:
Sometimes we can create an array without name such type of nameless arrays are called
anonymous arrays.
The main objective of anonymous arrays is "just for instant use".
new int[]{10,20,30,40};(valid)
new int[][]{{10,20},{30,40}};(valid)
At the time of anonymous array creation we can't specify the size otherwise we will get compile
time error.
Example:
new int[3]{10,20,30,40};//C.E:';' expected(invalid)
new int[]{10,20,30,40};(valid)
Based on our programming requirement we can give the name for anonymous array then it is no
longer anonymous.
Example:
int[] a=new int[]{10,20,30,40};(valid)
Example:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) System.out.println(sum(new int[]{10,20,30,40}));//100
6) }
7) public static int sum(int[] x)
8) {
9) int total=0;
10) for(int x1:x)
11) {
12) total=total+x1;
13) }
14) return total;
15) }
16) }
In the above program just to call sum() , we required an array but after completing sum() method.
For this instant use we can use anonymous arrays.
39 https://www.youtube.com/durgasoftware
OCJA
8) 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:
40 https://www.youtube.com/durgasoftware
OCJA
Example 2:
Case 3:
In the case of interface type arrays as array elements we can provide its implemented class
objects.
Example:
41 https://www.youtube.com/durgasoftware
OCJA
Q. The following grid shows the state of a 2D array:
Diagram
A) grid[3][1]='X';
B) grid[0][2]='X';
C) grid[1][3]='X';
D) grid[2][0]='X';
E) grid[1][2]='X';
Answer: D
Example:
int[] a={10,20,30};
char[] ch={'a','b','c'};
int[] b=a;//(valid)
int[] c=ch;//C.E:incompatible types(invalid)
Which of the following promotions are valid?
42 https://www.youtube.com/durgasoftware
OCJA
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 won't be copied, just
reference variables will be reassigned .Hence sizes are not required to be equal, 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)
43 https://www.youtube.com/durgasoftware
OCJA
Case 3:
Whenever we are assigning one array to another array dimensions must be matched that is in the
place of one dimensional array we should provide the same type only otherwise we will get
compile time error.
Example:
int[][] a=new int[3][];
a[0]=new int[4][5];//C.E:incompatible types(invalid)
a[0]=10;//C.E:incompatible types(invalid)
a[0]=new int[4];//(valid)
Note: Whenever we are performing array assignments the types and dimensions must be
matched but sizes are not important.
44 https://www.youtube.com/durgasoftware
OCJA
What is the output?
A) 10:20:30:40:50:
B) 10:20:30:
C) Compilation fails
D) ArrayIndexOutOfBoundsException at runtime
Answer: A
Example 1:
int[][] a=new int[3][2];
a[0]=new int[3];
a[1]=new int[4];
a=new int[4][3];
Ans: 11
45 https://www.youtube.com/durgasoftware
OCJA
Example 2:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) String[] argh={"A","B"};
6) args=argh;
7) System.out.println(args.length);//2
8) for(int i=0;i<=args.length;i++)
9) {
10) System.out.println(args[i]);
11) }
12) }
13) }
Output:
java Test x y
R.E: ArrayIndexOutOfBoundsException: 2
java Test x
R.E: ArrayIndexOutOfBoundsException: 2
java Test
R.E: ArrayIndexOutOfBoundsException: 2
Note: Replace with i<args.length
Example 3:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) String[] argh={"A","B"};
6) args=argh;
7) System.out.println(args.length);//2
8) for(int i=0;i<args.length;i++)
9) {
10) System.out.println(args[i]);
11) }
12) }
13) }
Output:
2
A
B
46 https://www.youtube.com/durgasoftware
OCJA
Example 4:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) String[] argh={"A","B"};
6) args=argh;
7)
8) for(String s : args) {
9) System.out.println(s);
10) }
11) }
Output:
A
B
47 https://www.youtube.com/durgasoftware
OCJA
Types of Variables
Division 1: Based on the type of value represented by a variable all variables are divided into
2 types. They are:
Primitive variables
Reference variables
Primitive variables:
Primitive variables can be used to represent primitive values.
Reference variables:
Reference variables can be used to refer objects.
Division 2: Based on the behavior and position of declaration all variables are divided into the
following 3 types.
Instance variables
Static variables
Local variables
Instance variables:
If the value of a variable is varied from object to object such type of variables are called
instance variables.
For every object a separate copy of instance variables will be created.
Instance variables will be created at the time of object creation and destroyed at the time of
object destruction hence the scope of instance variables is exactly same as scope of objects.
Instance variables will be stored on the heap as the part of object.
Instance variables should be declared with in the class directly but outside of any method or
block or constructor.
Instance variables can be accessed directly from Instance area. But cannot be accessed directly
from static area.
But by using object reference we can access instance variables from static area.
48 https://www.youtube.com/durgasoftware
OCJA
Example:
1) class Test
2) {
3) int i=10;
4) public static void main(String[] args)
5) {
6) //System.out.println(i);
7) //C.E:non-static variable i cannot be referenced from a static context(invalid)
8) Test t=new Test();
9) System.out.println(t.i);//10(valid)
10) t.methodOne();
11) }
12) public void methodOne()
13) {
14) System.out.println(i);//10(valid)
15) }
16) }
For the instance variables it is not required to perform initialization JVM will always provide
default values.
Example:
1) class Test
2) {
3) boolean b;
4) public static void main(String[] args)
5) {
6) Test t=new Test();
7) System.out.println(t.b);//false
8) }
9) }
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.
49 https://www.youtube.com/durgasoftware
OCJA
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.
java Test
Start JVM.
Create and start Main Thread by JVM
Locate(find) Test.class by main Thread.
Load Test.class by main Thread // static variable creation
Execution of main() method.
Unload Test.class // static variable destruction
Terminate main Thread.
Shutdown JVM.
Example:
1) class Test
2) {
3) static int i=10;
4) public static void main(String[] args)
5) {
6) Test t=new Test();
7) System.out.println(t.i);//10
8) System.out.println(Test.i);//10
9) System.out.println(i);//10
10) }
11) }
For the static variables it is not required to perform initialization explicitly, JVM will always
provide default values.
Example:
1) class Test
2) {
3) static String s;
4) public static void main(String[] args)
5) {
6) System.out.println(s);//null
7) }
8) }
50 https://www.youtube.com/durgasoftware
OCJA
Example:
1) class Test
2) {
3) int x=10;
4) static int y=20;
5) public static void main(String[] args)
6) {
7) Test t1=new Test();
8) t1.x=888;
9) t1.y=999;
10) Test t2=new Test();
11) System.out.println(t2.x+"----"+t2.y);//10----999
12) }
13) }
Local variables:
Some times to meet temporary requirements of the programmer we can declare variables
inside a method or block or constructors such type of variables are called local variables or
automatic variables or temporary variables or stack variables.
Local variables will be stored inside stack.
The local variables will be created as part of the block execution in which it is declared and
destroyed once that block execution completes. Hence the scope of the local variables is
exactly same as scope of the block in which we declared.
51 https://www.youtube.com/durgasoftware
OCJA
Example 1:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) int i=0;
6) for(int j=0;j<3;j++)
7) {
8) i=i+j;
9) }
10) }
11) }
Example 2:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) try
6) {
7) int i=Integer.parseInt("ten");
8) }
9) catch(NullPointerException e)
10) {
11) }
12) }
13) }
52 https://www.youtube.com/durgasoftware
OCJA
Example:
Example:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) int x;
6) if(args.length>0)
7) {
8) x=10;
9) }
10) System.out.println(x);
11) //C.E:variable x might not have been initialized
12) }
13) }
53 https://www.youtube.com/durgasoftware
OCJA
Example:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) int x;
6) if(args.length>0)
7) {
8) x=10;
9) }
10) else
11) {
12) x=20;
13) }
14) System.out.println(x);
15) }
16) }
Output:
java Test x
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.
54 https://www.youtube.com/durgasoftware
OCJA
10) b=3;
11) h=4;
12) p=0.5;
13) }
14) area=p*b*h;// Line-2
15) System.out.println(area);
16) }
17) }
Answer: D
Note: The only applicable modifier for local variables is final. If we are using any other modifier
we will get compile time error.
Example:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5)
6) public int x=10; //(invalid)
7) private int x=10; //(invalid)
8) protected int x=10; //(invalid) C.E: illegal start of expression
9) static int x=10; //(invalid)
10) volatile int x=10; //(invalid)
11) transient int x=10; //(invalid)
12) final int x=10;//(valid)
13) }
14) }
Conclusions:
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 won't provide any default values
compulsory we should perform initialization explicitly before using that variable.
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.
55 https://www.youtube.com/durgasoftware
OCJA
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.
If we are not declaring any modifier explicitly then it means default modifier but this rule is
applicable only for static and instance variables but not local variable.
Un Initialized arrays
Example:
1) class Test
2) {
3) int[] a;
4) public static void main(String[] args)
5) {
6) Test t1=new Test();
7) System.out.println(t1.a);//null
8) System.out.println(t1.a[0]);//R.E:NullPointerException
9) }
10) }
Instance level:
Example 1:
1) int[] a;
2) System.out.println(obj.a);//null
3) System.out.println(obj.a[0]);//R.E:NullPointerException
Example 2:
Static level:
Example 1:
1) static int[] a;
2) System.out.println(a);//null
3) System.out.println(a[0]);//R.E:NullPointerException
56 https://www.youtube.com/durgasoftware
OCJA
Example 2:
Local level:
Example 1:
1) int[] a;
2) System.out.println(a); //C.E: variable a might not have been initialized
3) System.out.println(a[0]);
Example 2:
Note:
Once we create an array every element is always initialized with default values irrespective of
whether it is static or instance or local array.
Note:
Every variable in Java should be either instance or static or local.
Every variable in Java should be either primitive or reference.
Hence the following are the various possible combinations for variables
57 https://www.youtube.com/durgasoftware
OCJA
58 https://www.youtube.com/durgasoftware
OCJA
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 can't access from
static area directly.
But static variables can be accessed from both instance and static areas directly.
59 https://www.youtube.com/durgasoftware
OCJA
Which of the following declarations are allowed within the same class simultaneously ?
a) 1 and 3
b) 1 and 4
c) 2 and 3
d) 2 and 4
f) 1 and 2
f) 3 and 4
Answer: a,c,d
Example:
1) class Test {
2) int x = 10;
3) public void methodOne() {
4) System.out.println(x);
5) }
6) }
Output:
Compile successfully.
Example:
1) class Test {
2) int x = 10;
3) public static void methodOne() {
4) System.out.println(x);
5) }
6) }
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);
Example:
1) class Test {
2) static int x = 10;
3) public void methodOne() {
4) System.out.println(x);
5) }
6) }
60 https://www.youtube.com/durgasoftware
OCJA
Output:
Compile successfully.
Example:
1) class Test {
2) static int x = 10;
3) public static void methodOne() {
4) System.out.println(x);
5) }
6) }
Output:
Compile successfully.
e) 1 and 2
Example:
1) class Test {
2) int x = 10;
3) static int x = 10;
4) }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: x is already defined in Test
static int x=10;
Example:
1) class Test {
2) public void methodOne() {
3) System.out.println(x);
4) }
5) public static void methodOne() {
6) System.out.println(x);
7) }
8) }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: methodOne() is already defined in Test
public static void methodOne(){
61 https://www.youtube.com/durgasoftware
OCJA
For static methods implementation should be available but for abstract methods implementation
is not available hence static abstract combination is illegal for methods.
case 1:
Overloading concept is applicable for static method including main method also.But JVM will
always call String[] args main method .
The other overloaded method we have to call explicitly then it will be executed just like a normal
method call .
Example:
Output :
String() method is called
case 2:
Inheritance concept is applicable for static methods including main() method hence while
executing child class, if the child doesn't contain main() method then the parent class main
method will be executed.
Example:
1) class Parent {
2) public static void main(String args[]) {
3) System.out.println("parent main() method called");
4) }
5) }
6) class child extends Parent {}
62 https://www.youtube.com/durgasoftware
OCJA
Output:
Example:
63 https://www.youtube.com/durgasoftware
OCJA
Output:
It seems to be overriding concept is applicable for static methods but it is not overriding it is
method hiding.
64 https://www.youtube.com/durgasoftware
OCJA
23) }
Answer: C
Explanation: In the above example, the variable myStr,which is declared inside try block is not
available outside of try block. Hence while printing, instance variable myStr will be considered.
Answer: D
Explanation: myStr is local variable of try block and we cannot access outside of try block.
65 https://www.youtube.com/durgasoftware
OCJA
Q. Consider the code
1) class Test
2) {
3) int x =10;
4) static int y = 20;
5) public static void main(String[] args)
6) {
7) Test t1 =new Test();
8) Test t2 =new Test();
9) t1.x=100;
10) t1.y=200;
11) t2.x=300;
12) t2.y=400;
13) System.out.println(t1.x+".."+t1.y+".."+t2.x+".."+t2.y);
14) }
15) }
A) 100..400..300..400
B) 100..400..100..400
C) 200..400..300..400
D) 100..200..300..400
Answer: A
Answer: A
1) class Test
2) {
3) int count;
4) public static void display()
5) {
6) count++;//Line-1
7) System.out.println("Welcome Visit Count:"+count);//Line-2
8) }
9) public static void main(String[] args)
10) {
67 https://www.youtube.com/durgasoftware
OCJA
11) Test.display();//Line-3
12) Test.display();//Line-4
13) }
14) }
Answer: C
68 https://www.youtube.com/durgasoftware
OCJA
D) 300:300
200:300
Answer: A
1) class Demo
2) {
3) int ns;
4) static int s;
5) Demo(int ns)
6) {
7) if(s<ns)
8) {
9) s=ns;
10) this.ns=ns;
11) }
12) }
13) void display()
14) {
15) System.out.println("ns = "+ns+" s = "+s);
16) }
17) }
18) public class Test
19) {
20) static int x;
21) int y;
22) public static void main(String[] args)
23) {
24) Demo d1= new Demo(50);
25) Demo d2= new Demo(125);
26) Demo d3= new Demo(100);
27) d1.display();
28) d2.display();
29) d3.display();
30) }
31) }
A. ns = 50 s = 125
ns = 125 s = 125
ns = 0 s = 125
B. ns = 50 s = 125
ns = 125 s = 125
ns = 100 s = 125
69 https://www.youtube.com/durgasoftware
OCJA
C. ns = 50 s = 50
ns = 125 s = 125
ns = 0 s = 0
D. ns = 50 s = 125
ns = 125 s = 125
ns = 100 s = 100
Answer: A
A) 400 200
B) 200 200
C) 400 400
D) Compilation Fails
Answer: A
70 https://www.youtube.com/durgasoftware
OCJA
10) }
11) catch (ArithmeticException e)
12) {
13) ans=0;//Line-1
14) }
15) catch(Exception e)
16) {
17) System.out.println("Invalid Calculation");
18) }
19) System.out.println("Answer="+ans);//Line-2
20) }
21) }
A) Answer=0
B) Invalid Calculation
C) Compiation Fails at Line-1
D) Compiation Fails at Line-2
E) Compiation Fails at Line-1 and Line-2
Answer: E
71 https://www.youtube.com/durgasoftware
OCJA
What is the result?
A. c =
b = false
f = 0.0
B. c = null
b = false
f = 0.0
C. c = 0
b = false
f = 0.0
D. c =
b = true
f = 0.0
Answer: A
Passing Arguments:
If we pass primitive type to a method and within that method if we perform any changes then
those changes won't be reflected to the caller. In this case a separate local copy will be created for
the primitive variable in that method.
72 https://www.youtube.com/durgasoftware
OCJA
Output
Inside Method:110..210
After Completing Method:100..200
A) 400 200
B) 200 200
C) 400 400
D) Compilation Fails
Answer: A
73 https://www.youtube.com/durgasoftware
OCJA
16) Test t = new Test(i,j);
17) System.out.println(i+"..."+j);
18) }
19) }
A) 9...25
B) 0...0
C) 3...5
D) Compilation Fails
Answer: C
If we pass object reference to a method and within the method if we perform any changes to the
object state, then those changes will be reflected to the caller also. In this case just duplicate
reference variable will be created and new object won’t be created.
Eg 2:
1) class Demo
2) {
3) int x;
4) int y;
5) };
6) public class Test
7) {
8) public void m1(Demo d)
9) {
10) d.x=888;
11) d.y=999;
12) }
13) public static void main(String[] args)
14) {
15) Demo d1 = new Demo();
16) d1.x=10;
17) d1.y=20;
18) Test t = new Test();
19) t.m1(d1);
20) System.out.println(d1.x+"..."+d1.y);
21) }
22) }
Output: 888...999
In the above example we are passing Demo object reference as argument to method m1(). Inside
method m1(),we are changing the state of the object. These changes will be reflected to the caller.
74 https://www.youtube.com/durgasoftware
OCJA
Practice Question:
1) class Product
2) {
3) double price;
4) }
5) public class Test
6) {
7) public void updatePrice(Product p,double price)
8) {
9) price=price*2;
10) p.price=p.price+price;
11) }
12) public static void main(String[] args)
13) {
14) Product prt = new Product();
15) prt.price=200;
16) double newPrice=100;
17)
18) Test t = new Test();
19) t.updatePrice(prt,newPrice);
20) System.out.println(prt.price+"...."+newPrice);
21) }
22) }
Answer: C
Explanation:
In the above example, we are passing Product object reference as argument to updatePrice()
method and within the method we are changing the state of object. These changes will be
reflected to the caller.
75 https://www.youtube.com/durgasoftware
OCJA
7) this.x=x;
8) y=this.y;
9) }
10) public void print()
11) {
12) System.out.print(x+":"+y+":");
13) }
14) public static void main(String[] args)
15) {
16) Test t1=new Test();
17) t1.x=100;
18) t1.y=200;
19)
20) Test t2 = new Test();
21) t2.doStuff(t1.x,t1.y);
22) t1.print();
23) t2.print();
24) }
25) }
A) 100:200:100:0:
B) 100:0:100:0:
C) 100:200:100:200:
D) 100:0:200:0:
Answer: A
76 https://www.youtube.com/durgasoftware
OCJA
17) }
18) }
A. a:e
o:o
B. e:e
i:o
C. a:e
i:o
D. e:e
o:o
Answer: A
Example:
class Test
{}
Output:
javac Test.java
java Test R.E: NoSuchMethodError: main
At runtime JVM always searches for the main() method with the following prototype.
77 https://www.youtube.com/durgasoftware
OCJA
If we are performing any changes to the above syntax then the code won't run and will get
Runtime exception saying NoSuchMethodError.
Even though above syntax is very strict but the following changes are acceptable to main()
method.
The order of modifiers is not important that is instead of public static we can take static public.
Case 1 :
Overloading of the main() method is possible but JVM always calls string[] argument main()
method only.
Example:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) System.out.println("String[] array main method"); //overloaded methods
6) }
7) public static void main(int[] args)
8) {
9) System.out.println("int[] array main method");
10) }
11) }
Output:
String[] array main method
The other overloaded method we have to call explicitly then only it will be executed.
Case 2:
Inheritance concept is applicable for static methods including main() method
hence while executing child class if the child class doesn't contain main() method then the parent
class main() method will be executed.
Example 1:
Parent.java
1) class Parent
2) {
3) public static void main(String[] args)
4) {
5) System.out.println("parent main"); }
6) }
7) class Child extends Parent
8) {
79 https://www.youtube.com/durgasoftware
OCJA
9) }
Analysis:
Example 2:
1) class Parent
2) {
3) public static void main(String[] args)
4) {
5) System.out.println("parent main"); // Parent.java
6) }
7) }
8) class Child extends Parent
9) {
10) public static void main(String[] args)
11) {
12) System.out.println("Child main");
13) }
14) }
80 https://www.youtube.com/durgasoftware
OCJA
Analysis:
It seems to be overriding concept is applicable for static methods but it is not overriding it is
method hiding.
Untill 1.6v if our class doesn't contain main() method then at runtime we will get Runtime
Exception saying NosuchMethodError:main
But from 1.7 version onwards instead of NoSuchMethodError we will get more meaning full
description
class Test {
}
1.6 version:
javac Test.java
java Test
RE: NoSuchMethodError:main
81 https://www.youtube.com/durgasoftware
OCJA
1.7 version:
javac Test.java
java Test
Error: main method not found in class Test, please define the main method as
public static void main(String[] args)
Case 2:
From 1.7 version onwards to start program execution compulsory main method should be
required, hence even though the class contains static block if main method not available then
won't be executed
1) class Test {
2) static {
3) System.out.println("static block");
4) }
5) }
1.6 version:
javac Test.java
java Test
output :
static block
RE: NoSuchMethodError:main
1.7 version:
javac Test.java
java Test
Error: main method not found in class Test, please define the main method as
public static void main(String[] args)
Case 3:
1) class Test {
2) static {
3) System.out.println("static block");
4) System.exit(0);
5) }
6) }
82 https://www.youtube.com/durgasoftware
OCJA
1.6 version:
javac Test.java
java Test
output :
static block
1.7 version:
javac Test.java
java Test
Error: main method not found in class Test, please define the main method as
public static void main(String[] args)
Case 4:
1) class Test {
2) static {
3) System.out.println("static block");
4) }
5) public static void main(String[] args) {
6) System.out.println("main method");
7) }
8) }
1.6 version:
javac Test.java
java Test
output :
static block
main method
1.7 version:
javac Test.java
java Test
output :
static block
main method
83 https://www.youtube.com/durgasoftware
OCJA
84 https://www.youtube.com/durgasoftware
OCJA
Example 1:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) for(int i=0;i<=args.length;i++)
6) {
7) System.out.println(args[i]);
8) }
9) }
10) }
Output:
java Test x y z
ArrayIndexOutOfBoundsException: 3
Replace i<=args.length with i<args.length then it will run successfully.
Example 2 :
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) String[] argh={"X","Y","Z"};
6) args=argh;
7) for(String s : args)
85 https://www.youtube.com/durgasoftware
OCJA
8) {
9) System.out.println(s);
10) }
11) }
12) }
Output:
java Test A B C
X
Y
Z
java Test A B
X
Y
Z
java Test
X
Y
Z
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 3 :
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) System.out.println(args[0]+args[1]);
6) }
7) }
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.
86 https://www.youtube.com/durgasoftware
OCJA
Example 4 :
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) System.out.println(args[0]);
6) }
7) }
Output:
E:\SCJP>javac Test.java
E:\SCJP>java Test "Sai Charan"
Sai Charan
Q. Which one of the following code examples uses valid java syntax?
A)
B)
C)
87 https://www.youtube.com/durgasoftware
OCJA
D)
Answer: A
A) javac Test
java Test Durga
C) javac Test.java
java Test Durga
D) javac Test.java
java Test.class Durga
Answer: C
88 https://www.youtube.com/durgasoftware
OCJA
7) public static void main(Object[] args)
8) {
9) System.out.println("Object[] main: "+args[0]);
10) }
11) public static void main(String[] args)
12) {
13) System.out.println("String[] main: "+args[0]);
14) }
15) }
A) int[] main 1
B) Object[] main 1
C) String[] main 1
D) Compilation Fails
E) An Exception raises at runtime
Answer: C
89 https://www.youtube.com/durgasoftware
OCJA
2.13) [] Operator
90 https://www.youtube.com/durgasoftware
OCJA
Increment and Decrement Operators
Increment Decrement
y = ++x; 10 11 11
y = x++; 10 10 11
y = --x; 10 9 9
y = x--; 10 10 9
We can Apply Increment and Decrement Operators only for Variables but Not for
Constant Values Otherwise we will get CE.
int x = 10;
int y = ++x;
System.out.println(y); //11
int x = 10;
int y = ++10;
System.out.println(y);
91 https://www.youtube.com/durgasoftware
OCJA
Nesting of Increment and Decrement Operators is Not allowed Otherwise we will get
Compile Time Error.
int x = 10;
int y = ++(++x);
System.out.println(y);
We can Apply Increment and Decrement Operators for every Primitive Data Type
except boolean.
If we Apply any Arithmetic Operations between 2 Variables a and b the Result Type is
Always Max(int, Type of a, Type of b).
In the Case of Increment and Decrement Operators Internal Type Casting Automatically
performed by the Compiler.
byte b = 10;
b++; b = (Type of b)(b++);
System.out.println(b); //11
Arithmetic Operators
If we are applying any Arithmetic Operation between 2 Variables a and b the Result
Type is Always Max(int, Type of a, Type of b).
5) int + long = long 10) char + double = double System.out.println('a' + 1.1); //98.1
93 https://www.youtube.com/durgasoftware
OCJA
Infinity:
In Integral Arithmetic (int, short, long, byte), there is No way to Represent infinity.
Hence, if the Infinity is the Result we will Always get
RE: ArithmeticException: / by zero) in Integral Arithmetic.
But in floating Point Arithmetic (float & double), there is a Way to Represent
Infinity.
For this float & double Classes contains the following 2 Constants.
POSITIVE_INFINITY;
NEGATIVE_INFINITY;
Hence Even though the Result is Infinity we won’t get any Arithmetic Exception in
floating Point Arithmetic.
But in floating Point Arithmetic there is a way to Represent Undefined Results, for
this Float & Double Classes a Constant NaN. Hence, Even though the Result is
Undefined we won’t get any Runtime Exception is floating Point Arithmetic.
System.out.println(0/0.0); //NaN
System.out.println(0.0/0); //NaN
System.out.println(-0/0.0); //NaN
For any x Value including NaN the Below Expressions Always Returns false.
System.out.println(Float.NaN == Float.NaN);
e
94 https://www.youtube.com/durgasoftware
OCJA
For any x Value including NaN the Below Expressions Always Returns true.
System.out.println(10 != Float.NaN);
x != Nan True
System.out.println(Float.NaN != Float.NaN);
True
Conclusion About Arithmetic Exception:
95 https://www.youtube.com/durgasoftware
OCJA
Consider the following Declarations
String a = “Durga”;
int b = 10, c = 20, d = 30;
1) a = b+c+d;
2) b = a+c+d; 4) b = b+c+d;
System.out.println(a); //Durga
CE: incompatible types
required: String
found: int
Relational Operators
We can’t Apply Relational Operators for Object Types. Otherwise we will get CE.
96 https://www.youtube.com/durgasoftware
OCJA
Nesting of Relational Operators are Not allowed.
97 https://www.youtube.com/durgasoftware
OCJA
For any Object Reference r, r = = null is Always null. But null == null is Always
true.
String s = null;
System.out.println(s == null); //true
System.out.println(null == null); //true
Bitwise Operators
98 https://www.youtube.com/durgasoftware
OCJA
Bitwise Compliment Operator (~)
We can Apply this Operators Only for Integral Data Types but Not for boolean
Types.
System.out.println(~4); //-5
4 = 000....0100
~4 = 1 1 1 . . . . 1 0 1 1
-ve
0 0 . . . . . .0 1 0 0
0 0 . . . . . .0 1 0 1 5
System.out.println(!4); //CE: bad operand type int for unary operator '!'
System.out.println(!true); //false
&, |, and ^ are Applicable for Both boolean and Integral Types.
~ Applicable Only for Integral Types but Not for boolean Types.
! Applicable Only for boolean type but Not for Integral Types.
&, | &&, ||
nd
Both Arguments should be 2 Argument Evaluation is Optional.
evaluated Always.
Relatively Performance is Low. Relatively Performance is High
Applicable for Both boolean and Applicable Only for boolean but Not
Integral Types. for Integral Types.
99 https://www.youtube.com/durgasoftware
OCJA
Note:
x && y y will be evaluated if and Only if x is true i.e. if x is false then y won’t
be evaluated.
x y int x = 10;
& 11 17 if((++x < 10) && (x/0 >10)) {
| 12 16 System.out.println("Hello");
}
&& 11 16
else {
|| 12 16 System.out.println("Hi");
int x = 10, y = 15;}
if(++x < 10 & ++y > 15) {
++x; 1) RE 2) CE 3) Hello 4) Hi √
}
else { Note: If we Replace && with & then we will get
++y; RE: java.lang.ArithmeticException: / by zero
}
System.out.println(x+”……..”+y);
instanceof Operator
We can Use instanceof Operator to Check whether the given Object is the Particular
Type OR Not.
Syntax r instanceof X
101 https://www.youtube.com/durgasoftware
OCJA
Type Cast Operator
There are 2 Types of Type Casting
1) Implicit Type Casting
2) Explicit Type Casting
The following are Various Possible Conversions where Implicit Type Casting will be
Performed.
Examples:
1) int x = 'a'; [Compiler Converts char int Automatically by Implicit Type Casting]
System.out.println(x); //97
2) double d =10; [Compiler Converts int double Automatically by Implicit Type Casting]
System.out.println(d); //10.0
The following are Various Possible Conversions where Explicit Type Casting will be
Performed.
102 https://www.youtube.com/durgasoftware
OCJA
Note:
Left Right Implicit Type Casting
Right Left Explicit Type Casting
Examples:
int x = 130;
byte b = x;
CE: possible loss of precision
required: byte
found: int
byte b = (byte) x;
System.out.println(b); //-126
Explanation:
Whenever we are assigning Higher Data Type Value to Lower Data Type Variable by
Explicit Type Casting then the Most Significant Bits will be Lost. We have to
Consider Only Least Significant Bits.
Example:
103 https://www.youtube.com/durgasoftware
OCJA
Whenever we are assigning floating Point Data Type Values to the Integral Data
Types by Explicit Type Casting then the Digits after the Decimal Point will be Lost.
double d = 130.456;
int x = (int)d;
System.out.println(x); //130
byte b = (byte)d;
System.out.println(b); //-126
Assignment Operators
There are 3 Types of Assignment Operators.
Simple Assignment
Chained Assignment
Compound Assignment
Chained Assignment:
int a,b,c,d;
a = b = c = d = 20;
System.out.println(a+".."+b+".."+c+".."+d); //20..20..20..20
int a = b = c = d = 20;
int b,c,d;
int a = b = c = d = 20; √
System.out.println(b+".."+c+".."+d); //20..20..20
104 https://www.youtube.com/durgasoftware
OCJA
Compound Assignment:
Some Time we can Mix Assignment Operator with Some Other Operator to form
Compound Assignment Operator.
int x = 10;
x += 20;
System.out.println(x); //30
The following with the List of All Possible Compound Assignment Operators in Java.
+= >>= &=
-= >>>= |=
*= <<= ^=
/=
%=
byte b = 127;
b += 3;
System.out.println(b); -126
int a, b, c, d;
a = b = c = d = 20;
a += b -= c *= d /= 2;
System.out.println(a +"...."+ b +"...."+ c +"...."+ d); //-160....-180....200....10
105 https://www.youtube.com/durgasoftware
OCJA
Conditional Operator (?:)
The Only Possible Ternary Operator in Java is Conditional Operator.
new Operator
We can Use new Operator to Create Objects in Java.
But there is No delete Operator in Java because Garbage Collector is Responsible to
Destroy Useless Objects.
[ ] Operator
We can Use this Operator to Declare and Create Arrays.
Operators Presidency
1) Unary Operators:
[ ], x++, x--
++x, --x, ~, !
new, <type>
2) Arithmetic Operators: *, /, %, +, -
8) Conditional Operators: ?:
106 https://www.youtube.com/durgasoftware
OCJA
Evaluation Order of Operands
There is No Operand Precedence and we have Only Operator Precedence.
Before applying any Operator all Operands will be evaluated from Left to Right.
class Test {
public static void main(String[] args) {
System.out.println( m1(1)+m1(2)*m1(3) / m1(4)*m1(5)+m1(6));
}
public static int m1(int i) { 1 1+2* 3 / 4-5+6
System.out.println(i); 2 1+6 / 4-5+6
return i; 3 1+1-5+6
} 4 2-5+6
} 5 -3+6
6 3
12
new Vs newInstance()
We can Use new Operator to Create Objects if we Know the Class Name at the
Begining.
1) Test t = new Test();
newInstance() is a Method Present in 'Class' class which can be used to Create Object if
we don't know the Class Name at the beginning and it is Available Dynamically at
Runtime.
class Test {
public static void main(String[] args) throws Exception {
Object o = Class.forName(args[0]).newInstance();
System.out.println("Class Name: "+o.getClass().getName());
}
}
NoClassDefFoundError Vs ClassNotFoundException
NoClassDefFoundError:
If Hard Coded Class Name is Not Available at Runtime then we will get Runtime
Exception Saying NoClassDefFoundError. Which Unchecked Exception.
At Runtime if Test.class is Not Available then we will get Runtime Exception Saying
NoClassDefFoundError: Test
ClassNotFoundException:
If Dynamically provided Class Name is Not Available at Runtime then we will get
Runtime Exception Saying ClassNotFoundException. Which is Checked Exception.
If Test123.class File is Not Available at Runtime then we will get Runtime Exception
Saying ClassNotFoundException: Test123.
108 https://www.youtube.com/durgasoftware
OCJA
instanceof Vs isInstance()
instanceof
We can Use instanceof Operator to Check whether the given Object is the
Particular Type OR Not and the Type is specified at the beginning.
isInstance():
isInstance() is a Method Present in class Class which can be used to Check whether
the given Object is Particular Type OR Not and we don't Know the Type at the
beginning and it is Available Dynamically at Runtime.
Note:
newInstance() is Equivalent of new Operator.
isInstance() is Equivalent of instanceof Operator.
109 https://www.youtube.com/durgasoftware
OCJA
Flow Control
Flow Control
110 https://www.youtube.com/durgasoftware
OCJA
Flow Control describes the Order in which the Statements will be executed at
Runtime.
Flow Control
Selection Statements
if - else:
if(b) {
Action if b is true
Syntax:
}
else {
Action if b is false
}
else { else {
System.out.println (“Hi”); System.out.println ("Hi");
} }
incompatible types
required: boolean
found: int
111 https://www.youtube.com/durgasoftware
OCJA
int x = 10; boolean b = true; boolean b = false;
if (x == 20) { if (b = false) { if (b == false) {
System.out.println ("Hello"); System.out.println ("Hello"); System.out.println ("Hello");
} } }
else { else { else {
System.out.println ("Hai"); System.out.println ("Hi"); System.out.println ("Hi");
} } }
Note: Semi Colon (;) is a Valid Java Statement which is Also Known as Empty
Statement.
switch Statement
switch(x)
{
case 1:
Action 1;
break;
case 2:
Action 1;
Syntax: break;
.
.
.
case n:
Action 1;
break;
default:
default Action;
}
112 https://www.youtube.com/durgasoftware
OCJA
Until 1.4 Version The allowed Argument Types for the switch Statement are byte,
short, char and int.
From 1.5 Version onwards the Corresponding Wrapper Classes and enum Type Also
allowed.
From 1.7 Version onwards even String Type Also allowed.
Curly Braces are Mandatory (switch is the Only Place where Curly Braces are
Mandatory. Except this Every Where Curly Braces are Optional).
Inside switch Both case and default are Optional.
switch (x)
{
}√
Within the switch Every Statement should be Under Some case OR default. That is
Independent Statements are Not allowed within the switch.
int x = 10;
switch(x) {
System.out.println("Hai"); //CE: case, default, or '}' expected
}
Every case Label should be Constant Expression Otherwise we will get Compile
Time Error.
class Test {
public static void main(String[] args) {
int x = 10;
int y = 20;
switch(x) {
case 10:
System.out.println(10);
break;
case y:
System.out.println(20);
}
}
} CE: constant expression required
113 https://www.youtube.com/durgasoftware
OCJA
Note: If we Declare y as final then we won’t get any Compile Time Error.
final int y = 20;
For Both switch Arguments and case Label we can Take Expressions. But case Label
should be Constant Expression.
int x = 10;
switch(x + 1) {
case 10:
System.out.println(10);
break;
case 10 + 20:
System.out.println(20);
}
Every case Label should be within the Range of switch Argument Type.
switch(x) {
case 97:
System.out.println(97);
break;
case 98:
System.out.println(98);
break;
case 'a': //CE: duplicate case label
System.out.println('a');
break;
}
114 https://www.youtube.com/durgasoftware
OCJA
1) It can be Expression but should be Constant
Expression.
Within the switch if any case OR default Matched, from that case onwards all
Statements will be executed until break OR End of the switch. This is called fall-
through Inside switch.
The Main Advantage of Fall-through Inside switch is we can define Common Action
for Multiple Cases. (Code- Reusability)
switch(x) {
case 0: x=0 x=1
System.out.println(“0”); 0 1
case 1: 1
System.out.println(“1”);
break;
case 2: x=2 x=3
System.out.println(“2”); 2
default: default default
System.out.println(“default”);
}
switch(x) {
case 1:
case 2:
case 3:
System.out.println("Q-4”);
break;
case 4:
case 5:
case 6:
System.out.println("Q-5”);
break;
.
.
}
115 https://www.youtube.com/durgasoftware
OCJA
default case:
Within the switch we can take default case at-most Once.
If No Other case Matched then Only default case will be executed.
We can Take default case anywhere within the switch. But it is Convention to Take
Last case.
switch (x) {
x=0 x=1
default:
0 1
System.out.println(“default”);
2
case 0:
System.out.println(“0”);
x=2 x=3
break;
2 default
case 1:
0
System.out.println(“1”);
case 2:
System.out.println(“2”);
} Iterative Statements
while Loop:
If we don't Know the Number of Iteration in Advance then the Best Suitable Loop is
while Loop.
Examples:
while (rs.next()) while (itr.hasNext()) while (e.hasMoreElements())
{ { {
::::::::::::::: ::::::::::::::: :::::::::::::::
::::::::::::::: ::::::::::::::: :::::::::::::::
} } }
while (b)
Syntax: {
Action
}
The Argument to the while should be boolean Type. By Mistake if we are Provide
any Other Type we will get Compile Time Error.
while(1) {
System.out.println("Hello");
}
CE: incompatible types
required: boolean
found: int
116 https://www.youtube.com/durgasoftware
OCJA
Curly Braces are Optional and without Curly Braces we can Take Only One
Statement Under while. Which should Not be Declarative Statement.
while(true) while(true);
System.out.println("Hello"); ; is Valid Java Statement
while(true) while(false)
{ {
System.out.println("Hello"); System.out.println("Hello");
} }
System.out.println("Hi"); System.out.println("Hi");
Note:
final Variables are Replaced by Value at Compile Time Only.
Compiler is Responsible to Identify Unreachable Statement and JVM is Not
Responsible for this.
do-while
If we want to execute Loop Body at least Once then we should go for do-while.
Syntax do {
Here Semicolon is Mandatory and
Body
Argument should be boolean Type.
}while(b);
Curly Braces are Optional and without Curly Braces we can Take Only One Statement
which should Not be Declarative Statement.
do do; do do
SOP(“Hello”); while(true); while(true); int x = 10;
while(true); while(true);
do { do while(true); do Output
int x = 10; SOP(“Hello”); while(true) Hello
} while(true); √ while(false)√ SOP(“Hello”); Hello
while(false); √ :::::::::
118 https://www.youtube.com/durgasoftware
OCJA
do { do {
System.out.println ("Hello"); System.out.println("Hello");
} while(true); }while(false);
System.out.println("Hai"); System.out.println("Hai");
//CE: unreachable statement
Output: Hello
Hai
for loop
for (Initialization _Section; Conditional _Check; Increment/Decrement _Section)
{
Body
}
Curly Braces are Optional and without Curly Braces we can Take Only One
Statement in the Loop, which should Not be Declarative Statement.
119 https://www.youtube.com/durgasoftware
OCJA
Initialization Section
1) int i = o; √
2) int i = 0, j = 0; √
4) int i = 0, int j = 0;
int i = 0; Output
for(System.out.println("Hello U R Sleeping "); i<3; i++) { Hello U R Sleeping
System.out.println("No Boss U Only Sleeping"); No Boss U Only Sleeping
} No Boss U Only Sleeping
No Boss U Only Sleeping
Conditional Section
Here we can Take any Valid Java Expression but should be boolean Type.
This Part is Optional and if we are Not writing anything, then Complier Always
Place true.
int i = 0; Output
for (System.out.println("Hello U R Sleeping"); ;i++ ) { Hello U R Sleeping
System.out.println("U Only Sleeping"); U Only Sleeping
} U Only Sleeping
::::::::::::::::::::::::::
int i = 0; Output
for(System.out.println("Hello"); i<3; System.out.println("Hi")) { Hello
i++; Hi
} Hi
Hi
120 https://www.youtube.com/durgasoftware
OCJA
Note: All 3 Parts of for Loop are Independent to Each Other and Optional.
Infinite Loops
for (; ; ) { for (; ; );
Body;
}
121 https://www.youtube.com/durgasoftware
OCJA
for-each Loop OR Enhanced for Loop (1.5)
10 20 30 40 50 60
122 https://www.youtube.com/durgasoftware
OCJA
For 3 Dimensional Array
for (int[][] x : a )
{ a
for(int[] y : x)
{
for (int z : y)
{
System.out.println(z);
}
}
}
for-each Loop is the Most Convenient Loop to Retrieve Elements of Arrays and
Collections but its Limitation is it is Applicable only for Arrays and Collections and
it is Not a General Purpose Loop.
for(int i =0; i<10; i++) {
System.out.println("Hello"); //We can't write Equivalent for-each Loop Directly
}
By using Normal for Loop we can Print an Elements of an Array in Reverse Order.
But by using for-each Loop it is Not Possible.
Iterable(I) Vs Iterator(I)
Iterable(I):
The Target Element in for-each Loop should be Iterable Object.
An Object is Said to be Iterable if and Only if the Corresponding Class implements
java.lang.Iterable Interface.
Iterable Interface introduced in 1.5 Version and it contains Only One Method.
public Iterator iterator()
All Array Classes and Collection Classes Already implements Iterable Interface.
Being a Programmer we are Not required to do anything.
Array/ Collection
for(Each Item x: Target)
{ It should be Iterable Object
-------------------
-------------------
}
123 https://www.youtube.com/durgasoftware
OCJA
Iterable (I) Iterator (I)
It is related to for-each Loop It is related to Collections
The Target Element in for-each We can Use Iterator Object to get Objects
Loop should be Iterable Object One by One from the Collection.
Introduced in 1.5 Version Introduced in 1.2 Version
Present in java.lang Package Present in java.util Package
Iterable Interface defines Only One Iterator Interface defines 3 Methods –
Method iterator() hasNext(), next() and remove()
Transfer Statements
break:
Inside switch: Inside the switch we can Use break to Stop Fall-through.
int x = 0;
switch(x) {
case 0:
System.out.println(0);
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
default: Output:
System.out.println("Default"); 0
} 1
Inside Loops: Inside Loops to break Loop Execution based on Some Condition.
124 https://www.youtube.com/durgasoftware
OCJA
Inside Labeled Block: Inside Labeled Block to break Block Execution based on Some
Condition.
class Test {
public static void main(String[] args) {
int x = 10;
l1: {
System.out.println("Begin");
if(x == 10)
break l1;
System.out.println("End");
}
System.out.println("Hello"); Output:
} Begin
} Hello
These are the Only Places where we can Use break Statement. If we are using
anywhere Else, we will get Compile Time Error.
class Test {
public static void main(String[] args) {
int x = 10;
if(x == 10)
break; //CE: break outside switch or loop
System.out.println("Hello");
}
}
continue:
We can Use continue Statement to Skip Current Iteration and continue for the Next
Iteration.
class Test {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) { Output:
1
if(i%2 == 0)
3
continue;
5
System.out.println(i);
7
} 9
}
}
We can Use continue Statement Only Inside Loops. If we are Use anywhere Else we will
get Compile Time Error.
125 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
int x = 10;
if(x == 10)
continue; //CE: continue outside of loop
System.out.println("Hello");
}
}
We can Use Labeled break and continue Statements to break OR continue a Particular
Loop.
l1:
for (--------------------) {
l2:
for (--------------------) {
for (--------------------) {
break l1;
break l2;
break;
}
}
}
126 https://www.youtube.com/durgasoftware
OCJA
do-while Vs continue (The Most Dangerous Combination)
127 https://www.youtube.com/durgasoftware
OCJA
Declaration and Access Modifiers
Agenda
1. Java source file structure
o Import statement
o Types of Import Statements
Explicit class import
Implicit class import
o Difference between C language #include and java language import ?
o 1.5 versions new features
o Static import
Without static import
With static import
o Explain about System.out.println statement ?
o What is the difference between general import and static import ?
o Package statement
How to compile package Program
How to execute package Program
o Java source file structure
2. Class Modifiers
o Only applicable modifiers for Top Level classes
o What is the difference between access specifier and access modifier ?
o Public Classes
o Default Classes
o Final Modifier
Final Methods
Final Class
o Abstract Modifier
Abstract Methods
Abstract class
o The following are the various illegal combinations for methods
o What is the difference between abstract class and abstract method ?
o What is the difference between final and abstract ?
o Strictfp
o What is the difference between abstract and strictfp ?
128 https://www.youtube.com/durgasoftware
OCJA
3. Member modifiers
o Public members
o Default member
o Private members
o Protected members
o Compression of private, default, protected and public
o Final variables
Final instance variables
At the time of declaration
Inside instance block
Inside constructor
Final static variables
At the time of declaration
Inside static block
Final local variables
o Formal parameters
o Static modifier
o Native modifier
Pseudo code
o Synchronized
o Transient modifier
o Volatile modifier
o Summary of modifier
4. Interfaces
o Interface declarations and implementations
o Extends vs implements
o Interface methods
o Interface variables
o Interface naming conflicts
Method naming conflicts
Variable naming conflicts
o Marker interface
o Adapter class
o Interface vs abstract class vs concrete class
o Difference between interface and abstract class?
o Conclusions
129 https://www.youtube.com/durgasoftware
OCJA
Java source file structure:
A Java Program can contain any no of classes but at most one class can be declared as
public. "If there is a public class the name of the Program and name of the public class
must be matched otherwise we will get compile time error".
If there is no public class then any name we gives for Java source file.
Example:
Case 1:
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
Ashok.java
Case 2:
If class B declared as public then the name of the Program should be B.java otherwise we will get
compile time error saying "class B is public, should be declared in a file named B.java".
130 https://www.youtube.com/durgasoftware
OCJA
Case 3:
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:
1) class A {
2) public static void main(String args[]) {
3) System.out.println("A class main method is executed");
4) }
5) }
6)
7) class B {
8) public static void main(String args[]) {
9) System.out.println("B class main method is executed");
10) }
11) }
12)
13) class C {
14) public static void main(String args[]) {
15) System.out.println("C class main method is executed");
16) }
17) }
18)
19) class D {
20) }
Output:
D:\Java>java A
A class main method is executed
D:\Java>java B
131 https://www.youtube.com/durgasoftware
OCJA
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 Ashok
Exception in thread "main" java.lang.NoClassDefFoundError: Ashok
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 won't 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: Ashok".
Import statement:
1) class Test {
2) public static void main(String args[]) {
3) ArrayList l = new ArrayList();
4) }
5) }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:3: cannot find symbol
symbol : class ArrayList
location: class Test
Example:
1) import java.util.ArrayList;
2) class Test {
3) public static void main(String args[]) {
132 https://www.youtube.com/durgasoftware
OCJA
4) ArrayList l = new ArrayList();
5) }
6) }
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.
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.
133 https://www.youtube.com/durgasoftware
OCJA
Case 3: Consider the following code.
The code compiles fine even though we are not using import statements because we used fully
qualified name.
Whenever we are using fully qualified name it is not required to use import statement.
Similarly whenever we are using import statements it is not require to use fully qualified
name.
Case 4:
Example:
1) import java.util.*;
2) import java.sql.*;
3) class Test {
4) public static void main(String args[]) {
5) Date d = new Date();
6) }
7) }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:7: reference to Date is ambiguous;
both class java.sql.Date in java.sql and class java.util.Date in java.util match
Note: Even in the List case also we may get the same ambiguity problem because it is available in
both util and awt packages.
Case 5:
While resolving class names compiler will always gives the importance in the following order.
134 https://www.youtube.com/durgasoftware
OCJA
Example:
1) import java.util.Date;
2) import java.sql.*;
3) class Test {
4) public static void main(String args[]) {
5) Date d = new Date();
6) }
7) }
The code compiles fine and in this case util package Date will be considered.
Case 6:
Whenever we are importing a package all classes and interfaces present in that package are by
default available but not sub package classes.
Example:
To use pattern class in our Program directly which import statement is required?
135 https://www.youtube.com/durgasoftware
OCJA
Case 7:
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)
Case 8:
"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".
#include import
It can be used in C & C++ It can be used in Java
At compile time only compiler copy the code At runtime JVM will execute the corresponding
from standard library and placed in current standard library and use it's result in current
program. program.
It is static inclusion It is dynamic inclusion
wastage of memory No wastage of memory
Ex : <jsp:@ file=""> Ex : <jsp:include >
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-on-fly".
1) For-Each
2) Var-arg
3) Queue
4) Generics
5) Auto boxing and Auto unboxing
6) Co-varient return types
7) Annotations
8) Enum
9) Static import
136 https://www.youtube.com/durgasoftware
OCJA
10) String builder
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 reduces readability of the code. Hence if there is no specific requirement never recommended
to use a static import.
Usually we can access static members by using class name but whenever we are using static
import it is not require to use class name we can access directly.
1) class Test {
2) public static void main(String args[]) {
3) System.out.println(Math.sqrt(4));
4) System.out.println(Math.max(10,20));
5) System.out.println(Math.random());
6) }
7) }
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.841306154315576
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
137 https://www.youtube.com/durgasoftware
OCJA
20
0.4302853847363891
138 https://www.youtube.com/durgasoftware
OCJA
Example 3:
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
hi
Example 4:
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:6: reference to MAX_VALUE is ambiguous,
both variable MAX_VALUE in java.lang.Integer and variable MAX_VALUE in java.lang.Byte match
System.out.println(MAX_VALUE);
Note: Two packages contain a class or interface with the same is very rare hence ambiguity
problem is very rare in normal import.
But 2 classes or interfaces can contain a method or variable with the same name is very common
hence ambiguity problem is also very common in static import.
While resolving static members compiler will give the precedence in the following order.
139 https://www.youtube.com/durgasoftware
OCJA
Example:
If we comet line one then we will get Integer class MAX_VALUE 2147483647.
If we comet lines one and two then Byte class MAX_VALUE will be considered 127.
140 https://www.youtube.com/durgasoftware
OCJA
Diagram
Usage of static import reduces readability and creates confusion hence if there is no specific
requirement never recommended to use static import.
Package statement:
It is an encapsulation mechanism to group related classes and interfaces into a single module.
141 https://www.youtube.com/durgasoftware
OCJA
Example:
1) package com.durgajobs.itjobs;
2) class HydJobs {
3) public static void main(String args[]) {
4) System.out.println("package demo");
5) }
6) }
Javac HydJobs.java generated class files 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.
142 https://www.youtube.com/durgasoftware
OCJA
Diagram:
If the specified package structure is not already available then this command itself will create
the required package structure.
As the destination we can use any valid directory.
If the specified destination is not available then we will get compile time error.
Example:
D:\Java>javac -d c: HydJobs.java
Diagram:
If the specified destination is not available then we will get compile time error.
Example:
D:\Java>javac -d z: HydJobs.java
If Z: is not available then we will get compile time error.
143 https://www.youtube.com/durgasoftware
OCJA
How to execute package Program:
D:\Java>java com.durgajobs.itjobs.HydJobs
Conclusion 1:
In any java Program there should be at most one package statement that is if we are taking more
than one package statement we will get compile time error.
Example:
1) package pack1;
2) package pack2;
3) class A
4) {
5) }
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected
package pack2;
Conclusion 2:
In any java Program the 1st non comment statement should be package statement [if it is
available] otherwise we will get compile time error.
Example:
1) import java.util.*;
2) package pack1;
3) class A
4) {
5) }
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected
package pack1;
144 https://www.youtube.com/durgasoftware
OCJA
145 https://www.youtube.com/durgasoftware
OCJA
Class Modifiers
Whenever we are writing our own classes compulsory we have to provide some information about
our class to the JVM.
Like
1) Public
2) Default
3) Final
4) Abstract
5) Strictfp
If we are using any other modifier we will get compile time error.
Example:
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.
146 https://www.youtube.com/durgasoftware
OCJA
Diagram:
Public Classes:
If a class declared as public then we can access that class from anywhere. Within the package or
outside the package.
Example:
Program1:
1) package pack1;
2) public class Test {
3) public void methodOne() {
4) System.out.println("test class methodone is executed");
5) }
6) }
Program2:
1) package pack2;
2) import pack1.Test;
3) class Test1 {
147 https://www.youtube.com/durgasoftware
OCJA
4) public static void main(String args[]) {
5) Test t = new Test();
6) t.methodOne();
7) }
8) }
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".
Example:
Program 1:
1) package pack1;
2) class Test {
3) public void methodOne() {
4) System.out.println("test class methodone is executed");
5) }
6) }
Program 2:
1) package pack1;
2) import pack1.Test;
3) class Test1 {
4) public static void main(String args[]) {
5) Test t = new Test();
6) t.methodOne();
7) }
8) }
Output:
D:\Java>javac -d . Test.java
D:\Java>javac -d . Test1.java
D:\Java>java pack1.Test1
148 https://www.youtube.com/durgasoftware
OCJA
Test class methodone is executed
Final Modifier:
Final Methods:
Example:
Program 1:
1) class Parent {
2) public void property() {
3) System.out.println("cash+gold+land");
4) }
5) public final void marriage() {
6) System.out.println("subbalakshmi");
7) }
8) }
Program 2:
1) class child extends Parent {
2) public void marriage() {
3) System.out.println("Thamanna");
4) }
5) }
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() {
149 https://www.youtube.com/durgasoftware
OCJA
Final Class:
If a class declared as the final then we cann't creates the child class that is inheritance concept is
not applicable for final classes.
Example:
Program 1:
1) final class Parent
2) {
3) }
Program 2:
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:
150 https://www.youtube.com/durgasoftware
OCJA
Abstract Modifier:
Abstract is the modifier applicable only for methods and classes but not for variables.
Abstract Methods:
Even though we don't 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:
Child classes are responsible to provide implementation for parent class abstract methods.
Example:
Program:
151 https://www.youtube.com/durgasoftware
OCJA
The main advantage of abstract methods is , by declaring abstract method in parent class we
can provide guide lines to the child class such that which methods they should compulsory
implement.
Abstract method never talks about implementation whereas if any modifier talks about
implementation then the modifier will be enemy to abstract and that is always illegal
combination for methods.
Diagram:
152 https://www.youtube.com/durgasoftware
OCJA
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:
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: Test is abstract; cannot be instantiated
Test t=new Test();
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
can't create object of that class.
Even though class doesn't 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 doesn't contain any abstract method.
Example2: Every adapter class is abstract but it doesn't contain any abstract method.
Example1:
1) class Parent {
2) public void methodOne();
3) }
Output:
Compile time error.
D:\Java>javac Parent.java
Parent.java:3: missing method body, or declare abstract
public void methodOne();
153 https://www.youtube.com/durgasoftware
OCJA
Example2:
1) class Parent {
2) public abstract void methodOne() {}
3) }
Output:
Compile time error.
Parent.java:3: abstract methods cannot have a body
public abstract void methodOne(){}
Example3:
1) class Parent {
2) public abstract void methodOne();
3) }
Output:
Compile time error.
D:\Java>javac Parent.java
Parent.java:1: Parent is not abstract and does not override abstract method methodOne() in
Parent class Parent
If a class extends any abstract class then compulsory we should provide implementation for every
abstract method of the parent class otherwise we have to declare child class as abstract.
Example:
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
154 https://www.youtube.com/durgasoftware
OCJA
If we declare class child as abstract then the code compiles fine but child of child is responsible to
provide implementation for methodTwo().
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.
Usually the result of floating point of arithmetic is varing from platform to platform , to
overcome this problem we should use strictfp modifier.
If a method declare as the Strictfp then all the floating point calculations in that method has to
follow IEEE754 standard, So that we will get platform independent results.
155 https://www.youtube.com/durgasoftware
OCJA
Example:
If a class declares as the Strictfp then every concrete method(which has body) of that class has to
follow IEEE754 standard for floating point arithmetic, so we will get platform independent results.
Example:
156 https://www.youtube.com/durgasoftware
OCJA
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:
1) package pack1;
2) class A {
3) public void methodOne() {
4) System.out.println("a class method");
5) }
6) }
D:\Java>javac -d . A.java
Program 2:
1) package pack2;
2) import pack1.A;
3) class B {
4) public static void main(String args[]) {
5) A a = new A();
6) a.methodOne();
7) }
8) }
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 can't 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.
157 https://www.youtube.com/durgasoftware
OCJA
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:
1) package pack1;
2) class A {
3) void methodOne() {
4) System.out.println("methodOne is executed");
5) }
6) }
Program 2:
1) package pack1;
2) import pack1.A;
3) class B {
4) public static void main(String args[]) {
5) A a = new A();
6) a.methodOne();
7) }
8) }
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java pack1.B
methodOne is executed
Example 2:
Program 1:
1) package pack1;
2) class A {
3) void methodOne() {
4) System.out.println("methodOne is executed");
5) }
158 https://www.youtube.com/durgasoftware
OCJA
6) }
Program 2:
1) package pack2;
2) import pack1.A;
3) class B {
4) public static void main(String args[]) {
5) A a = new A();
6) a.methodOne();
7) }
8) }
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 outside package we can access protected members only in child classes and should
be by child reference only that is we can't use parent reference to call protected members
from outside package.
159 https://www.youtube.com/durgasoftware
OCJA
Example:
Program 1:
1) package pack1;
2) public class A {
3) protected void methodOne() {
4) System.out.println("methodOne is executed");
5) }
6) }
Program 2:
1) package pack1;
2) class B extends A {
3) public static void main(String args[]) {
4) A a = new A();
5) a.methodOne();
6) B b = new B();
7) b.methodOne();
8) A a1 = new B();
9) a1.methodOne();
10) }
11) }
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java pack1.B
methodOne is executed
methodOne is executed
methodOne is executed
160 https://www.youtube.com/durgasoftware
OCJA
Example 2:
161 https://www.youtube.com/durgasoftware
OCJA
5)From non-child class of outside
package
Private<default<protected<public
Recommended modifier for variables is private where as recommended modifier for methods is
public.
Final variables:
DIAGRAM:
For the instance variables it is not required to perform initialization explicitly jvm will always
provide default values.
Example:
1) class Test {
2) int i;
3) public static void main(String args[]) {
4) Test t = new Test();
5) System.out.println(t.i);
6) }
162 https://www.youtube.com/durgasoftware
OCJA
7) }
Output:
D:\Java>javac Test.java
D:\Java>java Test
0
If the instance variable declared as the final compulsory we should perform initialization explicitly
and JVM won't provide any default values.
Whether we are using or not otherwise we will get compile time error.
Example:
Program 1:
1) class Test {
2) int i;
3) }
Output:
D:\Java>javac Test.java
D:\Java>
Program 2:
1) class Test {
2) final int i;
3) }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:1: variable i might not have been initialized
class Test
163 https://www.youtube.com/durgasoftware
OCJA
Rule:
For the final instance variables we should perform initialization before constructor completion.
That is the following are various possible places for this.
Example:
1) class Test {
2) final int i = 10;
3) }
Output:
D:\Java>javac Test.java
D:\Java>
Example:
1) class Test {
2) final int i;
3) {
4) i = 10;
5) }
6) }
Output:
D:\Java>javac Test.java
D:\Java>
3) Inside constructor:
Example:
1) class Test {
2) final int i;
3) Test() {
4) i = 10;
5) }
6) }
164 https://www.youtube.com/durgasoftware
OCJA
Output:
D:\Java>javac Test.java
D:\Java>
If we are performing initialization anywhere else we will get compile time error.
Example:
1) class Test {
2) final int i;
3) public void methodOne() {
4) i = 10;
5) }
6) }
Output:
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.
In the case of instance variables for every object a seperate copy will be created but in the
case of static variables a single copy will be created at class level and shared by every object of
that class.
For the static variables it is not required to perform initialization explicitly jvm will always
provide default values.
Example:
1) class Test {
2) static int i;
3) public static void main(String args[]) {
4) System.out.println("value of i is :"+i);
5) }
6) }
Output:
D:\Java>javac Test.java
D:\Java>java Test
165 https://www.youtube.com/durgasoftware
OCJA
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.
(The JVM won't provide any default values)
Example:
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.
Example:
1) class Test {
2) final static int i = 10;
3) }
Output:
D:\Java>javac Test.java
D:\Java>
166 https://www.youtube.com/durgasoftware
OCJA
2) Inside static block:
Example:
1) class Test {
2) final static int i;
3) static {
4) i = 10;
5) }
6) }
If we are performing initialization anywhere else we will get compile time error.
Example:
1) class Test {
2) final static int i;
3) public static void main(String args[]) {
4) i = 10;
5) }
6) }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to final variable i
i=10;
Example:
1) class Test {
2) public static void main(String args[]) {
3) int i;
4) System.out.println("hello");
167 https://www.youtube.com/durgasoftware
OCJA
5) }
6) }
Output:
D:\Java>javac Test.java
D:\Java>java Test
Hello
Example:
1) class Test {
2) public static void main(String args[]) {
3) int i;
4) System.out.println(i);
5) }
6) }
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:
1) class Test {
2) public static void main(String args[]) {
3) final int i;
4) System.out.println("hello");
5) }
6) }
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
Note: The only applicable modifier for local variables is final if we are using any other modifier
we will get compile time error.
168 https://www.youtube.com/durgasoftware
OCJA
Example:
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: illegal start of expression
private int x=10;
169 https://www.youtube.com/durgasoftware
OCJA
Formal parameters:
The formal parameters of a method are simply acts as local variables of that method hence it
is possible to declare formal parameters as final.
If we declare formal parameters as final then we can't change its value within the method.
Example:
For instance and static variables JVM will provide default values but if instance and static
declared as final JVM won't provide default value compulsory we should perform initialization
whether we are using or not .
For the local variables JVM won't provide any default values we have to perform explicitly
before using that variables , this rule is same whether local variable final or not.
Static modifier:
170 https://www.youtube.com/durgasoftware
OCJA
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 can't 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)
4) public void methodOne() {
5) System.out.println(x);
6) }
7)
8) public static void methodOne() {
9) System.out.println(x);
10) }
171 https://www.youtube.com/durgasoftware
OCJA
Which are the following declarations are allow within the same class simultaneously?
a) 1 and 3
Example:
1) class Test {
2) int x = 10;
3) public void methodOne() {
4) System.out.println(x);
5) }
6) }
Example:
1) class Test {
2) int x = 10;
3) public static void methodOne() {
4) System.out.println(x);
5) }
6) }
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:
1) class Test {
2) static int x = 10;
3) public void methodOne() {
4) System.out.println(x);
5) }
6) }
172 https://www.youtube.com/durgasoftware
OCJA
Output: Compile successfully.
d) 2 and 4
Example:
1) class Test {
2) static int x = 10;
3) public static void methodOne() {
4) System.out.println(x);
5) }
6) }
e) 1 and 2
Example:
1) class Test {
2) int x = 10;
3) static int x = 10;
4) }
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:
1) class Test {
2) public void methodOne() {
3) System.out.println(x);
4) }
5) public static void methodOne() {
6) System.out.println(x);
7) }
8) }
Output:
Compile time error.
D:\Java>javac Test.java
173 https://www.youtube.com/durgasoftware
OCJA
Test.java:5: methodOne() is already defined in Test
public static void methodOne(){
For static methods implementation should be available but for abstract methods implementation
is not available hence static abstract combination is illegal for methods.
Case 1:
Overloading concept is applicable for static method including main method also.But JVM will
always call String[] args main method .
The other overloaded method we have to call explicitly then it will be executed just like a normal
method call .
Example:
Case 2:
Inheritance concept is applicable for static methods including main() method hence while
executing child class, if the child doesn't contain main() method then the parent class main
method will be executed.
174 https://www.youtube.com/durgasoftware
OCJA
Example:
1) class Parent {
2) public static void main(String args[]) {
3) System.out.println("parent main() method called");
4) }
5) }
6) class child extends Parent {
7) }
Output:
Example:
175 https://www.youtube.com/durgasoftware
OCJA
Output:
It seems to be overriding concept is applicable for static methods but it is not overriding it is
method hiding.
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.
176 https://www.youtube.com/durgasoftware
OCJA
To use native keyword:
Pseudo code:
For native methods implementation is already available and we are not responsible to provide
implementation hence native method declaration should compulsory ends with semicolon.
o public native void methodOne();----invalid
o public native void methodOne();---valid
For native methods implementation is already available where as for abstract methods
implementation should not be available child class is responsible to provide that, hence
abstract native combination is illegal for methods.
We can't declare a native method as strictfp because there is no guaranty whether the old
language supports IEEE754 standard or not. That is native strictfp combination is illegal for
methods.
For native methods inheritance, overriding and overloading concepts are applicable.
The main advantage of native keyword is performence will be improves.
The main disadvantage of native keyword is usage of native keyword in Java breaks platform
independent nature of Java language.
177 https://www.youtube.com/durgasoftware
OCJA
Synchronized:
1. Synchronized is the modifier applicable for methods and blocks but not for variables and
classes.
2. 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.
3. The main advantage of synchronized keyword is we can resolve data inconsistency
problems.
4. 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.
For syncronized methods compulsory implementation should be available, but for abstract
methods implementation won't be available, Hence abstract - syncronized combination is illegal
for methods.
Transient modifier:
1) Transient is the modifier applicable only for variables but not for methods and classes.
2) At the time of serialization if we don't want to serialize the value of a particular variable to
meet the security constraints then we should declare that variable with transient modifier.
3) 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".
4) 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.
5) 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:
1) Volatile is the modifier applicable only for variables but not for classes and methods.
2) If the value of variable keeps on changing such type of variables we have to declare with
volatile modifier.
3) 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.
4) Once the value got finalized before terminating the thread that final value will be updated
in master copy.
5) 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 performance of the system. Hence if there is no specific
requirement never recommended to use volatile modifier and it's almost outdated.
6) Volatile means the value keep on changing where as final means the value never changes
hence final volatile combination is illegal for variables.
178 https://www.youtube.com/durgasoftware
OCJA
Summary of Modifier:
Inner Outer
Modifier Methods Variables Blocks Interfaces Enum Constructors
Classes Classes
Public
Private
Protected
Default
Final
Abstract
Strictfp
Static
Synchronized
Native
Transient
Volatile
Note:
The modifiers which are applicable for inner classes but not for outer classes are private,
protected, static.
179 https://www.youtube.com/durgasoftware
OCJA
Interfaces
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
180 https://www.youtube.com/durgasoftware
OCJA
Def 2: From the client point of view an interface define the set of services what is expecting. 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 customer is expecting 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.
Example:
1) interface Interf {
2) void methodOne();
3) void methodTwo();
4) }
181 https://www.youtube.com/durgasoftware
OCJA
Output:
Compile time error.
D:\Java>javac SubServiceProvider.java
SubServiceProvider.java:1:
SubServiceProvider is not abstract and does not override
abstract method methodTwo() in Interf
class SubServiceProvider extends ServiceProvider
Extends vs implements:
A class can extends only one class at a time.
Example:
1) class One {
2) public void methodOne() {
3) }
4) }
5) class Two extends One {
6) }
Example:
1) interface One {
2) public void methodOne();
3) }
4) interface Two {
5) public void methodTwo();
6) }
7) class Three implements One,Two {
8) public void methodOne() {
9) }
10) public void methodTwo() {
11) }
12) }
A class can extend a class and can implement any no. of interfaces simultaneously.
1) interface One {
2) void methodOne();
3) }
4) class Two {
5) public void methodTwo() {
182 https://www.youtube.com/durgasoftware
OCJA
6) }
7) }
8) class Three extends Two implements One {
9) public void methodOne() {
10) }
11) }
Example:
1) interface One {
2) void methodOne();
3) }
4) interface Two {
5) void methodTwo();
6) }
7) interface Three extends One, Two {
8) }
Ans: 6
Ans: 3
X extends Y, Z ?
X, Y, Z should be interfaces.
183 https://www.youtube.com/durgasoftware
OCJA
X extends Y implements Z ?
X, Y should be classes.
Z should be interface.
X implements Y, Z ?
X should be class.
Y, Z should be interfaces.
X implements Y extend Z ?
Example:
1) interface One {
2) }
3) class Two {
4) }
5) class Three implements One extends Two {
6) }
Output:
Compile time error.
D:\Java>javac Three.java
Three.java:5: '{' expected
class Three implements One extends Two{
Interface methods:
Every method present inside interface is always public and abstract whether we are declaring or
not. Hence inside interface the following method declarations are equal.
void methodOne();
public Void methodOne();
abstract Void methodOne(); Equal
public abstract Void methodOne();
As every interface method is always public and abstract we can't use the following modifiers for
interface methods.
Private, protected, final, static, synchronized, native, strictfp.
184 https://www.youtube.com/durgasoftware
OCJA
1. public void methodOne(){}
2. private void methodOne();
3. public final void methodOne();
4. public static void methodOne();
5. public abstract void methodOne();
Ans: 5
Interface variables:
An interface can contain variables
The main purpose of interface variables is to define requirement level constants.
Every interface variable is always public static and final whether we are declaring or not.
Example:
1) interface interf {
2) int x = 10;
3) }
final: Implementation class can access this value but cannot modify.
int x=10;
public int x=10;
static int x=10;
final int x=10; Equal
public static int x=10;
public final int x=10;
static final int x=10;
public static final int x=10;
As every interface variable by default public static final we can't declare with the following
modifiers.
o Private
o Protected
o Transient
o Volatile
185 https://www.youtube.com/durgasoftware
OCJA
For the interface variables compulsory we should perform initialization at the time of
declaration only otherwise we will get compile time error.
Example:
1) interface Interf {
2) int x;
3) }
Output:
Compile time error.
D:\Java>javac Interf.java
Interf.java:3: = expected
int x;
Ans: 5
Interface variables can be access from implementation class but cannot be modified.
Example:
1) interface Interf {
2) int x = 10;
3) }
186 https://www.youtube.com/durgasoftware
OCJA
Example 1:
Example 2:
Output:
D:\Java>javac Test.java
D:\Java>java Test
20
187 https://www.youtube.com/durgasoftware
OCJA
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:
1) interface Left {
2) public void methodOne();
3) }
Example 2:
1) interface Right {
2) public void methodOne();
3) }
Example 3:
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
Case 2:
If two interfaces contain a method with same name but different arguments in the
implementation class we have to provide implementation for both methods and these methods
acts as a overloaded methods
188 https://www.youtube.com/durgasoftware
OCJA
Example 1:
1) interface Left {
2) public void methodOne();
3) }
Example 2:
1) interface Right {
2) public void methodOne(int i);
3) }
Example 3:
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
Case 3:
If two interfaces contain a method with same signature but different return types then it is not
possible to implement both interfaces simultaneously.
Example 1:
1) interface Left {
2) public void methodOne();
3) }
Example 2:
1) interface Right {
2) public int methodOne(int i);
3) }
We can't write any java class that implements both interfaces simultaneously.
189 https://www.youtube.com/durgasoftware
OCJA
Is a Java class can implement any no. of interfaces simultaneously?
Yes, except if two interfaces contains a method with same signature but different return types.
Example 1:
1) interface Left {
2) int x = 888;
3) }
Example 2:
1) interface Right {
2) int x = 999;
3) }
Example 3:
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
D:\Java>java Test
888
999
190 https://www.youtube.com/durgasoftware
OCJA
Marker interface:
If an interface doesn't contain any methods and by implementing that interface if our objects will
get some ability such type of interfaces are called Marker interface (or) Tag interface (or) Ability
interface.
Example:
Serializable
Cloneable
RandomAccess These are marked for some ability
SingleThreadModel
.
.
.
.
Example 1:
By implementing Serilaizable 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 is responsible to provide required ability.
191 https://www.youtube.com/durgasoftware
OCJA
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 not. This approach increases length of the
code and reduces readability.
Example 1:
1) interface X {
2) void m1();
3) void m2();
4) void m3();
5) void m4();
6) //.
7) //.
8) //.
9) //.
10) void m5();
11) }
Example 2:
Example 1:
192 https://www.youtube.com/durgasoftware
OCJA
5) public void m4() {}
6) //.
7) //.
8) //.
9) public void m1000(){}
10) }
Example 2:
1) public class Test extend AdapterX {
2) public void m3() {
3) }
4) }
Example:
193 https://www.youtube.com/durgasoftware
OCJA
Note: Marker Interface and Adapter class are big utilities to the programmer to simplify
programming.
What is the difference between interface, abstract class and concrete class?
When we should go for interface, abstract class and concrete class?
If we don't know anything about implementation just we have requirement specification then
we should go for interface.
If we are talking about implementation but not completely (partial implementation) then we
should go for abstract class.
If we are talking about implementation completely and ready to provide service then we
should go for concrete class.
Example:
194 https://www.youtube.com/durgasoftware
OCJA
What is the Difference between interface and abstract class ?
We can't create object for abstract class but abstract class can contain
constructor what is the need?
abstract class constructor will be executed when ever we are creating child class object to perform
initialization of child object.
Example:
1) class Parent {
2) Parent() {
3) System.out.println(this.hashCode());
4) }
5) }
6) class child extends Parent {
7) child() {
8) System.out.println(this.hashCode());
195 https://www.youtube.com/durgasoftware
OCJA
9) }
10) }
11) class Test {
12) public static void main(String args[]) {
13) child c = new child();
14) System.out.println(c.hashCode());
15) }
16) }
Note: We can't create object for abstract class either directly or indirectly.
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. It may create performence problems also.
(This is just like recruiting IAS officer for sweeping purpose)
Why abstract class can contain constructor where as interface doesn't contain
constructor?
The main purpose of constructor is to perform initialization of an object i.e., provide values for the
instance variables, Inside interface every variable is always static and there is no chance of existing
instance variables. Hence constructor is not required for interface.
But abstract class can contain instance variable which are required for the child object to perform
initialization for those instance variables constructor is required in the case of abstract class.
196 https://www.youtube.com/durgasoftware
OCJA
Product.java:
package sales.products;
public class Product{}
Market.java:
1) package market;
2) //Line-1
3) public class Market
4) {
5) SalesMan sm;
6) Product p;
7) }
Which code fragment when inserted at line 2, enables the code to compile?
A) import sales.*;
B) import java.sales.products.*;
C) import sales;
import sales.products;
D) import sales.*;
import products.*;
E) import sales.*;
import sales.products.*;
Answer : E
Note: Whenever we are importing a package, all classes and interfaces present in that package
are by default available but not sub package classes. Hence to use sub package class, compulsory
we should write import statement until sub package level.
197 https://www.youtube.com/durgasoftware
OCJA
Q2. Consider the code
1) package pack1;
2) public class A
3) {
4) int p;
5) private int q;
6) protected int r;
7) public int s;
8) }
Test.java:
1) package pack2;
2) import p1.A;
3) public class Test extends A
4) {
5) public static void main(String[] args)
6) {
7) A obj= new Test();
8) }
9) }
Answer: B
198 https://www.youtube.com/durgasoftware
OCJA
B)
C)
D)
Answer: C
Which definition of the Book class adds a valid layer of abstraction to the class hierarchy?
A)
199 https://www.youtube.com/durgasoftware
OCJA
B)
C)
D)
Answer: A
1) interface Interf
2) {
3) public void m1();
4) public void m2();
5) }
6) class A implements Interf
7) {
8) public void m1(){}
9) }
Which of the following changes individually will compile the code successfully?
200 https://www.youtube.com/durgasoftware
OCJA
Answer: A and B
C) At Line-2 insert
public abstract void setBookMark();
D) At Line-4 insert:
public void setBookMark(){}
Answer : D
201 https://www.youtube.com/durgasoftware
OCJA
Q7. Given the content of 3 files
X.java
1) public class X
2) {
3) public void a(){}
4) int a;
5) }
Y.java
1) public class Y
2) {
3) private int doStuff()
4) {
5) private int i =100;
6) return i++;
7) }
8) }
Z.java
1) import java.io.*;
2) package pack1;
3) class Z
4) {
5) public static void main(String[] args)throws IOException
6) {
7) }
8) }
Answer: A
202 https://www.youtube.com/durgasoftware
OCJA
Q8. Given the code fragments:
A.java
1) package pack1;
2) public class A
3) {
4) }
B.java
1) package pack1.pack2;
2) //Line-1
3) public class B
4) {
5) public void m1()
6) {
7) A a = new A();
8) }
9) }
C.java
1) package pack3;
2) //Line-2
3) public class C
4) {
5) public static void main(String[] args)
6) {
7) A a = new A();
8) B b = new B();
9) }
10) }
203 https://www.youtube.com/durgasoftware
OCJA
Replace Line-2 with:
import pack1;
import pack1.pack2;
Answer: A
204 https://www.youtube.com/durgasoftware
OCJA
5.2) Abstraction
5.3) Encapsulation
5.8) Overloading
5.9) Overriding
5.11) Polymorphism
5.15) Constructors
5.16) Coupling
5.17) Cohesion
205 https://www.youtube.com/durgasoftware
OCJA
Data Hiding:
Our Internal Data should Not go out Directly OR Outside Person can't Access Our
Internal Data Directly. This is the Concept of Data Hiding.
Eg: After Providing Proper User Name and Password Only we can able to Access Our
Mail Information.
Eg: After swiping ATM Card and Providing Valid Pin Number we can able to Access Our
Account Information.
class Account {
private double balance;
::::::::::::::::::::::::
::::::::::::::::::::::::
}
Abstraction:
Hiding Internal Implementation and Highlight the Set of Services which are offering is
the Concept of Abstraction.
Eg: By using Bank ATM GUI Screen Bank People are highlighting the Set of Services
what they offering without highlighting Internal Implementation.
206 https://www.youtube.com/durgasoftware
OCJA
Encapsulation:
The Process of Binding Data and Corresponding Methods into a Single Unit is Called
Encapsulation.
class Student {
rollno; Data and its Corresponding
marks; Behaviors into a Single Capsule
name; Data
age;
Methods
+
updateMarks()
getName()
}
In any Component follows Data Hiding and Abstraction Such Type of Component is
Called Encapsulated Component.
207 https://www.youtube.com/durgasoftware
OCJA
The Main Advantage of Encapsulation is we can Achieve Security and the Main Disadvantage of
Encapsulation is it Increases Length of the Code and Slow Down Execution. So that Performance
will be Impacted.
A Class is Said to be Tightly Encapsulated if and only if Each and Every Variable of
that Class declared as private.
Whether the Class contains Getter and Setter Methods OR Not and whether these
Methods are declared as public OR Not. These things are not required to Check.
Which of the following Classes are Which of the following Classes are
Tightly Encapsulated? Tightly Encapsulated?
class A { class A {
private int x = 10; int x = 10;
} }
208 https://www.youtube.com/durgasoftware
OCJA
IS-A Relationship (Inheritance):
class P {
public void m1() {}
}
class C extends P {
public void m2() {}
}
class Test {
public static void main (String [] args) {
//Case 1
P p = new P();
p.m1();
p.m2(); cannot find symbol
symbol: method m2()
location: variable p of type P
//Case 2
C c = new C();
c.m1();
c.m2();
//Case 3
P p = new C();
p.m1();
p.m2(); cannot find symbol
symbol: method m2()
location: variable p of type P
//Case 4
C c = new P(); error: incompatible types
required: C
found: P
}
}
209 https://www.youtube.com/durgasoftware
OCJA
Conclusions:
1) Whatever Methods Parent has by Default Available to the Child. Hence on Child
Class Object we can Call Both Parent and Child Class Methods.
2) Whatever Methods Child has by Default Not Available to the Parent and Hence on
the Parent Class Reference we can't Call Child Specific Methods.
3) Parent Reference can be used to hold Child Object. But by using that Reference we
can Call Only Methods Available in Parent Class and we can't Call Child Specific
Methods.
4) Child Reference cannot be used to hold Parent Object. But Parent Reference can
be used to hold Child Object.
5) Parent Class contains the Common Functionality which required for Child Class.
Whereas Child Class contains Specific Functionality.
class HousingLoan {
300 Methods
}
class Loan {
250 Methods
}
Object
Exception Error
The Most Common Methods which are required for All Java Classes are defined
Inside Object Class. Hence Object Class Acts as Root for All Java Classes.
The Most Common Methods which are required for All Exceptions and Errors are
defined in Throwable Class. Hence Throwable Class Acts as Root for Exception
Hierarchy.
Multiple Inheritance:
A Java Class can't extend More than One Class at-a-Time. Hence Java won't Provide
Support for Multiple Inheritance with Respect to Classes.
P1 m1() P2 m1()
C
C c = new C();
c.m1();
An Interface can extend any Number of Interfaces at a Time. Hence Java Provides
Support for Multiple Inheritance with Respect to Interfaces.
interface A {} interface B {}
interface C extends A, B {} √
211 https://www.youtube.com/durgasoftware
OCJA
Why Ambiguity Problem won't be raised in Interfaces?
Even though Multiple Method Declarations Present, but Implementation is Unique.
Hence there is No Chance of Ambiguity Problem in Interfaces.
C.I
m1()
{ Unique
--------
---------
Implementation Class
}
Note:
If Our Class doesn’t extends Any Other Class then Only it is the Direct Child Class of
Object.
Eg: class A {}
Object
If Our Class extends Any Other Class then it is the In- Direct Child Class of Object.
Eg: class A extends B {}
B √ A
Cyclic inheritance:
Cyclic Inheritance is Not allowed in Java.
A A
212 https://www.youtube.com/durgasoftware
B
OCJA
HAS-A Relationship:
class Engine {
//Engine Specific
Functionality.
}
Composition Vs Aggregation
Composition
Without Existence of Container Object, if there is No Chance of Existence of
Contained Objects then Container and Contained Objects are Said to be Strongly
Associated and this Strong Association is known as Composition.
Composition
Container Object
Contained Object ECE EEE
CSE IT
Civil
Aggregation
213 https://www.youtube.com/durgasoftware
OCJA
Eg: Within a Department there May be a Chance of working Several Professors. Without
Existence of Departments Object there May be a Chance of existing Professors Object.
Hence Department and Professors are Loosely Associated and this Loose Association is
Known as Aggregation.
Reference D C
C X O
O
N
N
P T
T
P1 A
A
Reference D I
I X N
N
E
E
P D
R : P2
: O
O : :
: B
B :
: J
J
D E
E Reference C
C X T
T
P S
S
Departments Pn
Note:
In Composition Objects are Strongly Associated whereas in Aggregation Objects are
Weakly Associated.
In Composition Container Object holds Contained Objects Directly whereas in
Aggregation Container Object Just Holds References of Contained Objects.
Method Signature:
214 https://www.youtube.com/durgasoftware
OCJA
Within a Class 2 Methods with Same Signature Not allowed. Otherwise we will get
Compile Time Error Saying m1() is already defined in Test class.
Overloading
2 Methods are Said to be Overloaded if and only if Both Methods having Same Name
but Different Type of Arguments.
In C Language Overloading Concept is Not there hence we can't Declare 2 Methods
with the Same Name but different Type of Arguments. Hence If there is a Change in
Argument Type Compulsory we should go for New Method Name.
Eg: abs(int),
abs(long),
215 https://www.youtube.com/durgasoftware
OCJA
abs(float)
Case 1:
The Overloading Method Resolution is the Responsibility of Compiler based on
Reference Type and Method Arguments. Hence Overloading is Considered as Compile-
Time Polymorphism OR Early Binding.
class Test {
public void m1()
{
System.out.println ("no- args");
}
public void m1(int i)
{
System.out.println ("int- args"); Overloaded
} Methods
public void m1(double d)
{
System.out.println ("double-args");
}
public static void main(String[] args) {
Test t = new Test();
t.m1(); no-args
t.m1(10); int-args
t.m1(10.5); double-args
}
}
While Resolving Overloaded Methods if Exact Method with the required Argument is
Not Available then the Compiler won’t Raise Immediately Compile Time Error.
First Compiler will Promote Arguments to Next Level and Check is there any
Matched Method with Promoted Arguments.
If the Matched Method is Found then it will Considered Otherwise Compiler
Promotes the Argument to the Next Level.
This Process will be continued until all Possible Promotions.
After all Possible Promotions still the Compiler Unable to find the Matched Method
then it raises Compile Time Error.
216 https://www.youtube.com/durgasoftware
OCJA
The following is the List of all Possible Automatic Promotions in Overloading.
class Test {
public void m1() {
System.out.println ("no-args");
}
t.m1(); //no-args
t.m1(10); //int-args
t.m1(10.9f); //float-args
t.m1('a'); //int-args
t.m1(10l); //float-args
217 https://www.youtube.com/durgasoftware
OCJA
Case 3:
In Overloading exact Match will get High Priority.
In Overloading Child Class Argument will get More Priority than Parent Class
Argument.
class Test {
public void m1(String s) {
System.out.println ("String Version"); Object
}
public void m1(Object o) {
System.out.println ("Object Version");
String
}
public static void main(String arg[]) {
Test t = new Test();
t.m1("Durga"); //String Version
t.m1(new Object()); //Object Version
t.m1(null); //String Version
}
}
Case 4:
In Java, Method Overloading is Not Possible by Changing the Return Type of the
Method because there May Occur Ambiguity Problem.
class Test {
public void m1(String s) { Object
System.out.println ("String Version");
}
String StringBuffer
public void m1(StringBuffer sb) {
System.out.println ("StringBuffer Version");
}
218 https://www.youtube.com/durgasoftware
OCJA
Case 5: In General var-arg Method will get Least Priority i.e., if No Other Method
Matched then Only var-arg Method will get the Chance. It is Exactly Same as default
Case Inside switch.
class Test {
public void m1(int i) {
System.out.println ("General Method");
}
public void m1(int... i) {
System.out.println ("var-arg Method");
}
public static void main(String arg[]) {
Test t = new Test();
t.m1(); //var-arg Method
t.m1(10, 20); //var-arg Method
t.m1(10); //General Method
}
}
Case 6:
class Test {
public void m1(int i, float f) {
System.out.println("int - float Version");
}
public void m1(float f, int i) {
System.out.println("float - int Version");
}
public static void main(String arg[]) {
Test t = new Test();
t.m1(10.5f, 10); //float - int Version
t.m1(10, 10.5f); //int - float Version
t.m1(10, 10); // C.E: reference to m1 is ambiguous, both method m1(int,float) in Test and
method m1(float,int) in Test match
t.m1(10.5f, 10.5f); // C.E: cannot resolve symbol
symbol : method m1 (float,float)
location: class Test
}
}
Case 7:
Overloading Method Resolution will always take Care by Compiler based on the
Reference Type but not based on Runtime Object.
219 https://www.youtube.com/durgasoftware
OCJA
class Animal {}
class Monkey extends Animal {}
class Test {
public void m1(Animal a) {
System.out.println ("Animal Version");
}
public void m1(Monkey m) {
System.out.println ("Monkey Version");
}
public static void main(String arg[]) {
Test t = new Test();
Animal a = new Animal();
t.m1(a); //Animal Version
Overriding:
Whatever the Parent has by Default Available to the Child Class through
Inheritance.
If the Child Class is Not satisfied with the Parent Class Implementation then the
Child is allowed to redefined that Method in the Child Class based on its
Requirement.
The Parent Class Method which is Overridden is called Overridden Method and the
Child Class Method which is Overriding is called Overriding Method.
220 https://www.youtube.com/durgasoftware
OCJA
class P {
public void property()
{
System.out.println ("Land + Gold + Cash");
}
Overridden public void mary()
Method {
System.out.println ("Subbu Lakshmi");
}
}
Overriding
class C extends P {
public void mary()
{
System.out.println ("3sha/ 9tara/ 4me");
Overriding }
Method }
class Test {
public static void main(String[] args) {
P p = new P();
p.mary(); //Subbu Lakshmi (Parent Method)
C c = new C();
c.mary(); //3sha/ 9tara/ 4me (Child Method)
P p1 = new C();
p1.mary(); //3sha/ 9tara/ 4me (Child Method)
}
}
221 https://www.youtube.com/durgasoftware
OCJA
Rules for Method Overriding:
In Overriding, Method Names and Argument Types Must be Same. i.e Method
Signatures Must be Same.
In Overriding the Return Types Must be Matched. But this Rule is Applicable Only
until 1.4 Version. From 1.5 Version onwards Co- Variant Return Types are allowed.
According to this Child Class Method Return Types Need Not to be Same as Parent
Class Method Return Type. It’s Child Types Also allowed.
class P {
public Object m1() {
return null;
}
}
class C extends P {
public String m1() {
return null;
}
}
Note: Co-Varient Return Type Concept 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. But based on Our Requirement we can Define
Exactly Same Private Method in Child Class. It is Valid but Not Overriding.
class P {
private void m1() {}
} It is Valid but
class C extends P { Not Overriding
private void m1() {}
}
We can’t Override Parent Class final Methods in Child Class i.e., Overriding Concept
is Not Applicable for final Methods.
class P {
public final void m1() {}
} CE: m1() in C cannot
222 override m1() in P;
https://www.youtube.com/durgasoftware
class C extends P {
public void m1() {} overridden method is final
}
OCJA
We can Override Parent Class Abstract Method in Child Class to Provide
Implementation.
We can Override Parent Class Concrete Method as Abstract in Child Class.
class P {
public void m1() {}
}
abstract class C extends P {
public abstract void m1();
}
✖ √ √ √ √ √ √ √ √ √
While Overriding we can’t Reduce Scope of Access Modifier. But we can Increase.
class P {
public void m1() {}
}
class C extends P {
protected void m1() {} // CE: m1() in C cannot override m1() in P
attempting to assign weaker access privileges; was public
}
√ √ √ √
223 https://www.youtube.com/durgasoftware
OCJA
private < default < protected < public
If Child Class Method throws any Checked Exception Compulsory the Parent Class
Method should throw the Same Checked Exception OR it’s Parent. But there are No
Restrictions for Un- Checked Exceptions.
import java.io.*;
class P {
public void m1() throws IOException {}
}
class C extends P {
public void m1() throws EOFException, InterruptedException{}
// CE: m1() in C cannot override m1() in P
overridden method does not throw InterruptedException
}
Examples:
We can’t Override a Static Method as Non- Static Otherwise we will get CE.
class P {
public static void m1() {}
}
class C extends P {
public void m1() {} //CE: m1() in C cannot override m1() in P
overridden method is static
}
Similarly we can’t Override a Non- Static Method as Static.
class P {
public void m1() {}
}
class C extends P {
public static void m1() {}
CE: m1() in C cannot override m1() in P
overriding method is static
}
class P {
public static void m1() {}
} It is Method Hiding
class C extends P { but Not Overriding
public static void m1() {}
}
It Seems Overriding Concept Applicable for Static Methods but it is Not Overriding. It is
Method Hiding.
Method Hiding:
225 https://www.youtube.com/durgasoftware
OCJA
Except these differences all Rules for Overriding and Method Hiding are Exactly Same.
class P {
public static void m1() {
System.out.println ("Parent Method");
}
}
class C extends P {
public static void m1() {
System.out.println ("Child Method");
}
}
class Test {
public static void main(String arg[]) {
P p = new P();
p.m1(); //Parent Method
C c = new C();
c.m1(); //Child Method
P p1 = new C();
p1.m1(); //Parent Method
}
}
If Both Parent and Child Class Methods are Not- Static, then it will become
Overriding. In this Case Output is
Parent Method
Child Method
Parent Method
226 https://www.youtube.com/durgasoftware
OCJA
class P {
public void m1(int... i) {
System.out.println ("Parent");
}
Overloading }
class C extends P {
public void m1(int i) {
System.out.println ("Child");
}
}
class Test {
public static void main(String args[]) {
P p = new P();
p.m1(); //Parent
C c = new C();
c.m1(10); //Child
P p1 = new C();
p1.m1(10); //Parent
}
}
If we Replace Child Class Method also with var-arg Method then it will become
Overriding. In this Case the Output is Parent, Child, and Child.
Overriding Concept is Applicable Only for Methods but Not for Variables.
Variables Resolution always takes Care by Compiler, based on Reference Type (but
not based on Run Time Object).
This Rule is Same whether the Variable is Static OR Non- Static.
227 https://www.youtube.com/durgasoftware
OCJA
class P {
int x = 888;
}
class C extends P {
int x = 999;
}
class Test {
public static void main(String[] args) {
P p = new P();
System.out.println(p.x); //888
C c = new C();
System.out.println(c.x);//999
P p1 = new C();
System.out.println(p1.x);//888
}
}
228 https://www.youtube.com/durgasoftware
OCJA
Note:
In Overloading we have to Check Only Method Names (must be Same) and Argument
Types (must be different).
The remaining things we are not required to Check.
But in Overriding we have to Check Everything Like Method Names, Argument
Types, Return Types Etc.
229 https://www.youtube.com/durgasoftware
OCJA
3) public final void m1(int i) throws Exception Overriding
4) private static int m1(int i) throws Exception Overloading
5) public static abstract void m1(double d)
CE: error: illegal combination of modifiers: abstract and static
: error: C is not abstract and does not override abstract method m1(double) in C
Polymorphism
We can Use the Same List Reference to Hold any implemented Class Object.
new ArrayList();
new LinkedList();
List l new Vector();
new Stack();
Collection (I)
List (I)
Stack
230 https://www.youtube.com/durgasoftware
OCJA
Polymorphism
A BOY Start LOVE with the Word FRIENDSHIP, but GIRL Ends LOVE with the Same Word
FIRENDSHIP. Word is the Same but Attitude is different. This Beautiful Concept of OOPs
is Nothing but Polymorphism.
Encapsulation
Security
OOPs
Re Usability Flexibility
Inheritance Polymorphism
231 https://www.youtube.com/durgasoftware
OCJA
Static Control Flow
class Base {
static int i = 10;
0
First Static Block
static { Secons Static Block
m1(); 20
System.out.println("First Static Block"); main()
}
public static void main(String[] args) { i = 0; (RIWO)
m1(); ⓭ J = 0 (RIWO)
System.out.println("main()"); ⓯
} i = 10 (R & W)
public static void m1() { J = 20 (R & W)
System.out.println(j); ⓮
}
static {
System.out.println("Second Static Block"); ⓫
}
static int j = 20; ⓬
}
Whenever we are executing a Java Class the following Sequence of Steps will be
Performed Automatically.
❶ Identification of Static Members from Top to Bottom (1-6) Steps.
i = 0 (RIWO) Read Indirect Write Only
j = 0 (RIWO)
❷ Execution of Static Variable Assignments and Static Blocks from Top to Bottom
(7-12) Steps.
i = 0 (R & W)
j = 0 (R & W)
❸ Execution of main() (13-15) Steps.
If a Variable is Just Identified and Assign with Default Value then the Variable is
Said to be in Read in-directly write Only State.
If we are trying to Read any Variable Inside the Static Block that Read Operation is
called Direct Read.
If we are trying to Read a Variable Inside a Method that Operation is called In-direct
Read.
232 https://www.youtube.com/durgasoftware
OCJA
If a Variable is in RIWO State then we can’t Perform Read Operation Directly
Otherwise we will get CE: illegal forward reference.
Whenever we are executing Parent Child Class the following Sequence of Events will
be Performed Automatically.
Identification of Static Members from Parent Child [1-11]
Execution of Static Variable Assignments and Static Blocks from Parent Child.
[12-22]
Execution of Only Child Class main(). [23-25]
233 https://www.youtube.com/durgasoftware
OCJA
0 1st Step: (1 - 11) 2nd Step: (12 - 22) 3rd Step: (23 - 25)
Base First Static Block i = 0; (RIWO) i = 10; (R & W) Execution of
0 j = 0; (RIWO) j = 20; (R & W) Derived main()
Derived First Static Block x = 0; (RIWO) x = 100; (R & W)
Derived Second Static Block y = 0; (RIWO) y = 200; (R & W)
200
Derived main()
Note: Whenever we are loading Child Class Automatically Parent Class will be loaded.
But whenever we are loading Parent Class Child Class won’t be loaded.
Static Block:
A Class can contain Static Block, it will be executed at the Time of Class loading
Automatically. Hence while loading Class if we want to Perform any Activity we have
to define that Inside this Static Block Only.
Eg: After loading Driver Class Compulsory we have to Register with DriverManager. But
Every Database Driver Class contains a Static Block to Perform this Activity. Hence at
the Time of Driver Class loading Only registering with DriverManager will be happen
Automatically and we are Responsible to Perform Explicitly.
class Driver {
static {
//Register this Driver with DriverManager
}
}
234 https://www.youtube.com/durgasoftware
OCJA
Eg: At the Time of Java Class loading the Corresponding Native Libraries should be
loaded. Hence we have to define this Activity Inside Static Block.
class Native {
static {
System.loadLibrary("Native Library Path:");
}
}
Note: Inside a Class we can Take Any Number of Static Blocks and these Static Blocks
will be executed from Top to Bottom.
class Test {
static {
System.out.println("Hello....I can Print ");
System.exit(0);
}
}
Without using main() and Static Block is it Possible to Print Some Statements to the
Console?
Yes. There are Multiple Ways.
class Test {
static Test t = new Test();
{
System.out.println("Hello I can Print"); Instance Block
System.exit(0);
}
}
235 https://www.youtube.com/durgasoftware
OCJA
Note: From 1.7 Version onwards to Run a Java Program main() is Mandatory. Even
though we are writing Static Block, main() is Mandatory. Hence 1.7 Version onwards
without writing main() it is not Possible to Print Some Statements to the Console.
Whenever we are executing a Java Class 1st Static Control Flow will be executed.
In the Static Control Flow whenever we are creating Object then Instance Control
Flow will be executed.
class Parent {
int i = 10;
{
m1(); ❿ 0
System.out.println("First Instance Block"); ⓬ First Instance Block
} Second Instance Block
Parent() { Constrctor
System.out.println("Constrctor"); ⓯ Parent main()
}
public static void main(String[] args) { 1st Step (3 - 8)
Parent p = new Parent(); i = 0; (RIWO)
System.out.println("Parent main()");
j = 0; (RIWO)
}
public void m1() {
2nd Step (9 - 14)
⓫ System.out.println(j);
i = 10; (R & W)
}
j = 20; (R & W)
{
System.out.println("Second Instance Block"); ⓭
}
int j = 20; ⓮
}
Note:
Static Control Flow is One Time Activity and that will Execute at the Time of Class
loading.
But Instance Control Flow is Not One Time Activity and that It will be Execute for
Every Object Creation.
236 https://www.youtube.com/durgasoftware
OCJA
Instance Control Flow in Parent Child Relation:
0
Parent Instance Block
Parent Constructor
0
Child First Instance Block
Child Second Instance Block
Child Constructor
Child main()
Whenever we are creating Child Class Objects the following Sequence of Events will be
Performed Automatically.
2) Execution of Instance Variable Assignments and Instance Blocks only in Parent Class.
(15 - 19)
i = 10 (R & W)
j = 20 (R & W)
238 https://www.youtube.com/durgasoftware
OCJA
From Static Area we can’t Access Instance Members Directly because while executing
Static Area JVM May Not Identify Instance Members.
class Test1 {
int x = 10;
public static void main(String[] args) {
System.out.println(x); }
}
CE: error: non-static variable x cannot be referenced from a static context
Note: Object Creation is Most Costly Operation in Java. Hence if there is No Specific
Requirement then it Never Recommended to Create Object.
Test t = (Test)Class.forname("Test").newInstance();
OR
(Test)Test.class.newInstance();
Runtime r = Runtime.getRuntime();
DateFormat df = DF.getInstance();
4. By using clone():
5. By using Deserialization:
239 https://www.youtube.com/durgasoftware
OCJA
Constructor:
class Student {
String name;
name: Durga name: Ravi
int rollno;
rollno: 101 rollno: 102
Student(String name, int rollno) {
this.name = name;
this.rollno = rollno;
s1 s2
}
public static void main(String[] args) {
Student s1 = new Student("Durga",101);
Student s2 = new Student("Ravi",102);
:::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::
}
}
class Test {
static int count = 0;
{
count++;
}
Test() {}
Test(int i) {}
class Test {
void Test() { } It is a Method but Not Constructor
}
It is Legal (But Stupid) to have a Method whose Name is exactly Same as Class
Name.
The Only Applicable Modifiers for Constructor are public, private, protected and
default. If we are trying to Apply any Other Modifier we will get CE.
class Test {
final Test() { } // CE: modifier final not allowed here
}
Default Constructor:
241 https://www.youtube.com/durgasoftware
OCJA
Compiler generated
Programmers code
Code
class Test class Test
{ {
} Test()
{
super();
}
}
public class Test public class Test
{ {
} public Test()
{
super();
}
}
class Test class Test
{ {
void Test() Test()
{ {
} super();
} }
void Test()
{
}
}
class Test class Test
{ {
Test() Test()
{ {
} super();
} }
}
class Test class Test
{ {
Test(int i) Test(int i)
{ {
this(); this();
} }
Test() Test()
{ {
} super();
} }
}
class Test class Test
{ {
Test(int i) Test(int i)
{ {
super(); super();
} }
} }
242 https://www.youtube.com/durgasoftware
OCJA
The 1st Line Inside Every Constructor should be either super OR this. If we are Not
writing anything Compiler will always Place super().
Case1: We can use super() OR this only in 1st Line of the Constructor. If we are using
anywhere else we will get CE.
class Test {
Test() {
System.out.println ("Constructor");
super(); //CE: call to super must be first statement in constructor
}
}
Case2: Within the Constructor we can use either super OR this but not Both
Simultaneously.
class Test {
Test() {
super();
this(); //CE: call to this must be first statement in constructor
}
}
Case 3: We can Use super() and this() Only in Constructors. If we are using Outside of
the Constructor we will get CE. That is we can Invoke a Constructor Directly from
Another Constructor only.
class Test {
public void m1() {
super(); //CE: call to super must be first statement in constructor
}
}
243 https://www.youtube.com/durgasoftware
OCJA
We can write Only One but Not Both Any Number of Times.
Simultaneously.
class Test {
public static void main(String args[]) {
System.out.println( super.hashCode());
//CE: non-static variable super cannot be referenced from a static context
}
}
Overloaded Constructor
A Class can contain Muiltiple Constructors with Same Name but different Argument
Types. This Type of Constructors are called Overloaded Constructors. Hence
Overloading Concept is applicable for Constructors.
class Test {
Test(double d) {
this(10);
System.out.println("double-arg");
}
Test(int i) {
this();
System.out.println("int-arg");
}
Test() {
System.out.println("no-arg");
}
no-arg
public static void main(String arg[]) { int-arg
double-arg
Test t1 = new Test(10.8);
no-arg
Test t2 = new Test(10); int-arg
Parent Class Constructors by Default won’t Available to the Child and hence
Inheritance Concept is Not Applicable for Constructors.
244 https://www.youtube.com/durgasoftware
OCJA
As Inheritance Concept Not Applicable, by Default Overriding Concept Also Not
Applicable.
Every Class in Java including Abstract Class can contain Constructor. But Interface
cannot have/ contain Constructor.
class Test { abstract class Test { interface Test {
Test() {} Test() {} Test() {}
}√ }√ } ✕
class Test {
:::::::::::::: :::
public static void m1() {
:::::::::: :::
m2();
:::::::::: :::
}
:::
public static void m2() { m2()
:::
m1();
} m1()
public static void main(String arg[]) { m2()
m1();
System.out.println("Hello......Hai"); m1()
// RE: Exception in thread "main" java.lang.StackOverflowError main()
}
} Run Time Flow
class Test {
Test() {
this(10);
}
Test(int i) { //CE: recursive constructor invocation
this();
}
public static void main(String arg[]) {
System.out.println("Hello......Hai");
}
}
Case 2:
If the Parent Class contains Argument Constructor then while writing Child classes
we have to Take Special Care with Respect to Constructors.
245 https://www.youtube.com/durgasoftware
OCJA
Whenever we are writing any Argument Constructor it is Highly Recommended to
write no-arg Constructor Also.
class P {} class P {
P(int i) {}
class C extends P {} ✔
}
class C extends P {}
Case 3: If the Parent Class Constructor throws Some Checked Exception. Compulsory
the Child Class Constructor should throw the Same Checked Exception OR its Parent
Otherwise CE.
import java.io.*;
class P {
P() throws IOException {}
}
class C extends P {} //CE: unreported exception IOException in default constructor
import java.io.*;
class P {
P() throws IOException {}
}
class C extends P {
C() throws IOException|Exception|Throwable {
super();
}
}
Singleton Classes: For any Java Class if we are allow to Create Only One Object Such
Type of Class is called Singleton Class.
Eg: Runtime, ActionServlet, BusinessDelegate, ServiceLocator etc.
Advantage:
Instead of creating a Separate Object for Every Requirement we can Create Only
One Object and we can Reuse the Same Object for Every Similar Requirement.
So that Memory Utilization and Performance will be Improved.
This is the Main Advantage of Singleton Classes.
246 https://www.youtube.com/durgasoftware
OCJA
class Test {
private static Test t = null;
private Test() {}
In the Above Example for Test Class we are allowed to Create Only One Object and
Hence it is Singleton Class.
247 https://www.youtube.com/durgasoftware
OCJA
Creation of Our Own Doubleton Classes:
class Test {
private static Test x = null;
private Test() {}
Test t1 = Test.getTest(); t1 X
Test t2 = Test.getTest(); t3
::
:: t2 Y
t4
Note: This Type of Approach we can Use while developing Connection Pools, Thread
Pools etc.
Class is Not final but we are Not allowed to Create Child Class. How it is Possible?
If we Declare Every Constructor as Private then we can’t Create Child Class for that.
class Parent {
private Parent() {}
}
class Child extends Parent {} //CE: Parent() has private access in Parent
248 https://www.youtube.com/durgasoftware
OCJA
The Dependency between the Above Classes is More and Hence these Components are
Said to be Tightly Coupled with Each Other.
Tightly Coupling is Not a Good Programming Practice. Because it has Several Serious
Disadvantages.
Without effecting remaining Components we can't Modify any Component. Hence
Enhancement will become Difficult.
It doesn't Promote Re-usability of the Code.
It Reduces Maintainability of the Application.
Cohesion:
For Every Component we have to Define a Clear Well defined Functionality. Such Type
of Component is Said to be follow High Cohesion.
Note: Loosely Coupling and High Cohesion are Always Good Programming Practices.
Type Casting
A b = (c) d;
Class/ Interface Class/ Interface
Reference Variable Object/Reference Variable
❷ ‘C’ should be Either Same OR Derived Type of A. Otherwise we will get CE.
String s = new String ("Durga");
StringBuffer sb = (StringBuffer)s;
Runtime Checking
The Runtime Object Type of ‘d’ Must be either Same OR derived Type of ‘C’.
Otherwise we will get Runtime Exception saying ClassCastException : ‘d’ type
250 https://www.youtube.com/durgasoftware
OCJA
Object o = new StringBuffer(“Ravi”) ;
StringBuffer sb = (StringBuffer)o; √
Strictly speaking through Type Casting we are not creating any New Object for the
existing Object. We are providing another Type of Reference Variable.
class Test {
public static void main(String args[]) { Integer i
Integer i = new Integer(10);
Number n = (Number)i; Number n 10
Object o = (Object)n;
System.out.println(i.hashCode()); //10 Object o
System.out.println(n.hashCode()); //10
System.out.println(o.hashCode()); //10
System.out.println(i == n); //true
System.out.println(i == o); //true
}
}
Examples:
C c = new C(); C c = new C(c);
A m1() { sopln (“A”); }
P m1()
c.m1() √ c.m1(); // C
B m1() { sopln (“B”); }
c.m2() √ C m2() ( (B)c).m1(); //C
( (P)c ).m2()
CE: cannot find symbol It is Overriding and Method Resolution is Always based on
found: method m2() Runtime Object.
location: class P
C c = new C(c);
A static m1() { sopln(“A”); }
c.m1(); // C
C c = new C();
A int x = 999;
Sopln(c.x); //777
B int x = 888;
Sopln( (B)c).x); //888
252 https://www.youtube.com/durgasoftware
OCJA
1. Compare and contrast the features and components of Java such as: object orientation,
encapsulation, etc.
2. Describe inheritance and its benefits
3. Create methods with arguments and return values; including overloaded methods
4. Apply encapsulation principles to a class
5. Develop code that makes use of polymorphism; develop code that overrides methods;
differentiate between the type of a reference and the type of an object
6. Create and overload constructors; differentiate between default and user defined constructors
7. Use super and this to access objects and constructors
8. Determine when casting is necessary
Q1. Which three statements describe the object oriented featues of the java language?
Answer: B,C,E
Q2. What is the name of the Java concept that uses access modifiers to protect variables
and hide them within a class?
A. Encapsulation
B. Inheritance
C. Abstraction
D. Instantiation
E. Polymorphism
Ans: A
Explanation: This concept is data hiding, but that option is not available and hence we can choose
encapsulation
253 https://www.youtube.com/durgasoftware
OCJA
Q3. Which statement best describes encapsulation?
A. Encapsulation ensures that classes can be designed so that only certain fields and methods of
an object are accessible from other objects
B. Encapsulation enures that classes can be designed so that thier methods are inheritable
C. Encapsulation ensures that classes can be designed with some fields and methods declared as
abstract.
D. Encapsulation ensures that classes can be designed so that if a method has an argument X,any
subclass of X can be passed to that methods.
Answer: A
How should you write methods in ElectricAccount class at Line-1 so that the member variable bill
is always equal to the value of the member variable kwh multiplied by the member variable rate?
A)
254 https://www.youtube.com/durgasoftware
OCJA
3) this.kwh+=kwh;
4) this.bill=this.kwh*this.rate;
5) }
B)
C)
D)
Answer: C
255 https://www.youtube.com/durgasoftware
OCJA
Explanation:
Any amount of electricity used by Customer(represented by an instance of the Customer class)
must contribute to the Customer's bill(represented by member variable bill) through the method
useElectricity() method.
An instance of the customer class should never be able to tamper with or decrease the value of
the member variable bill
if we pass -ve value for kwh then we can decrease the bill. To prevent this we should check kwh>0
Which two changes would encapsulation this class and ensure that the area field is always
equal to length*height,whenever Rectangle class is used?
Answer: B,F
256 https://www.youtube.com/durgasoftware
OCJA
Q6. Given the following classes:
Which two options fail to compile when placed at Line 1 of the main method?
A. e.salary=50_000;
B. d.salary=80_000;
C. e.budget=2_00_000;
D. m.budget=1_00_000;
E. m.stockOption=500;
F. d.stockOption=1_000;
Answer: C and E
257 https://www.youtube.com/durgasoftware
OCJA
10) void resolve()//Line-3
11) {
12) }
13) protected void rotate()//Line-4
14) {
15) }
16) }
Answer: C,D
Explanation: While overriding, we cannot reduce the scope of access modifier, but we can
increase the scope
Q8. Given:
Base.java:
1) class Base
2) {
3) public void test()
4) {
5) System.out.println("Base");
6) }
7) }
DerivedA.java:
258 https://www.youtube.com/durgasoftware
OCJA
DerivedB.java
B.
Base
DerivedB
C.
DerivedB
DerivedB
D.
DerivedB
DerivedA
Answer: C
259 https://www.youtube.com/durgasoftware
OCJA
Q9. Which two are benefits of polymorphism?
Answer: C,D
Q10. Which three statements are true about the structure of a Java class?
Answer: C, D,F
Q11. Given:
1) class A
2) {
3) public void test()
4) {
5) System.out.print("A");
6) }
7) }
8) class B extends A
9) {
10) public void test()
11) {
12) System.out.print("B");
13) }
14) }
15) public class C extends A
16) {
17) public void test()
18) {
19) System.out.print("C");
20) }
21) public static void main(String[] args)
22) {
23) A a1 = new A();
260 https://www.youtube.com/durgasoftware
OCJA
24) A a2 = new B();
25) A a3 = new C();
26) a1.test();
27) a2.test();
28) a3.test();
29) }
30) }
A. AAA
B. ABC
C. AAB
D. ABA
Ans: B
Q12. Given:
261 https://www.youtube.com/durgasoftware
OCJA
What is the result?
A.
int sum is:30
double sum is:30.0
B.
int sum is:30
float sum is:30.0
C.
Integer sum is:30
double sum is:30.0
D.
Integer sum is:30
float sum is:30.0
Answer: A
A. 600
B. Compilation Fails at Line-1
C. Compilation Fails at Line-2
D. A ClassCastException is thrown at Line-1
E. A ClassCastException is thrown at Line-2
Answer: C
262 https://www.youtube.com/durgasoftware
OCJA
1) class Vehicle
2) {
3) String type="4w";
4) int maxSpeed=120;
5) Vehicle(String type,int maxSpeed)
6) {
7) this.type=type;
8) this.maxSpeed=maxSpeed;
9) }
10) }
11) class Car extends Vehicle
12) {
13) String trans;
14) Car(String trans)
15) {
16) //Line-1
17) this.trans=trans;
18) }
19) Car(String type,it maxSpeed,String trans)
20) {
21) super(type,maxSpeed);
22) this(trans);//Line-2
23) }
24) }
A. 4w 120 Auto
4w 150 Manual
B. null 0 Auto
4w 150 Manual
263 https://www.youtube.com/durgasoftware
OCJA
D. Compilatio Fails only at Line-2
E. Compilatio Fails at both Line-1 and Line-2
Answer: E
Q2. Given:
1) class CD
2) {
3) int r;
4) CD(int r)
5) {
6) this.r=r;
7) }
8) }
9) class DVD extends CD
10) {
11) int c;
12) DVD(int r, int c)
13) {
14) //line-1
15) }
16) }
Which code fragment should be inserted at Line-1 to instantiate dvd object successfully?
A. super.r=r;
this.c=c;
B. super(r);
this(c);
C. super(r);
this.c=c;
D. this.c=r;
super(c)
Answer: C
264 https://www.youtube.com/durgasoftware
OCJA
Q3. Given the code Fragment:
265 https://www.youtube.com/durgasoftware
OCJA
this("Durga",true,100)
Answer: A and C
Q4. Given:
1) class A
2) {
3) public A()
4) {
5) System.out.println("A");
6) }
7) }
8) class B extends A
9) {
10) public B()
11) {
12) //line-1
13) System.out.println("B");
14) }
15) }
16) class C extends B
17) {
18) public C()
19) {
20) //line-2
21) System.out.println("C");
22) }
23) public static void main(String[] args)
24) {
25) C c = new C();
26) }
27) }
A. CBA
B. C
C. ABC
D. Compilation Fails at line-1 and line-2
Answer: C
266 https://www.youtube.com/durgasoftware
OCJA
Q5. Given
1) class Vehicle
2) {
3) int x;
4) Vehicle()
5) {
6) this(10);// line-1
7) }
8) Vehicle(int x)
9) {
10) this.x=x;
11) }
12) }
13) class Car extends Vehicle
14) {
15) int y;
16) Car()
17) {
18) super();
19) this(20);//line-2
20) }
21) Car(int y)
22) {
23) this.y= y;
24) }
25) public String toString()
26) {
27) return super.x+":"+this.y;
28) }
29) }
A. 10:20
A. 0:20
C. Compilation Fails at Line-1
D. Compilation Fails at Line-2
Answer: D
267 https://www.youtube.com/durgasoftware
OCJA
Q6. Given the code fragment:
Answer: D
Q7. Given:
1) class Animal
2) {
3) String type="Canine";
4) int maxSpeed=60;
5) Animal(){}
268 https://www.youtube.com/durgasoftware
OCJA
6) Animal(String type,int maxSpeed)
7) {
8) this.type=type;
9) this.maxSpeed=maxSpeed;
10) }
11) }
12) class WildAnimal extends Animal
13) {
14) String bounds;
15) WildAnimal(String bounds)
16) {
17) //line-1
18) }
19) WildAnimal(String type,int maxSpeed,String bounds)
20) {
21) //line-2
22) }
23) }
Canine 60 Long
Feline 80 Short
269 https://www.youtube.com/durgasoftware
OCJA
super(type,maxSpeed);
this.bounds=bounds;
Answer: A and E
Q8.
1) class Employee
2) {
3) private String name;
4) private int age;
5) private int salary;
6)
7) public Employee(String name,int age)
8) {
9) setName(name);
10) setAge(age);
11) setSalary(2000);
12) }
13) public Employee(String name,int age,int salary)
14) {
15) setSalary(salary);
16) this(name,age);
17) }
18) //getter and setter methods goes here
19) public void printDetails()
20) {
21) System.out.println(name+":"+age+":"+salary);
22) }
23) }
Test.java
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) Employee e1= new Employee();
6) Employee e2= new Employee("Durga",50);
7) Employee e3= new Employee("Ravi",40,5000);
8) e1.printDetails();
9) e2.printDetails();
10) e3.printDetails();
11) }
12) }
270 https://www.youtube.com/durgasoftware
OCJA
What is the result?
B. null:0:0
Durga:50:0
Ravi:40:5000
C. null:0:0
Durga:50:2000
Ravi:40:5000
A. At line-2 insert:
amount=100;
B. At line-2 insert:
this.amount=100;
C. At line-2 insert:
acct.amount=100;
D. At line-1 insert:
1) public CheckingAccount()
2) {
3) amount=100;
4) }
271 https://www.youtube.com/durgasoftware
OCJA
E. At line-1 insert:
1) public CheckingAccount()
2) {
3) this.amount=100;
4) }
F. At line-1 insert:
1) public CheckingAccount()
2) {
3) acct.amount=100;
4) }
Answers: C, D and E
272 https://www.youtube.com/durgasoftware
OCJA
Exception Handling
1) Introduction
4) Exception Hierarchy
9) finally Block
273 https://www.youtube.com/durgasoftware
OCJA
Introduction
An Unwanted Unexpected Event that Disturbs Normal Flow of the Program is Called
Exception.
Eg: SleepingException, TyrePuncheredException, FileNotFoundException Etc…
Exception Handling:
try {
//Read Data from Remote File locating at London
}
catch (FileNotFoundException e) {
//Use Local File and Continue Rest of the Program Normally
}
Q) What is an Exception?
Q) What is the Purpose of Exception Handling?
Q) What is the Meaning of Exception Handling?
274 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() {
doMoreStuff();
}
public static void doMoreStuff() {
System.out.println("Hello"); //Hello
}
}
doMoreStuff()
doStuff( doStuff() doStuff(
)) ) main()
main() main() main() main()
Runtime Activation Record
Stack OR The Empty Stack
Stack Frame will be destroyed
by JVM
In Our Java Program Inside a Method if an Exception raised, then that Method is
Responsible to Create an Exception Object by including the following Information.
Name of Exception
Description of Exception
Location of Exception (Stack Trace)
After creating Exception Object Method Handovers that Object to the JVM.
JVM will Check whether Corresponding Method contain any Exception Handling
Code OR Not.
If the Method doesn't contain any Exception Handling Code then JVM Terminates
that Method Abnormally and Removes Corresponding Entry from the Stack.
JVM will Identify Caller Method and Check whether the Caller Method contain any
Exception Handle Code OR Not.
If Caller Method doesn't contain any Exception Handling Code then JVM Terminates
that Caller Method and Removes Corresponding Entry from the Stack.
275 https://www.youtube.com/durgasoftware
OCJA
This Process will be continued until main().
If the main() also doesn't contain Exception Handling Code then JVM Terminates
main() Abnormally and Removes Corresponding Entry from the Stack.
Then JVM Handovers the Responsibility of Exception Handling to the Default
Exception Handler, which is the Part of the JVM.
Default Exception Handler Just Terminates the Program Abnormally and Prints
Exception Information to the Console in the following Format.
Examples:
class Test {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() { doMoreStuff()
doMoreStuff(); ;
doStuff();
}
public static void doMoreStuff() { main()
System.out.println(10/0); Runtime Stack
}
}
RE: Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.doMoreStuff(Test.java:9)
at Test.doStuff(Test.java:6)
at Test.main(Test.java:3)
class Test {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() {
doMoreStuff();
System.out.println(10/0);
}
public static void doMoreStuff() {
System.out.println("Hello");
}
}
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.doStuff(Test.java:7)
at Test.main(Test.java:3)
276 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
doStuff();
System.out.println(10/0);
} Hello
public static void doStuff() { Hi
doMoreStuff(); Exception in thread "main"
System.out.println("Hi"); java.lang.ArithmeticException: / by zero
} at Test.main(Test.java:4)
public static void doMoreStuff() {
System.out.println("Hello");
}
}
Note:
In Our Program if all Methods Terminated Normally, then Only the Program will be
Terminated Normally.
In Our Program if at least One Method terminates Abnormally then the Program
Termination is Abnormal Termination.
Exception Hierarchy
Exception: Most of the Cases Exceptions are Caused by Our Program and these are Re-
Coverable.
Eg:
If Our Programming Requirement is to Read Data from the File locating at London.
At Runtime if London File is Not Available then we get FileNotFoundException.
If FileNotFoundException Occurs we can Provide Local File to Continue Rest of the
Program Normally.
Programmer is Responsible to Recover Exception.
Error:
Most of the Cases Errors are Not Caused by Our Program and these are Due to Lack
of System Resources.
Errors are Non- Recoverable.
Eg:
If OutOfMemoryError Occurs, being a Programmer we can't do anything and the
Program will be terminated Abnormally.
System Admin OR Server Admin is Responsible to Increase Heep Memory.
277 https://www.youtube.com/durgasoftware
OCJA
Checked Exceptions:
The Exceptions which are Checked by the Compiler for Smooth Execution of the
Program at Runtime are Called Checked Exceptions.
Compiler Checks whether we are handling Checked Exceptions OR Not. If we are
Not handling then we will get Compile Time Error.
Eg:
HallTicketMissingException, PenNotWorkingException, FileNotFoundException, Etc.
Unchecked Exceptions:
The Exceptions which are Not Checked by the Compiler are Called Unchecked
Exception.
Compiler won't Check whether we are Handle OR Not Unchecked Exceptions.
Eg: ArithmeticException, NullPointerException, BombBlostException, Etc.
Note:
Whether the Exception is Checked OR Unchecked Compulsory it will Occur at
Runtime Only.
There is No Chance of occurring any Exception at Compile Time.
Runtime Exceptions and its Child Classes, Errors and its Child Classes are
Unchecked Exceptions Excetp these all remaining are Considered as Checked
Exceptions.
278 https://www.youtube.com/durgasoftware
OCJA
Fully Checked Vs Partially Checked:
A Checked Exception is Said to be Fully Checked if and Only if all its Child Classes also
Checked.
Eg: IOException, InterruptedException, ServletException, Etc...
A Checked Exception is Said to be Partially Checked if and Only if Some of its Child
Classes are Unchecked.
Eg: Throwable, Exception.
2) RuntimeException Unchecked
4) Error Unchecked
6) ArithmeticException Unchecked
7) NullPointerException Unchecked
try
{
//Risky Code
}
catch (Exception e)
{
//Handling Code
}
279 https://www.youtube.com/durgasoftware
OCJA
Without try – catch With try - catch
class Test { class Test {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Statement 1"); System.out.println("Statement 1");
System.out.println(10/0); try {
System.out.println("Statement 2"); System.out.println(10/0);
} }
} catch(ArithmeticException e) {
System.out.println(10/2);
Statement 1 }
RE: Exception in thread "main" System.out.println("Statement 2");
java.lang.ArithmeticException: / by zero }
at Test.main(Test.java:4) } Statement 1
5
Abnormal Termination Normal Termination Statement 2
try {
Statement 1;
Statement 2;
Statement 3;
}
catch(X e) {
Statement 4;
}
Statement 5;
Conclusions:
Within the try Block if any where an Exception raised then Rest of the try Block
won't be executed even though we handled that Exception.
Hence within the try Block we have to Take Only Risky Code and Hence Length of
the try Block should be as Less as Possible.
If there is any Statement which raises an Exception and it is Not Part of the try
Block then it is Always Abnormal Termination.
280 https://www.youtube.com/durgasoftware
OCJA
In Addition to try Block there May be a Chance of raising an Exception Inside catch
and finally Blocks Also.
class Test {
public static void main(String[] args) {
try {
System.out.println(10/ 0);
}
catch (ArithmeticException e) {
e.printStackTrace(); //RE: java.lang.ArithmeticException: / by zero
at Test.main(Test.java:4)
System.out.println(e); //RE: java.lang.ArithmeticException: / by zero
System.out.println(e.getMessage()); /// by zero
}
}
}
281 https://www.youtube.com/durgasoftware
OCJA
try with Multiple catch Blocks
The way of handling an Exception is varied from Exception to Exception. Hence for
Every Exception Type we have to define a Separate catch Block. Hence try with
Multiple catch Blocks is Possible and Recommended to Use.
try { try {
:::::::::::: ::::::::::::::
:::::::::::: ::::::::::::::
} }
catch (Exception e) { catch (ArithmeticException e) {
::::::::::: //Perform these an Alternative
::::::::::: ArithmeticException
} }
catch (NullPointerException e) {
Not Recommended //Handling Related to null
}
catch (FileNotFoundException) {
//Use Local File Instead of Remote File
}
catch (SQLException e) {
//Use MySQL DB Instead of Oracle
}
catch (Exception e) {
Default Exception Handling
}
Recommended
Note:
If try with Multiple catch Blocks Present then the Order of catch Blocks are Very
Important. It should be from Child to Parent.
By Mistake if we are trying to Take Parent to Child then we will get Compile Time
Error Saying: exception XXX has already been caught
try {}
catch (Exception e) {}
catch (ArithmeticException e) {} //CE: exception ArithmeticException has already been caught
try {}
catch (ArithmeticException e) {}
catch (Exception e) {}
For any Exception if we are writing 2 Same catch Blocks we will get Compile Time
Error.
282 https://www.youtube.com/durgasoftware
OCJA
try {}
catch(ArithmeticException e) {}
catch(ArithmeticException e) {} //CE: error: exception ArithmeticException has already been caught
finally Block
It is Never Recommended to Define Clean-up Code Inside try Block. Because there
is No Guaranty for the Execution of Every Statement Inside try Block.
It is Never Recommended to Define Clean-up Code Inside catch Block. Because if
there is No Exception then catch Block won't be executed.
Hence we required Some Place to Maintain Clean-up Code which should be
executed Always irrespective of whether Exception raised OR Not raised and
whether Handled OR Not Handled. Such Type of Best Place is Nothing but finally
Block.
Hence the Main Objective of finally Block is to Maintain Clean-up Code.
try {
//Risky Code
}
catch(X e) {
//Handling Code
}
finally {
//Clean Up Code
}
class Test {
public static void main(String[] args) {
try {
System.out.println ("try");
System.out.println (10/0); try
} finally
catch (NullPointerException e) { Exception in thread "main"
System.out.println ("catch"); java.lang.ArithmeticException: / by zero
} at Test.main(Test.java:5)
finally {
System.out.println ("finally");
}
}
}
finally Vs return:
If return Statement Present Inside try OR catch Blocks 1st finally will be executed and
after that Only return Statement will be Considered i.e. finally Block Dominates return
Statement.
class Test {
public static void main(String[] args) {
try {
System.out.println("try");
return;
}
catch(Exception e) {
System.out.println("catch");
}
finally {
System.out.println("finally");
}
} try
} finally
If try-catch-finally Blocks having return Statements then finally Block return Statement
will be Considered i.e. finally Block return Statement has More Priority than try and
catch Block return Statements.
284 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
System.out.println(m1()); //999
}
public static int m1() {
try {
return 777;
}
catch(Exception e) {
return 888;
}
finally {
return 999;
}
}
}
finally Vs System.exit(0):
There is Only One Situation where the finally Block won't be executed that is
whenever we are System.exit(0).
Whenever we are using System.exit(0) then JVM itself will be Shutdown and hence
finally Block won't be executed. That is System.exit(0) Dominates finally Block.
class Test {
public static void main(String[] args) {
try {
System.out.println("try");
System.exit(0);
}
catch(Exception e) {
System.out.println("catch");
}
finally {
System.out.println("finally");
}
}
} try
System.exit(0);
☀ We can Use this Method to Exit (Shut Down) the System (JVM) Programmatically.
☀ The Argument Represents as Status Code.
☀ Instead of 0 we can Pass any Valid int Value.
☀ 0 Means Normal Termination, Non- Zero Means Abnormal Termination.
285 https://www.youtube.com/durgasoftware
OCJA
☀ So this status code internally used by JVM.
☀ Whether it is 0 OR Non- Zero Effect is Same in Our Program but this Number
Internally used by JVM.
final:
final is a Modifier is Applicable for Classes, Methods and Variables.
If a Class declared as final then we can't Create Child Class. That is Inheritance is
Not Possible for final Classes.
If a Method declared as final then we can't Override that Method in Child Classes.
If a Variable declared as final then we can't Perform Re- Assignment for that
Variable.
finally:
finally is a Block Always associated with try-catch to Maintain Clean Up Code.
The Specialty of finally Block is it will be executed Always Irrespective of whether
Exception raised OR Not and whether Handled OR Not Handled.
finalize():
finalize() is a Method Always Called by the Garbage Collector Just before Destroying
an Object to Perform Clean Up Activities.
Once finalize() Completes Automatically Garbage Collector Destroys that Object.
Note:
finally() is Responsible to Perform Object Level Clean-Up Activities whereas finally
Block is Responsible to Perform try Block Level Clean-Up Activities i.e. whatever
Resources we Opened at the Time of try Block will be Closed Inside finally Block
It is Highly Recommended to Use finally Block than finalize()because we can't
Expect Exact Behavior of Garbage Collector. It is JVM Vendor Dependent.
286 https://www.youtube.com/durgasoftware
OCJA
Case 1: If there is No Exception. 1, 2, 3, 5 and 6 Normal Termination.
287 https://www.youtube.com/durgasoftware
OCJA
Case 4: If an Exception raised at Statement 5 and Corresponding Inner catch Block has
Matched 1, 2, 3, 4, 7, 8, 9, 11, 12 Normal Termination.
Case 5: If an Exception raised at Statement 5 and Inner catch Block has Not Matched
but Outer catch Block has Matched. 1, 2, 3, 4, 8, 10, 11, and 12 Normal Termination.
Case 6: If an Exception raised at Statement 5 and Both Inner and Outer catch Blocks
are Not Matched then 1, 2, 3, 4, 8, and 11 Abnormal Termination.
Case 10: If an Exception raised at Statement 8 and Corresponding catch Block Not
Matched 1, 2, 3,.,.,.,., 11 Abnormal Termination.
Case 11: If an Exception raised at Statement 9 and Corresponding catch Block Matched
1, 2, 3,.,.,.,., 8, 10, 11, and 12 Normal Termination.
Case 12: If an Exception raised at Statement 9 and Corresponding catch Block Not
Matched 1, 2, 3,.,.,.,.,8, and 11 Abnormal Termination.
Note:
We can Take try – catch – finally Inside try Block i.e. Nesting of try – catch – finally
is Always Possible.
More Specific Exceptions can be handled by Inner catch Block and Generalized
Exceptions are handled by Outer catch Blocks.
288 https://www.youtube.com/durgasoftware
OCJA
Once we entered into the try Block without executing finally Block the Control
Never Comes Up.
If we are Not entering into the try Block then finally Block won’t be executed.
class Test {
public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) { 1) CE
System.out.println(10/0); 2) RE: ArihmeticException
} 3) RE: NullPointerException
finally { 4) RE: ArihmeticException and RE: NullPointerException
String s = null;
System.out.println(s.length());
}
}
}
Note: Default Exception Handler can Handle Only One Exception at a Time i.e. the
Most Recently raised Exception.
try {}
catch (X e) {}
try {}
catch (X e) {}
catch (Y e) {}
try {}
catch (X e) {}
catch (X e) {} // CE: exception ArithmeticException has already been caught
289 https://www.youtube.com/durgasoftware
OCJA
try {}
finally {}
try {}
catch (X e) {}
System.out.println("Hello");
catch (Y e) {} //CE: 'catch' without 'try'
try {}
catch (X e) {}
System.out.println("Hello");
finally {} //CE: 'finally' without 'try'
try {}
finally {}
catch (X e) {} //CE: 'catch' without 'try'
try {}
catch (X e) {}
try {}
finally {}
try {}
catch (X e) {}
finally {}
finally {} //CE: 'finally' without 'try'
try {}
catch (X e) {
try {}
catch (Y e1) {}
}
try {}
catch (X e) {}
finally {
try {}
catch (Y e1) {}
290 https://www.youtube.com/durgasoftware
finally {}
}
OCJA
try {
try {} //CE: 'try' without 'catch', 'finally' or resource declarations
}
catch (X e) {}
try {}
catch (X e) //CE:'{' expected
System.out.println("Hello");
try {}
catch (NullPointerException e1) {}
finally //CE: '{' expected
System.out.println("Hello");
throw Keyword:
Sometimes we can Create Exception Object Explicitly and we can Handover Our
Created Exception Object to the JVM Manually. For this we have to Use throw key
Word.
Eg:
throw new ArithmeticException("/by zero");
In General we can Use throw Key Word for Customized Exceptions but Not for
pre-defined Exceptions.
class Test {
public static void main(String[] args) {
System.out.println(10/0);
Case – 1 }
}
291 https://www.youtube.com/durgasoftware
OCJA
class Test1 {
public static void main(String[] args) {
throw new ArithmeticException("/ by zero Explicitly");
}
}
Case – 2
//Exception in thread "main" java.lang.ArithmeticException: / by zero Explicitly
In the Case – 1 main() is Responsible to Create Exception Object and Handover to the JVM.
This Total Activity will be performed Internally.
In the Case – 2 Programmer creating Exception Object Explicitly and Handover to the JVM
Manually.
Hence the Main Purpose of throw Key Word is to Handover Our Created Exception Object
to the JVM Manually.
Case 1: throw e;
If ‘e’ Refers ‘null’ then we will get NullPointerException.
class Test {
static ArithmeticException e = new ArithmeticException();
public static void main(String[] args) {
throw e;
}
}
class Test {
static ArithmeticException e;
public static void main(String[] args) {
throw e;
}
}
292 https://www.youtube.com/durgasoftware
OCJA
Case 2: After throw Statement we are Not allowed to write any Statements Directly
Otherwise we will get Compile Time Error Saying unreachable statement.
class Test {
public static void main(String[] args) {
System.out.println(10/0);
System.out.println("Hello");
}
}
class Test {
public static void main(String[] args) {
throw new ArithmeticException("/by zero");
System.out.println("Hello"); //CE: unreachable statement
}
}
Case 3: We can Use throw Key Word Only for Throwable Types. Otherwise we will get
Compile Time Error Saying incompatible types.
In Our Program if there is any Chance of raising Checked Exception then Compulsory
we should Handled that Checked Exception Otherwise we will get Compile Time Error
Saying unreported exception XXX; must be caught or declared to be thrown.
293 https://www.youtube.com/durgasoftware
OCJA
We can Handle this Compile Time Error in 2 Ways.
1) By Using try-catch
2) By Using throws Key Word
class Test {
public static void main(String args[]) {
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {}
}
}
class Test {
public static void main(String[] args)throws InterruptedException {
Thread.sleep(5000);
}
}
Conclusions:
1) We can Use to Delegate the Responsibility of Exception
Handling to the Caller.
294 https://www.youtube.com/durgasoftware
OCJA
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);
}
}
In the Above Program if we Remove at-least One throws Statement then the Code
won't Compile. We will get CE: unreported exception InterruptedException; must be
caught or declared to be thrown
Case 1: We can Use throws Key Word Only for Methods and Constructors but Not for
Classes.
Case 2:
We can Use throws Key Word Only for Throwable Types but Not for Normal Java
Classes. Otherwise we will get Compile Time Error Saying
incompatible types
required: java.lang.Throwable class Test {
found: Test public static void main(String[] args) throws Test {}
}
class Test {
public static void main(String[] args) {
try {
System.out.println("Hello");
}
catch (Error e) {}
}
} Unchecked Exception
Output: Hello
296 https://www.youtube.com/durgasoftware
OCJA
Summary of Exception Handling Key Words
4) unreachable statement
5) incompatible types
required: java.lang.Throwable
found: Test
6) try without catch or finally
297 https://www.youtube.com/durgasoftware
OCJA
java CustExceptionDemo 70
Exception in thread "main" TooYoungException: Please Wait Some More Time U will get Best
Match
at CustExceptionDemo.main(CustExceptionDemo.java:15)
java CustExceptionDemo 50
U will get Match Details Soon by Email...!
java CustExceptionDemo 15
Exception in thread "main" TooOldException: Your Age Already Crossed Marriage Age No Chance
of getting Match
at CustExceptionDemo.main(CustExceptionDemo.java:18)
298 https://www.youtube.com/durgasoftware
OCJA
Note:
☀ throw Key Word is Best Suitable for Customized Exceptions but Not for Pre-defined
Exceptions.
☀ It is Highly Recommended to define Customized Exceptions as Unchecked i.e. we
have to extends RuntimeException but Not Exception.
☀ To Make Description Available to Parent Class, from which Default Exception
Handler get these Description.
Top 10 Exceptions
Based on the Person who is raising Exception, all Exceptions are divided into 2 Types.
1) JVM Exceptions
2) Programmatic Exceptions.
JVM Exceptions: The Exceptions which are raised Automatically by the JVM whenever
a Particular Event Occurs Such Type of Exceptions are Called JVM Exceptions.
Eg: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException Etc.
Programmatic Exceptions:
The Exceptions which are raised Explicitly either by Programmer OR by API Developer
are Called Programmatic Exceptions.
Eg: IllegalArgumentException, TooYoungException, Etc.
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.
Eg:
int[] a = new int[10];
System.out.println(a[0]); //0
System.out.println(a[100]); //RE: java.lang.ArrayIndexOutOfBoundsException: 100
System.out.println(a[-100]); //RE: java.lang.ArrayIndexOutOfBoundsException: -100
NullPointerException:
It is the Child Class of RuntimeException and Hence it is Unchecked.
Raised Automatically by the JVM whenever we are trying to Perform any Method
Call on null Reference.
StackOverFlowError:
It is the Child Class of Error and Hence it is Unchecked.
Raised Automatically by the JVM whenever we are trying to Perform Recursive Method
Call.
299 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void m1() {
m2(); Recursive Method Call
::
}
::
public static void m2() {
::
m1();
::
m2()
}
::
m1()
public static void main(String[] args) {
::
main(
m1(); //RE: java.lang.StackOverflowError
} ) :: Stack
Runtime
::
}
::
::
::
ClassCastException: ::
It is the Child Class of RuntimeException and Hence it is Unchecked.
Raised Automatically by the JVM whenever we are trying to Type Cast Parent
Object to Child Type.
Eg:
String s = new String("abc");
Object o = (Object)s; //√
NoClassDefFoundError:
It is the Child Class of Error and Hence it is Unchecked.
Raised Automatically by the JVM whenever JVM Unable to find required .class File.
Eg: java Test
If Test.class is Not Available then we will get RuntimeException Saying
java.lang.NoClassDefFoundError: Test
ExceptionInInitializerError:
It is the Child Class of Error and Hence it is Unchecked.
Raised Automatically by the JVM if any Exception Occurs while executing Static
Variable Assignments and Static Blocks.
class Test {
static int i = 10/0; RE: Exception in thread "main" java.lang.ExceptionInInitializerError
} Caused by: java.lang.ArithmeticException: / by zero
300 https://www.youtube.com/durgasoftware
OCJA
class Test {
static {
Exception in thread "main"
String s = null;
java.lang.ExceptionInInitializerError
System.out.println(s.length());
Caused by: java.lang.NullPointerException
}
}
IllegalArgumentException:
It is the Child Class of RuntimeException and Hence it is Unchecked.
Raised Explecitly by the Programmer OR by API Developer to Indicate that a Method
has been invoked with Illegal Argument.
class Test {
public static void main(String[] args) {
Thread t = new Thread();
t.setPriority(10); √
t.setPriority(100); RE: Exception in thread "main" java.lang.IllegalArgumentException
} at java.lang.Thread.setPriority(Thread.java:1125)
} at Test.main(Test.java:5)
The Valid Range of Thread Priorities is 1 to 10. If we are trying to Set the Priourity
with any Other Value we will get Runtime Exception Saying
IllegalArgumentException.
NumberFormatException:
It is the Direct Child Class of IllegalArgumentException, which is Child Class of
RuntimeException and Hence it is Unchecked.
Raised Explecitly either by Programme OR by API Developer to Indicate that we are
trying to Convert String to Number but the String is Not Properly Formatted.
IllegalStateException:
It is the Child Class of RuntimeException and Hence it is Unchecked.
Raised Explecitly either by Programmer OR by API Developer to Indicate that a
Method has been invoked at Wrong Time.
Examples:
1) After Starting a Thread we are Not allowed to Re- Start the Same Thread Once
Again. Otherwise we will get Runtime Exception Saying IllegalThreadStateException.
Thread t = new Thread();
t.start();
t.start(); //RE: java.lang.IllegalThreadStateException
301 https://www.youtube.com/durgasoftware
OCJA
2) Once Session Expires we are Not allow to Call any Method on that Session Object. If
we are trying to Call we will get Runtime Exception Saying IllegalStateException.
AssertionError:
It is the Child Class of Error and Hence it is Unchecked.
Raised Explecitly to Indicate that assert Statement Fails.
Eg: assert(x > 10);
if(x !> 10) then we will get Runtime Exception Saying AssertionError.
1) ArrayIndexOutOfBoundsException
2) NullPointerException
3) StackOverflowError
Raised by JVM and Hence
4) ClassCastException these are JVM Exceptions
5) NoClassDefFoundError
6) ExceptionInInitializerError
7) IllegalArgumentException
Raised by Explicitly either by
8) NumberFormatException Programmer OR by API
Developer and Hence they are
9) IllegalStateException Programmatic Exceptions
10) AssertionError
302 https://www.youtube.com/durgasoftware
OCJA
1.7 Version Enhancements
In 1.7 Version as the Part of Exception Handling the following 2 Concepts Introduced.
try with Resources
Multi catch Block
try with Resources: Until 1.6 Version it is Highly Recommended to write finally Block
to Close All Resources which are Opened as the Part of try Block.
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Input.txt");
//Use br based on Our Requirement
}
catch (InterruptedException e) {
//Handling Code
}
finally {
if (br != null) {
br.close();
}
}
To Overcome these Problems SUN People Introduce try with Resources in 1.7 Version.
try (BufferedReader br = new FileReader("Input.txt")) { Resource
//Use br based on Our Requirements. br will be Closed Automatically Once the Control
Reaches End of try either Normally OR Abnormally
}
catch (InterruptedException e) {}
The Main Advantage of try with Resources is the Resources which are Opened as
the Part of try Block will be Closed Automatically and we are Not required to Close
Explicitly. It Reduces Complexity of the Programming.
It is Not required to write finally Block Explicitly and Hence Length of the Code will
be Reduced and Readability will be Improved.
303 https://www.youtube.com/durgasoftware
OCJA
Conclusions:
We can Declare Multiple Reasons and All these Resources should be Separated with
‘;’.
Syntax: try (R1; R2; R3) {
------------------
}
Eg: try ( FileWriter fw = new FileWriter("Output.txt");
FileWriter fw = new FileWriter("Input.txt"); ) {
--------------
}
This Interface introduced in 1.7 Version and it contains Only One Method
public void close();
import java.io.*;
class TryWithResources {
public static void main (String args[]) throws Exception {
try (BufferedReader br = new BufferedReader (new FileReader ("abc.txt"))) {
br = new BufferedReader (new FileReader ("Input.txt"));
}
} //CE: auto-closeable resource br may not be assigned
}
Until 1.6 Version try should be followed by either catch OR finally but from 1.7
onwards we can Take Only try with Resources without catch and finally Blocks.
Eg: try (R) {-----------}
The Main Advantage of try with Resources is finally Block will become Dummy
because we are required to Close the Resources Explicitly.
304 https://www.youtube.com/durgasoftware
OCJA
Until 1.6 Version even though Multiple Exceptions having Same Handling Code
Compulsory we have to write a Separate catch Block for Every Exception.
try {
-------
}
catch (ArithmeticException e) {
e.printStackTrace();
}
catch (NullPointerException e) {
e.printStackTrace();
}
catch (ClassCastException e) {
System.out.println(e.getMessage());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
The Problem in this Approach is it Increases Length of the Code and Reduces
Readability.
To Overcome this Problem SUN People Introduced Multi Catch Block in 1.7 Version.
In this Approach we can write a Single Catch Block which can Handle Multiple
Exceptions of different Types.
try {
-------
}
catch (ArithmeticException | NullPointerException e) {
e.printStackTrace();
}
catch (ClassCastException | IOException e) {
System.out.println(e.getMessage());
}
class MultiCatchBlock {
public static void main(String[] args) {
try {
//System.out.println(10/ 0);
String s = null;
System.out.println(s.length());
}
catch (ArithmeticException | NullPointerException e) {
System.out.println(e); //java.lang.NullPointerException
}
305} https://www.youtube.com/durgasoftware
}
OCJA
If Mutli Catch Block there should Not be any Relation between Exception Types
(Like Parent to Child OR Child to Parent OR Same Type) Otherwise we will get
Compile Time Error.
Exception Propagation:
☀ Within a Method if an Exception raised and if we are Not Handle that Exception
then that Exception Object will be propagated to Automatically to the Caller
Method.
☀ Then Caller Method is Responsible to Handle that Exception.
☀ This Process is Called Exception Propagation.
Exception Propagation
m1() { m2() {
m2() Exception
} }
Re-Throwing Exception
We can Use this Approach to Convert One Exception Type to Another Exception Type.
try {
System.out.println(10/ 0);
}
catch (ArithmeticException e) {
throw new NullPointerException();
}
306 https://www.youtube.com/durgasoftware
OCJA
Q1. Given the code fragment:
1) class X
2) {
3) public void printFileContent()
4) {
5) //Line-1
6) throw new IOException();//Line-2
7) }
8) }
9) public class Test
10) {
11) public static void main(String[] args)//Line-3
12) {
13) X x= new X();
14) x.printFileContent();//Line-4
15) //Line-5
16) }
17) }
A. Replace Line-3 with public static void main(String[] args) throws Exception
B. Replace Line-4 with:
1) try
2) {
3) x.printFileContent();
4) }
5) catch (Exception e){}
6) catch (IOException e){}
C. Replace Line-3 with public static void main(String[] args) throws IOException
D. Replace Line-2 with throw IOException("Exception Raised");
E. At Line-5 insert throw new IOException();
Answer: A, C
307 https://www.youtube.com/durgasoftware
OCJA
7) void checkCard(int cno) throws RuntimeException//Line-1
8) {
9) System.out.println("Checking Card");
10) }
11) public static void main(String[] args)
12) {
13) Test t = new Test();
14) int cardNo=1234;
15) t.checkCard(cardNo);//Line-2
16) t.readCard(cardNo);//Line-3
17) }
18) }
A. Checking Card
Reading Card
Answer: D
Q3. Given the following code for the classes MyException and Test:
308 https://www.youtube.com/durgasoftware
OCJA
20) try
21) {
22) throw Math.random() > 0.5 ? new Exception():new MyException();
23) }
24) catch (RuntimeException e)
25) {
26) System.out.println("B");
27) }
28) }
29) }
Answer: E
A. element 0
element 1
B. null element 0
null element 1
C. null
null
D. A NullPointerException is thrown at runtime
Answer: D
309 https://www.youtube.com/durgasoftware
OCJA
Q5. Given the code fragment:
A.
Invalid Name
omas
null
null
B.
Invalid Name
C.
Invalid Name
omas
D.
Compilation Fails
310 https://www.youtube.com/durgasoftware
OCJA
Answer: A
1) import java.util.*;
2) public class Test
3) {
4) public static void main(String[] args)
5) {
6) ArrayList l = new ArrayList();
7) String[] s;
8) try
9) {
10) while(true)
11) {
12) l.add("MyString");
13) }
14) }
15) catch (RuntimeException e)
16) {
17) System.out.println("Caught a RuntimeException");
18) }
19) catch (Exception e)
20) {
21) System.out.println("Caught an Exception");
22) }
23) System.out.println("Ready to use");
24) }
25) }
Answer: C
A. Improves the program structure because the error handing code is separated from the normal
program function.
311 https://www.youtube.com/durgasoftware
OCJA
C. Improves the program structure beacuase the programmer can choose where to handle
exceptions
D. Imporves the program structure because exceptions must be handled in the method in which
they occurred.
E. Allows the creation of new exceptions that are tailored to the particular program being created.
Answer:A,C,E
Answer: B,C,E
Ans: B,E
312 https://www.youtube.com/durgasoftware
OCJA
FAQ’s
1) What is An Exception?
8) If try With Multiple catch Block Present, Is Order of catch Blocks Important in
Which Order We Have To Take?
10) If An Exception Raised Inside catch Block Then What Will Happen?
17) If Return Statement Present Inside try, is Finally Block Will Be Executed?
18) What is The Difference Between final, finally And finalize ()?
313 https://www.youtube.com/durgasoftware
OCJA
24) Is it Possible To throw Any Java Object?
30) If We Are Taking catch Block For An Exception But There is No Chance of Rising
That Exception in try Then What Will Happen?
32) Which Class Act As Root For Entire Java Exception Hierarchy?
35) What is Difference Between Partially Checked And Fully Checked Exception?
39) Can You Give The Most Common Occurred Exception in Your Previous Project?
40) Explain The Cases Where You Used Exception Handling in Your Previous
Project?
314 https://www.youtube.com/durgasoftware
OCJA
1) Introduction
2) Object Class
3) String Class
4) StringBuffer Class
5) StringBuilder Class
315 https://www.youtube.com/durgasoftware
OCJA
Introduction
Object Class
Methods
1) public String toString()
2) public int hashCode()
toString() Vs hashCode()
3) public boolean equals(Object obj)
Relationship between ‘==’ Operator and .equals()
Difference between == Operator and .equals()
What is the Main Difference between == Operator and .equals()?
Contract between .equals() and hashCode()
4) protected Object clone() throws CloneNotSupportedException
Shallow Cloning Vs Deep Cloning
5) protected void finalize() throws Throwable
String Class
Interning of String Objects
Importance of SCP
Why SCP Concept is Available Only for String Object but Not for StringBuffer?
Why String Objects are Immutable where as StringBuffer Objects are Mutable?
String Class Constructors
String Class Methods
Creation of Our Own Immutable Class
final Vs Immutability
StringBuffer Class
Constructors
Methods
StringBuilder Class
316 https://www.youtube.com/durgasoftware
Method Chaining
OCJA
Introduction
For writing any Java Program whether it is Simple OR Complex, the Most Commonly
required Classes and Interfaces are defined in Separate Package which is nothing
but java.lang Package.
We are Not required to Import java.lang Package Explicitly because by Default it is
Available to Every Java Program.
Object Class
Every Class in a Java is the Child Class of the Object Class Either Directly OR
Indirectly.
So that Object Class Methods by Default Available to Every Java Class.
Hence Object Class Acts as Root for All Java Classes.
Note:
If our Class won’t extends any Other Class then Only it is the Direct Child Class of
Object.
class A Object
{
}
A
If our Class extends any Other Class then it is In - Direct Child Class of Object.
Multi-Level
B
A
Multiple
Inheritance Inheritance
A
Methods:
The toString():
class Student {
String name;
s1 Durga
int rollno;
101
Student(String name, int rollno) {
this.name = name;
this.rollno = rollno; s2 Ravi
} 102
In the Above Example Object Class toString() got executed which is implemented as
follows
public String toString() {
return getClass().getName() + “@” + Integer.toHexString(hashCode());
}
i.e. ClassName@Hexa_Decimal_String_of_hashcode
318 https://www.youtube.com/durgasoftware
OCJA
To Provide Our Own String Representation we have to Override toString().
For Example whenever we are trying to Print Student Reference to Print his Name
and RollNo we can Override toString() as follows.
import java.util.*;
class Test {
public String toString() {
return "Test";
}
public static void main(String[] args) {
l.add("A");
l.add("B");
System.out.println(s); //Durga
System.out.println(i); //10
System.out.println(l); //[A, B]
System.out.println(m); //{A=101}
System.out.println(t); //Test
}
}
319 https://www.youtube.com/durgasoftware
OCJA
The hashCode():
For Every Object JVM will generate a Unique Number which is nothing but Hash
Code.
JVM will use Hash Code while Saving Objects into Hashing related Data Structures
Like HashSet, Hashtable, HashMap Etc.
The Main Advantage of saving Objects based on Hash Code is Search Operation will
become Easy.
The Most Powerful Search Algorithm up Today is Hashing.
If we are Not Overriding hashCode() then Object Class hashCode() will be executed.
Which generates hashCode based on Address of an Object. It doesn’t Mean Hash
Code Represents Address of the Object (It is Impossible to find Address of an Object
in Java).
Based on our Requirement we can Override hashCode() then it is No Longer related
to Address.
Overriding hashCode() is Said to be Proper Way if and Only if for Every Object we
have to Generate a Unique Number as hashCode.
It is Improper Way of Overriding hashCode() because for all Objects we are
generating Same Number as Hash Code.
It is Proper Way of Overriding hashCode() because we are generating a Unique
Number as Hash Code.
toString() Vs hashCode()
If we are giving the Chance to Object Class toString() then it will Call Internally
hashCode().
But whenever we are Overriding toString() Call hashCode().
class Test {
int i;
Test(int i) {
this.i = i;
} Object toString()
public static void main(String[] args) {
Test t1 = new Test(10); Object hashCode()
Test t2 = new Test(100);
System.out.println(t1); //Test@6e3d60
System.out.println(t2); //Test@17fa65e
}
}
320 https://www.youtube.com/durgasoftware
OCJA
class Test {
int i;
Test(int i) { this.i = i; }
public int hashCode() { return i; }
Object toString()
public static void main(String[] args) {
Test t1 = new Test(10);
Test t2 = new Test(100); Test t hashCode()
System.out.println(t1); //Test@a
System.out.println(t2); //Test@64
}
}
class Test {
int i;
Test(int i) { this.i = i; }
public int hashCode() { return i; }
public String toString() { return i + ""; }
Test t toString()
public static void main(String[] args) {
Test t1 = new Test(10);
Test t2 = new Test(100);
System.out.println(t1); //10
System.out.println(t2); //100
}
Note: The Above 3 Programs Shows Link between toString() and hashCode().
The equals():
321 https://www.youtube.com/durgasoftware
OCJA
class Student {
String name;
int rollno; s1 name: Durga
rollno: 101
Student(String name, int rollno) { s4
this.name = name;
this.rollno = rollno; name: Ravi
} s2 rollno: 10
In the Above Example Object Class equals() got executed which is meant for
Reference Comparison.
Based on our Requirement we can Override equals() in our Class for Content
Comparison.
The following is the Valid Way of Overriding equals() for Content Comparison in
Student Class.
If 2 Students having the Same Name and Same rollno our equals() should Return
true.
322 https://www.youtube.com/durgasoftware
OCJA
class Student {
String name;
int rollno;
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equals(s3)); //true
System.out.println(s1.equals(s4)); //true
System.out.println(s1.equals("Durga")); //false
System.out.println(s1.equals(null)); //false
}
323 https://www.youtube.com/durgasoftware
OCJA
Simplified Version of equals()
Note: To Make Our equals() More Efficient we have to Take the following Code at the
beginning of equals().
if (obj == this)
return true;
i.e if 2 References pointing to the Same Object then our equals() should Return true
without performing any Comaprision.
Eg: String s1 = new String(“Durga”);
String s2 = new String(“Durga”);
System.out.println(s1.equals(s2)); //true
System.out.println(sb1.equals(sb2)); //false
System.out.println(s1.equals(sb1)); //false
324 https://www.youtube.com/durgasoftware
OCJA
If String Class equals() is Overridden for Content Comparison but in StringBuffer
Class equals() is not Overridden for Content Comparison Hence Object Class
equals() will be executed which is meant for Reference Comparison.
Note: In All Wrapper Classes, in All Collection Classes, in String Class equals() is
Overridden for Content Comparison. Hence it is Highly Recommended to Override
equals() in our Class Also.
325 https://www.youtube.com/durgasoftware
OCJA
Contract between .equals() and hashCode()
2 Equivalent Objects should be placed in the Same Bucket but all Objects Present in
the Same Bucket Need not be Equal.
Eg: In String Class equals() is Overridden for Content Comparison hence hashCode() is
also Overridden to generate Hash Code based on Content.
326 https://www.youtube.com/durgasoftware
OCJA
Which of the following hashCode() is Appropriate for Person Class?
Note: Based on which Parameters we Override equals() use the Same Parameters by
Overriding hashCode() also so that we can maintain Contract between equals() and
hashCode().
The clone():
Shallow Cloning
The Process of creating Bit Wise Copy of an Object is called Shallow Cloning.
If the Main Object contain any Primitive Variables exactly Duplicate Copy of
those Variables will be created in cloned Object.
If the Main Object contain any Referenced Variable then the Corresponding
Object won’t be Created Just Duplicate Reference Variable will be Created by
pointing to Old contained Object.
By using Main Object Reference if we Perform any Change to the contained
Object then those Changes will be reflected to the Cloned Object.
Object Class clone() by Default meant for Shallow Cloning.
327 https://www.youtube.com/durgasoftware
OCJA
class Cat {
int j; j = 20
Cat(int j) { this.j = j; } 999
}
class Dog implements Cloneable {
Cat c;
int i; c c
Dog(Cat c, int i) { i = 10 i = 10
this.c = c; 999
d1 d2
this.i = i;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class ShallowCloning {
public static void main(String[] args) throws CloneNotSupportedException {
Cat c = new Cat(20);
Dog d1 = new Dog(c, 10);
System.out.println(d1.i+"....."+d1.c.j); //10.....20
Dog d2 = (Dog)d1.clone();
d1.i = 888;
d1.c.j = 999;
System.out.println(d2.i+"....."+d2.c.j); //10.....999
}
}
Shallow Cloning is the Best Choice if the Object contains Only Primitive Values.
In Shallow Cloning by using Main Object Reference if we perform any Changes to
the contained Object then those Changes will be reflected to the cloned Copy.
To overcome this Problem we should go for Deep Cloning.
Deep Cloning:
328 https://www.youtube.com/durgasoftware
OCJA
class Cat {
int j; j = 20 j = 20
Cat(int j) { this.j = j; } 999
}
class Dog implements Cloneable {
Cat c; c c
int i; i = 10 i = 10
Dog(Cat c, int i) { 888
this.c = c;
this.i = i; d1 d2
}
public Object clone() throws CloneNotSupportedException {
Cat c1 = new Cat(c.j);
Dog d = new Dog(c1, i);
return d;
}
}
class DeepCloning {
public static void main(String[] args) throws CloneNotSupportedException {
Cat c = new Cat(20);
Dog d1 = new Dog(c, 10);
System.out.println(d1.i+"....."+d1.c.j); //10.....20
Dog d2 = (Dog)d1.clone();
d1.i = 888;
d1.c.j = 999;
System.out.println(d2.i+"....."+d2.c.j); //10.....20
}
}
If the Object contains Only Primitive Variables then Shallow Cloning is the Best
Choice.
If the Object contains Referenced Variables then Deep Cloning is the Best
Choice.
329 https://www.youtube.com/durgasoftware
OCJA
getClass():
finalize():
Just before destroying an Object Garbage Collector calls this Method for Clean-Up
Activities.
Once finalize() completes Automatically Garbage Collector destroys that Object.
wait(), notify() and notifyAll(): We can use all these Methods in Multi-Threading for
Inter Thread Communication.
330 https://www.youtube.com/durgasoftware
OCJA
String
Case 1
String s = new String(“Durga”); StringBuffer sb = new StringBuffer("Durga");
s.concat(“Software”); sb.append("Softwate");
System.out.println(s); //Durga System.out.println(sb); //DurgaSoftware
Once we created a String Object we can’t Once we created a StringBuffer Object we can
Perform any changes in the existing Object. If Perform any Type of changes in the existing Object.
we are trying to Perform any changes with This Changeable Nature is nothing but Mutability of
those changes a New Object will be created. StringBuffer Objects.
This non-changeable Nature is nothing but
Immutability. DurgaSoftware
Durga DurgaSoftware
sb
s Ready To Garbage Collection
Case 2
In String Class .equals() is Overridden for In StringBuffer Class .equals() is not Overridden for
Content Comparison Hence if the Content is Content Comparison Hence Object Class .equals() will
Same .equals() Returns True Even though be executed which is meant for Reference
Objects are Different. Comparison. Due to this if Objects are different
equals() Returns false Event though Content is Same.
s Durga
331 https://www.youtube.com/durgasoftware
OCJA
String s = “Ravi”;
In this Case only one Object will be created in the SCP and S is always refers to
that Object.
SCP
Durga
s
Note:
Garbage Collector is Not allowed to Access SCP Area Hence Even though Object Not
having the Reference Still it is Not Eligible for Garbage Collector if it is Present in SCP
Area.
At the Time of JVM Shutdown all SCP Objects will be destroyed automatically.
Object Creation in SCP is always Optional. First JVM will check is any Object already
Present in SCP with required Content if it is already Present then existing Object will
be re-used. If it is not already Present then only a New Object will be created.
Note:
Whenever we are using New Operator Compulsory a New Object will be created in
the Heap Area.
There may be a Chance of existing 2 Objects with Same Content on the Heap but
No Chance of existing 2 Objects with the Same Content in SCP Area i.e. Duplicate
Objects are Possible in Heap but there is No Chance of existing Duplicate Objects in
SCP.
Note:
For every String Constant one Object will be created on the SCP.
Because of Some Runtime Operation like Method Call if an Object is required to
create that Object will be created only in Heap but not in SCP.
332 https://www.youtube.com/durgasoftware
OCJA
class StringTest {
public static void main(String[] args) {
}
}
If the corresponding SCP Object is Not Available then intern() will Create that Object
in SCP and Returns it.
333 https://www.youtube.com/durgasoftware
OCJA
Importance of SCP:
Why SCP Concept is Available Only for String Object but Not for StringBuffer?
String Objects are Most Commonly used Objects in Java Hence SUN People provided
a Special Memory Management for the String Objects.
StringBuffer Objects are not commonly used Objects Hence SUN People won’t
provide any Special Memory Area for the StringBuffer Objects.
Why String Objects are Immutable where as StringBuffer Objects are Mutable?
In the Case of String Objects Just Because of SCP A Single Object can be referred
by Multiple References.
By using One Reference if we are allowed to Change the Content then remaining
References will be impacted. To overcome this Problem SUN People implemented
String Objects as Immutable.
According to this once we created a String Object we can’t perform any Changes in
the existing Object. If we are trying to Change with those Changes a New Object
will be created.
334 https://www.youtube.com/durgasoftware
OCJA
But in StringBuffer there is no Concept like SCP. Hence for every Requirement a
New Object will be created by using One Reference. If we are changing the Content
in existing Object there is No Effect on remaining References. Hence Immutability
Concept not required for StringBuffer Objects.
Note: SCP is the Only Reason why String Objects are Immutable.
2) String s = new String(String literal); Creates an Equivalent String Object for the
given String Literal.
3) String s = new String(StringBuffer sb); Creates an Equivalent String Object for the
given StringBuffer.
4) String s = new String(char [] ch); Creates an Equivalent String Object for the given
char[].
char[] ch = {‘a’, ’b’, ’c’, ’d’};
Eg: String s = new String(ch);
System.out.println(s); //abcd
5) String s = new String(byte[] b); Creates an Equivalent String Object for the given
byte[].
byte[] b = {100, 101, 102, 103, 104};
Eg: String s = new String(b);
System.out.println(s); //defgh
1) public char charAt(int index); Returns the char locating at specified Index.
String s = "Durga";
Eg: s = s.concat("Software");
//s = s+"Software"; OR s += "Software";
System.out.println(s); //DurgaSoftware
335 https://www.youtube.com/durgasoftware
OCJA
3) public boolean equals(Object o)
To Perform Content Comparison where Case is Important.
This is Overriding Version of Object Class equals().
Note: In General we can use equalsIgnoreCase() to Compare User Names where Case is
Not Important, whereas we can use equals() to Compare Passwords where Case is
Important.
Note: length is the Variable applicable for Array Objects where as length() is the
Method applicable for String Objects.
11) public String trim(); To Remove Blank Spaces Present at Starting and Ending of the
Sting. But not Middle Blank Spaces.
336 https://www.youtube.com/durgasoftware
OCJA
12) public int indexOf(char ch);
Returns the Index of First Occurance of specified Character.
Note:
Once We Created A String Object We Can't Perform Any Changes In The Existing
Object.
If We Are Trying To Perform Any Operation And If There Is A Change In The Content
With Those Changes A New Object Will Be Created.
With Our Operation If There Is No Change In The Content Then New Object Won't
Be Created Existing Object Will Be Reused. This Rule Is Same Whether The Object
Present In Heap Or SCP.
337 https://www.youtube.com/durgasoftware
OCJA
Creation of Our Own Immutable Class:
Once we created an Object we can’t perform any Changes in the existing Object.
If we are trying to perform any Changes with those Changes a New Object will be
created.
If there is No Change in the Content then New Object won’t be created and existing
Object will be reused.
Once we created a Test Object we can’t perform any Changes in the existing Object. If
we are trying to perform any Changes with those Changes a New Object will be
created. Hence Test Class Objects are Immutable.
final Vs Immutability:
final Keyword applicable for Variables but not for Objects whereas Immutability
Concept is applicable for Objects but not for Variables.
final and Immutability both are different Concepts.
By declaring a Reference Variable as final we won’t get any Immutability Nature
but we can’t perform re-assignment for that Reference Variable.
class Test {
public static void main(String[] args) {
final StringBuffer sb = new StringBuffer("Durga");
sb.append("Software");
System.out.println(sb); //true
sb = new StringBuffer("Solutions"); //CE: cannot assign a value to final variable sb
}
}
338 https://www.youtube.com/durgasoftware
OCJA
Note:
If the Content is Not Fixed and keep on changing then it is Never recommend to go
for String because for every Change a New Object will be created Internally.
To Handle this Requirement we should go for StringBuffer Class.
The Main Advantage of StringBuffer over String is all required Changes will be
performed in the existing Object only Instead of creating a New Object.
1) final variable √
2) final object
3) Immutable variable
4) Immutable object √
339 https://www.youtube.com/durgasoftware
OCJA
StringBuffer
Constructors:
Eg: sb.append("abcdefghijklmnop");
System.out.println(sb.capacity()); //16
sb.append("q");
System.out.println(sb.capacity()); //34
Once StringBuffer reaches Max Capacity then a New StringBuffer Object will be
created with new capacity = (currentcapacity + 1) * 2
Methods
340 https://www.youtube.com/durgasoftware
OCJA
5) public StringBuffer append(String s);
public StringBuffer append(int i);
public StringBuffer append(float f);
public StringBuffer append(double d); Overloaded Methods
public StringBuffer append(boolean b);
public StringBuffer append(Object o);
:::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::
341 https://www.youtube.com/durgasoftware
OCJA
11) public void ensureCapascty(int capacity);
To Increase Capacity on Fly based on our Requirement.
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); //16
sb.ensureCapacity(1000);
System.out.println(sb.capacity()); //1000
Note:
342 https://www.youtube.com/durgasoftware
OCJA
StringBuilder
StringBuffer StringBuilder
Every Method Present In Stringbuffer Is No Method Present In Stringbuilder Is
Synchronized. Synchronized.
At A Time Only One Thread Is Allow To At A Time Multiple Thread Are Allowed To
Operate On Stringbuffer Object And Operate On Stringbuilder Object And
Hence It Is Thread Safe. Hence It Is Not Thread Safe.
Threads Are Required To Wait To Operate Threads Are Not Required To Wait To
On Stringbuffer Object And Hence Operate On Stringbuilder Object And
Relatively Performance Is Slow. Hence Relatively Performance Is High.
Introduced In 1.0 Version. Introduced In 1.5 Version.
If the Content is Fixed and won’t changed frequently then we should go for String.
If the Content is Not Fixed and keep on changing but Thread Safety is required
then we should go for StringBuffer.
If the Content is Not Fixed and keep on changing but Thread Safety is Not required
then we should go for StringBuilder.
Method Chaining:
For most of the Methods in String, StringBuffer and StringBuilder the Return Types
are the Same Type (String, StringBuffer and StringBuilder Objects) only.
Hence After Applying a Method on the Result we can Call Another Method which
forms a Method Chaining. sb.m1().m2().m3().m4().m5()…..;
All these Method Calls will execute from Left to Right.
sb.append("Durga")
.append("Software") // DurgaSoftware
.append("Solutions") // DurgaSoftwareSolutions
.insert(2, "xyz") // DuxyzrgaSoftwareSolutions
. delete(7, 15) // DuxyzrgeSolutions
.reverse() // snoituloSegrzyxuD
.append("Hyd"); //snoituloSegrzyxuDHyd
System.out.println(sb); //snoituloSegrzyxuDHyd
343 https://www.youtube.com/durgasoftware
OCJA
Practice Questions for String and StringBuilder
Q1. Given the code fragment:
A. Match 1
B. Match 2
C. No Match
D. NullPointerException is thrown at runtime
Answer: B
Q2. Given:
344 https://www.youtube.com/durgasoftware
OCJA
11) }
12) }
A. ABCD
B. ACD
C. ABCC
D. ABD
E. ABDC
Answer: C
A. String str2=str1;
B. String str2=new String(str1);
C. String str2=sb1.toString();
D. String str2="Durga";
Answer: A
Q4. You are developing a banking module. You have developed a class named
ccMask that has a maskcc method.
Given the code fragment:
1) class CCMask
2) {
3) public static String maskCC(String creditCard)
4) {
5) String x="XXXX-XXXX-XXXX-";
6) //Line-1
7) }
8) public static void main(String[] args)
345 https://www.youtube.com/durgasoftware
OCJA
9) {
10) System.out.println(maskCC("1234-5678-9101-1121"));
11) }
12) }
You must ensure that maskCC method returns a String that hides all digits of the credit
card number except last four digits( and the hyphens that seperate each group of 4
digits)
Which two code fragments should you use at line 1, independently to achieve
the requirement?
B) return x+creditCard.substring(15,19);
Answer: B,C
A. true false
B. true true
C. false true
D. false false
Answer: D
346 https://www.youtube.com/durgasoftware
OCJA
Q6. Consider the following code:
A. String s3=s2;
if(s1==s3)
B. if(s1.equalsIgnoreCase(s2))
C. String s3=s2;
if(s1.equals(s3))
D. if(s1.toLowerCase()==s2.toLowerCase())
Answer: B
1) class MyString
2) {
3) String msg;
4) MyString(String msg)
5) {
6) this.msg=msg;
7) }
8) }
9) public class Test
10) {
11) public static void main(String[] args)
12) {
347 https://www.youtube.com/durgasoftware
OCJA
13) System.out.println("Hello "+ new StringBuilder("Java SE 8"));
14) System.out.println("Hello "+ new MyString("Java SE 8"));
15) }
16) }
A) Hello Java SE 8
Hello MyString@<hashcode>
B) Hello Java SE 8
Hello Java SE 8
C) Hello java.lang.StringBuilder@<hashcode>
Hello MyString@<hashcode>
D) Compilation Fails
Answer: A
Q8. Given:
A. 9
B. 8
C. 10
D. Compilation Fails
Answer: A
Q9. Which statement will empty the contents of a StringBuilder variable named sb?
A. sb.deleteAll();
B. sb.delete(0,sb.size());
C. sb.delete(0,sb.length());
D. sb.removeAll();
348 https://www.youtube.com/durgasoftware
OCJA
Answer: C
Q10. Given
Answer: C
349 https://www.youtube.com/durgasoftware
OCJA
Wrapper Classes
The Main Objectives of Wrapper Classes are:
To Wrap Primitives into Object Form. So that we can handle Primitives also Just
Like Objects.
To Define Several Utility Methods for the Primitives (Like converting Primitive to
the String Form).
Constructors:
If the String Argument is not representing Number then we will get RE:
NumberFormatException.
Eg: Integer I = new Integer("Ten");
//RE: java.lang.NumberFormatException: For input string: "Ten"
Float Class defines 3 Constructors with float, double and String Arguments.
Character Class contains only one Constructor with char Primitive as an Argument
Type.
Character ch = new Character(‘a’); √
Character ch = new Character(“a”);
Boolean Class contains 2 Constructors with boolean Primitive and String Arguments.
If we Pass boolean Primitive as an Argument the only allowed Values are true OR
false, Where Case and Content Both are Important.
System.out.println(X); //false
System.out.println(Y); //false
System.out.println(X.equals(Y)); //true
System.out.println(X == y); //false
Note:
In every Wrapper Class toString() is Overridden for Meaningful String
Representation.
In every Wrapper Class equals() is Overridden for Content Comparision.
Utility Methods
valueOf()
xxxValue()
parseXxx()
toString()
351 https://www.youtube.com/durgasoftware
OCJA
1) valueOf(): We can use valueOf() to Create Wrapper Object as Alternative to
Constructor.
Form 1: All the Wrapper Classes except Character Class contains a Static
valueOf() to Create Wrapper Object for the given String.
public static wrapper valueOf(String s);
Integer I = Integer.valueOf(‘10’);
Float F = Float.valueOf(“10.5”);
Boolean B = Boolean.valueOf(“Durga”);
Form 2: All Integral Wrapper Classes (Byte, Short, Integer, Long) Contains the
following valueOf() to Create Wrapper Object for the given specified Radix
String.
public static wrapper valueOf(String s, int radix);
Form 3: Every Wrapper Class including Character Class contains the following
valueOf() to Convert Primitive to Wrapper Object Form.
public static wrapper valueOf(primitive p);
Integer I = Integer.valueOf(10);
Character ch = Character.valueOf(‘a’);
Boolean B = Boolean.valueOf(true);
valueOf()
String/ Wrapper
Primitive √ Object
2) XxxValue():
We can use XxxValue() to find Primitive Value for the given Wrapper Object.
Every Number Type Wrapper Class [Byte, Short, Integer, Long, Float and
Double] contains the following XxxValue() to find Primitive Value for the given
Wrapper Object.
352 https://www.youtube.com/durgasoftware
OCJA
Examples
public byte byteValue(); Integer I = Integer.valueOf(130); OR Integer I = new Integer(130);
public short shortValue(); System.out.println(I.byteValue()); //-126
public int intValue(); System.out.println(I.shortValue()); //130
public long longValue(); System.out.println(I.intValue()); //130
public float floatValue(); System.out.println(I.longValue()); //130
public double doubleValue(); System.out.println(I.floatValue()); //130.0
System.out.println(I.doubleValue()); //130.0
charValue(): Character Class contains charValue() to find char Primitive for the given
kind of Character Object. public char charValue()
XxxValue()
Wrapper Primitive
√
Object Value
Form 1: Every Wrapper Class except Character Class contains the following
parseXxx() for converting String to Primitive Type.
public static primitive parseXxx(String s);
Form 2: Every Integral Type Wrapper Class contains the following parseXxx() to
Convert specified Radix String Form into Primitive.
public static primitive parseXxx(String s, int radix );
353 https://www.youtube.com/durgasoftware
OCJA
Eg: int i = Integer.parseInt("110", 2);
System.out.println(i); //6
parseXxx()
String Primitive
√
Value
4) toString();
Form 1:
All Wrapper Classes contains an Instance Method toString() for converting
Wrapper Object to String Type.
This is Overriding Method of Object Class toString().
Whenever we are trying to Print Wrapper Object Reference internally this
toString() will be Call. public String toString();
String s = I.toString();
System.out.println(s); //10
Form 2: Every Wrapper Class including Character Class defines the following
Static toString() for converting Primitive to String Representation.
public static String toString(primitive p);
String s = Integer.toString(10);
String s = Boolean.toString(true);
String s3 = Character.toString('a');
Form 3: Integer and Long Classes contains the following toString() to Convert
Primitive to specified Radix String Form.
public static String toString(primitive p, int radix );
354 https://www.youtube.com/durgasoftware
OCJA
Form 4: toXxxString()
Integer and Long Classes contains the following toXxxString() Methods to Return
specified Radix String Form.
String s = Integer.toBinaryString(10);
System.out.println(s); //1010
String s = Integer.toHexString(10);
System.out.println(s); //a
toString()
Wrapper String
Object √
String
parseXxx()
toString()
valueOf() toString()
XxxValue()
Wrapper
Primitive
Object
Value
valueOf()
355 https://www.youtube.com/durgasoftware
OCJA
Practice Questions for Wrapper Classes
Q1. Given the code fragment:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) Short s1=200;
6) Integer s2=400;
7) Long s3=(long)s1+s2;//Line-1
8) String s4=(String)(s3*s2);//Line-2
9) System.out.println("Sum is:"+s4);
10) }
11) }
Answer: C
A. true..false
B. true..null
C. Compilation Fails
D. NullPointerException is thrown at runtime
Answer: A
356 https://www.youtube.com/durgasoftware
OCJA
Q3. Given:
A. true..null
B. true..false
C. false..false
D. true..true
Answer: B
357 https://www.youtube.com/durgasoftware
OCJA
What is the result?
A) 123..true
123..true
B) 123..true
123..false
C) 123..false
123..true
D) Compilation Fails
Answer: A
358 https://www.youtube.com/durgasoftware
OCJA
Map
HashMap
Linked HashMap
WeakHashMap
IdentityHashMap
Hashtable
Properties
SortedMap
NavigableMap
TreeMap
1) Arrays are Fixed in Size that is Once we created an Array there is No Chance of
Increasing OR Decreasing Size based on Our Requirement. Hence to Use Arrays
Concept Compulsory we should Know the Size in Advance which May Not be
Possible Always.
2) Arrays can Hold Only Homogeneous Data Type Elements.
s[1]=new Customer();
CE: incompatible types
found: Costomer
required: Student
3) Arrays Concept is Not implemented based on Some Standard Data Structure Hence
Readymade Methods Support is Not Available. Hence for Every Requirement we
have to write the Code Explicitly which Increases Complexity of the Programming.
To Overcome Above Problems of Arrays we should go for Collections.
Advantages Of Collections:
360 https://www.youtube.com/durgasoftware
OCJA
Differences Between Arrays And Collections:
Arrays Collections
Arrays are Fixed in Size. Collections are Growable in Nature.
With Respect to Memory Arrays are Not With Respect to Memory Collections are
Recommended to Use. Recommended to Use.
With Respect to Performance Arrays are With Respect to Performance Collections are Not
Recommended to Use. Recommended to Use.
Arrays can Hold Only Homogeneous Data Collections can Hold Both Homogeneous and
Elements. Heterogeneous Elements.
Arrays can Hold Both Primitives and Collections can Hold Only Objects but Not
Objects. Primitives.
Arrays Concept is Not implemented based For every Collection class underlying Data
on Some Standard Data Structure. Hence Structure is Available Hence Readymade Method
Readymade Method Support is Not Support is Available for Every Requirement.
Available.
Collection:
It defines Several Classes and Interfaces which can be used to Represent a Group of
Objects as a Single Entity.
JAVA C++
Collection Container
Collection Frame Work Standard Template Library (STL)
1) Collection (I)
2) List (I)
3) Set (I)
4) SortedSet (I)
5) NavigableSet (I)
6) Queue (I)
7) Map (I)
8) SortedMap (I)
9) NavigableMap (I)
361 https://www.youtube.com/durgasoftware
OCJA
1) Collection (I):
If we want to Represent a Group of Individual Objects as a Single Entity then we
should go for Collections.
Collection Interface is considered as Root Interface of Collection Framework.
Collection Interface defines the Most Common Methods which are Applicable for
any Collection Object.
2) List (I):
It is the Child Interface of Collection.
If we want to Represent a Group of Individual Objects as a Single Entity where
Duplicates are allowed and Insertion Order Preserved. Then we should go for
List.
Collection (I)
(1.2 V)
List (I)
(1.2 V)
(1.0 V)
Note: In 1.2 Version onwards Vector and Stack Classes are re-engineered to
Implement List Interface.
3) Set (I):
It is the Child Interface of the Collection.
If we want to Represent a Group of Individual Objects as a Single Entity where
Duplicates are Not allowed and Insertion Order won't be Preserved. Then we
should go for Set Interface.
362 https://www.youtube.com/durgasoftware
OCJA
Collection (I)
(1.2 V)
Set (I)
(1.2 V)
HashSet (C)
(1.2 V)
LinkedHashSet (C)
(1.4 V)
4) SortedSet (I):
It is the Child Interface of Set.
If we want to Represent a Group of Individual Objects Without Duplicates
According to Some Sorting Order then we should go for SortedSet.
5) NavigableSet (I):
It is the Child Interface of SortedSet.
It defines Several Methods for Navigation Purposes.
Collection (I)
(1.2 V)
Set (I)
(1.2 V)
SortedSet (I)
(1.2 V)
NavigableSet (I)
(1.6 V)
TreeSet (C)
(1.2 V)
6) Queue (I):
It is the Child Interface of Collection.
If we want to Represent a Group of Individual Objects Prior to Processing then
we should go for Queue.
363 https://www.youtube.com/durgasoftware
OCJA
Eg: Before sending a Mail we have to Store All MailID’s in Some Data Structure and in
which Order we added MailID’s in the Same Order Only Mails should be delivered
(FIFO). For this Requirement Queue is Best Suitable.
Collection (I)
(1.2 V)
1.5 V
Queue (I)
PriorityBlockingQueue LinkedBlockingQueue
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 Key - Value Pairs then we should go for Map.
7) Map (I):
Map is Not Child Interface of Collection.
If we want to Represent a Group of Objects as Key - Value Pairs then we should
go for Map Interface.
Duplicate Keys are Not allowed but Values can be Duplicated.
8) SortedMap (I):
It is the Child Interface of Map.
If we want to Represent a Group of Objects as Key - Value Pairs according to
Some Sorting Order of Keys then we should go for SortedMap.
Sorting should be Based on Key but Not Based on Value.
364 https://www.youtube.com/durgasoftware
OCJA
9) NavigableMap (I):
It is the Child Interface of SortedMap.
It Defines Several Methods for Navigation Purposes.
Map (I)
(1.2 V)
SortedMap (I)
(1.2 V)
NavigableMap (I)
(1.6 V)
TreeMap (I)
(1.6 V)
365 https://www.youtube.com/durgasoftware
OCJA
Map (I)
(1.2 V) 1.0 V
Dictionary
(AC)
TreeMap (I)
(1.6 V)
1) Enumeration (I)
2) Iterator (I)
3) ListIterator (I)
1) Collection Interface:
Methods:
Collection Interface defines the Most Common Methods which are Applicable for
any Collection Objects.
The following is the List of the Methods Present Inside Collection Interface.
1) boolean add(Object o)
2) boolean addAll(Collection c)
3) boolean remove(Object o)
4) boolean removeAll(Collection c)
366 https://www.youtube.com/durgasoftware
OCJA
6) void clear()
7) boolean contains(Object o)
8) boolean containsAll(Collection c)
9) boolean isEmpty()
Note:
2) List:
5) Object set(int index, Object new): To Replace the Element Present at specified
Index with provided Object and Returns Old Object.
7) int lastIndexOf(Object o)
8) ListIterator listIterator();
367 https://www.youtube.com/durgasoftware
OCJA
2.1) ArrayList:
The Underlying Data Structure for ArrayList is Resizable Array OR Growable Array.
Duplicate Objects are allowed.
Insertion Order is Preserved.
Heterogeneous Objects are allowed (Except TreeSet and TreeMap
Everywhere Heterogeneous Objects are allowed).
null Insertion is Possible.
Constructors:
l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(l); //[A, 10, A, null]
l.remove(2);
System.out.println(l); //[A, 10, null]
l.add(2,"M");
l.add("N");
System.out.println(l); //[A, 10, M, null, N]
}
}
368 https://www.youtube.com/durgasoftware
OCJA
Usually we can Use Collections to Hold and Transfer Data (Objects) form One
Location to Another Location.
To Provide Support for this Requirement Every Collection Class Implements
Serializable and Cloneable Interfaces.
ArrayList and Vector Classes Implements RandomAccess Interface. So that we can
Access any Random Element with the Same Speed.
RandomAccess Interface Present in java.util Package and it doesn't contain any
Methods. Hence it is a Marker Interface.
Hence ArrayList is Best Suitable if Our Frequent Operation is Retrieval Operation.
ArrayList Vector
Every Method Present Inside ArrayList is Every Method Present in Vector is
Non – Synchronized. Synchronized.
At a Time Multiple Threads are allow to At a Time Only One Thread is allow to
Operate on ArrayList Simultaneously and Operate on Vector Object and Hence Vector
Hence ArrayList Object is Not Thread Safe. Object is Always Thread Safe.
Relatively Performance is High because Relatively Performance is Low because
Threads are Not required to Wait. Threads are required to Wait.
Introduced in 1.2 Version and it is Introduced in 1.0 Version and it is Legacy.
Non – Legacy.
By Default ArrayList Object is Non - Synchronized but we can get Synchronized Version
ArrayList Object by using the following Method of Collections Class.
369 https://www.youtube.com/durgasoftware
OCJA
Similarly we can get Synchronized Version of Set and Map Objects by using the
following Methods of Collection Class.
1) import java.util.*;
2) class Test
3) {
4) public static void main(String[] args)
5) {
6) List<String> l = new ArrayList<>();
7) l.add("Robb");
8) l.add("Bran");
9) l.add("Rick");
10) l.add("Bran");
11) if(l.remove("Bran"))
12) {
13) l.remove("Jon");
14) }
15) System.out.println(l);
16) }
17) }
Answer: A
370 https://www.youtube.com/durgasoftware
OCJA
Q2. Given the code fragment
1) import java.util.*;
2) class Test
3) {
4) public static void main(String[] args)
5) {
6) ArrayList l = new ArrayList();
7) String[] s;
8) try
9) {
10) while(true)
11) {
12) l.add("MyString");
13) }
14) }
15) catch (RuntimeException e)
16) {
17) System.out.println("RuntimeException caught");
18) }
19) catch (Exception e)
20) {
21) System.out.println("Exception caught");
22) }
23) System.out.println("Ready to use");
24) }
25) }
A.
RuntimeException caught
Ready to use
B.
Exception caught
Ready to use
C. Compilation Fails
D. A runtime error thrown in the thread main
Answer: D
Q3) Given:
1) import java.util.*;
2) class Patient {
3) String name;
4) public Patient(String name)
371 https://www.youtube.com/durgasoftware
OCJA
5) {
6) this.name=name;
7) }
8) }
9) class Test
10) {
11) public static void main(String[] args)
12) {
13) List l = new ArrayList();
14) Patient p = new Patient("Mike");
15) l.add(p);
16) //insert code here==>Line-1
17) if(f>=0)
18) {
19) System.out.println("Mike Found");
20) }
21) }
22) }
Which code inserted at Line-1 enable the code to print Mike Found.
A. int f=l.indexOf(p);
B. int f=l.indexOf(Patient("Mike"));
C. int f=l.indexOf(new Patient("Mike"));
D. Patient p1 = new Patient("Mike");
int f=l.indexOf(p1);
Answer: A
1) import java.util.*;
2) class Test
3) {
4) public static void main(String[] args)
5) {
6) ArrayList<Integer> l = new ArrayList<>();
7) l.add(1);
8) l.add(2);
9) l.add(3);
10) l.add(4);
11) l.add(null);
12) l.remove(2);
13) l.remove(null);
14) System.out.println(l);
15) }
16) }
372 https://www.youtube.com/durgasoftware
OCJA
What is the result?
A. [1, 2, 4]
B. NullPointerException is thrown at runtime
C. [1, 2, 4,null]
D. [1, 3, 4,null]
E. [1, 3, 4]
F. Compilation Fails
Answer: A
A.
ArrayList<Animal> l = new ArrayList<>();
l.add(new Tiger());
B.
ArrayList<Hunter> l = new ArrayList<>();
l.add(new Cat());
C.
ArrayList<Hunter> l = new ArrayList<>();
l.add(new Tiger());
D.
ArrayList<Tiger> l = new ArrayList<>();
l.add(new Cat());
E.
ArrayList<Animal> l = new ArrayList<>();
l.add(new Cat());
Answer: D
373 https://www.youtube.com/durgasoftware
OCJA
Java 10 - 2018
374 https://www.youtube.com/durgasoftware
OCJA
☀ The Main Objective of Lambda Expression is to bring benefits of functional programming into
Java.
Ex: 1
() {
public void m1() { sop(“hello”);
sop(“hello”); }
} () { sop(“hello”); }
() sop(“hello”);
Ex:2
If the type of the parameter can be decided by compiler automatically based on the context
then we can remove types also.
The above Lambda expression we can rewrite as (a,b) sop (a+b);
375 https://www.youtube.com/durgasoftware
OCJA
Ex: 3
Conclusions:
Ex:
() sop(“hello”);
(int a ) sop(a);
(inta, int b) return a+b;
2) Usually we can specify type of parameter. If the compiler expects the type based on the
context then we can remove type. i.e., programmer is not required.
Ex:
(inta, int b) sop(a+b);
(a,b) sop(a+b);
3) If multiple parameters present then these parameters should be separated with comma (,).
4) If zero number of parameters available then we have to use empty parameter [ like ()].
Ex: () sop(“hello”);
5) If only one parameter is available and if the compiler can expect the type then we can remove
the type and parenthesis also.
Ex:
(int a) sop(a);
(a) sop(a);
A sop(a);
6) Similar to method body lambda expression body also can contain multiple statements. If more
than one statements present then we have to enclose inside within curly braces. If one
statement present then curly braces are optional.
376 https://www.youtube.com/durgasoftware
OCJA
7) Once we write lambda expression we can call that expression just like a method, for this
functional interfaces are required.
Functional Interfaces
If an interface contain only one abstract method, such type of interfaces are called functional
interfaces and the method is called functional method or single abstract method (SAM).
Ex:
1) Runnable It contains only run() method
2) Comparable It contains only compareTo() method
3) ActionListener It contains only actionPerformed()
4) Callable It contains only call() method
Inside functional interface in addition to single Abstract method (SAM) we write any number of
default and static methods.
Ex:
1) interface Interf {
2) public abstract void m1();
3) default void m2() {
4) System.out.println (“hello”);
5) }
6) }
In Java 8, Sun Micro System introduced @Functional Interface annotation to specify that the
interface is Functional Interface.
Ex:
@Functional Interface
Interface Interf { This code compiles without any compilation errors.
public void m1();
}
Inside Functional Interface we can take only one abstract method, if we take more than one
abstract method then compiler raise an error message that is called we will get compilation error.
Ex:
@Functional Interface {
public void m1(); This code gives compilation error.
public void m2();
}
377 https://www.youtube.com/durgasoftware
OCJA
Inside Functional Interface we have to take exactly only one abstract method.If we are not
declaring that abstract method then compiler gives an error message.
Ex:
@Functional Interface {
interface Interface { compilation error
}
Ex:
1) @Functional Interface
2) interface A {
3) public void methodOne();
4) }
5) @Functional Interface
6) Interface B extends A {
7) }
In the child interface we can define exactly same parent interface abstract method.
Ex:
1) @Functional Interface
2) interface A {
3) public void methodOne();
4) }
5) @Functional Interface
6) interface B extends A { No Compile Time Error
7) public void methodOne();
8) }
In the child interface we can’t define any new abstract methods otherwise child interface won’t be
Functional Interface and if we are trying to use @Functional Interface annotation then compiler
gives an error message.
378 https://www.youtube.com/durgasoftware
OCJA
1) @Functional Interface {
2) interface A {
3) public void methodOne();
4) }
Compiletime Error
5) @Functional Interface
6) interface B extends A {
7) public void methodTwo();
8) }
Ex:
@Functional Interface
interface A {
public void methodOne(); No compile time error
}
interface B extends A {
public void methodTwo(); This’s Normal interface so that code compiles without
error
}
In the above example in both parent & child interface we can write any number of default
methods and there are no restrictions. Restrictions are applicable only for abstract methods.
1) interface Interf {
2) public void methodOne() {}
3) public class Demo implements Interface {
4) public void methodOne() {
5) System.out.println(“method one execution”);
6) }
7) public class Test {
8) public static void main(String[] args) {
9) Interfi = new Demo();
10) i.methodOne();
11) }
12) }
379 https://www.youtube.com/durgasoftware
OCJA
Above code With Lambda expression
1) interface Interf {
2) public void methodOne() {}
3) class Test {
4) public static void main(String[] args) {
5) Interfi = () System.out.println(“MethodOne Execution”);
6) i.methodOne();
7) }
8) }
1) interface Interf {
2) public void sum(inta, int b);
3) }
4) class Test {
5) public static void main(String[] args) {
6) Interfi = (a,b) System.out.println(“The Sum:” +(a+b));
7) i.sum(5,10);
8) }
9) }
380 https://www.youtube.com/durgasoftware
OCJA
Without Lambda Expressions
1) interface Interf {
2) publicint square(int x);
3) }
4) class Demo implements Interf {
5) public int square(int x) {
6) return x*x; OR (int x) x*x
7) }
8) }
9) class Test {
10) public static void main(String[] args) {
11) Interfi = new Demo();
12) System.out.println(“The Square of 7 is: “ +i.square(7));
13) }
14) }
1) interface Interf {
2) public int square(int x);
3) }
4) class Test {
5) public static void main(String[] args) {
6) Interfi = x x*x;
7) System.out.println(“The Square of 5 is:”+i.square(5));
8) }
9) }
381 https://www.youtube.com/durgasoftware
OCJA
16) }
17) }
1) class ThreadDemo {
2) public static void main(String[] args) {
3) Runnable r = () {
4) for(int i=0; i<10; i++) {
5) System.out.println(“Child Thread”);
6) }
7) };
8) Thread t = new Thread(r);
9) t.start();
10) for(i=0; i<10; i++) {
11) System.out.println(“Main Thread”);
12) }
13) }
14) }
1) class Test {
2) public static void main(String[] args) {
3) Thread t = new Thread(new Runnable() {
4) public void run() {
5) for(int i=0; i<10; i++) {
6) System.out.println("Child Thread");
7) }
8) }
9) });
10) t.start();
11) for(int i=0; i<10; i++)
12) System.out.println("Main thread");
13) }
14) }
382 https://www.youtube.com/durgasoftware
OCJA
With Lambda expression
1) class Test {
2) public static void main(String[] args) {
3) Thread t = new Thread(() {
4) for(int i=0; i<10; i++) {
5) System.out.println("Child Thread");
6) }
7) });
8) t.start();
9) for(int i=0; i<10; i++) {
10) System.out.println("Main Thread");
11) }
12) }
13) }
Note:
☀ Anonymous inner class can extend concrete class, can extend abstract class, can implement
interface with any number of methods but
☀ Lambda expression can implement an interface with only single abstract method (Functional
Interface).
☀ Hence if anonymous inner class implements Functional Interface in that particular case only
we can replace with lambda expressions. Hence wherever anonymous inner class concept is
there, it may not possible to replace with Lambda expressions.
☀ Anonymous inner class! = Lambda Expression
Ex:
383 https://www.youtube.com/durgasoftware
OCJA
Ex:
1) interface Interf {
2) public void m1();
3) }
4) class Test {
5) int x = 777;
6) public void m2() {
7) Interfi = () {
8) int x = 888;
9) System.out.println(x); 888
10) System.out.println(this.x); 777
11) };
12) i.m1();
13) }
14) public static void main(String[] args) {
15) Test t = new Test();
16) t.m2();
17) }
18) }
☀ From lambda expression we can access enclosing class variables and enclosing method
variables directly.
☀ The local variables referenced from lambda expression are implicitly final and hence we can’t
perform re-assignment for those local variables otherwise we get compile time error
Ex:
1) interface Interf {
2) public void m1();
3) }
4) class Test {
5) int x = 10;
6) public void m2() {
7) int y = 20;
8) Interfi = () {
9) System.out.println(x); 10
10) System.out.println(y); 20
11) x = 888;
12) y = 999; //CE
13) };
14) i.m1();
15) y = 777;
16) }
17) public static void main(String[] args) {
18) Test t = new Test();
384 https://www.youtube.com/durgasoftware
OCJA
19) t.m2();
20) }
21) }
385 https://www.youtube.com/durgasoftware
OCJA
Default Methods
☀ Until 1.7 version onwards inside interface we can take only public abstract methods and public
static final variables (every method present inside interface is always public and abstract
whether we are declaring or not).
☀ Every variable declared inside interface is always public static final whether we are declaring
or not.
☀ But from 1.8 version onwards in addition to these, we can declare default concrete methods
also inside interface, which are also known as defender methods.
☀ We can declare default method with the keyword “default” as follows
☀ Interface default methods are by-default available to all implementation classes. Based on
requirement implementation class can use these default methods directly or can override.
Ex:
1) interface Interf {
2) default void m1() {
3) System.out.println("Default Method");
4) }
5) }
6) class Test implements Interf {
7) public static void main(String[] args) {
8) Test t = new Test();
9) t.m1();
10) }
11) }
Note: We can’t override object class methods as default methods inside interface otherwise we
get compile time error.
386 https://www.youtube.com/durgasoftware
OCJA
Ex:
1) interface Interf {
2) default inthashCode() {
3) return 10;
4) }
5) }
CompileTimeError
Reason: Object class methods are by-default available to every Java class hence it’s not required
to bring through default methods.
1) Eg 1:
2) interface Left {
3) default void m1() {
4) System.out.println("Left Default Method");
5) }
6) }
7)
8) Eg 2:
9) interface Right {
10) default void m1() {
11) System.out.println("Right Default Method");
12) }
13) }
14)
15) Eg 3:
16) class Test implements Left, Right {}
387 https://www.youtube.com/durgasoftware
OCJA
How to override default method in the implementation class?
In the implementation class we can provide complete new implementation or we can call any
interface method as follows.
interfacename.super.m1();
Ex:
388 https://www.youtube.com/durgasoftware
OCJA
Static methods inside interface:
☀ From 1.8 version onwards in addition to default methods we can write static methods also
inside interface to define utility functions.
☀ Interface static methods by-default not available to the implementation classes hence by using
implementation class reference we can’t call interface static
☀ methods. We should call interface static methods by using interface name.
Ex:
1) interface Interf {
2) public static void sum(int a, int b) {
3) System.out.println("The Sum:"+(a+b));
4) }
5) }
6) class Test implements Interf {
7) public static void main(String[] args) {
8) Test t = new Test();
9) t.sum(10, 20); //CE
10) Test.sum(10, 20); //CE
11) Interf.sum(10, 20);
12) }
13) }
☀ As interface static methods by default not available to the implementation class, overriding
concept is not applicable.
☀ Based on our requirement we can define exactly same method in the implementation class,
it’s valid but not overriding.
Ex:1
1) interface Interf {
2) public static void m1() {}
3) }
4) class Test implements Interf {
5) public static void m1() {}
6) }
389 https://www.youtube.com/durgasoftware
OCJA
Ex:2
1) interface Interf {
2) public static void m1() {}
3) }
4) class Test implements Interf {
5) public void m1() {}
6) }
Ex3:
1) class P {
2) private void m1() {}
3) }
4) class C extends P {
5) public void m1() {}
6) }
From 1.8 version onwards we can write main() method inside interface and hence we can run
interface directly from the command prompt.
Ex:
1) interface Interf {
2) public static void main(String[] args) {
3) System.out.println("Interface Main Method");
4) }
5) }
390 https://www.youtube.com/durgasoftware
OCJA
Predicates
A predicate is a function with a single argument and returns boolean value.
To implement predicate functions in Java, Oracle people introduced Predicate interface in 1.8
version (i.e.,Predicate<T>).
Predicate interface present in Java.util.function package.
It’s a functional interface and it contains only one method i.e., test()
Ex:
interface Predicate<T> {
public boolean test(T t);
}
Ex:1 Write a predicate to check whether the given integer is greater than 10 or not.
Ex:
public boolean test(Integer I) {
if (I >10) {
return true;
}
else {
return false;
}
}
(Integer I) {
if(I > 10)
return true;
else
return false;
}
I (I>10);
391 https://www.youtube.com/durgasoftware
OCJA
System.out.println (p.test(100)); true
System.out.println (p.test(7)); false
Program:
1) import Java.util.function;
2) class Test {
3) public static void main(String[] args) {
4) predicate<Integer> p = I (i>10);
5) System.out.println(p.test(100));
6) System.out.println(p.test(7));
7) System.out.println(p.test(true)); //CE
8) }
9) }
# 1 Write a predicate to check the length of given string is greater than 3 or not.
Predicate<String> p = s (s.length() > 3);
System.out.println (p.test(“rvkb”)); true
System.out.println (p.test(“rk”)); false
#-2 write a predicate to check whether the given collection is empty or not.
Predicate<collection> p = c c.isEmpty();
Predicate joining
It’s possible to join predicates into a single predicate by using the following methods.
and()
or()
negate()
these are exactly same as logical AND ,OR complement operators
Ex:
1) import Java.util.function.*;
2) class test {
3) public static void main(string[] args) {
4) int[] x = {0, 5, 10, 15, 20, 25, 30};
5) predicate<integer> p1 = i->i>10;
6) predicate<integer> p2=i -> i%2==0;
7) System.out.println("The Numbers Greater Than 10:");
8) m1(p1, x);
9) System.out.println("The Even Numbers Are:");
10) m1(p2, x);
11) System.out.println("The Numbers Not Greater Than 10:");
12) m1(p1.negate(), x);
13) System.out.println("The Numbers Greater Than 10 And Even Are:―);
392 https://www.youtube.com/durgasoftware
OCJA
14) m1(p1.and(p2), x);
15) System.out.println("The Numbers Greater Than 10 OR Even:―);
16) m1(p1.or(p2), x);
17) }
18) public static void m1(predicate<integer>p, int[] x) {
19) for(int x1:x) {
20) if(p.test(x1))
21) System.out.println(x1);
22) }
23) }
24) }
393 https://www.youtube.com/durgasoftware
OCJA
Practice Questions on Lambda Expressions
Q1. Given the code fragment:
Person.java:
Test.java:
1) class Test
2) {
3) public static void checkAge(List<Person> list,Predicate<Person> predicate)
4) {
5) for (Person p: list)
6) {
7) if(predicate.test(p))
8) {
9) System.out.println(p.name+" ");
10) }
11) }
12) }
13) public static void main(String[] args)
14) {
15) List<Person> iList=Arrays.asList(new Person("Durga",45),
16) new Person("Ravi",40),
17) new Person("Shiva",38));
18) //line-1
394 https://www.youtube.com/durgasoftware
OCJA
19) }
20) }
Which code fragment,when inserted at line-1 enables the code to print Durga?
A. checkAge(iList,()->p.getAge()>40);
B. checkAge(iList,Person p->p.getAge()>40);
C. checkAge(iList,p->p.getAge()>40);
D. checkAge(iList,(Person p)-> {p.getAge()>40;});
Answer: C
395 https://www.youtube.com/durgasoftware
OCJA
To overcome this problem in the 1.8version oracle people introduced Joda-Time API. This API
developed by joda.org and available in Java in the form of Java.time package.
1) import Java.time.*;
2) public class DateTime {
3) public static void main(String[] args) {
4) LocalDate date = LocalDate.now();
5) System.out.println(date);
6) LocalTime time=LocalTime.now();
7) System.out.println(time);
8) }
9) }
O/p:
2015-11-23
12:39:26:587
Once we get LocalDate object we can call the following methods on that object to retrieve
Day,month and year values separately.
Ex:
1) import Java.time.*;
2) class Test {
3) public static void main(String[] args) {
4) LocalDate date = LocalDate.now();
5) System.out.println(date);
6) int dd = date.getDayOfMonth();
7) int mm = date.getMonthValue();
8) int yy = date.getYear();
9) System.out.println(dd+"..."+mm+"..."+yy);
10) System.out.printf("\n%d-%d-%d",dd,mm,yy);
11) }
12) }
Once we get LocalTime object we can call the following methods on that object.
396 https://www.youtube.com/durgasoftware
OCJA
Ex:
1) importJava.time.*;
2) class Test {
3) public static void main(String[] args) {
4) LocalTime time = LocalTime.now();
5) int h = time.getHour();
6) int m = time.getMinute();
7) int s = time.getSecond();
8) int n = time.getNano();
9) System.out.printf("\n%d:%d:%d:%d",h,m,s,n);
10) }
11) }
If we want to represent both Date and Time then we should go for LocalDateTime object.
LocalDateTimedt = LocalDateTime.now();
System.out.println(dt);
O/p: 2015-11-23T12:57:24.531
We can represent a particular Date and Time by using LocalDateTime object as follows.
Ex:
LocalDateTime dt1 = LocalDateTime.of(1995,Month.APRIL,28,12,45);
sop(dt1);
Ex:
LocalDateTime dt1=LocalDateTime.of(1995,04,28,12,45);
Sop(dt1);
Sop(“After six months:”+dt.plusMonths(6));
Sop(“Before six months:”+dt.minusMonths(6));
To Represent Zone:
ZoneId object can be used to represent Zone.
Ex:
1) import Java.time.*;
2) class ProgramOne {
3) public static void main(String[] args) {
4) ZoneId zone = ZoneId.systemDefault();
5) System.out.println(zone);
6) }
7) }
397 https://www.youtube.com/durgasoftware
OCJA
We can create ZoneId for a particular zone as follows
Ex:
ZoneId la = ZoneId.of("America/Los_Angeles");
ZonedDateTimezt = ZonedDateTime.now(la);
System.out.println(zt);
Period Object:
Period object can be used to represent quantity of time
Ex:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1989,06,15);
Period p = Period.between(birthday,today);
System.out.printf("age is %d year %d months %d
days",p.getYears(),p.getMonths(),p.getDays());
398 https://www.youtube.com/durgasoftware
OCJA
LocalDate date=LocalDate.of(yyyy,mm,dd);
only valid values we have to take for month,year and day
LocalDate dt=LocalDate.of(2012,01,32);==>invalid
LocalDate dt=LocalDate.of(2012,15,28);===>invalid
LocalDate dt=LocalDate.of(2012,7,28);===>valid
1) import java.time.*;
2) public class Test
3) {
4) public static void main(String[] args)
5) {
6) LocalDate dt=LocalDate.of(2012,01,32);
7) dt.plusDays(10);
8) System.out.println(dt);
9) }
10) }
Answer: D
RE:
Exception in thread "main" java.time.DateTimeException: Invalid value for DayOfMonth (valid
values 1 - 28/31): 32
1) import java.time.*;
2) import java.time.format.*;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) String date=LocalDate.parse("2014-05-
04").format(DateTimeFormatter.ISO_DATE_TIME);
8) System.out.println(date);
9) }
10) }
A) May 04,2014T00:00:00.000
B) 2014-05-04T00:00:00.000
C) 5/4/14T00:00:00.000
D) An exception is thrown at runtime
Answer: D
RE:
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:
Unsupported field: HourOfDay at java.time.LocalDate.get0(Unknown Source)
400 https://www.youtube.com/durgasoftware
OCJA
Eg:
LocalDateTime dt=LocalDateTime.parse("2014-05-04T13:45:45.000");
String s=dt.format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(s);
Output: 2014-05-04T13:45:45
1) import java.time.*;
2) import java.time.format.*;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) LocalDate date1=LocalDate.now();
8) LocalDate date2=LocalDate.of(2018,4,15);
9) LocalDate date3=LocalDate.parse("2018-04-15",DateTimeFormatter.ISO_DATE);
10) System.out.println("date-1:"+date1);
11) System.out.println("date-2:"+date2);
12) System.out.println("date-3:"+date3);
13) }
14) }
B.
date-1:04/15/2018
date-2:2018-04-15
date-3:Apr 15,2018
C. Compilation Fails
Answer: A
401 https://www.youtube.com/durgasoftware
OCJA
Q4. Given the code fragment:
1) import java.time.*;
2) import java.time.format.*;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) LocalDateTime dt=LocalDateTime.of(2014,7,31,1,1);
8) dt.plusDays(30);
9) dt.plusMonths(1);
10) System.out.println(dt.format(DateTimeFormatter.ISO_DATE));
11) }
12) }
A. 2014-07-31
B. 07-31-2014
C. 2014-09-30
D. An Exception is thrown at runtime
Answer: A
dt.plusDays(30);
dt.plusMonths(1);
With these new objects will be created and dt is always point to specified date only(2014,7,31,1,1)
402 https://www.youtube.com/durgasoftware
OCJA
Garbage Collections
1) Introduction
4) Finalization
403 https://www.youtube.com/durgasoftware
OCJA
Introduction
☀ In Old Languages Like C++, Programmer is Responsible for Both Creation and
Destruction of Useless Objects.
☀ Usually Programmer taking to Very Much Care while creating Objects and
neglecting Destruction of Useless Objects.
☀ Due to this Negligence, at certain Point for Creation of New Object Sufficient
Memory May Not be Available and entire Application will be Down with Memory
Problems.
☀ Hence OutOfMemoryError is Very Common Problem in Old Languages Like C++.
☀ But in Java, Programmer is Responsible Only for Creation of Objects and he is Not
Responsible for Destruction of Useless Objects.
☀ SUN People provided One Assistant which is Always Running in the Background for
Destruction of Useless Objects.
☀ Just because of this Assistant, the Chance of failing Java Program with Memory
Problems is Very Less (Robust).
☀ This Assistant is Nothing but Garbage Collector.
☀ Hence the Main Objective of Garbage Collector is to Destroy Useless Objects.
The following are Various Possible Ways to Make an Object Eligible for GC.
If an Object is No Longer required, then Assign null to all its Reference Variables.
Then that Object Automatically Eligible for Garbage Collection.
404 https://www.youtube.com/durgasoftware
OCJA
2) Re Assigning the Reference Variables:
If an Object is No Longer to required then Re Assign its Reference Variable to any New
Objects, then Old Object is Automatically Eligible for GC.
Objects Created Inside a Method are by Default Eligible for GC Once Method
Completes (Because the Reference Variables are Local Variables of that Method).
class Test {
public static void main(String[] args) {
m1(); //After m1() 2 Objects are Eligible for GC
}
public static void m1() {
s1
Student s1 = new Student();
Student s2 = new Student();
} s2
}
class Test {
public static void main(String[] args) {
Student s = m1(); //After m1() Only 1 Object is Eligible for GC
}
public static Student m1() {
Student s1 = new Student();
Student s2 = new Student();
return s1; //Here s1 Object Referenced s, s1 and s2 is Not Pointing After m1() Execution
}
}
405 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
m1(); //After m1() 2 Objects are Eligible for GC
}
public static Student m1() {
Student s1 = new Student();
Student s2 = new Student();
return s1;
}
}
class Test {
static Student s;
public static void main(String[] args) {
m1(); //After m1() Only 1 Object is Eligible for GC
}
public static voide m1() {
Student s1 = new Student();
s = new Student();
}
}
4) Island of Isolation:
class Test {
Test i; No Object is Island of Isolation
public static void main(String[] args) { Eligible for GC
Test t1 = new Test(); t1 i
Test t2 = new Test();
Test t3 = new Test();
t1.i = t2; t2 i
t2.i = t3;
t3.i = t1;
t3 i
t1 = null;
t2 = null;
t3 = null;
} Before t3 = null No Objects are Eligible for GC
}
After t3 = null All 3 Objects are Eligible for GC
406 https://www.youtube.com/durgasoftware
OCJA
Note:
1) If an Object doesn't have any Reference then it is Always Eligible for GC.
2) Even though Object having Reference Still there May be a Chance of Object Eligible
for GC (If All References are Internal References)
Eg: Island of Isolation
Once we Made an Object Eligible for GC if May Not Destroy Immediately by the
Garbage Collector.
Whenever JVM Runs GC then Only Object will be Destroyed. But Exactly at what
Time JVM Run GC, we can't Expect. It Depends on JVM Vendor.
Instead of waiting until JVM Runs GC, we can Request JVM to Run Garbage
Collector. But there is No Guarantee whether JVM Accept Our Request OR Not.
But Most of the Times JVM Accept Our Request.
The following are Various Ways for requesting JVM to Run Garbage Collector:
Once we got Runtime Object we can Call the following Methods on that Object.
1) freeMemory(); Returns Number of Bytes of Free Memory Present in the Heap.
407 https://www.youtube.com/durgasoftware
OCJA
import java.util.Date;
class RuntimeDemo {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
System.out.println(r.totalMemory()); //16252928
System.out.println(r.freeMemory()); //15956808
System.out.println(r.freeMemory()); //15772752
r.gc();
System.out.println(r.freeMemory()); //16074976
}
}
Note: gc() Present in System Class is Static Method whereas gc() Present in Runtime
Class is Instance Method.
Which of the following is Valid Way for requesting JVM to Run Garbage Collector?
1) System.gc(); √
4) Runtime.getRuntime().gc(); √
Note:
With Respect to Convenience it is Recommended to Use System.gc().
With Respect to Performance wise it is Recommended to Use r.gc(). Because
Internally System.gc() Calls r.gc().
Finalization:
Just Before Destroying an Object Garbage Collector Calls finalize() to Perform
Cleanup Activities.
Once finalize() Completes Automatically GC Destroys that Object.
finalize() Present in Object Class with the following Prototype
protected void finalize() throws Throwable
Based on Our Requirement we can Override finalize() in Our Class to Perform
Cleanup Activities.
408 https://www.youtube.com/durgasoftware
OCJA
Case 1:
Just before Destroying an Object Garbage Collector Always Calls finailze() on that
Object, then the Corresponding Class finalize() will be executed.
For Example, if String Object Eligible for GC, then String Class finalize() will be
executed. But Not Test Class finalize().
class Test {
public static void main(String[] args) {
String s = new String("Durga");
s = null;
System.gc();
System.out.println("End of Main");
}
public void finalize() {
System.out.println("finalize Method Called");
}
} Output: End of Main
In the Above Example String Object Eligible for GC and Hence String Class finalize()
got executed. Which has Empty Implementation. Hence in this Case Output is End
of Main.
If we Replace String Object with Test Object, then Test Class finalize() will be
executed. in this Case Output is
Case 2:
Based on Our Requirement we can Call finalize() Explicitly, then it will be executed
Just Like a Normal Method Call and Object won't be Destroyed.
But before destroying an Object Garbage Collector Always Calls finalize().
class Test {
public static void main(String[] args) {
Test t = new Test();
t.finalize();
t.finalize(); finalize() Called
t = null; finalize() Called
System.gc(); finalize() Called
System.out.println("End of main()"); End of main()
}
public void finalize() {
System.out.println("finalize() Called");
}
}
409 https://www.youtube.com/durgasoftware
OCJA
In the Above Example finalize() got executed 3 Times.
2 Times explicitly by the Programmer and 1 Time by the Garbage Collector.
Note:
Before destroying Servlet Object, Web Container Always Calls destroy() to Perform
Cleanup Activities.
But Based on Our Requirement we can Call destroy() from init() and service()
Methods Explicitly, then it will be executed Just Like Normal Method Call and
Servlet Object won't be Destroyed.
Case 3:
If the Programmer Calls finalize() Explicitly and while executing that finalize() if any
Exception Occurs and which is Uncaught, then the Program will be terminated
Abnormally.
If Garbage Colector Calls finalize() and by executing that finalize(), if any Exception
raised Uncaught then JVM Run Rest of the Program will be executed Normally.
class Test {
public static void main(String[] args) {
Test t = new Test();
t.finalize(); 1
t = null;
System.gc();
System.out.println("End of main()");
}
public void finalize() {
System.out.println("finalize() Called");
System.out.println(10/0);
}
} finalize() Called
End of main()
If we are Not Commenting Line 1 then Programmer Calls finalize() and while executing
that finalize() ArthimeticException raised which is Uncaught. Hence the Program will
be terminataed Ubnormally by raising ArthimeticException. In this the Output is
finalize() Called
Exception in thread "main" java.lang.ArithmeticException: / by zero
If we Comment Line 1 then Garbage Collector Calls finalize() and while executing that
finalize() ArthemeticException raised which is Uncaught. JVM Ignores that Exception
and Rest of the Program will be executed Normally.
410 https://www.youtube.com/durgasoftware
OCJA
Which of the following is true?
Case 4:
On any Object Garbage Collector Calls fianlize() Only Once. Even though that Object
Eligible for GC Multiple Times.
class FinalizeDemo {
static FinalizeDemo s;
public static void main(String[] args) throws InterruptedException {
System.out.println(f.hashCode());
f = null;
System.gc();
Thread.sleep(5000);
System.out.println(s.hashCode());
s = null;
System.gc();
Thread.sleep(10000);
System.out.println("End of main()");
}
We can't Expect Exact Behavior of the Garbage Collector. It is JVM Vendor Dependent.
It is varied from JVM to JVM. Hence the following Questions we can't Answer Exactly.
411 https://www.youtube.com/durgasoftware
OCJA
3) In which Order Garbage Collector Destroys the Objects?
4) Whether Garbage Collector Destroys All Eligible Objects OR Not?
5) What is the Algorithm followed by Garbage Collector. Etc………
Note:
Usually whenever the Program Runs with Low Memory JVM will Run Garbage
Collector. But we can't Expect Exactly at what Time.
Most of the Garbage Collectors follow Mark and Sweep Algorithm. But it doesn't
Means Every Garbage Collector follows the Same Algorithm.
class Test {
static int count = 0;
public static void main(String[] args) {
for (int i=0; i<10; i++) {
Test t = new Test();
t = null;
}
}
public void finalize() {
System.out.println("finalize() Called: "+count);
}
}
The Objects which are Not using in Our Program and which are Not Eligible for
Garbage Collection, Such Type of Useless Objects are Called Memory Leaks.
In Our Program if Memory Leaks Present then we will get Runtime Exception Saying
OutOfMemoryError.
To Overcome this Problem if an Object No Longer required, then it is Highly
Recommended to Make that Object Eligible for GC.
In Our Program if Memory Leaks Present, then it is Purely Programmers Mistake.
The following are Various Memory Management Tolls to Identify Memory Leaks in
Application
☀ HP-J-METER
☀ HP-OVO
☀ J-PROBE
☀ HP-PATROL
☀ IBM-TIVOLI
412 https://www.youtube.com/durgasoftware
OCJA
A. 1
B. 2
C. 3
D. 4
Answer: A
1) class Student
2) {
3) String name;
4) int age;
5) }
6) And,
7) public class Test
8) {
9) public static void main(String[] args)
10) {
11) Student s1= new Student();
12) Student s2= new Student();
13) Student s3= new Student();
413 https://www.youtube.com/durgasoftware
OCJA
14) s1=s3;
15) s3=s2;
16) s2=null;-->line-1
17) }
18) }
Answer: C
414 https://www.youtube.com/durgasoftware