Core Java Meterial PDF
Core Java Meterial PDF
Index :
2. Arrays ……………………………………………………..19
• Array Declaration …… 20
• Construction of Arrays …. 21
• 2-D Arrays Construction ….. 22
• Array Initialization …… 24
• Length vs Length() ….. 27
• Anonymous Arrays …..28
• Different Type of Variables ….31
• Command Line Arguments …. 40
1
8. Object – Oriented Concepts ……………………………111
9. Overriding…………………………………………………120
2
SCJP Syllabus
1. Language Fundamentals.
2. Operators and Assignment ***
3. Declaration and Access Control
4. Oops – Encapsulation,
Inheritance,
Aggregation (Composition)
Polymorphism
Coupling & Cohesion.
5. Multi-Threading (15 to 20 hrs.)
6. Java. Lang – Object Class
String
String butter
String builder
Wrapper classes
7. Exception Handling (10 hrs.)
8. Assertions [used for debugging purposes (5hrs)]
9. Garbage Collection
10. File I/O & Serialization Customized (4hrs)
11. Auto boxing & Auto unboxing, static impolts, var-arg method, num
12. Collection framework (25 to 30 hrs).
Generics. (40 – 50 days)
13. Development
Exam Pattern :
72 QS (Multiple Choice) & (Drag and Drop) → 43 QS ⇒ 59%
3
I. Language Fundamentals
a) Identifier
b) Keywords
c) Data types
d) Literals
e) Arrays
f) Types of variables
- Instance
- Local
- Static
g) Main Method
h) Var-arg Methods (in Notes No. 3)
(a) Identifiers :
A name in any program is called “identifier” which can be used for identifying
classes, methods, variables and labels.
Eg : Class Sample
{
P S V Main( ) [String args( )]
{
into x = 100;
:
:
}
}
No. of identifiers : - 4 – Sample, main, args, x
4
3. We r not allowed to use keywords as identifiers violation leads to compile-time
error.
4. There is no length limit for java identifiers. But Sun highly recommends upto
15 characters suggestable for identifiers. (In C++ 256 is max. length)
5. The java identifiers are case sensitive. i.e. Number, NUMBER, number can be used
as different identifiers within the same program and all are legal.
6. All the pre-defined Java Classes and inter fore name we are allowed to be used as
Compile − time
identifiers. There is no errors.
Run − time
Eg. : int String = 10; (Pre-defined class name but not the keyword).
S.O.P(string);
O/P : 10.
Note : But take care of ambiguity problem because in some cases U can’t distinguish
String (A class name) as predes class (or) identifier name.
(b) Keywords :
Some identifiers are reserved in java, which are always associated with a separate
functionality or special meaning. Such type of reserved identifiers are called
“Reserved Worlds”
Reserved Worlds (53)
5
Keywords for flow control : (11)
if for
else
do
while return
switch
case break
default continue
throw
throws
Volatile : (Volatile variables change from time to time which create concurrency
problems, so if any var. is of volatile JVM takes care of special
arrangement).
6
Void return type keyword : (1)
- indicates no return type by a void method.
(We should declare return type for a method)
- Indicates nothing returned by a method.
(If void is not mention for a method returning nothing, it gives compile time error).
7
(c) Data types : 2Q**
- In java, every variable / expression has a type and every type is strictly defined
(i.e. min & max sizes…..) The compiler strongly checks for type compatibility.
Hence Java is considered as “strongly – typed” language.
boolean b = o;
int i = 10.5;
- Data types
For representing whole numbers.
Numeric types Integral type : byte, short, int and long
Boolean type (for representing logical values like true (or) false)
- Except char and boolean all the remaining data types in java are signed data types.
i.e. we can represent both positive and negative numbers.
- When compared with previous languages, java is object orientied lang. in a high
level.
- But when java alone is considered, java is not pure object – oriented programming
language because of the inpure non-object primitive data types. But by using
“wrapper classes” we can view these primitive data types in object form.
- Table :
Size, Range, What cases suitable, What happens it we base out of range.
8
1. byte : **
- Size : 8 - bits
Range : - 128 (min) to 127 (max)
2. Short :
- Size : 2 bytes
- Range : -215 to 215 –1
(-32.768 to 32767)
- Short S = 32768;
Comp. Error : PLP
found : int
required : short
- Rarely used data type.
But where it is used ?
When Java was introduced in 1995, processors are of 16-bits, they used
short data type. But now, 16 – bit processors are outdated, the short data
type is also outdated (almost). This is why is rarely used in regular pgmg.
Short d.t is best used for 16-bit processors like 8086.
9
3. int :
- The most commonly used datatype in Java is ‘int’ type.
Java is ‘Robust’ in the sense, the chances of getting o/p of java program failed are
low w.r.t p/f to p/f.
In ‘C’ – int - 2 byte (16 – processor), 4 byte (32 – processor)
The pgm written in ‘C’ on 16-bit proc can be executed on 32-bit processor but
vice-versa is not possible. ⇒ ‘C’ is non-robut language.
- The size of ‘int’ is always 4-bytes irrespective of platform. But in case of ‘C’ the
size of int varies from p/f to p/f ⇒ chance of failing ‘C’ pgm from p/f to p/f is
very high. This behavior is known as non-roburt behavior. But in case of Java,
size of any d.t is fixed and it won’t vary from p/f to p/f.
Hence the chance of failing the java pgms is very very less and hence it is
considered as robutst language.
- Because there are no memory problems in java because of Garbage collector, it is
considers as robust.
- Size : 4 – bytes
- Range : -231 to 231 - 1
(-2147483648 to 2147483647)
- Because our required values are only in the range of int it is most widely used.
10
Floating – Point
d.types :
Float Double
Size : 4-byte Size : 8-byte
This is suitable if U This is suitable if U
want to consider 6 to 7 want to consider 14 to 15
fractional digits of accuracy fractional digits of accuracy
is required. is required.
This is single – precision (6 to 7) This is double – precision (14 to 15)
⇒ Less accurate. ⇒ More accurate.
Range : -1.4e –45 to 3.4 e 38 Range : 4.9 e –324 to 1.8 e 308
Boolean type :
- In case of C, C++ size of Boolean is fixed, but in Java, size for Boolean is not
applicable (JVM dependant)
- Size : Not applicable
- Range : Not applicable, but allowed values are true and false.
Eg : boolean b = true;
boolean b = TRUE;
boolean b = false;
boolean b= FALSE;
Comp error : Cannot resolve symbol TRUE, FALSE
11
Eg : int x = 0
if (x)
{
SOPln (“Hello”);
}
else
{
SOPln (“Hi”);
}
Literals : **
A literal represents the constant value which can be assigned for the variable
12
Integral literals :
- Literals that are assigned to Integral data types such as int, long, short and byte.
- For the integral types, we are allowed to specify the value by using one of the
following possible literals.
i) Decimal literals :
Allowed digits 0-9
Eg : int x = 10;
Eg : Class Test
{
Public Static Void Main (String args [ ])
{
int x = 10;
int y = 010;
int z = 0X10;
S.O.Pln (x + “……….” + y + “…..” + z);
}
}
O/P : 10…8…..16.
Note : We can give i/ps to JVM in decimal, octal and hexadecimal but the O/P of
JVM is always in decimal form. O/P can be displayed as binary, Oct & Hex
by using methods (to Octal String ( ) etc) in Util Package.
By default all the integral literals (either decimal / octal / hexa decimal) are of
‘int’ type. We can specify explicitly a long literal by suffixing either
‘l’ (or) ‘L’.
Eg : long y = 10 l;
int x = 10 l;
13
req : int.
** - There is no direct way to specify an integral literal is of byte type (or) short type.
We can assign an int value to the byte or short variables but it should be within
the range supported by the. Corresponding data type.
Eg : byte b = 10;
10 is also int type, but because 10 is within range of byte,
it is considered as byte.
byte b = 10b;
This is similar to short also.
Short S = 10;
Short S = 10s;
Eg : double d = 123.456;
float f = 123.456;
Comp. Error : Possible Loss of Precision (PLP)
found : double
required : float
- We can specify explicitly a floating point literal of float type by suffixing with
‘f’ (or) ‘F’.
123.456 f ;
Eg : float f = 123.456 F ;
@@ - We can’t specify a floating – point literal by using base-8 [octal] (or) base – 16
[Hexa decimal] notation. i.e. The only possible way to specify floating point
literals is base – 10 [Decimal] notation only.
14
Eg : float f = 10;
S.O.P(f);
O/P : 10.0
Note : No need of Suffix ‘f/F’ For integral literal when assigned to floating point data
types.
Exercise :
1. float f = 123.456;
2. float f = 123.456f;
3. double d = 123.456d;
4. double d = 123.456;
5. double d = 123.456D;
6. float f = 123;
#7. float f = 0123;
#8. float f = 0X123;
7., 8., are valid 0123, 0x123 constitue only integer literals, they are converted to integer
decimal type and stored in & l – literals.
Eg : float f = 123;
float f = 0123;
float f = 0X123;
9. float f = 123e2(f);
Note : For integer data type we shouldn’t age 123e2 assigned to int variable.
15
Possible assignment :
byte → short
int → long → float → double
char
Boolean literals :
The only possible literals for boolean type variables are true / false. But not
TRUE/FALSE
Eg : boolean b = true;
boolean b = TRUE;
Comp. Error : Cannot resolve symbol
Symbol : Variable TRUE
Location : ------
Here we don’t get PLP error, be cause we are not storing the literal value in its equally
compatible data type but of entirely different data type.
16
Exercise :
1. boolean b = true;
boolean b = FALSE; - Can’t resolve symbol
boolean b = O; - Incompatible types
boolean b = yes; - Can’t resolve symbol
boolean b = (10>20);
(x > y); x = 10, y = 20.
While compiling behave like a compiler & while running behave like JVM.
“Char” literals :
1. ∆ Char literal can be specified as single character within single quotes.
Eg : Char ch = ‘a’;
Char ch = ‘face’;
Char ch = “a”;
(it is string literal but not char literal. Enclosed in double quote)
2. For every character there exists a corresponding Unicode literal. A char literal can
also be specified by using its Unicode value.
Eg : Char ch = 97; SOP(ch); O/P : a
Char ch = 3I47;
Note : Valid integers than can be assigned to char variables are from 0 to 65,535.
- After a particular range (Eg. 1000 to 68535) the O/P is ‘?’ i.e. for the entire range, it
is printing the same ‘?’. Because the value within above range may represent some
Arabic character (symbol) or the other but the JVM installed in the system supports
only English, we got the same symbol.
17
3. A char literal can also be represented by using Unicode notation.
Exercise :
Char Ch = ‘\u0012’;
Char Ch = ‘\uface’;
Char Ch = ‘\ubeef’;
Char Ch = ‘\iface’;
Eg. Char
Ch = ‘\t’;
Ch = ‘\r’;
Ch = ‘\b’;
Ch = ‘\n’;
Ch = ‘\m’;
Escape Sequences :
Escape Unicode Character
Sequence Value
\b \u0008 Backspace
\t \u0009 Horizontal tab
\n \u000a New line
\r \u000d Carriage return
\f \u000c Form feed
\’ \u0027 Single quote
\” \u0022 Double quotes
\\ \u005c Backspace
18
String literals :
- A sequence of characters within double quotes is considered as a string literal.
Eg : Strings = Cognizant Technology Solution.
Sopln(s);
String Si = “cognizant\n Technology \n Solution”;
\u0009
\u00a
Note : Instead of ‘\n’ and ‘\r’ we are not allowed to use the corresponding unicodes
(\u000a and \u000d). Violation leads to compile time error.
The above unicodes r not allowed even in the comments also. The error appears
for the next line.
19
(2-3 Qs) Arrays
Agenda (Arrays)
1. Arrays Intro
2. ↓ Declaration
3. ↓ Construction
4. ↓ Initilization
5. ↓ Declaration, Construction & Initialization in a single line.
6. Length vs length ( )
7. Anonymous arrays (Nameless)
8. Array element Assignments
9. Array variable Assignments
20
Array Declaration : (1 – 1 arr decl)
Eg : int[ ] a; {int (datatype), [ ] (dimension), a; (Name of array)}
This approach is suggestible because, by seeing the stmts only we can say ‘a’
is a single dimensional array of int type.
int a[ ]; It is valid that we can place the dimension even beside the name of
the array.
- At the time of declaration, we are not allowed to specify the size, violation leads to
fompile time error. I.e.
Eg : int[6] a;
21
Construction of Arrays : (1-D array Construction)
- An array itself is an object in Java, whether it may be of any dimension.
1. Construction :
3. It is legal to have an array with size ‘O’ in Java. No compile-time / Run – time
exceptions.
4. If U want to specify size of array by using some variable, the allowed data types are
bye, short, int and char. i.e. any data type which can be implicitly converted to int
type
Canbepromoted
- byte → short
int → long → float → double
char
5. The maximum allowed array int array size in Java is 2147483647. (The may no
represented by int type).
22
6. We can assign the size of the array even with a realizable also.
Eg : byte b
b
short s = 100; int[ ] an = new int [ s ];
i
int i
long l = 10L; int[ ] arz = new int = [ l ];
Error : PLP
- chart ch = ‘a’;
int [ ] i = new int [ ch ];
⇒ array size is ‘97’ ints.
int[ ] i = new int [ ‘a’ ];
- int [ 10 ] a = new int [ 10 ];
↓
At the time of declaration we shouldn’t mention the size.
2 – D arrays construction :
- 2-D arrays r known as Matrices. These matrices form is in C, c++ but in Java there is
no matrices concept. It stores every thing in a single row.
a base array
23
Eg : My req;
a[0] a[1] a[2]
a→ - base array
Exercise :
int [ ][ ] a = new int [ ] [ ]; Missing base size
int [ ][ ] a = new int [ 2 ] [ 3 ];
int [ ][ ] a = new int [ ] [ 3 ]; (Specify size from L → R)
int [ ][ ] a = new int [ 1 ] [ ] [ ] [ 4 ]; → Comp. Error
a→
a[0] [0] [0 ]
24
Code : int[ ][ ][ ] a = new int [ 3 ] [ ][ ];
a[ 0 ] = new int [ 2 ] [ ];
a [ 0 ] [ 0 ] = new int [ 3 ] ;
a [ 0 ] [ 1 ] = new int [ 2 ] ;
Exercise :
1. int [ ][ ][ ] a = new int [ 3 ] [ ] [ ];
2. int [ ][ ][ ] a = new int [ ] [ 4 ] [ 5 ];
3. int [ ][ ][ ] a = new int [ 3 ] [ ] [ 6 ];
*** If u have given value for any dimension, all its previous dimensions must be defined.
Structure :
a→
Array Initialization :
- Once we constructed an array, all the elements will get default values automatically.
Eg : int [ ] a = new int [ 3 ];
S.O.Pln (a[0]); //O.P. = O
- If we r performing any initialization explicitly, the default values will be over ridden
with our specified values.
25
Eg.1 : double [ ] [ ] d = new double [ 2 ] [ 3 ];
Internal Structure :
d[ 0 ] d[ 1 ]
d→
reference of d[0] [0] reference of d[1] [0]
d [0] [0] d [0] [1] d [0] [2] d [1] [0] d [1] [1] d [1] [2]
Object array 0.0 0.0 0.0 0.0 0.0 0.0
26
Eg.4 : int [ ] a = new int [ 3 ]; a [ 1.5 ] = 60;
a [ 0 ] = 10;
a [ 1 ] = 20;
a [ 2 ] = 30;
a [ 3 ] = 40; AIOOBE (Run time Error)
a [ -1 ] = 50; AIOOBE
If we r accessing an array element, with –ve index (or) an index value which is in out of
range, we will get a run-time exception saying “Array – Index Out Of Bounds
Exception” along with index number.
- In the above approach U can’t create an array of ur own size with some values of ur
own and some with default values.
- Declaration, construction & Initialization is a single line. If U r dividing into 2 nd line,
it results in a compile – time error.
27
- D,C,I of Multi –D array in a single row.
Internal Structure :
10 20 30 40 50 60
Length Vs Length ( ) :
(variable) (method)
Length :
1. “length” is a final variable which is applicable for “array” objects.
2. It represents no. of elements present inside array. / returns the size of the array.
Length( ) :
1. It is a final method, which can be applicable for the string objects.
Eg : String str = “Raghava”;
S.O.Pln (S.length ( )); // O/p : 7
S.O.Pln (S.length); // Comp. Error.
2. It represents the no. of characters present in string object / returning the size of the
string.
28
Exercise :
1. int [ ] a = new int [ 6 ];
S.O.Pln (a length); // O.P : 6
2. int [ ] [ ] a = new int [ 2 ] [ 3 ];
a.length = 6
a.length = 2 (size of base array)
a[ 0 ].length = 3
- There is no direct method which represents, the total no. of elements of multi-
dimensional array.
For multi – Darray :
S.O.P (a.length x a[ i ].length); O/P : 6
- Because there is an inner class for an array object, and length is as variable of
that inner class, we can find length of array using that variable.
Anonymous Arrays :
- Anonymous arrays r the arrays without name.
- Where we use ?
These arrays are just fo instant use.
Eg : Public Static int Sum (int [ ] a)
{
int total = 0;
for (int i = 0; i < a.length; i ++)
{
total = total + a[I];
}
return total;
}
Class test
{
P S V Main (String [ ] args}
{
Sopln (Sum (new int [ ] {10,20,30,40}));
}
}
O/P : 100
- After using the anonymous array object, since its address is not holded by any
variable, immediately it is available for “Garbage Collection”.
- int [ ] a = new int [ ] {10,20,30,40};
29
new int [ ] [ ] {{10,20}, {30,40}};
**
- While Declaring anonymous arrays, we r not allowed to specify the size. Violation
leads to compile – time error.
i.e. new int [ ] {10,20,30};
new int [ 3 ] {10,20,30};
Eg : Expected.
- int [ ] a = new int [ 2 ] {10,20}; (shouldn’t be mentioned)
- in general, all the static methods are utility methods.
30
Array variable assignments :
- While performing assignment of one array to another array, we have to check the
declared types, not its sizes.
Eg :
int [ ] a = {10,20,30}; int [ ] a = {10,20,30,40,50,60,70,80};
int [ ] b = {40,50,60}; int [ ] b = {100};
a = b; b = a;
SOP (b.length); //
SOP (b[3]); // 40
31
comp. error : Incompatible types.
found : int
req : int [ ]
1. Primitive variables :
These variables can be used for holding primitive values
Eg : int a = 10; (a = P.V.)
2. Reference Variables :
These variables can be used for refereeing objects.
Eg String S = “kiran”; (S = R.V.)
- Based on the position and the purpose, variables are divided into the following 3
categories :
1. Instance variables
2. Static variables and
3. Local variables
32
- These instance variables will be created when the corresponding object is created. If
the object is destroyed by the Garbag. Collector (GC), automatically the
corresponding instance variables will also be destroyed.
- “Instance variables exist as long as the corresponding object present on the heap.
- We have to declare instance variables within the class, outside of any method or
constructor.
Eg :
Class Test
{
int i;
P S V M(S[ ] a)
{
SOPln (i); // we should create object first.
}
}
Test t = new test( );
SOP (t.i);
2. Static variables :
Eg : class student
{
string sname;
int rollno;
string coll-name;
}
- In the above class, even though u create a lot of objects, all of them having same coll-
name duplicated in all object which is of no use. So, U maintain that value in a single
variable of type ‘static’ which is a class level variable.
- If the value of a variable, is same for all objects, such type of variables not
suggestable to declare at object level. We have to declare these variables at class level
so that a single copy is shared by all instances. Such type of variable we have to
declare by using keyword “static”.
33
- i.e. Instance variables are object level variables but static variables are class level
variables.
Note :
Don’t assume, because static variables r declared within class they r called as “class
variables”. Because, though instance variables r created within the class – they r
called as “instance variables” but not class level variables.
34
Local Variables :
- Also known as “Temporary Variables” (or) “Stack Variables” (or) “Automatic
Variables”.
- Within a block if we declare any variable, for temporary purpose, such type of
variables are called “Local variables”. The Scope (where these can be present) of is
where they are declared within a block.
Eg : class sample
{
P.S.V.M (S[ ] a)
{
int i;
Sopln (i);
}
}
O/P :
Comp. Error : Variable ‘i’ might not have been initialized.
- For the local variables, there won’t be the concept of “Default Initilization”. It is
programmer’s responsibility to perform initialization for local variables explicitly.
- Before using a local variable, we should perform initialization, otherwise compile
time error.
Eg : class sample
{
P.S.V.M (S[ ] a)
{
int i;
Sopln (“Don’t Sleep”);
}
}
O/P : Don’t sleep (no comp. error. ‘i’ is not used till now)
35
Eg : class sample
{
P.S.V.M (S[ ] a)
{
int i;
if (args.length > 0)
{
i = 10;
}
Sopln (i);
}
}
O/P : Comp. error : V ‘i’ m n h i.
Note : Initialization is not suggestable in the conditional blocks.
Eg : class sample
{
P.S.V.M (S[ ] a)
{
int i;
if (args.length > 0)
{
i = 10;
}
else;
{
i = 20;
}
SOP (i);
}
}
O/P : No compile time & run-time error.
36
Conclusions :
- If U R not performing initialization, for the static and instance variables, default
values will come. But for the local variables, default values will come. But for the
local variables, there is no concept of default initialization we should perform
initialization before using local variable.
- Local variables, the only allowed modifier is “final”. i.e. the following local variable
declarations.
- Local variables can’t be static because static variables can be accessed with
classname and object of class outside the methods also, but local variables can’t be
used outside the block.
Un initialization in Arrays :
Eg : class sample
{
int [ ] a;
P S V M (S[ ] a)
{
Sample S = new sample ( );
Sopln (s.a.); // null
Sopln (s.a[ 0 ]); // Null pointer exception (Run time exception)
}
}
At the instance level :
1. int [ ] a sopln (obj. a); null.
sopln (obj. a [ 0]); NPE
2. int [ ] a = new int [ 6 ]; sopln (obj.a); i@ 12D34
sopln (obj.a[ 0]); O
37
Static :
1. int [ ] a; sopln (a); null.
sopln (a [ 0]); NPE
2. int [ ] a = new int [ 6 ]; sopln (a); i@ 1add 2dd
sopln (a[ 0]); O
‘Local’ level :
1. int [ ] a; sopln (a); CE
No need of its components
2. int [ ] a = new int [ 4 ]; sopln (a); // i@ 1add 2dd
sopln (a[ 0]); O
- Whether an array is declared instance static (or) local its elements always assigned
with default values.
When arrays r declared at static / instance level, V can print the address (reference) of
an array object as null, but V can’t print a3[ 0 ], results in CJE because null object
points to nothing.
Where as if V declare an array as local, then, V can’t print reference of an array
object, Vget CTE : variable <array> might not have been initialized.
38
Different cases w.r.t. main ( ) :
1. class test
{
-----
-----
}
> javac test
> java test No such method error.
- Compiler never checks whether class contain main method or not but at run-time
JVM checks for the main method with the specified signature. If it is not finding
any method with the specified signature, it lises “no-such method” error.
Note : It is run-time error only, but not compile time error.
2. Class test
{
Private static void main (String[ ] args)
{
-----
-----
}
}
Run – time error : Main Method not public.
In java, a method is not allowed to be declared within another method.
3. Class test
{
Public void main (String[ ] args)
{
SOP (“…….”);
}
}
O/P: Run – time error : No such method error.
39
4. Class test
{
Public static int main (String[ ] args)
{
SOP (“…….”);
return 10;
}
}
RJE : No such method error.
5. Class test
{
Public static void main (String[ ] args)
{
SOP (“…….”);
}
}
NO CTE, RTE; No such method error.
40
7. Public static synchronized void main (String [ ] args) { }
8. Public static void main (String args) { }
RTE ; No such method error.
9. Public static void main (String [ ] Pavan Kiran) { }
10. Public static void main (String …… args) { }
41
Eg : Public class A
{
P S V M (S[ ] args)
{
String [ ] [ ] argcopy = new string [ 2 ] [ 2 ];
int x;
argcopy [ 0 ] = args;
x = argcopy [ 0 ].length;
for (int y = 0; y<x; y ++)
{
SOP (“ “ +argcopy[ 0 ] [ y ]);
}
}
}
java A 1 2 3
O/P : 1
2
3
42
Operators & Assignments
Agenda :
1. Increment / Decrement Operators.
2. Arithmetic Operators
3. Shift Operators 9Not in 1.5 but in 1.4)
4. String Concatenation
5. Comparison Operators
6. Equality Operators
7. Bit wise Operators
8. Short Circuit Operators
9. Instance of Operator
10. Primitive typecasting
11. Conditional Operator
12. ‘new’ operator
13. [ ] – Array Declaration Operator
14. Precedence of Java Operators
15. Evolution order of Java Operands.
43
Decrement Operators : y - -; Post Decrement
- - y; Post Decrement
Table :
Expression Initial Final Initial Final
Value of Value of Value of Value of
‘x’ ‘x’ ‘y’ ‘y’
y = ++x 4 5 5 5
y = x++ 4 5 4 4
y = --x; 4 3 3 3
y = x --; 4 3 3 4
3. We can’t apply Increment / Decrement Operators for the final variables. Violation
leads to compile time error.
Eg : final int x = 4;
++x; // x ++
(Here re-initialization for ‘x’ after increment done but in is final)
SOP (x);
44
CTE : Can’t assign a value to final variable
4. We can apply Increment / Decrement operators, even for float and double variables
also.
Eg : double d = 10.6;
d ++;
SOP (d);
O/p : 11.6
5. If U apply arithmetic operators b/w variables a and b the result is always max (int,
type of a, type of b)
Eg : byte a = 10;
byte b = 20;
bute c = a + b; (+ - results in int)
Sopln ( c);
CTE : PLP
found : int
required : byte.
Eg : Short S = 10 + 20;
Sopln (S); // 30
Short S1 = 10;
Short S2 = 20;
Short S = S1 + S2; CTE : PLP
Eg : final short S1 = 10;
final short S2 = 20;
short S = S1 + S2;
Eg : byte b = 10;
b = b + 1;
Sopln (b);
45
CTE : PLP
found : int
required : byte
46
Double
Integer
- For representing infinity, there r constants defined in the Float and Double
wrapper classes.
They r: public static final positive infinity
public static final negative infinity
But there is no such arrangement in the case of Integral types (Byte, Short, Int
and Long) represent infinity. Hence “Division by zero AE” results only in
case of integral types but not in floating point data types.
int 10/0 → int (but no const in Integer class)
double 10.0/0 → double (there is a const / defined in double class
for representing infinity)
-10.0/0 → (-Infinity)
Consolidated :
10/0 ⇒ A.E
10.0/0 ⇒ Infinity
-10.0/0 ⇒ −Infinity
47
-0/0 ⇒ AE
-0.0/0 ⇒ NaN
There is no math class in 1.5 but there in 1.4
3. 1.4 :
S.O.Pln (Math. Sq.rt (4)); O/P : 2.0
SOPln (Math. Sq.rt (-4)); O/P : NaN
4. For any ‘x’ value including NaN, the following statements results.
x > Float NaN
x< “
x> “
x< “
x== “
O/P : False
[SODln (x ! = Float.NaN), O/P : true]
But, the result of below stmt is true.
Float.Non! = Flat.NaN → O/P; True
SOPl (Float.Non! = Flat.NaN); → True
SOPln (Float.Non! = Flat.NaN); → False.
Conclusion :
Arithmetic Exception :
- meant for only integral types not for float, double
- only & operators (/, %) cause their exception.
4. String Concatenation Operator :
Till 1.4, only ‘+’ operator is overloaded. But in 1.5, ‘%’ operator is also overloaded.
‘+’ Operator is the overloaded operator in Java. Sometimes it acts as Addition
operator and sometimes it acts as String Concatenation Operator.
If atleast one of the operands is the string type, then ‘+’ oprator simply acts as
“Concatenation” operator. If both operands are numbers then ‘+’ acts as Arithmetic
Addition operator.
Eg 1: 2 + 3 = 5
“ab” + “cd” = abcd
“ab” + 3 = ab3
48
Eg 2: int a = 10;
int b = 20;
int c = 30;
String d = “durga”;
SOPln (a+b+c+d); // 60 durga
(a+d+b+c); // 10 durga 2030
(d+a+b+c); // durga 102030
(c+d+a+b); // 30 durga 1020
(a+b+d+c); // 30 durga 30
Note : If same operator is more than once; then associatively arises and for ‘+’ it is
L→R associativity.
6. Equality Operator : byte → short → int → long → float → double
chart
1. Only z : = = and ! =
return type is “Boolean”.
Eg : SOP (10 = = 20); // false
SOP (10.0 = = 10); // true
Note : Before comparing 10.0, 10, JVM promotes lower type into higher type.
SOP (97 = = ‘a’); // true
Char can be promoted to int
SOP (‘a’ = = true); // CTE
CTE : Operator = = cannot be applied to char and boolean.
2. We can apply “Equality Operators” for both primitive types and object
references. In case of primitive data types, these operators check magnitudes.
Eg : Sample S1 = new sample ( );
Sample S2 = new sample ( );
Sample S3 = S1;
SOPln (S1 = = S2); // false
SOPln (S1 = = S3); // true
In case of object references, ‘ = =’ operator always checks for address
comparison. i.e. (S1 = = S2) is true, if and only if both S1 & S2 pointing to
the same object (observe above eg).
Eg : Sopln (“durga” = = “xxxyyy”); // flase
Sopln (“durga” = = new Integer (10));
C..T.E. : Incomparable types.
49
Note : We can’t use = = operator for different type of objects. Violation
leads to compile-time error, saying “Incomparable types”.
- For any object reference ‘S’, S = = null, the result is always false.
String S = null;
Object O = null;
Integer i = null;
SOP (null = = “durga”); // false
SOP (new integer (10) == “null”);
- null = = null always results in (true).
- 10 = = 20 // flase
10 = = 20 = = 30
L→R
CTE : = = Cannot be applied to Boolean, int
5. Comparison Operator :
They are <, <=, >, > =
Always return boolean type.
These can be applicable only for primitives except boolean.
Eg : 10 < 20 → true
30 > 15 → true
30 < = 15 → false
“durga” < “xxxyyy”.
CTE : Operator < cannot be applied to string and string.
10 < 20 < 30
CTE : Operator < cannot be applied to boolean, int.
7. Bit-wise Operator :
1. They r &, |, ∧
AND ← & - If both r true then only true.
OK ←| - If atleast one is true then result is true.
XOR ← ∧ - If both are different, then only true. If both r same, then false.
50
Exercise :
TθF→F
T | F→T
T ∧ F→T
2. 4θ 5→4 4 – 0100
5 – 0101
& - 0100 → 4
4| 5→5 4 – 0100
5 – 0101
| - 0101 → 5
4∧5→1 4 – 0100
5 – 0101
∧ - 001 → 1
3. We can apply for bolean & Integral types, not applicable to floating point and
char types.
Eg : 1.5 & 2.6
CTE : ‘θ’ operator cannot be applied to double and double.
4. Bit-wise complement operator : ( ~ )
- We can apply Bit-wise complement operator, only for integral types but not
for Boolean types.
Eg : ~ 4
~ true
CTE : Operator ~ cannot be applied to boolean.
SOP (~4); // -5
51
4 → 0000 0000 …….. 0100
~4 →1111 111……… 1011
000 000......0100
=-
5 01015
= -5
15 → 0000 …… 1111
~15 →1111 …… 0000
→ 000 …… 1111
10000
- 16
SOP (~15); // -16
5. Boolean - complement operator : (!)
! true → false
! flase → true
! 3 → CTE
CTE : Operator ! cannot be applied to int.
Conclusion :
& | ∧ - can be applied for both integral & boolean types.
~ → Only for integral types.
! → Only for boolean types.
52
// L1min → total 21 min
}
false
else if → 10 min
10 min
{
//
}
In the normal logical operators & and | we have to calculate both arguments
(expression values). Compulsorily sometimes, it may create performance problems.
To improve the performance, short-circuit operators were introduced.
They are && and ||
Comparison b/w biterise and short – circuit operators :
Bit-wise Short-circuit
(&, |) (&&, ||)
1. Can be applicable for both 1. Applicable only for boolean
boolean & integral types types.
2. Both operands must be evaluated 2. Evaluation of 2nd argument is optional.
(x && y → if x is true.
then only y will be calculated)
(x || y → if x is false,
then only y will be calculated)
3. Performance is low 3. Performance is high.
53
++x;
Sopln(x);
Sopln(y);
}
else
{
++y;
Sopln(x);
Sopln(y);
}
x y
& 11 17
| 12 16
&& 11 16
|| 12 15
if (10<15 || (10/0)<2)
{
Sopln(“hai”);
}
else
{
Sopln (“Hello”);
}
O/P : Hai
54
ii) Explicit typecasting
i) - Compiler responsible for Implicit typecasting.
- Keeping small value in a big container, is called Implicit typecasting
- No loss of information
- Also known as “Widening”
- All possible implicit type castings
Eg 2: int i = 150;
byte b = (byte) i;
short S = (short) i;
Sopln (b); -106
55
Sopln (s); 150
150 → 0000….. 1001 0110
-ve 110 1001
110 1010
b = -106
s = 150
Eg 3: float f = 123.456f;
int i = (int) f;
SOP (i); 123
If we type cast a float value into the ‘int’ type, by explicit type
casting the decimal part (digits after decimal point) will be lost.
Object – type casting pending.
9. Instance of Operator :
We can use instance of operator to check whether the given object is an instance of
the specified class / interface.
a instance of x
Object / Class /
Object reference Interface
56
Conclusion :
a instance of x
- The type of a and x must be related, otherwise compile time error saying
“inconvertible types”.
Eg : Object obj = new Object( );
Sopln (obj. instance of String); // false
NO CTE.
null instance of x
result is always “false”
Doubts :
1. How to know the unicode value for a particular character.
A: www.unicode.org
2. What the diff b/w (char ch1 = Ox61; char ch2 = ‘\u0061’;
A: Nothing but the representation.
3. I think we have ‘\v’ - vertical tab, what abt that ?
A: No. That tab is present in C, C++. But not is Jav
4. In comments, can we use escape seq other than unicodes of \n & \r
A: yes, we can
5. r both collections & arrays same ?
6. a → 2-D int
b → 1-D int
b = a ? a = b ‘No’
Error : Incompatible type
Found : Z-D
Req : 1 –D
57
Conditional Operator :
The only available ternary operator is the “conditional operator”.
Syntax : int a = (Boolean expression) ? (value if TRUE) : (value if FALSE)
Eg : int a = (x > 20) ? z : y
Int a = true ? 10 : 20; // a = 10
We can perform nesting of conditional operator also.
Eg : int x = (false) ? 30 : ((true) ? 40 : 50);
// x = 40
byte x = (true) ? 10 : 20;
(true → compile-time const/ - then compiler doc.print
bother about type of operands)
SOP (x) ; // x=10
byte x = (a<b) ? 10 : 20;
(a<b → expression – executed by JVM, compiler bothers about
types of operands)
CTE : PLP required : byte
found : int
Assignment Operators :
Divided into 3 categories :
i) Simple – assignment ( = ) Eg : I = 10;
ii) Compound – assignment
iii) Chained - assignment
ii) Compound – assignment :
int a = 10; byte b = 20;
a + = 10; b + = 30;
SOP (a); (10) SOP (b); (50)
In case of compound assignment operator, compiler will take care about typecasting
problems. i.e. it can perform internal automatic typecasting similar concept in
Inc/Dec. Opes.
byte b = 20; byte b = 20;
b = b+30; b + = 30;
SOP (b); SOP (b); (50)
CTE
58
The following r all possible compound ass operators :
+ =, -=, *=, /=, %= Eg : int a = 4;
>>=,<<=, >>>=, a = a & 5;
&=, |=, ∧= a& = 5;
Adv : Implicit type-casting
Chained ass Operators :
Eg : int a,b,c,d;
a = b = c = d = 40;
int a = b = c = d = 40;
CTE
(a,b,c,d not declared – No seperator b/w 2 variables)
New Operator :
1. This can be used for creation of objects
2. New and instance of are both keywords as well as operators.
[ ] Operator :
1. This can be used for declaration and construction of arrays.
59
2. Arithmetic Operators (binary operators):
i) *, /, %
ii) +, -
3. Shift Operators :
i) <<, >>, >>>
4. Comparison Operators :
<, <=, >, >=, instance of
5. Equality Operators :
==, !=
6. Bitwise Operators :
&, ∧, |
7. Short-circuit Operators :
&&
||
8. Conditional Operators :
?:
9. Assignment Operators :
=, +=, -=, *=, /=, %=, >>=, <<=, >>>=, &=, | =, ∧=
60
O/P : 123456 -3
1 + 2 * 3 / 4 –5 % 6
1 + 6/4 – 5 % 6
1 + 1 –5
2 – 5 = -3
Conclusion :
Before applying any operator, first we have to evaluate all the operands. The order
of evaluation of operators is always from L → R
After evaluation of operands, we have to apply the operators according to
precedence.
Control Flow :
Flow control describes the order of execution of statements (code) at run-time i.e. it
describes the order in which the statements will execute.
Selection Statements
⇒ Among Several choices u pick one
i) if – else ii) switch
Transfer statements
⇒ Flow transferred to another place
i) break ii) continue iii) return
iv) try-catch-finally v) assertions
If-else :
1. Curly braces { }, and else part both are optional.
2. The valid argument for the if-statement is always Boolean, violation leads to CTE.
61
Case 1 : int i = 10;
if (i)
{
SOP (“Hi”)
}
else
{
SOP (“Hello”);
}
62
Case 4: boolean b = true;
if (b = false)
{
SOP (“Hi”);
}
else
SOP (“Hello”);
O/P : Hello
63
“Switch” Statement :
1. Curly braces are mandataory, violation leads to CTE.
2. Both case and default are optional
Eg. int x = 4;
switch (x)
{ } - No case and default statements
No CTE, NO RTE
3. Valid arguments for switch statement are :
byte
short → unitl 1.4 version
chart
int
From 1.5 version onwards, the corresponding wrapper class objects (Byte, Short,
Character and Integer) are also allowed.
Switch can take an enum object also as argument.
Eg : Integer i = new intger (10);
Switch (i) { } valid in 1.5
Invalid upto 1.4
4. If us want to keep any statement inside switch, it must be under some case of
default. Otherwise compile time error.
Eg : int x = 4;
Switch (x)
{
SOP (“Pandu”);
}
CTE : ‘Case’, ‘default’ (or) ‘}’ expected.
5. Case Labels :
All the case labels must be compile time constants otherwise CTE. Saying constant
expression required.
Eg : int x = 10;
int y = 40; // final y = 40
Switch (x)
{
case 10;
case 20;
64
case 30;
case y :
}
CTE : Constant expression required.
65
⇒ The case labels :
- Must be compile time constants
- Must be in the range of switch argument
- Must not be duplicated
6) ‘default” case :
- The default case can be kept anywhere, but it is convention to keep default
case always as the last case.
7) Case labels r always checked from top to bottom and default is executed at the
last, called fall – through switch stmt
Eg : Switch (x)
{
Case 0 :
SOP (“0”);
Case 1 :
SOP (“1”);
Case 2 :
SOP (“2”);
default:
SOP (“default”);
}
x=0 ⇒ 0,1,2
x= 1 ⇒ 1,2
x=2 ⇒ 2
x=4 ⇒ default
Once any case or default is matched, then all the stmts will be executed from top
to bottom until break (or) end of switch stmts. This is called “fall through inside
switch”.
int x =
switch (x)
{
default :
SOPln (“default”);
Case 0 :
SOPln (“0”);
66
Case 1 :
SOPln (“1”);
Case 2 :
SOPln (“2”);
}
x=0 ⇒ 0,1
x= 1 ⇒ 1
x=2 ⇒ 2
x=4 ⇒ default
Iteration Statements :
1. ‘While’ loop :
If we don’t know the number of iterations in advance, then we should go for
“while” loop.
The valid argument for the while loop is Boolean.
Curly braces are optional, without curly braces only one statement is allowed, that
statement should not be declarative statement.
If the controller never reaches any statement then compiler gives an error saying.
“Unreachable Statement”
Eg.1 : while (true) (compile – time constants)
{
SOP (“Hi”);
}
SOP (“Hello”); (unreachable stmt)
Eg.2 : while (false) (compile – time constants)
{
SOP (“Hi”); (unreachable stmt)
}
SOP (“Hello”);
67
Eg.3 : int a = 10;
int b = 20;
while (b > a)
{
SOPln (“Hi”);
}
SOPln (“Hello”);
Here there won’t be any CTE, (b > a) expression is executed at run-time 10g JVM
but not by compiler. If compiler couldn’t resolve expression then it won’t check
for unreachable stmts/. Hence no CTE.
68
do CTE : while expected.
while (b);
do do
; No CTE ;
while (b); ;
do while(b);
{ CTE (; expected)
}
while (b); ;
without curly braces only | stmt/ is allowed, but it should not be declarative statement.
do
int i = 10;
while (b);
do
{
SOPln (“Hi”);
} NO Unreachable stmt
While (false);
SOPln (“Hello”);
do
{
SOPln (“Hi”);
}
while (true);
SOPln (“Hello”); Unreachable stmt.
69
final int a = 10;
final int b = 20;
do
{
SOPln (“Hi”);
} CTE
while (a<b);
SOPln (“Hello”); Unreachable
3. for loop :
The most commonly used loop.
If we know the no. of iterations in advance then we go for ‘for’ loop.
Eg : for (int i = 10; i < 10; i ++)
{
SOPln (i);
}
Syntax : for (initialization part; conditional check; inc/dec)
{
// loop body
}
3. Initialization :
Here, more than one variable of different data types r not allowed to declare.
Eg : int i = 10, j = 0;
int i = 0, int j = 0;
i.e. we have to declare all the variables of the same type and the data type must be
mentioned only one time.
i.e : int i = 0, j = 0;
int i = 0, int j = 0;
int i = 0, float f = 10.0;
As the initialization part, we r allowed to take any valid java statement, include
‘S.O.Pln’ also, but it is not conventional.
Initialization part is optional.
4. Conditional Expression :
As the conditional expression, we can give any expression but it should return
boolean value.
The conditional expression is optional and the default value is ‘true’. In case of
while & do-while there is no such concept of default value.
70
5. Increment / Decrement Part :
Here we r allowed to give any valid Java statement including SOP also.
Case 1 :
for (; ; ); (valid).
All the 3 parts of for loop and curly braces { } are optional.
for (; ; ); indicates infinite loop. (condition is always true)
Case 2 :
for (int i = 0; ; i ++)
{
SOPln (i);
}
SOPln (“Hello”); → (CTE unreachable stmtl)
Case 3 :
for (int i = 0; false; i ++)
{
SOPln (i); (CTE Entire loop body is unreachable)
}
SOPln (“Hi”);
Case 4 :
int a = 10; int b = 20;
for (int i = 0; a < b ; i ++) (because of i ++ no problem of type casting)
{
SOPln (i);
}
SOPln (“Hello”)
O/P : 0 1 2 ………
71
For – each loop :
1. Introduced in 1.5, more convenient loop for iterating elements of arrays and
collections.
Eg : int[ ] a = {10, 20, 30, 40};
for (int i = 0; i<a.length; a++)
{
SOP (a[i]); (older versions)
}
for-each
int[ ] a = {10, 20, 30, 40};
for (int x : a) (for each every element ‘x’ in a)
{
SOP (x);
}
The main limitation of for – each loop is that it can’t be used for general purpose
and it is applicable for arrays and collections.
Write code to display elements of 2-D array by using for-each loop.
int[ ] [ ] a = {{10, 20, 30, 40}, {50, 60}};
for (int [ ] x : a)
{
for (int [ ] y : x)
{
SOP (y);
}
}
Transfer Statements :
1. ‘break’ statement :
We can use ‘break’ in the following cases :
i. within the loops to come out of the loop
ii. In the switch statement to come out of switch block
iii. In the labeled block to come out of the label block
72
If we use ‘break’ other than in above mentioned cases, we will get compile time error
saying “break outside switch or loop”.
Eg : int x = 10;
if (x = = 10)
{
break;
}
2. Continue Statement :
We can use continue statement only in loops, to skip the current iteration and
continue for the next iteration.
Eg : int i = 10;
do
{
i ++; SOPln (i);
if (i<16)
Continue;
SOPln(i);
}
while (++i<20);
In the do-while, continue statement will shift the transfer to conditional checking.
Eg : int x = 10;
if (x > 10)
Continue; CTE : Continue outside of loop.
3. Labelled break and labeled continue :
In the nested loops, if we want to break / continue a particular loop; then we should
go for labeled break and continue statements..
L1 : for (---------)
{
---------
---------
L2 : for (---------)
{
---------
73
L3 : for (---------)
{
break L2;
continue;
}
}
}
Eg : L1:
for (int i = 0; i<5; i++)
{
L2:
for (int j = 0; j<5; j++)
{
if (i = = j)
break : //continue//break L1;
SOPln (i+ “……”+j);
}
}
74
III. Declarations & Access Control
75
class sample
{
P S V M (S[ ] a)
{
Array List a = new Array List ( );
}
}
CTE : Cannot resolve symbol
Symbol : Class Array list.
1. But how compiler knows that Array List is a class ?
A : Because in stmt (1), we r doing object creation and that object creation is always
done for a class. Hence that is why it is displayed as class AL.
Suppose if we give :
1 → Array List ( );
CTE : Can’t resolve symbol
Symbol : Method Array list ( )
76
IDE always use java.util.ArrayList but not
Java.util *
Instead of specifying fully qualified name every time, we can use import statements
once and the corresponding classes by short name (or) (by its own name only)
i.e. import statement is mean for typing short cut. It is not equal to c language
# include < > statement.
77
Date is present in both util & sql packages. Compiler finds ambiguous from
which package it has to take the date class.
Note : The same above problem may come in the case of ‘List’ also because it is
available in both java.util and java.awt packages.
Eg : import java.util.date;
import java.sql.*; / j.sql.date;
class test
{
P S V M (S[ ] a)
{
Date d = new Date( );
}
}
No CTE & RTE
(Even we use import….. *; all the classes won’t be loaded only the required
classes will be loaded)
Import statements totally effect or compile time not on runtime. I.e. more no. of
import statements will increase the time for compilation but no effect on time to run
(or) execute.
78
Illegal :
import java.util;
import java.util.Array List. *;
import java.util.Array List,
java. util.Date;
> java c verbose sample.java
Note : If we r using ECI, then the corresponding class files will be loaded even we
r not using those classes in our code.
U can seen them with the command
> javac – verbose <sample>.java.
Static imports :
- Math is a utility class which provides all static methods.
- This feature was introduced in 1.5 version. According to sun people, static imports
improves the readability of the code. But, world wide java experts r not accepting
this conclusion. It increases the confusion instead of readability. So, sun people told
that to not to use static imports not very frequently.
- Static imports can be used to import static members of a class. But this static
imports should be used only when it is compulsion.
- Usually, static members can be accessed by using class name. But, if we r using
static import, no need to use class name. i.e. static imports can be used for
importing static members of the class.
Eg 1 :
Class sample
{
P S V M(String[ ] args)
{
SOPln (math.sqrt(9));
SOPln (math.random( ));
}
}
79
Eg 2 :
import static math . ; (using static import) import static java.lang.math.;
class sample 2
{
P S V M(String[ ] args)
{
SOPln (sqrt(9));
SOPln (random( ));
}
}
The following static import statements r illegal :
Illegal :
1. Import static java.lang.math;
Reason : Static import should end with a method but not with a class name.
2. Import static java.lang.math.sqrt.*;
Reason : Either <method name> (or) * Should be there
If our class also contain a static method with the same name, then the local method
will get priority.
Eg : import static java.lang.integer.*;
import static java.lang.* ;
class sample
{
P S V M (String args[ ])
{
SOPln (MAX-VALUE);
}
}
CTE : Reference to MAX_VALUE is ambiguous.
Case 1 : In the above eg, declare a local static variable with name MAX_VALUE
⇒ Class containing our own static MAX_VALUE then local variable
will get the chance.
Case 2 : Among static imports the Explicit static import will get the precedence.
80
* import static java.lang.system.out;
class sample
{
P S V Main (S [ ] a.)
{
Out.Println (“Hi”);
}
}
O/P : Hi
Declaration of Packages :
Keyword :
Package com.durga;
Class sample
{
P S V M (S[ ] a)
{
SOPln (“Hi”);
}
81
}
Compiling :
> javac –d (destination . sample.java)
We can declare a package stmt. By using the keyword “Package”. Above eg.
Compilation :
If U use > javac sample.java
⇒ sample. class will be generated and placed in current working directory.
But if we r using package declaration, it is suggestible to place generated class file
in the corresponding package structure. We can achieve this by using –d flag of
javac.
> javac – d . sample.java
⇒ create sample. class in the current working directory inside a package
-d → specifies where to place generated class files ⇒ destination.
→ Current working directory.
If the needed package structure is not available, this command automatically creates
the required package structure.
Instead of , we can use C:
E:
D:
⇒ > javac –d C : sample.java ⇒ Need not be always.
The compiler can create needed folder structure but it cannot create destination
structure. If the specified destination is not available, we will get a compile-time
error saying : The system cannot find the path specified.
Eg : > javac –d z : sample.java. (error in writing)
Run :
> java com/durga/sample.
Hi >java com.durga.sample
Inside a java program, we r not allowed to get more than one package statement.
Violation leads to compile-time error.
Saying : “class” or ‘interface’ expected.
82
If we r not specifying any package statement, the generated class file will be placed
in the default package, which is nothing but “current working directory”.
The package, import and class statements must be placed in following order.
1. package statement – Atmost one
2. import statements – Any number
3. Class / interface declarations – Any
Conclusions :
i. Almost 1 package stmt is allowed and it must be the non-comment statement
in the program.
2. Class level access modifiers :
Once we r creating a class, we should specify some meaning f… information
(whether object creation is allowed or not) hid class creation is allowed) about our
class to the JVM. We can specify, this information by using the corresponding
access specified or modifier.
The only allowed modifiers, for the top level classes are :
i. public
ii. default
iii. final (top level classes & inner classes)
iv. abstract
v. strctfp
If we use any other modifier, we will get a compile-time error. Saying:
- modifier < modifier-name> not allowed.
Public :
Public classes :
1. If a class declared as public, we can access that class from anywhere ie within or
from outside the package or even from the N/W also . ⇒ from remote area also we
can access.
Eg : Package pack 1 ; Compile : >javac –d A.java.
/* Public */ class A
{
Public void M1( )
{
83
SOP (“In A’S M1”)
}
}
Package Pack 2;
// import Pack 1. A; Compile : >javac –d B.java.
class B
{
P S V M (S[ ] a)
{
A al = new A( );
A1.Ml( );
}
}
If class A in pack 1 is not declared as ‘public’, then while compiling class B, we
will get a CTE, Saying :
Pack 1. A in pack 1 is not public and cannot be accessed from outside package.
(Class A if not mentioned as public will be treated as default and default classes
can’t be accessed from outside the package).
Issue can be resolved by mentioning class A in pack 1 as public
Run : > java pack 2/B. O/P. in A’s M1.
Default Classes :
1. If a class is declared as the default, we r allowed to access that class from within
the package only, if we r trying to access from outside package, it results in
CTE.
2. Default access is also known as “Package Level Access”
3. There is no default keyword for class level modifiers. But “default” keyword is
there for switch statement.
Abstract Classes :
1. Would be used for good programming practice. Most used by real-time experts.
2. “abstract” is a keyword which can be applied for classes and methods. i.e we
can’t apply abstract keyword for variables.
3. If we don’t know about implementation of a method, still we r allowed to
declare such type of methods in our classes by using abstract modifier.
84
4. if a method is declared as abstract in a class, it indicates that we don’t know
about implementation, child class is responsible for providing implementation.
The following is the valid abstract method declaration
abstract int no of wheels ( );
5. ‘abstract’ is the term which never talks about implementation. Hence it is illegal
to combine “abstract” keyword with any of the modifier which talks about
implementation. So, the following combinations r illegal, in case of methods.
final
syncharized
abstract native
private
static
strictfp
The valid combination r : abstract → public, protected.
Concrete methods : Methods having body.
85
Eg : HhpServlet class is an abstract class which doesn’t contain a single
abstract method.
What is d use of creating HhpServlet as abstract class ?
8. If u don’t want to create an instance of the class, declare that class as abstract
class; whether it contains abstract methods or not.
9. Inside abstract classes we r allowed to keep constructors, i.e an abstract class
may contain constructors but the programmer is not allowed to create an object
of abstract class, but internally JVM is allowed to create an instance.
10. The 1st child class extending an abstract class is responsible to provide
implementation for all the abstract methods present in the parent class,
otherwise the child class should also be declared as “abstract”.
Final Classes :
1. ‘final’ is a keyword which can be applied for the classes methods and variables.
2. final methods :
If a method declared as final, we r not allowed to over side this method in the
child class violation leads to CTE.
Eg : Public class A
{
final public void M1( )
{
SOP (“A’s M1 Method”);
}
}
Class B extends A
{
Public void M1( )
{
SOP (“B’s M1 Method”);
}
}
CTE : M1( ) in B can’t override M1( ) in A.;
Overridden Method is final
86
If a class declared as final, then u r not allowed to create the child class. Violation
leads to CTE.
87
abstract void M1( ); final … void M1( );
} final void M1( ) { };
}
88
Member Modifiers
(Variable + Method)
1. Member Modifiers :
1) public 2) <default> 3) private 4) protected 5) native
6) abstract 7) strictfp 8) final 9) static 10) synchronized
Variable Modifiers :
1) Volatile 2) transient
Public Members :
If a method / variable declared as public, U r allowed to access that Method
(variable) from anywhere.
(But the corresponding class must be visible).
Eg : package pack1; package pack 2;
Class A import pack1.A;
{ class B
Public void M1( ) {
{ Public void M2( )
SOP(“M1”); {
} SOP(“M2”)
} }
>javac –d. A.java P S V M ([SC] a)
{
A a1 = new A( );
a1.M1( )
}
}
>>javac –d B.java
89
CTE : Can’t be accessed because class A is default and from outside package.
(Issue can be resolved by declaring class A is public).
Suppose class A is public but member M1( ) is not public then also we can’t
access we get CTE :
M1( ) is not public in pack 1.A; can’t be acened from outside the package.
⇒ A class member both should be declared as public to be act. essed from
outside the package.
Default Members :
If a member declared as default, we can access that member, within the current
package only i.e. if we r trying to access from outside package, we will get a
compile-time error.
Private Members :
If a member declared as private, we can access that member only in current
class, i.e. from outside the class if u r trying to access we will get a compile-
time error.
Protected Members :
If a member declared as protected, we can access that member within the
current package anywhere but in outside package, only in child classes we can
access.
So, Protected = <default> + kids.
(Default – within current package, Kids – within subclasses in outside package)
The most misunderstood modifier in java is ‘Protected’ (cattle sierra statement)
Eg 1 : Package Pack 1;
Public class A
{
Protected void M1( )
{
SOP (“M1 in A”);
}
}
Class B extends A
{
P S V M (SC) args)
{
90
A a1 = new A( );
a1.M1( ); // M1 in A
B b1 = new B( );
b1.M1 ( ) // M1 in A
A a2 = new B( );
A2.M1( ); //M1 in A
}
}
Eg 2 : II
Package Pack 2;
I
1. result in CTE : M1( ) has protected access in pack 1.A;
2. No CTE
3. result in CTE
Conclusion :
If u want to access protected member, within the current package either by
using parent class reference (or) by using child class reference.
But from outside package if u want to access protected member, we should
access by using child class reference only.
i.e. by using parent class reference we r not allowed to access protected
members from outside package. Violation leads to compile-time error.
If we place class B in pack 1 all combinations are legal.
Summarization table :
Visibility Private <default> Protected Public
within the class YES YES YES YES
within the current
package either from NO YES YES YES
91
It is recommended (by default) that declare data members as private and the
methods as public.
‘final’ Variables :
1. ‘ final’ instance variables :
i. Instance variables generally will get default values, but final instance variables
won’t get any default values.
Eg : class test
{
final int i ;
P S V M (S[ ] a)
{
test t = new test( );
SOP (t.i);
}
}
CTE : Variable ‘i’ might not have been initialized.
ii. Whether we r using or not, for the final instance variables, we should perform
initialization, otherwise CTE.
iii. Initialization for the final instance variable may be completed “before object
creation”. i.e. we can perform initialization for the final instance variables in one of
following places.
a) At the time of declaration
b) Inside contractor
c) Inside instance initialization block
(will be executed before executing constructor only. before creating object)
They r :
final int i = 10;
test ( )
{
i = 10;
}
{
i = 10;
}
92
2. final static variables :
i. Static variables generally get default values. But final static variables won’t get
any default values.
ii. Whether we r using or not we should perform initialization for the final static
variables, otherwise CTE.
Eg : class test
{
final static int i;
P S V M (S[ ] a) { }
}
CTE : variable ‘i’ might not have been initialized.
static blocks will execute during class coding into memory
iii. the final static variables must be initialized before the class loaded into the
memory. i.e. in the class loaded into the memory. I.e. in one of the following
places, we can perform initialization :
a) At the time of declaration;
final static int i = 100;
b) Inside static block;
final static int i;
static
{
i = 100;
}
(main( ) method executes after. Class loaded into memory)
(final static variables must be initialized before class loaded into memory)
3. final local variables :
i. Local variables won’t get any default values, we should perform initialization
before using that variable.
ii. Even though the local variable declared as the final, there is no need to perform
initialization until if we r not using the local variable.
Eg : P S V Main( ) PSVM( )
{ {
final int i; final int i;
} SDP (i);
}
No CTE CTE
93
iii. For the local variables, the only allowed modifier is “final”. if v r using any
other modifier we will get a compile time error.
Saying : illegal start of expression
iv. formal arguments :
The variables which are declared as the arguments of a method are simply act as
local variables of that method.
We r allowed to declare a formal parameter as final. If it is declared as the final,
then v r not allowed to perform any reassignment within the method.
Eg 1: class test
{
public static void M1(int ‘i’ int ‘j’)
{ (I = local variables) (J = formal arguments )
SOP (i); SOP (j);
}
P S V M (S[ ] a)
{
M1 (100, 200);
}
}
Eg 2: class test
{
public static void M1(final int i, int j)
{ (formal parameter as final)
i = 10;
j = 20;
SOP (i); SOP (j);
}
P S V M (S[ ] a)
{
M1 (100, 200);
}
}
CTE : final parameter I may not be assigned.
94
Static :
i. “Static” is a keyword, which can be applied for variables and methods. We can’t
apply static keyword for the top level classes but we can apply for inner classes.
(Such type of inner classes are called static nested classes).
Necessity of static :
Class student
{
String name : → Instance variables
Int rollno;
Static String College – name; → static variables
}
Conclu :
In the case of instance variables, for every object a separate copy will be
created. But in the case of static variables, a single global copy will be creates
and shared by all instances.
Eg: class test
{
int i = 10;
static int j = 20;
P S V M (String[ ] args)
{
Test t1 = new test ( );
t1.j = 100;
t1.j = 200;
Test t2 = new test ( );
t2.j = 300;
t2.j = 3000;
SOPln (“t1.i + “…….” +t1.j);
SOPln (“t2.i + “…….” +t2.j);
}
}
95
Disadv of Static :
As all the objects are sharing single global copy of the static variable, if any object
changes its value (by using ob; ref), that changed value will be reflected for all the
objects. Hence, security is the major problem in the case of static variables.
Hence, there is no thread safety for the static variables. To overcome this problem,
usually static variables always associated with “final” keyword.
Eg: class test
{
int i = 10;
P S V M (String args [ ])
{
SOPln (i);
}
}
CTE : non-static variable ‘i’ cannot be referenced from a static context.
Static members can be referenced from anywhere i.e. either from static or
instance area but non-static members can be accessed only from instance area.
Eg : Consider the following 4 declarations :
i) int i = 10;
ii) static int i = 10;
iii) public void M1( ) {SOPln (i)};
iv) public static void M1( ) { SOPln (i)};
Which of the following 2 is allowed within a single class :
a) i & iii b) i & iv c) ii & iii d) ii & iv
(instance var can be accessed from instance method).
CTE : instance non-static variables, can’t be referenced from static context.
(static variables can be referenced from anywhere)
“Static” is nothing but utility and can be used from anywhere by anyone.
“Static” means complete implementation available but ‘abstract’ means no
implementation available. Hence static, abstract combination is illegal in the
case of methods.
96
Eg : class P > javac p.java
{
P S V M(S[ ] a) p.class d.class
{
SOPln (“parent main”); > java p
} parent main
} > java c
Class C extends P { }; parent main
⇒ The static methods can be inherited only main method will be executed but
any stmtsl…. Present in child class won’t be executed.
We can’t override static methods. It seems to be overriding applicable but it is
method hiding ⇒ changing the implementation of a class by using other classes
makes no sense.
But overloading applicable for the static methods.
⇒ Inheritance
Overriding (explanation later)
Overloading
Transient : (Interviews)
1. “transient” is the keyword which can be applied only for variables. We can’t
apply transient for methods and classes.
(Process of saving object (values in object) into a file is known as serialization.
If we don’t want to store some of the values of object into a file we go for
transient).
2. transient means → not to serialize i.e. while saving the state of object to a file,
(this process is called serialization) JVM ignores the values of transient
variables. Instead of original value, JVM stores default values.
Eg : class account
{
string accname;
string accno;
string UID;
string PWD;
}
97
OOS FOS
i = 10 → i = 10
j = 20 j = 20
Sample S abc.tx+
OIS FIS
i = 10 ←
j = 20
abc.tx+
OIS.read Object( ); → return object.
The process of getting (reading) an object from a file is called “De Serialization”.
98
SOPln (t1.i + “…..” +t1.j); // 10…..20
} (same as before)
} // 10……. 0 (j-tray)
// 0……0 (I,j-tray)
Before After
Serialization Serialization
1. int i = 10; i = 10;
int j = 20; j = 20;
2. transient int i = 10; i = 0;
int j = 20; j = 20;
3. transient int i = 10; i = 0;
transient int j = 20; j = 0;
4. transient static int i = 10; i = 10;
transient int j = 10; j = 0;
5. transient final int i = 10; i = 10;
transient int j = 20; j = 0;
6. transient static int i = 10; i = 10;
transient final int j = 20; j = 20;
“Native” Modifier :
1. “native” is the keyword which can be applied only for methods. i.e we r not allowed
to use native keyword for the classes and variables.
2. If a method is implemented in non-java (like C, C++ mostly) is called native
method (or) foreign method.
In olden days, java is performance very poor when compared to C/C++. But later
because of advs of Java slowly shifting to java. But now also performance wise not
that much good.
99
Now – a days 10% real-time projects are with C/C++ with Unix called open
systems, - C/C++ code is M/c understandable in a higher level than compared to
Java.
Native keyword is breaking Java’s p/f independent concept.
Java code is easily understood by pgmgs when compared to C code but perf wix
slow and java pgm should be converted to .class 1st and then to .exe files.
3. The main objective of using native keyword in java is i) to improve performance of
the ii) to communicate with language code, (using code developed in any lang. as it
is)
4. The use of native keyword breaks p/f I feature of java.
5. Pseudo code for using native libraries in java :
If want to lodd some libraries during the time of loading the class, we put it in static
block.
Class native
{
static
{
System.loadlibrary (“Native Library Path”);// load native libraries.
}
native void M1( ); // native method declaration.
} (Implementation is already there)
class client
{
P S V M (S[ ] a)
{
Native n = new Native ( );
n.M1( ); // invoking a native method.
}
} (We can do this in the same native class also)
6. ‘native’ method means – implementation is already available, but abstract method
means implementation is not available, child class is responsible for
implementation. Hence, native and abstract combination is always illegal for
methods.
7. The ‘native’ and ‘strictfp’ combination is also illegal for the methods. - follows
IEEE 754 standards but may or may not IEEE 754 stds.
8. We CAN OVERRIDE !!! a native method. It is recommended to override a native
hash code method available in the object class.
9. Inheritance & overloading possible for native methods.
100
Synchronized Keyword
1. “Synchronized” is the keyword which can be applied for methods and blocks. i.e we
can’t apply synchronized keyword for a variable and class.
2. If a method declared as synchronized, at a time only one thread is allowed to
execute, that method on the given specified common object.
3. Adv. Of synchronization :
i. Security
ii. Prevent data corruption and increase data consistency.
Disadvantage :
i. It slows down the and results low performance.
Until & unless required don’t go for synchronized like final.
Interfaces
1. What is an I ?
2. Importance of an I ?
3. I declaration
methods in I declaration
variables declaration
4. Tag or marker interfaces
5. Interface Naming conflicts.
101
1. What is an I ?
1. From the client point of view an I, defines set of services what the client is
expecting.
2. From the service provider point of view an I defines the set of services what
service provider is providing.
Hence an I is nothing but contract b/w the client and service provider.
Advantages :
1. Security : As we r not highlighting our internal implementation, outside person is
not able to iee or get the internal formulae.
2. Enhancement is very easy
⇒ without effecting outside person, we r allowed to check our internal
implementation.
As the I doesn’t contain any implementation, it is considered as
100% pure abstract class.
Declaring an (I) :
Eg : interface transferable
{
public void transfer( );
}
⇒ we can declare an interface by using “interface” keyword.
The allowed modifiers for the top level interface are :
Public, <default>, abstract & strictfp.
Implementing an interface :
1. We can implement an (I) by using implements keyword. The class which
implements an interface must be responsible to provide implementation for all
the interface methods, otherwise the class must be declared as abstract violation
leads to CTE.
2. In the implementation class, every interface method must be declared as the
public.
102
Eg : class test implements transferable 1
{
public void transfer ( )
{
;;;;;;
}
Interface variables :
1. Whether, we r declaring or not every interface variable by default public static
and final. ie. The following variable declarations inside an interface are equal.
Int x = 10;
Public int x = 10;
Final int x = 10;
Static int x = 10;
Public static final int x = 10;
2. Because there is no concept of object creation for an interface, there is no
concept of transient.
3. As the interface variables r by default public, static final we r not allowed to
declare an interface variable by using the following modifiers.
Private, protected, volatile, transient etc.
103
Exercise :
1. int i = 10;
2. int i ;
(default values r not applicable for final static, initialization must be done)
3. volatile int i = 10; CTE : ‘----‘ expected.
4. Transient int i = 10;
5. Public final static int i = 10;
6. Private final static int I = 10;
Note : Inside an interface, for the variables we should perform initialization at
the declaration time only. otherwise compile time error.
Static { } r not allowed in interfaces.
4. All the interface variables, by default available in the implemented classes, but
they will get only read access. The implemented class is not allowed to change
the value of interface variables, violation leads to CTE.
Eg : interface x
{
int i = 10;
}
class test implements x
{
P S V M (S[ ] a)
{
i = 100; // CTE
SOP (i);
}
}
CTE : Cannot assign a value to the final variable ‘i’
- A class can extend only one class at a time, but an interface can extend any
number of (I)s.
- A class can implement any no. of interfaces, but an interface can’t implement
any interface.
104
1. After installing jdk 1.5/1.4, type javac in and prompt. If U get “bad command”, then
type set path = “c:\jdk1.4\bin”. Type again javac.u% get it
<path where jdk installed>
2. The above process has to be repeated every time U closes & opens the command
prompt which is a tedious process.
3. To avoid this, My computer properties → Advanced tab <my name>
→ Environment variables → User variables for pandu
→ New variable → Variable name : Path → O.K → O.K.
Variable value : C:\jdk1.4\bin.
Now, no need of repeating 1) every time cond prompt opens. Koooooo1…..
The variable name should be : path (irrespective of case) no other name is allowed.
Note : 1. No need, of setting this path in system variables if U have set in user
variables.
2. Otherwise (i.e. if U didn’t set in), in system variables there will be a variable
‘path’ by default click eqlit button after clicking (selecting) variable.
3. In that, variable name : path
variable value : …… ; c:\jdk1.4\bin
o.k → o.k.
4. This will also result in the same.
5. No need of setting path in both variables.
Case 1: If 2 interfaces contain methods with the same signature and same return type
in the implementation class one method implementation is enough.
Eg : interface Left {void M1( );}
interface Right { void M1( );}
Class Test implements Left, Right
{
Public Void M1( ) { }
}
105
Case 2: If 2 interfaces contain methods with the same names, return type but with
different signatures implementation class has to provide implementation for
both methods.
Eg : interface Left {void M1( );}
interface Right { void M1(int i );}
Class Test implements Left, Right
{
Public Void M1( ) { }
}
(Methods implementation is required)
Signature → Method name followed by arguments.
Case 3:
Eg : interface Left {void M1( );}
interface Right { int M1( );}
Class Test implements Left, Right
{
Public Void M1( ) { }
Public Void M1( ) { }
106
If 2 (I)s contain the same variables, in the implementation class we can distinguish
by using interface name.
1.5 Features
107
Variables :
The variable names r usually nouns at class level starts with lower case letter and
then normal camel case follows.
Eg : balance, bandwidth, customer name…. etc.
Constants :
Usually we can declare constants with static and final keywords. All the letters must
be in capital and if it is a multiple words, the words r separated with ( ).
Eg : MAX – VALUE
MAX – PRIORITY
MIN – PRIORITY
Java Bean Standards :
1. Java Beans are simple java classes that have private properties. We can access the
private properties by using getter and setter methods.
Syntax of getter method :
Public <return type of property> get <property name>( )
(should start with a capital letter)
- It should be public.
- It the property is not Boolean, the prefix of the method name must be get followed
by property.
Eg : Public String get Name( );
- If the property is Boolean, we may use either get (or) is as the prefix.
Eg : public Boolean is Empty ( );
- For the getter methods, we should not pass any arguments.
108
Java Bean Class :
Class Student Bean
{
Private String name ; (Properties must be private)
Private int rollno;
Public string get Name ( ) (Setter & getter must be public)
{
return name ;
}
Public void set Name (String name) (Setter & getter must be public)
{
this.name = name;
}
}
Var-arg Methods:
Eg : If there is a sum method with 2 args, then we can call it with sum (10, 20). If 3 nos.
are there to add we should create another sum method with 3 args and so on… to
avoid this we go for var-arg.
109
1. This concept was introduced in 1.5 version, we can declare a method that can take
variable number of arguments which is called var-arg method.
Eg : M1(int…a)
Calling M1: M1( ); M1(10); M1(10,20,30) any no.
WAP by using var-arg method for printing the sum of any number of integers.
Class test
{
public static void sum (int….a)
{
int total = 0;
for (int x : a)
{
total = total + x;
}
SOP (“Sum is:” + total);
P S V M (S[ ] a)
{
Sum ( ); // Sum is : O
Sum (10);
Sum (10, 20);
Sum (10, 20, 30);
}
}
By using var-arg method display the elements of 2-D array : (single-D array of another 1)
Class test
{
public static void meth (int[ ]….x)
{
for (int[ ] y : x)
{
for (int z : y)
{
SAOPln (z);
}
110
}
}
P S V M (String[ ] args)
{
int( ) a = {1,2,3,4};
int( ) b = {4,5,6};
(a,b); (both r 1-D arrays)
}
}
Conclusions :
1. We should keep… after the type only not after the name of the variable.
i.e. Sum (int[ ] a) = sum (int a[ ])
↓
equals to
Sum (int… a) = Sum (int + a….) (bade syntax)
2. We can mix a normal argument with var-org arguments. But in that case, the var-
arg parameter must be the last parameter.
i.e. Sum (float f, int….a);
Sum (int….a, float f);
3. We can’t keep more than one var-arg parameter in var-arg methods.
i.e. Sum (int… a, int….b);
Sum (int… a, float….f);
Exercise :
1. Void M1 (int….a){ }
2. Void M1 (int a…){ } (Bad syntax)
3. Void M1 (float f, int….a){ }
4. Void M1 (int….a, flat f){ }
5. Void M1 (double d float….a, char…ch) { }
4. Eg : class test
{
P S V M1 (int I)
{
111
SOPln (“General Method”);
}
P S V M1 (int…a)
{
SOPln (“var-arg method”);
}
P S VM (String[ ] args)
{
M1( ); // Var-arg
M1 (10); // General – method
}
}
112
I. Data Hiding :
1. It means, the data should not go out directly. We can achieve this by declaring
data members as private. (providing security)
2. The outside person is allowed to access data through methods only.
II. Abstraction :
1. Hiding implementation details is called “abstraction”.
Eg : Generation of a car 1.men 2. rod. 3. key 4. touch screen only by owner.
Abstraction may be comfortable but too much cause – ve serve.
Advantages :
1. As we r not highlighting our internal implementation; we can get more
security.
2. Without affecting outside word, v r able to change internal implementation.
Hence, enhancement is easy.
We can achieve abstraction by providing a public interface for the end user.
Eg : Keyboard is an interface for us, the internal implementation is always hided
113
Tightly Encapsulated Class :
1. A class is said to be tightly encapsulated if and only if all the data members are
declared as “private”.
Eg : which of the following classes r tightly encap sulted ?
i. class x
{
private int i = 10; (Tightly encapsulated – data member declared as private)
public int get i ( )
{
return i;
}
public void set i (int i)
{
this. i = i;
}
}
ii. class x
{
private int i = 10;
public void set i (int i)
{
this. i = i;
}
}
(Outside person can’t access (i) directly i.e. data not going out directly
⇒ tightly encapsulated)
iii. class x
{
private int i = 10;
}
class y extends x
{
int j = 10;
114
}
(class y is not T.E. – there is no rule that if parents is T.E., Child also has to
be T.E., - Y data member is not P.Vote it is not T.E.)
iv. class x
{
int i = 10; x is not T.E.
}
class x extends
{
private int j = 20;
}
class z extends
{
private int k = 30;
}
(Y is extending x, the non-private data of x is available to ‘y’ also)
(Generally in java class itself indicates encapsulation)
Conclusion :
If the parent is not tightly encapsulated then no child class is tightly encapsulated
Note :
The protected member is available to the child class directly but not at all available
to its sub child classes.
115
string sleep( )
}
Eg 2: class SWEngg extends person
{
string devignation;
float salary;
float code ( );
float dance ( );
float play ( );
float sleep ( )
}
Eg 3: Amitab
↓
Abishek → Suggestible
↓
Chetab
Eg 4: A – has 10 methods
↓
B – 12 (10 + 2)
↓
C – 12 (10+2+1)
↓
D
↓
E
↓
F
↓
G
We think ‘C’ has all the methods and it is advs. This is tve side
But –ve side is : To create child class obj all its parent class objs have to be created,
but obj. creation is always.
Costliest ⇒ performance issue.
116
4. According to real-time coding standard, 8-10 levels of inheritance is acceptable,
beyond that it is not suggestible because it may create performance problems;
for every child class object creation all the parent class objects we have to
create.
Eg : class parent
{
public void M1( )
{
SOPln (“parent”);
}
}
Class child extends parent
{
Public void M2( )
{
SOPln (“Child”);
}
P S V M (String args[ ])
}
117
}
(Parent class ref. Can hold child clan obj but by using that ref we can’t call child
clay specific methods.)
(Child class ref can’t hold parent class object)
Conclu :
1. The parent never aware of child-class specific.
Methods. Parent.M2( );
2. Child aware of all the parent class methods.
Child.M1 ( );
3. Child class reference can never hold parent class object.
Child C = new parent ( );
4. The parent class ref can be used to hold child class instances. But by using that
reference we r allowed to call only parent class methods. We r not allowed to call
child class specific methods. Violation leads to CTE.
If parent class method is overridden in child class, and if v calling that parent
method with children clan reference then the overridden method is executed but not
the parent clan method.
118
4. HAS – A relationship increases the dependency between components which
results in maintenance and enhancement problems.
Eg : without engine there is no car ⇒ dependency
Eg : class sample
{
P S V M (String[ ] args)
{
system out print in (“Kiran”);
}
}
Method Signature :
In C, C++ method signature refers to return type + method name + arguments list.
Eg ; Void M1( )
1. In Java, method signature consists of method name followed by arguments
(the order of arguments is also important) Eg : M1( )
Eg : Public Void M1( ) Meth. Signature → M1( )
Public int M2 (int i, float f) → M2 (int i, float f)
Note : Return type is not part of method signature in java.
2. class test
{
P Void M1( ) { }
P void M2 (int I) { }
P void M3 (int I, float f) { }
}
For the above class, compiler creates a table containing method signatures.
Test:
1 M1( )
2 M2 (int)
3 M3 (int, float)
class client
{
P S V M (S[ ] a)
{
119
Test t = new Test( );
t.M1( ); → compiler checks;
t.M2(10);
t.M3(23);
}
(CTE : can’t resolve symbol M3 (double) method signature)
(‘t’ which class ref – test then it cheking M1( ) signature in table, if it
matches the corresponding method is executed).
3. 2 methods with same signature is not possible in Java. Violation leads to
compile time error. (Because compiler finds it ambiguous which method has
to be executed).
CTE : M1() is already defined in test
Class test
{
P V M1( ){ }
P int M1( ) { } return 10;
}
4. In order to link method calls with corresponding implementations, compiler
checks the method signature.
Overloading :
1. Overloading & overriding, both comes under polymorphism.
In C, to find absolute value of an integer we have a method abs (int).
To find abs value of long int we can’t use we have labs (long int) for floating point
abs value fabs (float f)
⇒ For every data types we have separate type we have to remember all the in.. &
code is complex. It is because 2 methods with same signature is not possible.
This problem is resolved in oops by using over OR.
2. In C, 2 methods with same name is not allowed.
Eg : If u want to find absolute value we have the following methods:
abs ( ) – int
labs ( ) – long
fabs ( ) – float…etc
For every data type, declaring anew method is always problem and it increases the
complexity of the programming.
120
3. To resolve this, in the object oriented pgmg we can declare more than one method
with the same sname (which is nothing but method over leading) so that the
programming becomes very simple:
Method Overloading :
1. Two methods with the same method name but different arguments (atleast order) r
said to be over loaded methods.
2. In case of overloading, the method names must be same, the arguments list must be
different, never consider return type/access modifiers throws clause.
Eg 1 : class test
{
P V M1( ) { SOPln (“No arg”);}
P V M1 (int i) { SOPln (“inte”);}
}
CTE : P V M1( )
P int M1( )
Eg 2: class test 1
{
P V M1( ) { SOPln (“No arg”);}
P V M1 (int i) { SOPln (“inte”);}
P S V M (S[ ] args)
{
Test 1 t1 = new test ( );
t1.M1( ); // No-arg
t1.m1(10); // Inte
}
}
121
3. Compiler is checking (or) resolve methods based on reference type (not based on
runtime objects) in case of overloading, which is also known as “Compile-time
resolution of overloaded methods.
122
P V M1(String S) {SOPln (“String Version”);}
P V M1(Object O) {SOPln (“Object Version”);}
P S V M(S[ ]a)
{
Test t = new Test ( );
t1.M1(‘Pandu’); // String Version
t1.M1(‘new Object( )); // Object Version
t1.M1(‘new Thread( )); // Object Version,
Thread is implicitly promoted to object.
t1.M1(null); // NO CTE. O/P : String Version
}
}
Case 2 :
Class test
{
P V M1(int i, float f)
{
SOPln (“int, float”); Perfectly Overloaded.
} (Only order of arguments is changed)
P V M1(float f, int i)
{
SOPln (“float, int”);
}
P S V M (S[ ] a)
{
test t = new test ( );
t1.M1(10, 10.5f); // Int, Float
t1.M1(10.5f, 10); // Float, Int
t1.M1(10, 10); // CTE : Ambiguous reference to M1 is ambiguous.
}
}
123
int, float float, int int, int
t.M1 CTE float, int int, int
(10,10)
124
P S V M(S[ ]a)
}
Conclu : In case of overloading, the compile resolves the method call based on
reference type not based on run-time objects.
Overriding :
Eg : Class Father Class child extends father
{
Gold
Land Available
Money
Subbu( ) {different implementation}
}
1. Whatever the parent has by default available for the child classes. If the
child class doesn’t want to use a particular method of the parent class it
is allowed to provide its own implementation by overriding parent class
method.
While overriding we have to follow certain rules :
Overriding Rules :
1. Method names and the argument list order also must be same. i.e.
signature of the methods must be same.
Eg : Class P Class C extends P
{ {
125
Public Void MIC Public Void MIC
------- {
------- ------- ⇒Overriding
} -------
}
}
2. If parent class method, doesn’t want to allow child class to override,
declare that as ‘final’ (security purpose).
The final methods cannot be overridden.
Eg : Class P Class C extends P
{ {
Final Public Void M1( ) Public Void M1( )
{ {
SOP(“Parent”); SOP(“Child”);
} -------
} }
}
CTE : M1 in C can’t override M1 in P; Overridden method is final.
126
Eg :
Class P
{
Public Void M1( ) {SOP (“Parent”);};
}
Class C extends P different return types.
{
Public int M1 ( ) {SOP(“Child”);}
}
127
{
return “Kiran”;
}
}
A
Overriding
Not B (Child of A)
overriding Overridding
C (Child of B)
8. While overrding, weakering the access specifier is not allowed.
Violation leads to CTE.
Parent : Public Protected Default Private
Child : Public
Protected
Default
Private
Note : Same Private methods in parent, child class r not considered as
overridden methods but treated as separate methods.
Eg :
Class P
{
Public Void M1( ) CTE :
{ M1( ) in C cannot
SOP(“Parent”); Override M1( ) in
} P Attempting to
assign
} weaker access pri vileges;
Class C access decreased was public.
{
Private Void M1( )
{
SOP(“Child”)
}
128
}
Exceptions in Overriding :
1. The exceptions which r checked by compiler for smooth execution of the
program at run time r called “Checked Exceptions”
The exceptions which r unable to check by the compiler r called “unchecked
Array IOOBE Arithmetic Exceptions”
2. Error and its subclass r considered as
Runtime Exception and its subclasses unchecked exceptions
and all the remaining by default considered as checked exceptions.
3. Whether an exception is checked or unchecked it is always occur at Run-time
only.
4. Checked Exceptions r again divided into partially checked and fully checked.
A checked exception is called fully checked exception if and only if all its child
classes also checked other wise considered as partially checked exception.
Eg : for fully checked : IO Exception
Eg : for partially checked ; Exception
1. In the case of overriding v r not allowed to increase the size of the checked
exceptions. But there is no rule for unchecked exceptions.
We can decrease (or) remain same the checked exception.
129
Import java 10-*;
Eg :
Class P 1 throws IO Exception
{ 2 throws IO Exception
Public Void M1( ) 3 throws IO Exception
{ 4 Exception
SOPln(“Parent”); 5 throws IO Exception
} 6 throws IO Exception
}
Class C extend P 1 throws IO Exception
{ 2 throws IO Exception
Public Void M1( ) 3 throws IO Exception
{ 4 throws IO Exception
SOP(“Child”) 5 throws IO Exception
}
} 6 throws IO Exception
> javac c.java
2. Results in CTE :
(The size of checked exception is increased)
M1( ) in C can’t override M1( ) in ‘P’; overridden method does not throw
java.lang. exception.
130
class C extends P
{
Void M1( ) { }
}
Eg2 :
Class P
{
void M1( ) { }
} non-abstract to abstract (SUPERUUU)
abstract class C extends P
{
abstract void M1( );
}
5.
Class P
{
Public Void M1( )
{
SOPln (“Parent”);
}
}
Class C extends P
{
Public Void M1( )
{
SOPln (“Child”);
}
P S V M (String[ ] args)
}
Case 1 : P P1 = new P( );
P1.M1( ); // Parent
Case 2 : C C1 = new C( );
C1.M1( ); // Child
131
Case 3 : P P = new d( );
P.M1( ); // Child
/* Note : Parent class reference can hold child class instance. At compile time
compiler checks the reference type P and checks whether M1 ( ) is
present or not if not them CTE once it is satisfied, later at rum-time JUM
checks which run-time (child class) object is that, once it is decided
whether method M1( ) is overridden, then child class method is called,
it not a then parent class method is executed because parent class
members r by default available for child class */
In case of overriding, the method resolution taken case by JVM based on
run-time object this process is also known as :
“Dynamic method dispatch” (or)
“Dynamic Polymorphism” (or)
“Runtime Polymorphism” (or)
“Last binding”.
132
}
SOP (“Child”);
}
P S V Main (String[ ]args)
{
P P1 = new C ( );
P1.M1( ); // Parent
Note : If it is overriding, child class method has to execute, since it is
method hiding parent class method is executed.
133
5. Return type No restrictions Must be same until 1.4 /
from 1.5, covariant return
types also allowed.
Class B
{
Public Void M1( ) { }
}
Which of the following methods r allowed in the derived class ?
1. Public void M1 (int i) { } Overloading
2. Private void M1 (double d) throws exception overloading
3. Public void M1 ( ) { } overriding
4. Private void M1 ( ) { } CTE : M1( ) is already declared.
5. Public void M1( ) throws AE { } Overriding
134
{
M1( );
SPOln (“First Static Block”);
}
Public Static Void Main (String[ ] args)
{
M1 ( );
SOPln (“Main Method”);
}
Public Static void M1( )
{
SOPln (j); // j = 0 // j = 20
}
Static
{
SOPln (“Second Static Block”);
}
j = 0 (RIWO) static int j = 20;
}
NO CTE, RTE
O/P : 20 (Mine)
FSB
SSB
20
Main Method
135
SSB
20
Main Method
Note : ⇒ Variables can be declared at the last place (or) any where.
Static blocks r executed while class is loading in to the memory.
Eg : After loading driver registering the driver stuff is written in static block
of the driver class.
1. Load driver, 2. Connection, 3. State, 4. Execute, 5. Result set
Static blocks :
1. Syntax : Static { }
2. Static blocks executed while the class is loaded into the memory.
3. If u want to perform any activity while can be executed while loading the
class that activity should be defined inside static block.
Eg1 : Loading native libraries must be performed while the class is loaded into
the memory. Hence this activity should be declared inside static block.
Eg2 :Registering database driver with Driver Manager can be performed by
executing static block available in driver class.
1. If a variable is just identified by JVM but the proper explicit assignment not
takes place then that variable is in the mode of RIWO (State – Read Indirectly
Write Only) and assigned with default values.
If a variable is in RIWO State, we r not allowed to perform read operation
directly, violation leads to compile – time error saying :
Illegal forward reference.
Eg.1 : Static
{
// M1( );
SOP (j); // SOP (Base.j);
SOP (“First Static Block”);
}
2. Later variable comes into R&W State, then we can read & write values
directly.
Eg.2 : Static
{
// M1( );
136
SOP (i);
SOP (“First Static Block”);
}
3. Static blocks should be declared only at class level, but shouldn’t be declared
inside methods.
Printing a statement to the console without using main( ) and static block.
Class Google – 3rd - Round
{
Static int i = M1( );
P Static int M1( )
{
SOPln (“Hi I can Print….”);
return 10;
}
}
O/P : Hi I can Print….
No Such Method Error.
Class Base
{
Static int I = 10;
Static;
{
M1( );
SOP (“Base Static Block”);
}
P S V M (S[ ] a)
{
SOPln (“Base Main Method”);
}
P S V M1( ) {(SOPln ( j ); }
Static int j = 20;
137
}
Class Derived Extends Base
{
Static int x = 100;
Static { M2( );
SOP (“Derived First Static Block”);
}
P S V M (S[ ] args)
{
M2 ( );
SOP (“Derived Main Method”);
}
P S V M2 ( )
{
SOPln ( y ); y = 0; y = 200;
}
Static
{
SOP (“Derived Second Static Block”);
}
Static int y = 200;
@ : Whenever Derived class is loaded ⇒ base class
should also be already loaded.
Save : Derived. java
Compile : Derived. Class
Base.class
Run : java derived
O/P : O Correct O/P :
DFSB O
DSSB Base SB
200 O
D Main Method Derived FSB
Derived SSB
200
Derived Main
138
Flow :
1. Identification of static members from parent to child (I) to (II)
2. Execution of static variable assignments and static blocks from. Parent
3. Executive of Derived class main method.
Case 1: Suppose in the derived class if there is no main method, then the parent class
main method will execute because static members can be inherited.
Case 2: > java base 1
O/P : O
Base static block
Base Main Method.
⇒ Derived Class won’t be loaded.
139
}
P S V M(String[ ] args)
{
Parent P = new Parent( ); // of Case (ii)
SOPln (“Main Method”);
Parent P1 = new parent( );
}
P V M1( )
{
SOPln (j);
}
{
SOPln (“Second Instance Init Block”);
}
int j = 20;
}
140
FIIB
SIIB
Constructor
Flow :
1. Whenever we r creating an object, the instance control flow will start. For
every, object creation instance control flow will be repeated.
The following is the sequence of events in the instance control flow :
a. Identification of instance members of the class. (From T to B)
b. Execution of instance variable assignments and instance blocks
(From T to B)
c. Execution of the constructor. (That is why object creation is costliest)
d. Main Method.
141
M2( );
SOPln (“Child First Instance Init Block”)
}
Child ( )
{
SOPln (“Child Constructor”)
}
P S V M(String[ ] args)
{
Child C = new child( );
SOPln (“Child Main Method”)
}
Public Void M2( )
{
SOPln (y);
}
{
SOPln (“Child SIIB”); int y = 200;
}
}
Flow :
a. Identification of instance members from parent to child.
b. Execution of instance variable assignments and instance blocks only in parent
class.
c. Execution of parent class constructor.
d. Execution of instance variable assignments and instance blocks in the child
class.
e. Execution of child class constructor.
> java child
O/P : O
PIIB
P Constructor
O
CIIB Repeats for every child object creation.
CSIB
C Constructor
Main Method
142
Suppose if parent class one more parent & etc. suppose there r 8 levels the for
creation of child obj all remaining parent class objs should be created
⇒ performance problem.
Exercise :
What is the O/O when u compile & run the following code ?
Public Class Myclass
{
P S V M (S[ ] args)
{
My Class Obj = new My Class (i)
}
Static int i = 5;
Static int l;
Int j = 7;
Public Myclass (int M)
{
SOP(i+”,” + j + “,” + k + “,” + l + “,” + m);
}
{
j = 70; // Instance initializer block
l = 20;
}
Static
{
i = 50; // Static initializer block
}
}
O/P : 50, 70, 0, 20, 0
Trace :
i = 0 (RIWO)
l = 0 (RIWO)
i = 5 (R/W)
i = 50
My class (0)
J=0
143
k=0
j=7
j – 70
l – 20
144
Static String M = MSG(“1”);
{
M = MSG (“2”);
}
Static
{
M = MSG(“3”);
}
P S V M (String[ ] args)
{
Object obj = new Initialization ( );
}
}
Constructors :
Eg : Class Student
{
String Sname;
int rollno;
P S V M (S[ ]a)
{
Student S1 = new student( );
}
}
* For any no of objects, the sname is null and roll no is ‘O’, which is clumsy, i.e.
creation of obj is not enough initialization is also req. to provide proper service.
1. Creation of object is not enough, we should perform initialization, then only the
object can able to provide service for the remaining objects.
/* So where we can initialize ?
1. At the time of declaration only. But, all d objects have same no and name
not. (not suggestible.
2. Giving values in invoice initialization block also results in same above
problem.
3. In main method, s.name = “Ki”; S.rollno = 701; For 600 obj 1200 lines of
Code ⇒ cumbeyone code ⇒ Not suggestible.
145
4. So we will pay values as arguments to the constructor.
*/
2. The main objective of constructor is to parlor initialization.
/* The main objective of constructor is it takes parameters */
3. Whenever we r creating an object, the constructor will execute automatically to
perform initialization.
Eg : Class Student
{
String Sname;
Int rollno;
Studnet (Sname, int rollno)
{
this.sname = sname;
this.rollno = rollno;
{
P S V M (S[ ] arg)
{
Student S1 = new student (“Kiran”, 101);
Student S2 = new student (Karthikeya”, 102);
}
}
4. The main difference b/w instance initialization block and constractors is .
Constructor can take arguments but instance initialization block won’t take any
arguments. Hence common initialization for all the object inside instance
initialization block, where as object specific initialization we can perform inside
constructor.
Rules for Writing Constructors :
1. Constructor is the concept applicable for every class including abstract classes
also, but interfaces don’t have any constructors concept.
2. The name of the constructor must be same as class name. (for compilation
understanding purpose).
3. The only allowed modifiers for the constructors are : Public, Protected, <default>
and private. If v r declaring constructors with any other modifiers v will get a
compile time exception saying :
146
Modifier <other than above 4> not allowed here.
Eg : Class Test
{
Static Test( )
{
}
}
CTE : Modifier Static not allowed here.
4. Return type is not applicable/allowed for the constructors. By mistake, if U
keep return type compiler treats it as a method instead of constructor but
there is no compile time error.
Eg :
Class Test
{
Void Test ( )
{
SOPln (“Constructor”);
}
P S V M (S[ ] args)
{
Test t = new Test( );
}
}
⇒ It is legal (but stupid) to have a method whose name is same as class name.
5. Default Constructor :
Every class should have the constructor that may be written by programmer (or)
generated by compiler.
If the programmer is not placing any constructor, then only compiler places (or)
generates “Default Constructor”.
If the programmes already provided any constructor, then the compiler won’t
general any default constructor. I.e. Either programmer provided constructor
(or) compiler generated constructor is possible but not both simultaneously.
Proto type of Default Constructor :
- The access modifier of the default constructor is same as access modifier of
the class (either public or default).
147
- Default constructor is always no argument constructor only.
- The Default constructor contains only one line i.e. a no argument call to the
super class constructor. [Super ( );]
Eg :
Public Class Test
{
Public Test ( )
{
Super( );
}
}
148
{ {
Void Test (int i) Void Test (int i)
{ } { }
Test ( )
{
Super ( );
}
}
Overloaded Constructors :
1. For any class we can write any number of constructors and are considered as
overloaded constructors.
2. By using “Super” and “this”, we will invoke other constructors.
“Super” can be used for calling (invoking) parent class constructor and
“this” can be used for invoking overloaded constructors of the same class.
Eg :
Class Test
{
Test ( )
{ // Super( );
SOP (“No arg constructor”);
}
Test (int i)
{
This ( );
SOPln (“Int Constructor”);
}
Test (double d)
{
This (10);
SOPln (“Double Constructor”);
}
P S V M(S[ ] args)
{
Test t = new Test (10.6);
149
}
}
O/P : No arg constructor
Int Constructor
Double Constructor
this. i – invoking a member (variable / method)
this ( ) – invoking a constructor
super. i – invoking parent class member
super ( ) – invoking a parent class constructor
3. In every constructor, the first line should be a call to either a super class
constructor (Super ( );) (or) a call to overloaded constructor (this ( );)
If u r not providing anything either super( ) (or) this( ) then the compiler
always places super( ) by default.
(Automatic primitive casting is done in case of overloaded constructors)
4. Super( ) and this( ):
i. We should use Super( ) and this( ) in constructors only. i.e. we can
invoke a constructor from another constructor only. We can’t invoke a
constructor directly from a method.
ii. We should use only one but not both.
iii. We can use either super( ) (or) this( ) must be as the 1 st statement
only.
iv. If U don’t keep Super ( ) (or) this( ), then compiler always places no
argument Super( ) as the 1st Statement in a Constructor.
Eg :
Class Test
{
Test ( )
{
Super( ); this ( );
}
Void M1( )
{
this ( );
}
CTE : Call to this( ) must be the 1st stmt in a constructor.
150
5. We can overload a constructor but inheritance and overriding is not
possible. ⇒ Parents class variables & method r available to child class, but
constructors won’t be available.
Case (i): Recursive method call is always a run problem. JVM rises Stack
Over Flow Error. But, compiler point of view there is no problem
at all.
Eg :
Class Test
{
Void M2( )
{
M1( );
}
Void M1( )
{
M2 ( );
}
P S V M(String[ ] args)
{
Test t = new Test( );
t.M1( );
}
}
NO CTE
RTE : Java.lang. Stack Over Flow Error
6. But in case of constructors, recursive constructor invocation is a compile
time error. Compiler is responsible for checking everything related to
constructors.
Eg :
Class Test
{
Test( )
{
this(10);
}
Test (int i)
{
151
this( );
}
P S V M(S[ ] a)
{
SOP(“Hello”);
}
}
CTE : Recursive constructor invocation.
Compiler checks about constructor because if pgmgr didn’t provide,
compiler has to provide default constructor.
152
Conclu : If the parent class has same argument constructor, it is suggestible to
place always no argument constructor also, otherwise, while writing
child class constructors, we should take care of calling super class
constructor properly.
Class P Class P
{ {
P(int i) P (int i)
{ {
} Super( );
} }
Class C extends P }
{ Class C extends P
C (int i) }
} C(int i)
} {
} Super( );
}
}
CTE : bcoz no-arg constructor is not there in P class.
Case (iii) : If the parent class – constructor throws some checked exception, the
child class constructors also should throw the same checked exception
or its parent (Higher type).
Eg: Class P 1 C ( ) throws Exption
{ {
P( ) throws exception{ } Super( ); NOCTE
} }
Class C extends P
{ 2 C( )
C ( ) {Super( );} {
} tru
{
Catch (Exception C)
{ }
CTE : Super must be stmt.
CTE : Unreported exception java.lang. Exception, must be caught or
declared to be thrown.
Exception Handling :
1. Exception :
153
An “Exception” is an unexpected event which disturbs entire flow of the
program.
Eg : Arithmetic Exception
Null Pointer Exception
File not Found Exception
2. If an exception occurred, the program terminates abnormally, which is not at
all suggestible because it may effect the performance of the system.
To overcome this problem, we should handle the exception for graceful
termination of your program.
3. “Exception Handling” means V r providing alternative possibility but it does
not mean that v r repairing the exception.
154
{
P S V M(S[ ] args)
{
do stuff( );
}
P S V do stuff( )
}
do more stuff( );
}
P S V do more stuff( );
{
SOP (“Hi, h r u”);
}
}
155
4. JVM will check for the handler in that method. If it is not finding any
handler then JVM terminates that method abnormally and the corresponding
entry from the stack will be removed.
5. It repeats the same process for the caller of the method. Even in the caller if
it is not finding the exception handler then it will terminate that method
followed by removing corresponding entry from the stack.
6. The whole process is repeated until main method. Even in the main method,
if JVM is not finding the Handler it will terminate main method also
abnormally and the corresponding thread will be terminated.
7. JVM hand over the responsibility of exception handling to the Default
Exception Handler.
8. The Default Exception Handler just displays the error info on the console,
nothing more.
Case :
Put SOP (10/0) Statement in
i) do stuff method
ii) main method and see the O/P.
Exception Handling :
Throwable
Exception Error
(We can handle) (We can’t handle)
(recoverable) (irrecoverable)
156
/* byte code verifier is part of JVM which checks whether generated. Class
file is by java C (Compiler) or not */ .
Exception
Arithmetic Exception
Null Pinter Exception
157
1 We can implement Exception – Handling by using try – catch statements.
The risky code we keep in inside ‘try’ block and the corresponding handlers,
we can keep inside ‘catch’.
Eg: Class Test
{
P S V M(S[ ] args)
{
SOPln(“Stmt1” );
try
{
SOP (10/0);
}
Catch (Arithmetic Exception)
{
SOPln(“Stmt2”);
}
}
O/P : Stmt 1
5
Stmt 2
Eg: try
{
Stmt 1;
Stmt 2;
Stmt 3;
}
Catch (X e)
{
Stmt 4;
}
Stmt 5 ;
Case (ii) : An exception raised at Stmt 2 and the corresponding catch block has
158
has matched.
⇒ Stmt 1,4 followed by 5 will be executed.
Indicates Normal Termination.
Case (iii) : An exception raised at Stmt 2 and the corresponding catch block has
has matched.
⇒ Stmt 1 only will be executed.
Indicates Normal Termination.
Eg : Catch (Exception e)
{
e. print Stack Trace ( );
SOP (e. to String( ));
SOP (e. get Message ( ));
}
159
2. If V have multiple catch blocks, the order of catch blocks is very important.
V should take child to parent, violation leads to CTE saying :
160
Stmt 7;
}
Stmt 8;
}
Catch (x e)
{
Stmt 9;
}
Stmt 10;
Case (i) : Exception raised at stmt 2 and corresponding catch block has found.
Flow : Stmt 1, 9 followed by 10
Normal Termination.
Case (iii) : Exception raised at Stmt 2 and corresponding catch block has
not found.
Flow : Stmt 1 only
Abnormal Termination.
Case (iv) : Exception raised at Stmt 5 and the corresponding inner catch has
matched.
Flow : 1,2,3,4,7,8 and 10
Normal Termination.
Case (v) : Exception raised at Stmt 5 but the inner catch has not matched but
Outer catch has matched.
Flow : 1,2,3,4,9 and 10
Normal Termination.
Case (vi) : Exception raised at Stmt 5 but inner and outer catch blocks
r not matched.
Flow : 1,2,3,4
Abnormal Termination.
161
Case (vii) : Exception raised at Stmt 8, the corresponding catch block has
matched.
Flow : 1,2,3,4,5,6,9 and 10
1,2,3,4,5,7,9 and 10
1,2,3,4,5,7,9 and 10
1,2,3,4,5,6,9 and 10
Normal Termination.
Case (viii) : If an Exception raised at Stmt 7 and the corresponding catch block
has matched.
Flow : 1,2,3,4,5,6,7,9 and 10
Normal Termination.
Case (ix) : Exception raised at Stmt 7 but the corresponding catch block has not
matched.
Flow : 1,2,3,4,5,6
Abnormal Termination.
“Finally” : /* try
{
Open
read
close
}
Catch( )
{
162
}
∗/
1. For the graceful terminal of the program, we have to deal locate all the
resources like :
- Closing DB Connection,
2. This clean-up code is not suggestible to place in try block because there is
no guarantee for the execution of all d stmts/.. in try block.
Hence finally block will always execute even in the case of abnormal
termination also.
Eg : Class Test
{
P S V M (String[ ] args)
{
SOP (“Hai”);
System.exit(O); // SOP (10/0); return;
163
Catch (AE e)
{
SOP(“Caught”);
}
Finally
{
SOP (“finally block”);
}
SOP(“Hello--------“);
}
}
Suppose if u place return stmt in try block, finally executes first then return stmt is
executed.
The finally will always executed once u entered into the try block, even in the case
of return statement also. But, if v r calling explicitly system.exit(O), Method,
(⇒shutdown JVM Programme) the finally won’t execute. This is the only
exceptional case where the finally block won’t execute.
164
Final : is a modifier applicable to variables, methods and classes.
Finally : To execute clean-up code irrespective of exception occurrence / handling
we keep that code in finally block.
Finalized : It is also for maintaining clean-up code only, (just before destroying
unreferred obj).
.finalized( )
Finally & Finalized : is better be finally always executes where as we don’t know
when GC occurs. */
165
{
}
finally
{
}
VALID
B/W try and catch (or) b/w catch block (or) b/w catch and finally. V r not allowed
to keep any stmt, violation leads to compile-time error.
Saying :
(i) try without catch or finally
(ii) catch without finally. (Null Pointer Exception)
2. try
{
}
Catch ( )
{
}
VALID
The code which is not handled by try but compulsorily executed should be
placed in try – finally, later pgm gets terminated & DEH cones into picture.
4. try
{
}
IN VALID
166
5. try
{
}
finally
{
}
Catch( )
{
}
Order should be followed. Only 1 error occurs. Try finally cal ready there.
Catch without finally – error.
167
Flow : 1, 5
Abnormal Termination.
Case (iv) : Exception at Stmt 4.
Flow : Exception at 1 (or) 2 (or) 3……. 5
Abnormal Termination.
Case (v) : Exception at Stmt 5 (or) Stmt 6.
Abnormal Termination.
168
Case (1) : If there is no exception.
Flow : 1,2,3,4,5,6,8,9, 11 & 12
Normal Termination (N.T)
Case (2) : An Exception at Stmt 2 and Corresponding catch block has found
Flow : 1,10,11 & 12
Normal Termination.
Case (3) : Exception at Stmt 2 and Corresponding catch has not matched.
Flow : 1, 11
Abnormal Termination (A.T)
Case (4) : Exception at Stmt 5 and corresponding inner catch has matched.
Abnormal Termination.
“throws” clause :
class test
{
P S V M(S[ ] args)
{
do stuff ( );
}
P S V do stuff( )
{
do more stuff ( );
}
P S V do more stuff ( )
{
169
SOPln (“Hi”);
thread.sleep (2000);
}
}
1. “throws” clause is used for legating the responsibility of handling exception to the
caller.
If there is any chance for rising checked exception, we should handle that exception
explicitly otherwise we have to delegate that responsibility to the caller. Violation
leads to CTE.
Eg : class sample
{
P S V M(S[ ] args)
{
thread.sleep (1000);
}
}
Eg : class test
{
P S V M(S[ ] args) throws IE
{
do stuff ( );
}
P S V do stuff( ) throws IE
{
do more stuff ( );
}
P S V do more stuff( ) throws IE
{
thread.sleep (1000);
170
}
}
“throw” Keyword :
1. We can use ‘throw’ keyword for hand over exception object to the JVM. Some
times, it is required to create our own customized exception objects and we have to
handover to the JVM we can achieve this by using ‘throw’ keyword.
Eg : class test
{
P S V M(S[ ] args)
{
throw new Arithmetic Exception ( );
}
}
171
}
Eg : try
{
SOPln(“Hi”);
}
Catch (AE e) Catch (Exception e)
{
}
Catch (IO Exception e)
CTE : Exception java. io. IO Exception is never thrown in body of corresponding try
statement.
Consolidated CTES in Exception Handling :
1. Exception has already been caught.
2. Unreported Exception must be caught or declared to be thrown.
3. Unreachable stmt.
4. Exception is never thrown in the body of corresponding try statement.
5 keywords, 4 CTEs
Customized Exceptions :
Eg : Entering age in matri mony.com. If ventered 90 (or) 13 then that site should throw
exception age too low / too high ⇒ customized exception.
1. Based on our programming requirement, V have to create our own customized
exceptions like [Too Young exception (in Matrimony.com), Insufficient Funds
Exception….. etc) using ‘throw’ key word.
172
RuntimeException
Eg : Class too young exception extends. Exception
{
Too Young Exception (String S)
{
Super(S);
}
}
class sample
{
P S V M (S[ ] arg) throws exception
{
int age = Integer. Parse Int (args[0]);
if (age>40)
{
throw new Too Young Exception
(“P/S wait some more time, U will get best match”);
}
else if (age<15)
{
throw new Too Young Exception (“Ur age is already crossed”);
}
else
{
SOPln (“U will get match info by mail very soon”);
}
}
173
{
Static Arithmetic Exception e;
P S V M(S[ ] args)
{
throw e; - null pointer exception
}
}
174
}
4. Class Cast Exception :
- It is child class of Runtime Exception and it is unchecked exception.
- This is thrown by the JVM, when attempting to cast a reference variable to a type
that fails Is – A test.
Eg: Class Sample
{
P S V M(S[ ] args)
{
Object O = new object( );
String S = (String) O; // CCE, fails IS -A
}
}
5. No class Def Found Error :
- This is thrown by the JVM, when the JVM (or) class loader tries to load the
definition of a class and no definition of the class found.
6. Exception in Initializer Error :
- Thrown by the JVM to indicate that an exception occurred during initialization of a
static variable (or) Stati( ) Initialization block.
Eg: Class Sample
{
Static int I = M1( );
Public Static int M1( )
{
SOP (10/0); ⇒ // EI Error caused by arithmetic exception
return 10;
}
P S V M(S[ ] args)
{
SOP (“Hello”);
}
RTE : Exception in Initializer Error Caused by : java.lang. Arthmetic Exception / by
zero.
7. Illegal Argument Exception :
175
- It is a child class of Runtime Exception and is unchecked exception thrown by API
developer to indicate that a method has been called with in appropriate argument.
Eg: Class Sample
{
P S V M(String[ ] args)
{
thread. Current thread( ). Set priority ( );
// priority range 1 to 10
}
}
RTE Error : java.lang. Illegal Argument Exception.
Summarization Table
Exception / Error Thrown by
1. Null Pointer Exception
2. Stack Overflow Error
3. Array Index Out of Bounds → JVM
176
Exception
4. Class Cast Exception
5. No Class Def Found Error
6. Exception in Initializer Error
7. Illegal Argument Exception
8. Number Format Exception
9. Illegal State Exception → Thrown Programatically by the
10. Assertion Error Programmer / API Developer
Garbage Collector :
1. Introduction
2. Ways of making object eligible for GC
3. The ways of requesting JVM to run GC
4. Finalization and finalize( )
Introduction :
/* In C++, creation of object by using new( ) and deleting the object by using delete( ).
This is the responsibility of programmer. But programmer never pays much attention in
deleting the memory as he did in case of creating object. It is similar to people who seek
others for their requirement but once it is fulfilled they forget them. Who ch is not at all
suggestible. Instead of taking the work of deleting memory Java kept an assistant for
deleting the memory, 99% of Java appln/. Won’t fail because of memory problems. Java
is robust because of this GC. */
1. Most of old OOP languages like C++ the programmer is responsible for both
creation and destruction of objects. But the pgmgr is very much interest for creation
of object but be usually neglects the destruction of objects. As a result, at certain
177
time there won’t be memory for the creation of new objects, hence the program will
fail.
/* In real – time for every problem after solution, v should provide RCA – Root
Cause Analysis.
When servers r facing out of memory then V should restart the system. Restarting
the servers take time and during that time applns/- won’t work, which is a big loss
for client. There may be some objects which unreferred but not eligible for GC,
which is one of the reasons of memory problems ⇒ complete dependency on GC
for deletion for unreferred object is not suggestible.*/
We cannot give any guarantee for its behavior. We cannot predict when JVM runs
GC and what algorithm GC is using for identifying useless objects, and whether the
Garbage collector destroys the identified object or not.
178
b) Reassigning the reference variable :
By reassigning the reference variable, v can make objects eligible for GC.
Eg : Student S1 = new Student ( );
Student S2 = new Student ( );
→ No obj. eligible for GC S2 = 21;
→ 1 obj. eligible for GC
Eg 2 : Class Sample
{
P S V M(S[ ] a)
{
Student S3 = M1( ); // M1( )
→ At this line object referred by S2 is eligible for GC
}
P S Student M1( )
{
Student S1 = new student( );
Student S2 = new student( );
return S1;
}
}
/* Whenever JVM feels that our main pgm is lacking memory then JVM gives less
priority to main thread and gives high priority to GC thread. But V don’t know when
JVM does this process*/
/* Whenever main ( ) method over, then GC won’t run ⇒ JVM shutdown*/
179
/* The thread which is running in the background is considered as “Demon thread”.
Eg : GC */
4. Island of Isolation : SCJP
/* Class Test
{ t1 → i=
Test i;
P S V M(S[ ] a)
{
Test t1 = new test( ); t2 → i
Test t2 = new test( );
Test t3 = new test( );
→ No obj eligible for GC
}
} t3 → i=
*/
Eg : Class test
{
Test i;
P S V M(S[ ] args)
{
Test t1 = new test( );
Test t2 = new test( );
Test t3 = new test( );
t1.i = t2;
t2.i = t3;
t3.i = t1;
t1 = null;
t2 = null;
→ At this line also no object is eligible for GC
t3 = null; Test t4 = t2.i; Nullptr
}
}
→ At this point all d 3 objs eligible for GC, even though the objects
having internal references, this group of objs. Doesn’t have any
reference from live thread, hence eligible for GC.
180
→ If a group of objects don’t have any external reference, still this
group of objects eligible for GC even though internal reference
present. Such group of objects r called “Island of Isolation”.
If the object doesn’t have any external references then it is always eligible for GC.
Even though, the objects having some references still the object is eligible for GC
sometimes (Island of isolation)
Eg : describing GC
class run time demo
{ (Free memory varies from run to run)
P S V M(String[ ] args)
{
Runtime r = Run time . get Runtime ( );
SOPln (r. total memory( )) ; 23222596 bytes
181
SOPln (r. free memory( )) ; 12345 bytes , (total bytes)
for (i = 0; i < 1000; i ++)
{
java.util.date d = new java.util.Date( );
d = null;
}
SOPln (r. free memory( )) ;
r.gc( ); //System.gc( );
SOPln (r. free memory( )) ;
}
}
IDE - ?
Heap Memory - ?
Static Method / Factory meth both r same.
Finalization :
/* The algorithm mark & sweep used to destroy the objects is purely vendor dependent
and it changes from DB to DB*/
1. In our class v can override finalize( ) method to maintain clean-up code. The
signature of the finalize( ) method present in the object class is
Protected void finalize ( ) throws throw able.
2. GC calls finalize( ) method just before destroying any object to perform clean-up
activities.
/* When gc thread is called from main thread, but which thread executes v can’t give
assurance, because both r threads */
Eg 1 : Class test
{
Public Static V M (S[ ] a) throws Interrupted Exception
{
String S = new String (“Kiran”);
S = null;
Sytem.gc( );
182
Thread.sleep (3000);
SOPln (“End of Main”);
}
Public Void finalize( )
{
SOPln (“Finalize Method Called”);
}
}
Note : The GC calls the finalize method on the object which is eligible for garbage
collection (⇒ “Kiran”. Finalize ( )). In the above eg. GC calls destroying finalize method
on string object and finalize method available in the string class has executed (which
perform nothing i.e. why O/P is only end of main).
Eg 1 : Class test
{
P S V M (S[ ] m) throws IE
{
Test S = new ( );
S = null;
Sytem.gc( ); // thread. Sleep (3000)
SOPln (“End of main”);
}
Public Void finalize( )
{
SOPln (“Finalize Method Called”);
}
}
183
{ Public void finalize ( )
P S V M(S[ ] a) {
{ SOPln (“Finalize Method”);
Test t = new Test( ); SOPln (10/0);
t.finalize( ); }
}
}
Caught {
Normal termination. try
{ {
Test t = new Test( ); SOPln (“Finalize Method”);
t.finalize( ); SOPln (10/0);
} }
} Catch (Fle e)
{
SOPln (“Caught”);
}
}
/* Thumb rule : If I made a mistake it is blunder, if my dad did that ignorable. */
/* Generally, v don’t put SOP stmts/.., v put cleanup code (DB Closing, N/W closing
etc)*/
Eg 1 : Class test
{
P S V M (S[ ] args)
{
Test t = new. Test ( );
t = finalize ( );
}
P Void Finalize( )
{
SOP (“F Method”);
SOP (10/0)
}
}
O/P : Finalize Method.
Exception thrown followed by
184
(Abnormal Termination)
Note : We are allowed to call finalize( ) method explicitly. At that time if any exception
raised in finalize( ) method, the corresponding catch block will execute. If there is no
catch block then it is abnormal termination.
Eg 2 : Class test
{
P S V M (S[ ] a) throws IE
{
Test t = new. Test ( );
t = null;
System.g( );
Thread.sleep (3000);
}
Public Void Finalize ( )
{
SOPln (“Finalize Called”);
SOP (10/0); // SOP (“Hai”);
}
}
O/P : Finalize Called.
Note : While executing finalize( ) method which is called by GC any uncaught
exceptions are simply ignored by the JVM. Once an exception rises; JVM ignores and
remaining code won’t execute.
Case 3 : Going till the edges of hell & coming back.
Once an object eligible for Garbage College, it may not be always destroyed by GC
(Some times it is save), i.e. even after an object eligible for farbage collection, it may get
the reference, then that object is not eligible for Garbage Collection.
/* And later if that object loses its ref, GC comes & now, it won’t execute finalize( )
method, directly deletes that object */
Case 3 Eg Pgm :
Class Finalize Demo
{
Static Finalize Demo S;
// Static since I want to access from everything
P S V M (String[ ] args)
{
Finalized Demo S1 = new Finalize Demo ( );
SOPln (S1.hashCode( ));
S1 = null
System.g( );
Thread.sleep (2000);
SOPln (S.hash Code ( ));
185
S = null;
System.gc ( );
Thread. Sleep (3000); SOP (“Hi, end of main”);
}
}
/* If pgmgr calls finalize( ) the GC won’t consider this count, it considers only its own
count*/
Multi – Threading :
1. Introduction (Terminology)
2. Define a thread, Instantiate & Start extens thread implements runable a thread.
3. Set & get the name of a thread.
4. Thread priorities.
5. How v can prevnt a thread from exfution ?
i. Yield ( )
ii. Sleep ( )
iii. Join ( )
6. “Synchronized” Keyword
7. Inter-thrad communication → [wait( ), notify( ), notify all ( )]
8. Dead lock
9. Daemon – threads (1/2 hr)
10% of real-time java projs r of core java, where multi – threading is important.
186
Introduction :
/* Mult-tasking : Doing multiple tasks simultaneously. Eg : Human being – sleeping,
listening, writing */
1. Multi - Tasking :
- Executing several tasks simultaneously is considered as “Multi-tasking”.
- The main motto of multi-tasking is to improve the performance (of an appln).
- The taks in multi-tasking rexecuted independent of each other.
Multi – tasking
ii. In general, this type of multi tasking is best suitable at O/S level, and it is costly to
implement because each & every process requires separate memory and so on….
iii. The exs. Mentioned in chart for process based MTK r not at all useful in client
scenerrio. Such egs. For the client don’t make sense. So this type of MTK is not at
all signifible.
/*
Consider the following Process :
Java 10000 pgm → independent parts (threads) light weight process
→ is a process (or) execution of stmts.
187
→ Main is default 10000 b in java pgm
Motto : Calculating temp.
Cpgm : O/P after 1 hr., since line by line execution at last it finds temp after 1 hr.
Jpgm : It divides pgm into no. independent parts and executes simultaneously. This
individual part is known as thread. Because of this response time decrease and
pert incs.
*/
Thread-based MTK :
i. Executing several independent tasks simultaneously where each task is a separate
independent part of the same program is considered as : “thread-based MTK”.
(Wonderful feature of OOP).
/* Java is simple because, java pgms, can be implanted easily, because knowing how to
use libraries is enough, v never bother about internal implention */
188
Thread : Part of Process */
/* In CGI, process-based MTK, For every request a separate process is created after the
use destroyed ⇒ creation & deletion is costly ⇒ CGI fails to deliver scalable applns..
So creation of thread instead of process came into pecture which made the CGI outdated.
⇒ CGI is outdated because of Multi-threading.
Adv : in CGI is no problem of symchronitation. */
In process based MTK, all d processes r using their own memory areas hence there is no
question of synchronization problems. But in case of thrad based MTK, all d threads r
using the same common memory, hence synchronization (concurrency) problems vil
come.
/* Movie : All these parts of movie rexecuted 1 after the other then that movie would be
reality horrible, so because M.td can into picture & made all party of movie executed
simultaneouls. */
The major appln area of multi-threading is multi-media and graphics like implementing
video games, simulators etc.
Client asks for ugability ⇒ Out of 100 hrs how many hours applicable r perfectly main.
(98 hrs) ⇒ 98% possibility performance is < 98% for every 1 mnt – 12 hor RS has to
give to client 3 hrs → 3 cores.
189
2. Defining, Instantiating and Starting a Thread:
1. V can define a thread in the following ways :
i) By extending thread class.
ii) By implementing “Runnable” interface;
/* If U keep all stmts/. In a single main( ) thread, ⇒ executing line by line (similar to
(pgm), execution depending on that single thread main( ) is entirely cycle SS. So in the
pgm of 10000 lines v will take some parts of pgm which r independent of other, but them
in separate thread (childs of main thread) ⇒ resp time perf i.e. the use of thread */.
/* Suppose in the main there r 3 threads which one executes first v can’t say it is done by
assistant thrual schedulear which is vendor dependant and stimes p/f depen dart */
There is no need that after 10 time GM picting only, v have to print 10 more times GM.
So, maintain separate thred for printing 10 times GM. So v have to create a new thread by
entending a clan with thread & overvide P.V. run( ) method. Run( ) method is heart of
the thread and v. But all stmts the trhead to perform in the run( ) method */
190
Eg : Class Mythread extends thread
{
Public Void run( )
{
for (int i = 0; i<10; i++)
{
SOPln (“GM : Child thread”);
}
}
Thread Scheduler :
- Part of JVM. Stmts thread scheduler links with process scheduler of O/S.
- If more than 1 thread is available, which thread vil get the chance for execution vil be
decided by thread scheduler. The behavior of thread scheduler is totally vendor
dependant. Hence v can’t say in which order the threads vil execute. When the
situation comes to multi-threading the guaranteed behavior is very very low. V can
tell the possible O/P bmt not. The exact O/P.
191
Marathi Movies :
Case (i) : Defference b/w t.start( ) and t.run( ).
In the case of t.start( ) a new thread vil create and that thread is responsible for the
execution of run( ) method.
But in the case of t.run( ), no new thread vil create and the main thread is wholely
responsible for execution fo run( ) Method also i.e. run( ) will execute like a normal
method instead of a thread.
Eg : Replace t.start( ) with t.run( ) in above pgm the following is the O/P :
GM : Child thread (10 times)
GM : Mainthread (10 times) - Entire O/P produced by Main( ) thread.
Case (ii) : Importance of thread class start method.
Once v created a thread, v r responsible for registering our own created thread with
the threat scheduler. This activity will be performed by start( ) method available in
the thread class. Hence, for starting a new thread, v have to call start( ) method
instead of run( ) method. After completing, joining formalities for our thread, start
method will invoke run( ) method.
Public Void Start ( )
{
1. Joning formalities for our thread like : Registering the thread
with the thread scheudler
2. Invoke (call) run( ) method.
}
Case (iii) : If v r not overriding run method :
→ t.Start( ) internally calls, thread class run( ) method who has empty
implentation, which is doing nothing.
→ v.Should override run( ) method to define, our job (Strictly
recommended).
192
SOPln (“run”);
}
Public Void Start( )
{
SOPln (“Start”);
}
}
When v override start( ) method, no new thread is created, it won’t call run( )
method, it will execute as a normal method.
Case (v) :
193
}
V can overload run method, but thread class start ( ) method will always call nen( )
method without any arguments.
Just like a normal method, v can call explicitly overloaded run( ) method.
194
/* Once V start a thread, restarting the same is foolish as similar to assign brachure to
make us born once again */
In the program, write t.start( ) – 2 times.
No CTE, but RTE : Illegalthread State Exception.
1. Once a thread is started, V r not allowed restart the same thread again. Violation leads
to Run time Exception Saying :
- “Illegal thread state exception”.
extends
Mythread
Runnable
Mythread
1. Is not suggestible because once v rextending thread class v can’t extend any other
⇒ missing the concept of oop (inheritance)
2. Is best because eventhough v r implementing, v can extend are more class also.
195
{
SOPln (“Run”);
}
}
Class Thread Demo
{
P S V M (String[ ] a)
{
Myrunnable r = new Myrunnable ( );
/* V wn’t write r.start( ), (CTE) because. My Runnable class is not extending Thread
class */
/* v can’t write above stmts, because t.start( ) calls run( ) method of thread class which
does nothing */
t.start( );
SOP(“Main Thread”);
How above approach incs/ perf ? A : Perf is not that much low (Match of 2 or 3 ns)
[negligible]. Disadv : Writing one more stmt //. Adv : Not missing Oop – innerhence.
i) Thread class start( ) method will execute, which calls, Myrunnable, run( )
method. In this case, a new separate thread created.
196
(Almost similar to overriding concept)
t.run( );
My Runnable run( ) method will be executed by the main( ) thread only just like a
normal method. No new thread created.
In the above pgm, if u r replacing t.start( ) with trun( ), v will get the O/P (run
Main Thread)
Until & unless u call start( ) method of thread class no new thread will be created.
MyRunnable run( ) method will execute just like a normal method. No new thread
will be created.
- In the case of implements runnable, our class can extend any other class. Hence v r
not missing inheritance benfit. Hence this approach is suggestible for the real-time.
197
1. No-arg constructor :
Thread t = new thread ( );
2. Constructor with argument as string object (so that v can give our own name to the
thread)
Thread t = new thread (string name);
3. Constructor with argument as any runnable interface refeence
Thread t = new thread (Runnable r);
4. Constructor with Runnable, string args.
Thread t = new thread (runnable r, string sname)
5. Thread grouping : (very rarely used in real-time) not i.e. SCJP
Thread t = new thread (thread group g, string name);
6. Thread t = new thread (thread group of, runnbale r);
7. Thread t = new thread (threadgroup of runnable r, string name);
198
t1.start( ); → run method of mythread will be executed,
a new thread is also created.
SOPln (“Main – Thread”);
}
}
For every thread, r can assign the name, thread class contain the following methods for
setting and getting the name of a thread.
Eg : Class Sample
{
P S V M(S[ ] args)
{
SOPln (thread current thread ( ).get Name ( ));
}
}
O/P : Main
Eg : Class Sample
{
P S V M(S[ ] args)
{
Threadd.currentthread( ).setName (“Karthikeya”).
199
// SOP (10/0); → Exception in thread karthikeya.
}
}
O/P : Karithikeya
Thread Priorities :
If all the threads have same priority, which thread vil execute v can’t say. It is
purely vendor depending */
1. Every thread in java has some priority. The valid range of thread priorities is :
1 – 10
2. For defining standard priorities, thread class has the following constants. They are :
3. The thread scheduler uses these priorities, while allocating CPU. The thread which
is having highest priority will get the chance of execution first.
4. V can set and get the priorities by using the following tread class methods :
If v give value for argument not within the range 1-10, v will get a Runtime
Exception Saying : “Illegal Argument Exception”.
200
// Demo pgm on Thread Priorities :
Class Sample Thread t = thread current thread( );
{
Public Static Void Main (String[ ] args)
{
SOPln [Thread.currentThread( ).getpriority()];
Thread.current thread.setpriority (10);
// Thread current thread. Set priority (thread. MAX – PRIORITY);
SOPln [Thread. Current thread( ).getpriority( )]; //
}
}
201
for (int i = 0; i<10; i++)
{
SOPln (“Main Thread”);
}
Conclus :
For affecting priorities O/S support must also be required. Some O/S may not
support thread priorities. Eg : Windows XP some versions.
Default Priority :
V can change the priority of a thread even after the ch read started, but v can’t
change the damon nature of a thread once it is started.
***
202
203