262
CORE JAVA Index : 1. Language Fundamentals ………………………………… 3 Identifiers ……….. 3 Keywords ………...4 Data Types ……….7 Literals ……………11 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 3. Operators and Assignments ………………………………42 Increment and Decrement Operators ….. 42 Arithmetic Operator …… 45 String Concatenation Operator ….. 47 4. Control Flow ………………………………………………60 5. Declaration and Access Control …………………………74 Declaration of Packages ………….80 Class Level Access Modifiers …… 82 Member Modifiers …… 88 Synchronized Keyword …. 100 1

Core Java Meterial

Embed Size (px)

Citation preview

Page 1: Core Java Meterial

CORE JAVA

Index :

1. Language Fundamentals ………………………………… 3 Identifiers ……….. 3 Keywords ………...4 Data Types ……….7 Literals ……………11

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

3. Operators and Assignments ………………………………42 Increment and Decrement Operators ….. 42 Arithmetic Operator …… 45 String Concatenation Operator ….. 47

4. Control Flow ………………………………………………60

5. Declaration and Access Control …………………………74 Declaration of Packages ………….80 Class Level Access Modifiers …… 82 Member Modifiers …… 88 Synchronized Keyword …. 100

6. Interfaces ……………………………………………….. 100

7. Java 1.5 Features ………………………………………..106

8. Object – Oriented Concepts ……………………………111

1

Page 2: Core Java Meterial

9. Overriding…………………………………………………120

10. Constructor ……………………………...………………144

11. Exception Handling …………………………………….155

12. Garbage Collector ………………………………………176

13.Multi Threading ………………………………………….185

2

Page 3: Core Java Meterial

SCJP Syllabus

1. Language Fundamentals.

2. Operators and Assignment ***

3. Declaration and Access Control

4. Oops – Encapsulation,Inheritance, Aggregation (Composition)PolymorphismCoupling & Cohesion.

5. Multi-Threading (15 to 20 hrs.)

6. Java. Lang – Object ClassStringString butterString builderWrapper 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%

Most of the Indian Projects are “Maintenance” only.

3

Page 4: Core Java Meterial

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

Rules for creation of identifiers : 1Q *

1. An identifier is a sequence of characters, which is composed of i) alphabet a to z (either upper or lower case) (or) ii) a digit from 0 to 9 (or) iii) currency symbol $ (or) iv) correcting punctuation such as (-).

If we use any other character, like @, #….. we will get :

Compile time error : Illegal character (which is not allowed in ur identifier)

Eg : abc123123abc

abc @ 123 ……….etc.

2. No identifier in Java Starts with the digit.

4

Page 5: Core Java Meterial

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

identifiers. There is no errors.

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)

Key Words (50) Reserved literals (3)

Used Key Un-used (2) true, false to represent Words (48) goto, const. boolean value

null for representing object references

Primitive Keywords for data types : (8)

byte float short doubleint charlong boolean (logical)

5

Page 6: Core Java Meterial

Keywords for flow control : (11)

if for

else dowhile return

switchcase breakdefault continue

Keywords for exception - handling : (6)

trycatchfinally

throwthrows

assert (introduced in 1.4) Mainly used as tool for debugging purposes.

Keywords for modifiers : (11)

Public Synchronized (not synchronize)Protected Private Volatile

TransientStatic NativeAbstract Strictfp (not Strict Fp)Final

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).

Class related keywords : (6)

ClassInterfaceExtends (not extend)Implements (not implement or implemented)Import (not imports)

Object – related keywords : (4)

New (operator as well as keyword)Instance of (not instance Of)Superthis

6

Page 7: Core Java Meterial

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).

Unused Keywords : (2)

const – use finalgoto – its considered harmful.

Just to avoid java programmers to use above in the pgm, sun mentioned them as keywords otherwise they create confusion.

‘enum’ Keyword : (1)

- This keyword can be used for defining a group of named constants.

- This keyword was introduced in 1.5 version.

- Even though ‘enum’ was introduced for before, why they introduced in 1.5 (Tiger version) ?

So it they added extra features to old enum and introduced enum. Sun people don’t want to miss the wonderful enumeration concept.

Eg. : enum month {

JAN, FEB, MAR….. etc. }

Reserved Words for defining literals : (3)

truefalsenull

Note 1 : All the keywords (reserved words) in java contain only alphabet symbols and all are in lower case.

Note 2 : assert – introduced in 1.4enum – introduced in 1.5No keyword introduced in 1.6

Creating a new keyword creates so many complexities. Next 4 or 5 versions may not have new key (or) reserved words.

Note 3 : Java is considered as strongly – typed lang. because :

- Every has the type

- Compiler always searches for type compatibility Boolean b = o;

7

Page 8: Core Java Meterial

(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

For representing real numbers.Float and double : Floating point data types

Character type (char for representing characters)

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 :

Primitive – type Corresponding Wrapper class

byte Byteshort Shortint Integerlong Longfloat Floatdouble Doublechar Characterboolean Boolean

Size, Range, What cases suitable, What happens it we base out of range.

8

Page 9: Core Java Meterial

1. byte : **

- Size : 8 - bitsRange : - 128 (min) to 127 (max)

(MSB) Sign bit 0 +ve1 -ve

- If it is a +ve no, the remaining 7-bits represent the magnitude of the number.

- If it is a –ve no, the remaining 7-bits do not represent the magnitude. We will take 2’s complement.

- In general, Range : -2n-1 to 2 n-1 – 1

- If U want to save data in a file, to transfer across a network, to handle data interns of streams (iron a N/W or from the file) this “byte” data type is the best suitable.

Note : Compiler also checks for the assignments.

Eg : byte b = 130; byte b = 127;

Comp Error : Possible loss of precision required : byte found : int.

2. Short :

- Size : 2 bytes

- Range : -215 to 215 –1(-32.768 to 32767)

- Short S = 32768;

Comp. Error : PLPfound : intrequired : 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

Page 10: Core Java Meterial

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.

4. ‘long’ data type :

- If the size of int is not enough to hold big values [e.g. : the amount of distance traveled by light in 1000 days (1,86,000 x 60 x 60 x 24 x 1000)] then we go for long data type.

- This kind of requirement is very low and hence long data type is also very rarely used data type in java.

- Size : 8 – bytes

- Range : -263 to 263 -1

10.235 = 10235x10-3 = 10235e-3

Floating – Point data types :

Byte, short, int and long can be used for representing whole values only. If u want to represent real numbers (with fractional digits) we should go for floating point data types.

10

Page 11: Core Java Meterial

Floating – Pointd.types :

Float Double

Size : 4-byte Size : 8-byte

This is suitable if U This is suitable if Uwant to consider 6 to 7 want to consider 14 to 15fractional digits of accuracy fractional digits of accuracyis 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

“Char” data type :

- Size : 2 – bytes

- Range : 0 to 65, 535 characters (language independent)

Unicode Unique code for every world wide character.

- Java uses Unicode for representing characters. In order to cover all world-wide character sets, 8-bits (1 byte) are not enough, that is why we should go for 16-bits (2 byte).

Note : Unicode: Unique code for every character irrespective of language and irrespective of platform. But ‘c’ pgm can be developed only in English.

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

Page 12: Core Java Meterial

Eg : int x = 0if (x){ SOPln (“Hello”); } else { SOPln (“Hi”); }

O/P : Comp. Time error : incompatible types found : int required : Boolean

Summarization table of Java Primitive data types :

Data type Size Range Wrapper class Default value

1. byte 1 –128 to 127 Byte 0

2. short 2 –32768 to 32767 Short 0

3. int 4 –231 to 231 –1 Integer 0

4. long 8 –263 to 263 –1 Long 0

5. float 4 –3.4e38 to 3.4e38 Float 0.0

6. double 8 –1.7e308 to 1.7e308 Double 0.0

7. char 2 Unicode values : Character 0[indicates0 to 65, 535 blank space

character]

8. boolean NA NA Boolean false(allowed values are (but in C, C++true / false) (1) i.e True)

Literals : **

A literal represents the constant value which can be assigned for the variable

Eg. Int x = 10;

datatype name of constant value keyword variable literal identifier

12

Page 13: Core Java Meterial

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;

ii) Octal literals : Allowed digits 0 - 7 Eg : int x = 010; (The number must be prefixed with ‘Zero’).

iii) Hex (or) Hexadecimal literals

Allowed literals : 0 to 9 and

This is one of the very few areas, where java is not case – sensitive.

Eg : int y = ; (‘x’ in any case) (Any case is allowed)

The number must be prefixed with either ox (or) OX.

- We can’t assign binary literals for integral data types.

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;

comp error : PLP

13

Page 14: Core Java Meterial

found : long 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;

Floating – Point Literals :

@@ - By default, floating – point literal is of double type we can’t assign a floating – point literal directly to the float variable.

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’.

Eg : float 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.

Note : int x = 10.5; com. error : PLP

found : double;required : int.

- We can’t assign floating point literals for integral types

@@ - We can directly assign an integral literal to the float data type.

14

Page 15: Core Java Meterial

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.

Note : @@ We can specify explicitly a floating point literal is of double type by specifying ‘D’ (or) ‘d’ at suffix (of course not required, because floating – point literal is of double type by default).

@@ An integral literal can be assigned to floating point data type whether it is expressed in decimal / octal / hexadecimal form

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.

Eg: int i = 123e2;

10. double d = 123e2; 123456e98;

15

Page 16: Core Java Meterial

Possible assignment :

byte short int long float doublechar

11. float f = 123.45D;

12. float f = 0x123L;

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 symbolSymbol : Variable TRUELocation : ------

Eg : boolean b = 1; in case of C, C++boolean b = 1; in case of Java.Comp. Error : In compatible type

Fount : intRequired : bodlean.

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.

But in case of; int i = 23.45;

Error : PLP

because both found & required data types are compatible with each other, but not equally compatible.

Eg : int x = 10;if(x){ SOPln (“Hello”); }else { SOPln(“Hi”) }(Code is valid in IO but valid in Java)

O/P : Comp. Error : Incompatible types

16

Page 17: Core Java Meterial

Exercise :

1. boolean b = true;boolean b = FALSE; - Can’t resolve symbolboolean b = O; - Incompatible typesboolean b = yes; - Can’t resolve symbolboolean b = (10>20);

(x > y); x = 10, y = 20.

Note : If U See ‘e’ in a no. Eg : 123e45 it is by default float value.

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’;

Error : Unclosed character literal. (because multiple characters are not allowed within single quotes)

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 : aChar ch = 3I47;

Note : Valid integers than can be assigned to char variables are from 0 to 65,535.

Eg: Char ch = 65536;

Comp. Error : PLP. Found : int required : char. There is a compatability b/w found & required data types.

- 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.

Eg : Char ch = 0x97; (Hexa)Char ch = 0100; (Octal)sChar Ch = 0x61;Char Ch = ‘\u0061’;

17

Page 18: Core Java Meterial

3. A char literal can also be represented by using Unicode notation.

Unicode representation is nothing but, \U followed by a 4-digit Hexadecimal number, all within single quotes.

Ex : Char Ch = ‘\40000’; (4 – D Hex dec no.)

Exercise :Char Ch = ‘\u0012’;Char Ch = ‘\uface’;Char Ch = ‘\ubeef’;Char Ch = ‘\iface’;

4. A char literal can also represent an escape sequence character;

Eg. Char Ch = ‘\t’;Ch = ‘\r’;Ch = ‘\b’;Ch = ‘\n’;Ch = ‘\m’;

Error : illegal escape character unclosed char literal.

Escape Sequences :

Escape Unicode CharacterSequence 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

big farms need red tractors

18

Page 19: Core Java Meterial

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

Page 20: Core Java Meterial

(2-3 Qs) Arrays

- An “Array” is an indexed collection of fixed number of homogeneous data elements.

Eg : Student[ ] S = new student (100); S[0] = new student ( ); S[0] = new customer( );

We can over come the problem of storing homogeneous elements.

Limitations of Object Array :

1. Arrays basically hold homogeneous elements but by using ‘object arrays’ we can overcome this limitation.Eg: Object[ ] 01 = new Object ( );

Object (5);

2. Arrays r fixed in size, based on our req, we

Can’t increase or we can’t decrease size. Hence, memory point of view arrays r not good.Solution is : Collections

Arrays r fixed in size but Array list is not fixed in size. The collection objects (Array list) r growable in nature but performance wise these r not good. These collection show worst performance, because they create a new copy of all the existing objects.

3. There is no under lying data structure present for arrays. Hence we r unable to represent array information in some sorting order we can’t avoid duplicate object insertion by default.

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

Array Declaration : (1 – 1 arr decl)

20

Page 21: Core Java Meterial

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;

L – dimensional array declaration :

Eg : The dimension can be specified after the name (or) after the type.

1. Int[ ] [ ] a;2. Int a[ ] [ ];3. Int [ ] a[ ];4. Int[ ] [ ] a;

This dimension is allowed only for the 1st variable this dimension will be added to the declaration int type.

- int [ ] a,b; a,b are single dime. Arraysint[ ] [ ]a,b; a – 2-D

b – 2-D int[ ] [ ]a, [ ]b; Comp. Error.

Becoz the dimension should not be preceded before the 2nd variable, it is only & only for the 1st variable.

int[ ] [ ]a, b[ ] a – 2D b – 3D

Exercise :int[ ] [ ] [ ] a; a – 3Dint[ ] [ ] [ ] a, b; a,b – 3Dint [ ] [ ] [ a ] a, b [ ] [ ]; a – 3D, b – 5Dint [ ] [ ] [ ]a, [ ]b;int [ 6 ] a;

3-D array declaration:int [ ] [ ] [ ] a;int a[ ] [ ] [ ];int [ ] a [ ] [ ];int [ ] [ ] a[ ];int [ ] [ ] [ ] a;int [ ] [ ] [ ]a;int [ ] [ ] a ;int [ ] [ ]a [ ], [ ] b [ ];

Construction of Arrays : (1-D array Construction)

21

Page 22: Core Java Meterial

- An array itself is an object in Java, whether it may be of any dimension.

1. Construction :

int [ ] a = new int [ 6 ];

At the time of construction, we should specify the size. Violation leads to compile time error

i.e. int a = new int [ ];

Comp Error : The size is missing Array dimension is missing.

2. int [ ] a = new int [ 6 ];

Run time exception : (Negative array size) Run time Exception.

We are not allowed to specify the size by using negative number [(or) integer]. Violation leads to run-time exception saying.

3. It is legal to have an array with size ‘O’ in Java. No compile-time / Run – time exceptions.

i.e. int[ ] a = new int [ 0 ];

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

- byte short

int long float double char

- The all rules applicable to arrays of any dimension.

int [ ] a = new int [10.6];

10.6 is a double no and double cannot be promoted to int it is a compile time error PLP found : double, req : int

5. The maximum allowed array int array size in Java is 2147483647. (The may no represented by int type).

6. We can assign the size of the array even with a realizable also.

Eg : byte b

22

Page 23: Core Java Meterial

short s = 100; int[ ] an = new int [ ];

int ilong 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.

Eg : int [ ] [ ] a = new int [ 2 ] [ 3 ];

base size

a base array

Array of Arrays Concept.

- In Java, Multi-dimensional arrays are implemented as “Array of Arrays” for improving the performance w.r.t. Memory.

Eg : My req; a[0] a[1] a[2]

23

Page 24: Core Java Meterial

a - base array

int [ ] [ ] a = new int [ 3 ] [ ]; ([3] – optional, [ ] – compulsory)

a[ 0 ] = new int[ 2 ];

a[ 1 ] = new int [ 1 ];

a[ 2 ] = new int [ 3 ];

Note : At the time of construction of multi-dim arrays, the base-dimension should be compulsorily specified otherwise compile-time error.

i.e. int[ ] [ ] a = new int [ ] [ ];

because base size is not mentioned.

Exercise :

int [ ] [ ] a = new int [ ] [ ]; Missing base sizeint [ ] [ ] a = new int [ 2 ] [ 3 ]; int [ ] [ ] a = new int [ ] [ 3 ]; (Specify size from L R)int [ ] [ ] a = new int [ 1 ] [ ] [ ] [ 4 ]; Comp. Error

Eg : for Arrays of Arrays a[0] a[1] a[2]

a

a[0] [0] a[0] [1]

a[0] [0] [0 ]

Code : int[ ] [ ] [ ] a = new int [ 3 ] [ ] [ ];

a [ 0 ] = new int [ 2 ] [ ];

a [ 0 ] [ 0 ] = new int [ 3 ] ;

24

Page 25: Core Java Meterial

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.

4. int [ ] [ ] [ ] a = new int [ 3 ] [ 4 ] [ 1 ];

5. int [ ] [ ] [ ] a = new int [ 2 ] [ 3 ] [ 1 ];

Structure :

a

6. int [ ] [ ] [ ] a = new int [ 2 ] [ 0 ] [ 3 ];

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.

Eg.1 : double [ ] [ ] d = new double [ 2 ] [ 3 ];

Internal Structure :

25

Page 26: Core Java Meterial

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

S.O.Pln (d[ 0 ] [ 2 ]); // O.P. 0.0

S.O.Pln (d[ 0 ]); // O.P. cd @ 1 add 2cd

Eg.2 : double [ ] [ ] d = new d[ 2 ] [ ];

d [ 0 ] [ 1 ]

d null null

Since 2nd dimension is not defined, d[ 0 ] points to nothing Those objects r not

created. Hence it stores default value ‘null’

S.O.P (d(0)); //O.P. = null

S.O.P (d[ 0 ] [ 1 ]); // O.P = Runtime error

If d [ 0 ] is pointing to null there won’t be any value for d [ 0 ] [ 1 ] Null pointer

exception.

Eg.3 : int [ ] a = new int [100];

a[ 0 ] = 10;

a[10] = 100;

S.O.Pln

[(0, 0 = default values) – (10, 100 Over hidden values)]

O.P. = 110/

Eg.4 : int [ ] a = new int [ 3 ]; a [ 1.5 ] = 60;

a [ 0 ] = 10;

a [ 1 ] = 20;

26

Page 27: Core Java Meterial

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.

Declaration, Construction and Initialization in a Single line :

Eg :

int[ ] a; String [ ] str = {“xxx”, “yyy”, “zzz”};a = new int [ 3 ]; Char [ ] ch = {‘a’, ‘a’, ‘c’};a [ 0 ] = 10; int [ ] a = {10, 20, 30};a [ 1 ] = 20; (Internally JVM creates an a [ 2 ] = 30; array object of size 3)

Sphagetti Code Real time code

- 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.

Eg : int [ ] a = { 10, 20, 30};

int [ ] a;

a = {10, 20, 30}; (C.E. Illegal Start of expression)

- D,C,I of Multi –D array in a single row.

Eg : int [ ] [ ] a = {{10,20}, {30,40,50}, {60}};

27

}

Page 28: Core Java Meterial

Internal Structure :

10 20 30 40 50 60

- int [ ] [ ] a = {{10,20}, {30,40,50}, { }};

base array length is ‘}‘

in that a [ 0 ] – has 2 elements

a [ 1 ] – 3 elements

a [ 2 ] – 0 elements

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.

Eg : int [ ] a = new int [ 6 ];S.O.Pln (a length ( )); - Method Comp. Error.S.O.Pln (a.length); - O.P : 6

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 : 7S.O.Pln (S.length); // Comp. Error.

2. It represents the no. of characters present in string object / returning the size of the string.

Exercise :

1. int [ ] a = new int [ 6 ]; S.O.Pln (a length); // O.P : 6

28

Page 29: Core Java Meterial

2. int [ ] [ ] a = new int [ 2 ] [ 3 ];a.length = 6a.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};

- Anonymous 2-D array :

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};

29

Page 30: Core Java Meterial

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.

int i = ‘a’; float f = 10;SOP (i); //97 SOP (f); // 10.0

Array element assignments :

- We can assign any value to an array element. As array element we can give any values which can be implicitly promoted to declared type.

Eg : byte b = 10; char ch = ‘c’;short s = 20;

int [ ] a = new int [ 6 ];

a[ 0 ] = 1;

a[ 1 ] = b;

a[ 2 ] = s;

a[ 3 ] = ‘a’;

a[ 4 ] = ch;

a[ 5 ] = 10l; (long can’t be promoted to int)

- If an array is declared of type “Object” class, we allowed to give any kind of objects as elements.

i.e In the cause of array of reference type it can take the declared type objects and its child class objects also as array elements.

Eg : Object [ ] ob = new object [ 3 ];ob [ 0 ] = “Pavan”;

ob [ 1 ] = new object ( );

ob [ 2 ] = new integer (10);

Array variable assignments :

- While performing assignment of one array to another array, we have to check the declared types, not its sizes.

Eg :

30

Page 31: Core Java Meterial

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

- A single character can be promoted to int but not a character array.

- A char array can’t be promoted to into array but we can promote a char value to the int value at array element level.

Eg :

char [ ] ch = {‘a’,’b’,’c’};

int [ ] i = {10,20,30};

i = ch;

comp. Error : Incompatible types.

found : char [ ]

req : int [ ]

- In the case of reference arrays for the parent type array, we can assign child array type.

Eg.1 :

string[ ] s = {‘A’,’B’ };

object [ ] ob = s;

Eg.2 :

car [ ] c = new car [ 3 ];

zen [ ] z = new zen [ 3 ];

c = z;

- In place of I-D array, U can’t provide value.

Int [ ] [ ] a = new int [ 3 ] [ 2 ];a [ 0 ] = new int [ 2 ];

a [ 0 ] = new int [ 100 ];

a [ 1 ] = 10;

comp. error : Incompatible types.

found : int

req : int [ ]

31

Page 32: Core Java Meterial

- int [ ] [ ] a = {{10,20}, {30,40}}

int [ ] b = {50};

a = b;

comp. error : Incompatible types.

found : 2-D

req : 1-D

int [ ] a[ ]; that space is ignored by JVM within [ ]

Different types of variables :

- Based on the values represented by the variables, they are divided into 2 categories,1. Primitive variables2. Reference variables.

1. Primitive variables :

These variables can be used for holding primitive valuesEg : 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 variables2. Static variables and3. Local variables

1. Instance variables / Member variables / attributes (Object – level variable)

- For every object, a separate copy of instance variables will be created.

- Hence, the values of these variables vary object to object.

- 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

32

Page 33: Core Java Meterial

{ int i;

P S V M(S[ ] a) { SOPln (i); // we should create object first. }}Test t = new test( );SOP (t.i);

CTE : non-static variable ‘i’ can’t be referenced from a static text. - There is no need to perform initialization for the instance variables, by default

instance variables, will always get default values.

- Observe the above eg.

- Values varying from obj to obj, we will declare them as instance vary.

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”.

- 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.

33

Page 34: Core Java Meterial

Conclusions reg static variable :

1. In case of static variables, a single copy will be created and all the objects will share that variable which is very useful in view of memory.

2. Static variables can be accessed with class name as well as object reference.

By using object reference, if a person changed the value of a static variable, these changes will be reflected for all the objects. To prevent this, most of the cases, static variables are always associated with “final” keyword.

3. The static variables will be created while the class loaded into the memory and destroyed while unloading the class from the JVM Memory. I.e. static variables will exist as long as the corresponding class present in JVM memory.

4. A single global copy is created for static variables which can be accessed by remaining all objects.

5. In case of static variables (As similar to instance variables), default values will be assigned if u r not performing any explicit initilization.

Eg : Class Sample

{

Static int i;

P S V M (S[ ] args)

{

Sample S = new sample ( );

Sopln (s.i); // legal but not recommended

Sopln (sample. i); // legal & recommended

Sopln (i);

}

}

O/P : O O O

Local Variables :

- Also known as “Temporary Variables” (or) “Stack Variables” (or) “Automatic Variables”.

34

Page 35: Core Java Meterial

- 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

Page 36: Core Java Meterial

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

Page 37: Core Java Meterial

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.

Invalid Error : illegal start of expression

Public int i = 10; final int i = 10;

Private int i = 10; int i = 10;

Static int i = 10;

- 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

Page 38: Core Java Meterial

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.

Signature (or) Complete Declaration of Main Method :

- Public static void main (String[ ] args)

{

------ ------

}

Public : To call this method by JVM from anywhere (JVM is configured in such a way that it finds the main method in its defined signature.

Static : Without object also we can in invoke this method.

Void : This method doesn’t return anything to JVM.

Main : Name of the method.

String[ ] args : Command line arguments array.

* If there is no main method, in run-time while executing we get error : No such method error.

38

Page 39: Core Java Meterial

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

Page 40: Core Java Meterial

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.

Exercise : (w.r.t. main( ) method)

1. Public static void main (String[ ] args) { }

2. Protected static void main (String[ ] args) { }

RTE : ‘Main’ not public

RTE : No Such Method Error

3. Public void main (String [ ] args) { }

4. Public static int main (String [ ] args)

{

return 10;

}

RTE : No such method error.

5. Public static void MAIN (String[ ] args) { }

RTE : No such method error.

6. Public static final void main (String [ ] args) { }

But it is foolish to write main as final, because we won’t over write main method.

40

Page 41: Core Java Meterial

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) { }

Command – line arguments :

- Arguments passed during run-time in command prompt

Eg : java test arg [ 0 ] [ 1 ] [ 2 ] [ 3 ]

10 20 30 40 Command-line arguments

If U access args [ 4 ] – error.

- args [ 0 ] – 1st Gmd line argument

args [ 1 ] – 2nd Gmd line argument

args.length – the no. of command-line args.

Args [ 4 ] – 5th Gmd line arg, but there is no such args results in

“Array Index Out Of Bounds” Exception.

- WAP to display all Gmd and line args.

Class test

{

P S V M (S[ ] a)

{

for (int i = o; i < args.length; i + +)

S.O.Pln (i);

}

}

Public, Static, Void } KeywordsString } Class nameArgs, Main } Not keywords

41

Page 42: Core Java Meterial

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

Page 43: Core Java Meterial

Operators & AssignmentsAgenda :

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.

1. Increment / Decrement Operators :

Increment Operators : x ++ Post Increment

++ x; Pre Increment

43

Page 44: Core Java Meterial

Decrement Operators : y - -; Post Decrement

- - y; Post Decrement

Table :

Expression Initial Final Initial FinalValue 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

Conclusions w.r.t. SCJP :

1. int y = + + 4;

compile-time error : un excepted value x = 5;

required : variable int y = ++ x;

found : value

* Increment / Decrement operators, we should apply only for variables not for constant values violation leads to CTE.

2. Nesting of Increment / Decrement Operators is not allowed violation leads to CTE

int x = 4;

int y = + + (++x) (returns a const. But not variable and ++ (const) is invalid)

CTE : Unexpected value.

required : variable

found : value

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

Page 45: Core Java Meterial

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.

byte + byte intshort + short intint + long longfloat + double doubleint + byte intint + int int

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

Page 46: Core Java Meterial

CTE : PLP

found : int

required : byte

Internal Typecasting is the best utility of I/d operators

6. Difference b/w b++ and b = b 1.

In case of increment or decrement operators, compiler will take care of implicit typecasting.

But, in case of b = b + 1, the programmer is responsible to perform typecasting.

i.e. b ++ is equivalent to b = (type of b (b + 1);

Eg : byte a = 10;

byte b = 20;

int c = a + b;

Eg : byte b = 127;

b ++;

SOP (b);

b = (byte) (b + 1);

= (byte) (128)

= -128

2. Arithmetic Operators :

The result of arithmetic expression is atleast ‘int’. There is no chance of byte (or) short.

1. If we apply Arith. OP b/w 2 operands a & b, we will get result is of type :

Max (int, type of a, type of b)

int + byte int

float + double double

short + float float.

The arithmetic operators are : +, -, *, / and %

2. S.O.Pln (10/0)

RE : Arithmetic Exception : / by zero

S.O.Pln (10./0)

O/P : Infinity

> javap jav.lang. Float

Double

46

Page 47: Core Java Meterial

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)

3. Nan / (Not a Number)

SOP (0/0) ; A.E : / by zeror (RTE)

SOP (0.0/0) ; NaN

If the result of an Arithmetic Expression is underfined, there is no way to represent that undefined values in the integral arithmetic. Hence it results in Arithmetic Exception.

Eg : SOP (0/0);

CTE : A.E. : / by zero

But in the case of floating point arithmetic, if the result is undefined, there is a constant available for representing undefined results. (NaN).

Hence,

Eg : SOP (0.0/0);

O/P : NaN (No Compile & Runtime Errors)

Consolidated :

10/0 A.E

10.0/0 Infinity

-10.0/0 Infinity

-0/0 AE

-0.0/0 NaN

47

Page 48: Core Java Meterial

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

Eg 2: int a = 10;

int b = 20;

int c = 30;

48

Page 49: Core Java Meterial

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 LR 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.

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.

49

Page 50: Core Java Meterial

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.

Exercise :

T F F

T | F T

50

Page 51: Core Java Meterial

T F T

2. 4 5 4 4 – 01005 – 0101

& - 0100 4

4 | 5 5 4 – 01005 – 0101

| - 0101 5

4 5 1 4 – 01005 – 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

4 0000 0000 …….. 0100

~4 1111 111……… 1011

= -

= -5

15 0000 …… 1111

51

Page 52: Core Java Meterial

~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.

8. Short – Circuit Operators :

if &

{

// L1min total 21 min

}

else if 10 min

{

//

}

52

Page 53: Core Java Meterial

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.

Eg: int x = 10;

int y = 15;

if (++x < 10 & + +16y > 10)

{

++x;

Sopln(x);

Sopln(y);

}

else

{

++y;

Sopln(x);

53

Page 54: Core Java Meterial

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

Type – Cast Operator :

1. These r 2 types of type castings r possible in case of primitive types.

They are :

i) Implicit typecasting

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

byte short int long float double

54

Page 55: Core Java Meterial

chart

Eg : int i = 10;

float f = I; Here ‘int’ value converted to ‘float’ by compiler.

SOP (f); // 10.0

ii) Explicit – typecasting :

Eg : int i = 10;

byte b = i; byte b = (byte) i;

CTE : PLP

- Programmer is responsible for “Explicit typecasting”

- Keeping a big value in a small container

- It may result in loss of information

- Also known as “Narrowing”

Eg 1: int i = 130;

byte b = (byte) i;

SOP(b); // -126. (130 lead to –126)

- In the case of explicit type casting, it we assign a big value to the small data type the most significant bits (except the magnitude bits-remaining) will be lost.

Eg 2: int i = 150;

byte b = (byte) i;

short S = (short) i;

Sopln (b); -106

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;

55

Page 56: Core Java Meterial

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

Eg 1 : Thread + = new Thread ( );

Sopln (+ instance of thread); // true

Sopln (+ instance of object); // true

Sopln (+ instance of runnable); // true

Because : Object

Runnable

implements

Thread

*** Sopln ( + instance of string);

CTE : inconvertible types

found : java.lang.Thread

required :java.lang.String.

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”

56

Page 57: Core Java Meterial

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

Page 58: Core Java Meterial

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

Page 59: Core Java Meterial

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.

Note : Chained assignment is not allowed at the time of declaration.

int a,b,c,d;

a = b = c = d = 40;

a+ = b* = c| = d = 10

a = 80, b = 40, c = 1, d = 30.

All compound operators have called precedence.

Assignment always takes place from R L.

Precedence of Java Coperators :

1. Unary Operators :

i) [ ], x ++, x –

ii) +=x, --x, ~, !

iii) new, <type> - type-casting operator)

59

Page 60: Core Java Meterial

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 :

=, +=, -=, *=, /=, %=, >>=, <<=, >>>=, &=, | =, =

Evaluation Order of Operands:

[ Not precedence of operators]

class sample

{

Public static int m1 (int i)

{

Sopln (i);

return i;

}

P S V M (S[ ] args)

{

Sopln [m1(1) + m1(2) * m1(3) / m1(4) = m1(5) %m1(6)],

}

}

60

Page 61: Core Java Meterial

O/P : 1 2 3 4 5 6 -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

Flow Control Iteration statements

Set of stmts/.. to be executed repeatedly

i) for ii) while iii) do-while iv) for- each

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

Page 62: Core Java Meterial

Case 1 : int i = 10;

if (i)

{

SOP (“Hi”)

}

else

{

SOP (“Hello”);

}

CTE : Incompatible types. required : Boolean

found : int

Case 2 : int i = 10;

if (i = = 10)

{

SOP (“Hi”);

}

else

{

SOP (“Hello”);

O/P : Hi.

Case 3: int i = 10;

if (i = 20)

{

SOP (“Hi”);

}

else

{

SOP (“Hello”);

}

O/P : CTE, Since assignment operator not equality operator.

62

Page 63: Core Java Meterial

Case 4: boolean b = true;

if (b = false)

{

SOP (“Hi”);

}

else

SOP (“Hello”);

O/P : Hello

Case 5: boolean b = true;

if (b)

{

SOP (b);

int i = 10;

}

SOP (i);

CTE ‘i’ is within if block

Case 5.1 : Under if ; without curly braces only.Single statement is allowed. But, that statement should not be a “Declaration Statement”, violation leads to compile time error.

Eg :

boolean b = true;

if (b)

SOP (“Hi”);

if (b)

int x = 20;

SOP (“Hi”);

CTE : int x = 20 is not a statement.

Case 5.2 : boolean b = trueif (b)

{

int x = 10;

}

Sopln (“Hi”);

Because, the same ‘x’ within the block may be used later so it is a valid stmts.

63

Page 64: Core Java Meterial

“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 = 40Switch (x){case 10;case 20;

64

Page 65: Core Java Meterial

case 30;case y :}CTE : Constant expression required.

Eg : final int y = 20;

int x = 10;

switch (x)

{

case y :

}

All the case labels must be in the range of switch argument, otherwise compile time error.

Eg : byte b = 10;

switch (b)

{

case 10 :

case 100:

case 1000:

case 10000 :

}

CTE : PLP

found : int

required : byte

The case labels should not be duplicated, violation leads to compile time error, saying “Duplicate cases not allow”.

Eg : int x = 10;

switch (x)

{

case 97 :

case 98:

case ‘a’:

case ‘d’:

}

CTE : Duplicate cases not allowed

65

Page 66: Core Java Meterial

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,2x= 1 1,2x = 2 2x = 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

Page 67: Core Java Meterial

Case 1 :

SOPln (“1”);

Case 2 :

SOPln (“2”);

}

x = 0 0,1x= 1 1x = 2 2x = 4 default

If x is final then x - 1

x - 2

x – 3 …. R also final.

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

Page 68: Core Java Meterial

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.

Eg.4 : final int a = 10;

final int b = 20;

while (b > a) (compile-time comparison)

{

SOP (“Hi”);

}

SOPln (“Hello”);

CTE : Unreachable stmt/-

2. do – while :

If the loop body has to be executed at least once, go for do-while loop.

Syntax : do

{

------------------

}

while (b);

Omission of ; results in compile time error.

Curly braces r optional but b/w do and while there should be atleast a single statement. i.e. do-while with zero. Statements in b/w results in CTE. The single stmt b/w do-while might be empty statement.

68

Page 69: Core Java Meterial

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 stmtWhile (false);SOPln (“Hello”);

do

{SOPln (“Hi”);}while (true);SOPln (“Hello”); Unreachable stmt.

int a = 10, b = 20;

do

{SOPln (“Hi”);} NO CTE (Hi) infinite timeswhile (a<b);SOPln (“Hello”);

69

Page 70: Core Java Meterial

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

Page 71: Core Java Meterial

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

Page 72: Core Java Meterial

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

Page 73: Core Java Meterial

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

Page 74: Core Java Meterial

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

Page 75: Core Java Meterial

III. Declarations & Access Control

1. Java source file structure

2. Class – level access modifiers

3. Member (variable + Method) Modifiers

4. Interfaces.

Entered into JAVA

1. Java source file structure

In Real-time situations, one file should contain only a single class. But in general, a film may contain more than one class.

A Java program may contain any number of classes. But, we r allowed to declare, atmost are class as the public.

If there is a public class, the name of the program and the name of the public class must be matched otherwise compile – time error.

If there is no public class, then we r allowed to keep any class name as the file name.

Class B{};

Eg 1: Class A { };

Public Class B { }; Saved with name A.java

Class C { };

If we compile above pgm, we get compile-time error saying:

Class B is public, should be declared in a file named B.java.

Eg2: Public Class A { };

Class B { }; Saved with name A.java

Public Class C { };

CTE : Class C is Public, should be declared in a file named C.java.

Note : According to real-time coding convention, a file should contain only one class.

For every class in ur file including inner classes also a separate.

Class file will be created.

At nun time it is not mandatory that the class name as argument, any class name within the file can be given.

75

Page 76: Core Java Meterial

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 ( )

1 SOP (Array list);

CTE : Can’t resolve symbol

Symbol : Variable Array list.

1 Java.util. Array List l = new java. Util Array List ( );

NO CTE

Fully qualified name

Problem is, every time ur using Array List, U should mention the entire fully available name which is a tedious process. Instead if that, - Array List is unique, we can import that class from a package with import stmtl. in the file.

Such as import sava.util.ArrayList;

This import statement is not at all similar to the #include statement. because, in ‘c’ language # include < > loads all the header files in the current program, but in java that class file is not loaded into the current pgms memory one demand, only the required class is loaded at that particulars moment.

We can use the stmtl.. import java.util. *;

But in real time java.util *; Shouldn’t be used because it decreases the readability. In the util package, which class we r using we don’t know.

76

Page 77: Core Java Meterial

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.

import java.util. Array List – considered as “Explicit class inport”(ECI)

import java.util * - considered a“Implicit class import”;(ICI)

- ECI Improves readability of the code

ICI reduces readability of the code

- ECI is highly recommended for real – time. (because the developer need not be maintained. To make it readable to everyone ECI is always preferable)

ICI is recommended for AMEERPET

(Indian S/w Engg is a perfect example of monkey)

Case 1 : class test extends java.rmi.uni cast remote object

{

}

which of the following is true ?

a) the code fails to compile because of lack of import

b) valid

Because, once we r using fully qualified name, no need to specify any import stmt.

Case 2 : import java. util. *;import java.sql. * ;class test{P S V m (S[ ] a){Date d = new Date ( );}}

CTE : reference to date is ambiguous both J.S.D. Match

77

Page 78: Core Java Meterial

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.

Not for SCJP

Note : For compiler :

i) ECI is always convenient

ii) The classes present in current working directory no need of import

iii) ICI

The compiler searches for a class in the order :

i), ii) and iii) If it got in the 1st any only, it ignores remaining 2 cases.

The compiler resolves the class names in the following order :

i) Explicit class import

ii) Classes present in current working directory

iii) Implicit class import

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

Page 79: Core Java Meterial

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

Page 80: Core Java Meterial

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.

* import static java.lang.system.out;

80

Page 81: Core Java Meterial

class sample

{

P S V Main (S [ ] a.)

{

Out.Println (“Hi”);

}

}

O/P : Hi

Package Statement : (All state insurance project)

If there r no. of classes, out of which one class should be used as utility, the convention is utility java.

If suppose more than 1 person developed some classes and came with a single utility class name utility.java, while integrating all the class from developers naming conflicts rise. Hence awe go for packages pat all classes in their own packages.

- packages in java is an encapsulation mechanism to grow related classes and interfaces a single module.

- the main objective of package concept is to resolve ‘Naming conflicts”.

- while naming don’t use pack 1, pack 2…. etc. there is universally accepted naming convention is available for packages. i.e. use their internet domain names in reverse.

Eg : com.imb. Allstate

<proj name>

com.cts. All state

Declaration of Packages :

Keyword :

Package com.durga;

Class sample

{

P S V M (S[ ] a)

{

SOPln (“Hi”);

}

}

Compiling :

81

Page 82: Core Java Meterial

> 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.

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.

82

Page 83: Core Java Meterial

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( )

{

SOP (“In A’S M1”)

}

}

Package Pack 2;

83

Page 84: Core Java Meterial

// 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.

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 ( );

Note : ( ; ) is mandatory and it indicates no implementation is defined here.

84

Page 85: Core Java Meterial

But, abstract int no of wheels ( ){ }; results in CTE.

Because { } indicates implementation which is not allowed for an abstract method.

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.

6. If a class declared as abstract, then we r not allowed to create an instance of that class. If the class contains, at least one abstract method, it indicates that the implementation is not complete. Then we r not allowed to create an instance of that class. Hence it must be declared as “abstract”. Class containing atleast one abstract method must be declared as abstract, violation leads to CTE.

Eg : abstract

class vehicle

{

abstract int no of wheels ( );

}

7. It is not mandatory that abstract classes should at least contain single abstract method i.e abstract classes have a possibility of having zero (0) abstract method.

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.

85

Page 86: Core Java Meterial

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

Disadvantage of ‘final’ Classes :

If a class declared as final, then u r not allowed to create the child class. Violation leads to CTE.

Eg : final public class a class B extends A

{ { };

86

Page 87: Core Java Meterial

P V M1( ) CTE : Can’t inherit from final ‘A’.

{

SOP (“Pandu”);

}}

Note : Until & unless there is no specific requirement, don’t use final keyword in the real-time coding, because the programmer is missing the wonderful key concept of object – oriented programming – INHERITANCE

Eg : for final classes :

String, Wrapper Classes, Math…..etc

String Buffer, String Builder…..

Comparison between final and abstract :

1. An abstract method means : it never talks about implementation.

A final method means its implementation is final. No one allowed to override this method. Hence, final and abstract combination is illegal combination, for the methods.

2. An abstract class means, we should create the child class to provide implementation for the abstract methods.

But, final class means, we should not create the child class because parent class implementation is final.

Hence final and abstract combination is illegal for classes also.

3. A final class never allows to constrain abstract methods but an abstract class may contain final methods.

Eg : final class A abstract class A

{ {

abstract void M1( ); final … void M1( );

} final void M1( ) { };

}

Strict fp : (floating point)

87

Page 88: Core Java Meterial

1. If U perform 10.0/3 the result is 3.333…. ‘3’ repeats after decimal point unit the O/S (or) processor – bit, size supports. We say Java as P/f independent but the floating point arithmetic results in P/f dependency. Which is sense less.

2. Strictfp is a keyword which can be applied only for methods and classes i.e we r not allowed to declare a variable as a strictfp.

3. If a method declared as a strictfp all the floating point calculations has to follow IEEE 754 standard, So that we can get p/f independent results.

4. If a class declared as the strictfp, all the concrete methods in that class have to follow IEEE 754 standards, for floating point arithmetic.

5. Strictfp always talks about implementation, but abstract never talks about implementation. Hence abstract and strictfp combination is illegal for methods.

6. Strictfp and abstract combination is illegal for methods but it is legal for classes.

Eg : strictfp abstract class A

{

M1( ) { }

M2( ) { }

abstract void M3( );

}

1. abstract –final Illegal for methods

Illegal for classes

2. abstract – strictfp Illegal for methods

Legal for classes

88

Page 89: Core Java Meterial

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

2. Everybody thinks the specifiers are :

Public, Private, <default> and protected and remaining are modifiers. But these discrimination is only w.r.t. Ameerpet, but ‘Sun” Specified there r no such specifiers / modifiers. Both r same.

Eg : Private class A { };

CTE : Modifier “Private’ not allowed.

(Modifier – but we think private as specifier)

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 BPublic 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

Page 90: Core Java Meterial

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

Page 91: Core Java Meterial

A a1 = new A( );a1.M1( ); // M1 in AB b1 = new B( );b1.M1 ( ) // M1 in AA 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

child / non-child NO NO YES YESfrom outside package (But it mustbut in child class be invoked on

child class ref)

from outside package NO NO NO YESin non-child class

* Private < <default> <protected < public.

91

Page 92: Core Java Meterial

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

Page 93: Core Java Meterial

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( ) P S V M ( )

{ {

final int i; final int i;

} SDP (i);

}

No CTE CTE

93

Page 94: Core Java Meterial

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

Page 95: Core Java Meterial

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

Page 96: Core Java Meterial

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

Page 97: Core Java Meterial

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.

InheritanceOverriding (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

Page 98: Core Java Meterial

i = 10 i = 10j = 20 j = 20

Sample S abc.tx+

FOS – File O/P Stream.

OOS – Object O/P stream

(the process of writing an object to a file is called “serialization”)

i = 10j = 20

abc.tx+

OIS.read Object( ); return object.

The process of getting (reading) an object from a file is called “De Serialization”.

Demo program w.r.t transient and serialization :

Import java.10.*;

Class transient demo (implements serializable)

{

int i = 10; // transient int i = 10, j = 20;

int j = 20; // transient int j = 20;

P S V M (String[ ] a) throws exception

{

Transient Demo + = new transient demo( );

SOPln (t.i +”…..”+t.j); // 10…..20

File Output Stream FOS = new File Output Steam (“abc.tx+”);

Object Output Stream OOOS = new Object Output Stream (FOS);

OOS.Write Object (t); /* t1.j=100; t1.j = 100 */

File Input Stream fis = new File Input stream (“abc.txt”);

Object input stream ois = new object input stream (fis);

Transient Demo t1 = (Transient Demo) ois. read object( );

SOPln (t1.i + “…..” +t1.j); // 10…..20

} (same as before)

98

OOS FOS

OIS FIS

Page 99: Core Java Meterial

} // 10……. 0 (j-tray)

// 0……0 (I,j-tray)

‘Static’ variables never participated in the serialization process because these r not part of object state. If we r declaring static variable as the transient there is no effect at all.

All the object can’t be serialized, only objects of class implementing serializable interface can be serialized. Hence we provide implements serializable in the above example.

If we declare a final variable as transient, there is no effect at all.

Before AfterSerialization 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;

transient static final int i = 10; i = 10

“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.

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.

99

Page 100: Core Java Meterial

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.

Synchronized Keyword

100

Page 101: Core Java Meterial

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.

Volatile : (Ameerpet student mentality)

1. “Volatile” is a keyword which can be applied only for variables.

2. If a variable value keep on changing by multiple threads it will create data inconsistency problems. To over come this, we have to declare such type of variables as volatile variables.

3. If a variable declared as volatile, JVM will create separate private copy for every thread. The thread is allowed to read the value from its local copy so that there won’t be any inconsistent problems.

4. To achieve this, the JVM has to create so many local copies of the same variable. Creating and maintaining multiple copies is very difficult and creates big performance problems. hence, volatile concept is completely outdated now a days and it is replaced with synchronization.

5. We can’t declare a final variable as a volatile. Violation leads to compile time error. (Final const and volatile variable, both r contradictory)

Interfaces1. 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.

1. What is an I ?

101

Page 102: Core Java Meterial

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.

Eg : class test implements transferable 1

102

Page 103: Core Java Meterial

{

public void transfer ( )

{

;;;;;;

}

Interface method declaration :

1. Whether we r declaring or not every interface method by default public and abstract. I.e. the following method declarations are equal (valid) inside an interface.

Void M1( );

Public void M1 ( );

Abstract void M1 ( );

Public abstract void M1 ( );

2. As interface method by default abstract and public, we not allowed to declare an interface method by using the following modifiers.

Private, Protected, final, static, nature, synchronized and strictfp.

Eg : Public Void M1 ( );

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.

Exercise :

103

Page 104: Core Java Meterial

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

Page 105: Core Java Meterial

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.

Interface naming Conflicts :

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( ) { }

}

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.

105

Page 106: Core Java Meterial

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( ) { }

Public V Left M1( ) { }

Public I Right M1( ) { }

}

Note : If 2 interfaces contain methods with same name same arguments but with different return types, IT IS NOT POSSIBLE to implement & interfaces simultaneously in the same class.

Case 4: Variable naming conflicts

Eg : interface Left {int i = 100;}interface Right {int i = 20;}Class Test implements Left, Right{P S V M (S[ ] a){SOP (i); // CTE : reference to i is ambi.SOP (Left i); // 100SOP (Right i); // 20}}

If 2 (I)s contain the same variables, in the implementation class we can distinguish by using interface name.

106

Page 107: Core Java Meterial

1.5 Features

Java Coding Standards : (1 – 3Q)

For a good pgmg practice, it is mandatory to follow java coding standards. In 1.4, these r not available. (Also known as Java coding conventions)

Classes & Interfaces :

Classes :

1. According to coding standards, the class names must be nouns.

Eg ; class Dog { }; class Account { };

2. The first letter should be capitalized and if several words are linked together to form the name, the 1st letter of inner world should be upper case . (known as “Camel Case”)

Eg : Class Dog Sample { };

Class Student Info { };

Class Account Details { };

Interfaces :

1. Interface names should be adjectives and the remaining rules are exactly similar to that of class names (camel case format)

Eg : Serializable ;

Resizable

Transferable

Cloneable.

Methods :

The method names usually verb-noun pairs. Method name must start with lower case letter and every inner word starts with capital letter (camel case).

Eg : get Details ( )

Print Details ( )

get Balance ( )

get Customer Name ( )

Variables :

107

Page 108: Core Java Meterial

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.

Syntax of Setter Method :

Public void set <property Name> (argument of property type)

- The setter must be declared as public with void return type and argument represents property type.

Eg : public void set Name

{

this .name = name;

}

Java Bean Class :

108

Page 109: Core Java Meterial

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;

}

}

Listeners Naming Conventions :

For registering a listener :

Public void add My Action Listener My Action Listener l

Exercise :

Valid way of registering a listener according to coding standard.

1. Public void set My Action Listener (My Action Listener l);

2. add My Action Listener (My Listener l);

3. add My Action Listener (My Listener l);

For unregistering a listener :

Public void remove My Action Listener (MyActionListener l);

The method name must be public with void return type and the method name must be prefixed with ‘remove’.

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

Page 110: Core Java Meterial

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

Page 111: Core Java Meterial

}

}

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)

{

SOPln (“General Method”);

111

Page 112: Core Java Meterial

}

P S V M1 (int…a)

{

SOPln (“var-arg method”);

}

P S VM (String[ ] args)

{

M1( ); // Var-arg

M1 (10); // General – method

}

}

Var-arg methods will always get least preference.

We can declare main method in one of the following possible :

Public static void main (String[ ] args) { }

Public static void main (String….. args) { }

Object – Oriented Concepts :

1. Data - Hiding

2. Abstraction

3. Encapsulation

4. Inheritance. (IS-A relationship)

5. Aggregation (HAS – A relationship)

6. Method signature

7. Polymorphis M Overloading Overrding Methodhding

8. Coupling and (1.5 features)

9. Cohesion

10. Static control flow

11. Instance control flow

12. Constructors

I. Data Hiding :

112

Page 113: Core Java Meterial

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

III. Encapsulation : (key benefit of is security i.e. data hiding)

1. If a class follows – Data Hiding and Abstraction, that class is said to be encapsulated class.

Encapsulation : data hiding + abstraction

Note : The getter and setter methods, in real-time contain code regarding authentication.

2. Hiding data behind methods is the central concept of encapsulation.

Advantages :

i. Security

ii. Enhancement

iii. Maintainability (of code)

iv. Modularity

Disadv :

The –ve side of encapsulation is :

It increases the length of code (because for every property (data member) we have to write getter & setter methods) and slows

down the execution.

Note : In encapsulation, data hiding has more importance.

Tightly Encapsulated Class :

113

Page 114: Core Java Meterial

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

Page 115: Core Java Meterial

(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.

IV Inheritance (Is-A relationship) :

1. “Is –A” relationship is also known as inheritance.

2. By using “extends” keyword, we can implement inheritance concept.

3. The key benefit of inheritance is reversibility.

Eg 1: class person

{

int age;

string name;

string weight;

string height;

string eat( );

string sleep( )

115

Page 116: Core Java Meterial

}

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.

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;

116

Page 117: Core Java Meterial

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[ ])

}

Case 1 : Parent P = new parent ( );

P.M1 ( ); // Parent

P.M2( ); // Parent has no idea of what child class has, with parent

clan ref. Child clam can’t be called.

Case 2 : Child C = new child( );

C.M1( ); // Parent no such mett (M1) by in child clam, it executes parent class methods.

C.M2( ); // Child

Case 3 : Parent P = new child( ); Runtime object is child.

P.M1( ); // Parent

P.M2( ); // CTE

}

}

(Parent class ref. Can hold child clan obj but by using that ref we can’t call child clay specific methods.)

117

Page 118: Core Java Meterial

(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.

V. Aggregation (Has A relationship):

(We use this concept in general but we don’t know)

Note : Also known as composition.

Eg : Car contains (cabiposed of) engine, steer, seats – etc.

Car has Engine

1. HAS – A relationship also known as composition or aggregation. By using several objects, we can compose an object.

Eg : Class Engine Class Car

{ {

M1( ) Engine C = new Engine( );

M2( ) }

M3( )

}

A car HAS-A Engine reference.

2. The advantage of HAS-A relationship is reusability.

3. No keyword for mentioning HAS-A relationship.

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

118

Page 119: Core Java Meterial

{

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)

{

Test t = new Test( );

t.M1( ); compiler checks;

t.M2(10);

t.M3(23);

119

Page 120: Core Java Meterial

}

(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.

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:

Eg : ‘max’ method in math

Class

120

Page 121: Core Java Meterial

Max (int i, int j)

Max (long l, long m)

Max (double d, double e)

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

}

}

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.

Automatic promotion in Overloading :

1. In the case of overloading method resolution, compiler will always check for exact matched signature. If it is not finding, compiler will promote the argument to the

121

Page 122: Core Java Meterial

next level. If it is not finding at that level also, it repeats the same process for the next level until double type, still if the compiler will not find the desired method, at last it will rise compile-time error.

The following r possible promotions in java method over leading.

byte short int long float double

chart

Eg : class test

{

P V M1(double d) {SOPln (“double”)};

P S V M(S[ ] a)

{

Test t1 = new Test ( );

t1.M1(‘a’);

t1.M1(‘10’);

t1.M1(‘10L’);

t1.M1(’10.3f’);

t1.M1(’10.3’);

}

}

O/P : double (only)

If we declare any method with double as the argument that method can be applicable for any primitive data type except Boolean. Eg. Math.sqrt (double)

By using this method, we can find sqrt of byte, short, char, int, long, float and double values.

Case 1 :

Class test

{

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

122

Page 123: Core Java Meterial

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.

}

}

Note : float, int float, float float, intint, float float, int int, int

t.M1 CTE float, int int, int(10,10)

Always child level data types get priority. (done by compiler).

Case 3 :

Class test

123

Page 124: Core Java Meterial

{

P V M1(String Buffer S)

{

SOP (“String Buffers”);

}

P V M1 (String S1)

{

SOP (“String”);

}

P S V M(S[ ] a)

{

Test t = new Test( );

t.M1(null); //CTE

}

}

CTE : reference to M1 is ambiguous t.M1(null)

Case 4 :

Class test

{

Public void M1(Animal a) Class Animal

{ {

SOP (“Animal Version”); }

} Class Monkey

Public Void M1(Monkey M) Extends Animal

{ {

SOP (“Monkey Version”); }

}

P S V M(S[ ]a)

}

Case 1 : Test t = new Test ( );

Monkey M = new Monkey ( );

124

Page 125: Core Java Meterial

t.M1(M); // Monkey Version.

Case 2 : Animal a = new Animal ( );

t.M1(a); // Animal Version.

Case 3 : Animal as = new Monkey( );

t.M1(a1); // Animal Version

Compiler never bothers the run time obj, it considers only reference type.

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{GoldLand AvailableMoneySubbu( ) {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{ {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.

125

Page 126: Core Java Meterial

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.

3. A final method cannot be overridden but a non-final method can be overridden as final.

i.e. declaring M1( ) of ‘C’ as final.

4. Private methods will not be available for the child class and hence overriding concept is not applicable for the private methods.

5. If u want, we can declare exactly similar parent class method in the child class, but these methods r not overriding methods.

Eg :

Class P

{

Private Void M1( ) {SOP (“Parent”);};

}

Class C extends P These r not overriding methods.

{

Private void M1( ) {SOP(“Child”);}

}

No CTE

6. In the case of overriding, the return types must be same. This rule is applicable until 1.4 version, violation leads to CTE.

Eg :

Class P

{

126

Page 127: Core Java Meterial

Public Void M1( ) {SOP (“Parent”);};

}

Class C extends P different return types.

{

Public int M1 ( ) {SOP(“Child”);}

}

CTE Saying : M1( ) in C can’t override M1( ) in P; attempting to use incompatible return types.

found : int

required : void

7. But from 1.5 version onwards covariant return types r also allowed.

Co-variant return type means, need not be parent class return type its child classes also allowed as the return type.

Eg : If the return type of parent class method is object then the return type of child class method must be object until 1.4 version.

But in 1.5 version, need not be object may be its child class like string is also allowed.

Eg :

Class P

{

Public Object M1( )

}

return new object ( );}

} Co-variant return type

Class C extends P allowed in 1.5 but not in

{

Public String M1( )

{

return “Kiran”;

}

}

Note : P = Object P = StringC = String C = Object

127

Page 128: Core Java Meterial

Co-variant Not co-variantreturn types

The concept of co-variant return types application for only object/reference types but not for primitive types.

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 : PublicProtectedDefaultPrivate

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 cannotSOP(“Parent”); Override M1( ) in

} P Attempting to assign

} weaker access pri vileges;Class C access decreased was public.{Private Void M1( ){SOP(“Child”)}

}

9. Inside interface all the methods r by default public and abstract.

128

Page 129: Core Java Meterial

While implementing any interface method we should declare that method as public, otherwise V will get a compile time exception saying :

Attempting to assign weaker access privileges.

Eg : interface Left {void M1( );}

Class x implements Left

{

Public Void M1( ) { }

Void M1( ) { }

Private Void M1( ) { }

Protected Void M1( ) { }

}

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.

Import java 10-*;

Eg : Class P 1 throws IO Exception

129

Page 130: Core Java Meterial

{ 2 throws IO ExceptionPublic Void M1( ) 3 throws IO Exception { 4 ExceptionSOPln(“Parent”); 5 throws IO Exception} 6 throws IO Exception

}Class C extend P 1 throws IO Exception{ 2 throws IO ExceptionPublic Void M1( ) 3 throws IO Exception{ 4 throws IO ExceptionSOP(“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.

Exercise : Already mentioned in the pgm.

2. We can override a synchronized method as non-synchronized and a non synchronized method as the synchronized.

3. We can override a native method as non-native and non-native method as a native.

Eg : It is recommended to override native has a code method in our classes.

4. We can override an abstract method as non-abstract method to provide implementation we can also override a non-abstract method to abstract. In that case, the child classes of child class r responsible to provide implementation abstract.

Eg1 :

Class P

{

abstract void M1( );

} Generic abstract to non-abstract

class C extends P

{

Void M1( ) { }

}

Eg2 :

130

Page 131: Core Java Meterial

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

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

131

Page 132: Core Java Meterial

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”.

Overriding in the case of static methodsA static method cannot be overridden as non-static method (class level behavior can’t be changed). We can’t override a non-static method as static.

Method Hiding : (Child class method is hidden by parent class method)

1. All the rules of method hiding r exactly similar to overriding rules except both methods declared as static.

2. In the method hiding, the method resolution takes care by compiler based on reference type. (Irrespective of run-time object).

Eg :

for method hiding

Class P

{

Public Static Void M1( )

{

SOP (“Parent”);

}

}

Class C extends P

{

Public Static Void M1( )

}

SOP (“Child”);

}

P S V Main (String[ ]args)

132

Page 133: Core Java Meterial

{

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.

Overrding in case of variables :

Eg :

Class P { int i = 10;}Class C extends P { int i = 20};

P S V M (String[ ] args)

{

Case 1 : P P1 = new P( );SOP(P(i); //10.

Case 2 : ( C1 = new (( );SOP(C1.i); // 20

Case 3 : P P1 = new (( );SOP(P1.i); // 10

(Overriding not applicable for variables and compile check the

ref type only)

Overriding concept is not applicable for variables. The variable resolution always taken care by compiler based on reference type. Variable hiding is possible, not overriding.

Comparison b/w Overloading & Overriding :

Property Overloading Overriding

1. Method Names Must be same Must be same

2. Arguments Must be different Must be same (at least order)

3. Signature Must be different Must be same

4. Access Modifiers No restrictions Weakering the accessopecifier is not allowed

5. Return type No restrictions Must be same until 1.4 /from 1.5, covariant return types also allowed.

133

Page 134: Core Java Meterial

6. Throws clause No restrictions Increasing size of checkedexceptions is not allowed, but there r no restrictions for unchecked exceptions.

7. Final We CAN (Yes) We CAN (No)

8. Private We CAN (Yes) No

9. Static We CAN We cannot but method hiding is possible.

10. Native We CAN We CANsynchronizedabstract

SCJP ‘Q’ regarding Overloading and Overriding :

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

Not in SCJP, But in real time

Static Control Flow :

Eg :

Class Base

{

i = O (RIWO) Static int i = 10;

Static

{

M1( );

SPOln (“First Static Block”);

}

Public Static Void Main (String[ ] args)

134

Page 135: Core Java Meterial

{

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

Static Control Flow :

While class loaded into the memory

1. Identification of static members. (From top to bottom)

2. Execution of static variable assignments and static blocks (from top to bottom).

3. Execution of main method.

Correct O/P : O

FSB

SSB

20

Main Method

135

Page 136: Core Java Meterial

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( );

SOP (i);

SOP (“First Static Block”);

}

136

Page 137: Core Java Meterial

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.

Static Control Flow in the Parent and Child Class Relationship :

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;

}

Class Derived Extends Base

{

Static int x = 100;

Static { M2( );

137

Page 138: Core Java Meterial

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. ClassBase.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

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.

138

Page 139: Core Java Meterial

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.

Instance Control Flow :

1. Non-static variable can’t be referred from static context directly because they may not be identified by the JVM.

Eg 1: Class Sample{

int i = 10;

P S V M (String[ ] args)

{

SOPln (i);

}

}

CTE : Non-static variable ‘i’ can’t be referred from static context (directly).

Eg 2: Class Parent{

int i = 10;

{

M1( );

SOP (“First Instance Init Block”);

}

Parent ( )

{

SOPln (“Constructor”);

}

139

Page 140: Core Java Meterial

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;

}

O/P : Only Main Method //

Object is not yet created.

P S V Main(S[ ] a)

{

Parent P1 = new Parent( );

SOPln(“Main Method”);

}

O/P of Case (ii) : O

FIIB

SIIB

Constructor

Main Method

O

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.

140

Page 141: Core Java Meterial

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.

2. Instance control flow in the parent and child class relationship :

Class Parent{

int i = 10;

{

M1( );

SOPln (“Parent Instance Initialization Block”);

}

Parent ( )

{ SOPln (“Parent Constructor”); }

P S V M(S[ ] args)

{

SOPln (“Parent Main Method”);

}

Public Void M1 ( )

{

SOPln (j);}int j = 20;}Class Child Extends Parent{int x = 100;{M2( );SOPln (“Child First Instance Init Block”)}Child ( ){SOPln (“Child Constructor”)}P S V M(String[ ] args)

141

Page 142: Core Java Meterial

{

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

P I I B

P Constructor

O

C I I B Repeats for every child object creation.

C S I B

C Constructor

Main Method

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.

142

Page 143: Core Java Meterial

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 = 50My class (0)J = 0k = 0j = 7j – 70l – 20

143

Page 144: Core Java Meterial

What is O/P when V compile & run ?

Public Class Initialization

{

Private static string MSG(String MSG)

{

SOP (MSG);

Return MSG;

}

Public Initialization ( )

{

M = MSG (“1”);

}

{

M = MSG (“2”);

}

String M = Msg (“3”);

P S V M(String[ ] args)

{

Object obj = new initialization( );

}

}

Trace : M = 1;

Public Class Initialization

{

Private Static String Msg (String Msg)

{

S.O.Pln(MSG);

Return MSG;

}

Static String M = MSG(“1”);

{

M = MSG (“2”);

}

Static

{

M = MSG(“3”);

144

Page 145: Core Java Meterial

}

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.

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.

145

Page 146: Core Java Meterial

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 :

Modifier <other than above 4> not allowed here.

Eg : Class Test

{

Static Test( )

{

}

}

CTE : Modifier Static not allowed here.

146

Page 147: Core Java Meterial

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).

- 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 ( )

{

147

Page 148: Core Java Meterial

Super( );

}

}

Programmer’s Code Compiler General Code

1. Class Test Class Test

{ { Test( )} {Super( );

}}

2. Public Class Test Public Class Test

{ {} Public Test ( )

{ Super( );}}

3. Class Test Class Test

{ {Test ( ) Test ( ){ {} Super( );} }

}

4. Class Test Class Test

{ {Test (int i) Test (int i){ {Super( ); Super ( );} }} }

5. Class Test Class Test

{ {Void Test (int i) Void Test (int i){ } { }

Test ( ){Super ( );}}

148

Page 149: Core Java Meterial

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);

}

}

O/P : No arg constructor

Int Constructor

Double Constructor

this. i – invoking a member (variable / method)this ( ) – invoking a constructorsuper. i – invoking parent class membersuper ( ) – invoking a parent class constructor

149

Page 150: Core Java Meterial

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 1st 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.

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( )

{

150

Page 151: Core Java Meterial

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){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.

151

Page 152: Core Java Meterial

Case (ii) : Compiler’s Code

Class P Class P{ {} P ( ) {Super( );}Class C extends P }{ Class C extends P} {

(C) {Super( );}}

NO CTE : Compiles Successfully.

Case (iii) : Compiler’s Code

Class P Class P{ {P(int I) P (int i){ {} Super( );Class C extends P }{ }} Class C extends P

{C ( ) {Super( ); }}

But parent class already contain constructor with int argument, - already 1 contest is present compiler won’t generate any default constr./ So, Super( ) calling which is not present.

P (int) in P can’t be applied to ( ) C extends P.

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 PC (int i) }

152

Page 153: Core Java Meterial

} 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 :

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.

153

Page 154: Core Java Meterial

Default Exception Handling in Java :

/* For every thread, a separate stack is there. Main is a thread. For every method calls performed by that method is stored in that run-time stack.

Eg: Class Test{P S V M(S[ ] a){do stuff( ); } P S V do stuff( )}do more stuff( );

}

P S V do more stuff( );

{

SOP (“Hi”);

}

} */

1. For every thread, there is corresponding run-time stack is associated. For every method call, one entry is going to store in the stack which is called “Activation record” (or) “Stack frame”, whenever the method completes, the corresponding record entry from the stack will be popped out automatically. If the last method also going to be completed, then the thread is ready to die (or) destroy. Before destroying thread, the corresponding stack object will be destroyed first.

Eg: Class Test{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”);}}

154

Page 155: Core Java Meterial

Eg. Describing Default Exception Handling:

Class Test{P S V M(S[ ] args) {do stuff ( );}P S V do stuff( ) {do more stuff ( );}P S V do more stuff( ) {SOP (10/0);}}

1. If any exception is coming, the corresponding method is responsible for the creation of Except Object.

/* Explanation :

Exception happened in do more stuff ( ) method, now the same method is responsible for creating an Exception Object which includes :

Exception Object : What is the ExceptionWhere it is occurredWhat is the reason

Object to the JVM. JVM 1st removes do more stuff( ) checks who is the cause for calling do more stuff, it finds stuff then it deletes that method & go to main & deletes that main also and calls default reception handle. The DEH provides the cause of exception.

*/

2. The Exception object contains the following into :i) Name of the Exceptionii) Description of the Exceptioniii) Location where it occurred (stack trace)

3. After creation of Exception object, the method hand over the object to the JVM.

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.

155

Page 156: Core Java Meterial

RTE for pgm 2 :

Exception in thread main : Arithmetic Exception : / by zeroat test. do more stuff (at test. java : 33)at test. do stuff (at test. java : 18)at test. main (at test. java : 4)

Case :Put SOP (10/0) Statement ini) do stuff methodii) main method and see the O/P.

Exception Handling :

Throwable

Exception Error

(We can handle) (We can’t handle)(recoverable) (irrecoverable)

Linkage Assertion Virtual Mk ErrorError Error

Verify No Class Def Out of Memory Stack OverError Found Error Error flow error

Can be handled by pgmgr.1. Errors r irrecoverable where as Exceptions r recoverable.

/* byte code verifier is part of JVM which checks whether generated. Class file is by java C (Compiler) or not */ .

Exception

Run time IO IO SQL RemoteException Exception Exception Exception Exception

Arithmetic Exception Null Pinter Exception

156

Page 157: Core Java Meterial

Index Out of Bound Exception

Array Index Out of Bound Exception String Index Out of Bound Exception

Class Cast Exception

Illegal State Exception

Array Index Out Of Bounds Exception

Checked Versus Unchecked Exceptions :

- The Exceptions which r checked by compiler for the smooth execution of the pgm at Run time r called “Checked Exceptions”.

Eg : IO Exception.

- The Exceptions which r unable to check by the compiler r called “Unchecked Exceptions”. Run time Exceptions.

Eg : Arithmetic Exception

- Run time Exception and its child classes, error and its child classes r unchecked but the remaining r considered as checked exceptions.

Partially Vs Tully Checked Exceptions :

- A checked Exception is said to be fully checked if and only if all its child classes also checked. Eg : IO Exception.

- A checked Exception is said to be partially checked if some of its sub classes r checked its subclasses need not be checked. Eg. Exception.

Exception Handling by using try – catch :

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){

157

Page 158: Core Java Meterial

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 (i) : If there is no exception.

Stmt 1,23 followed by 5 will be executed.

Indicates Normal Termination.

Case (ii) : An exception raised at Stmt 2 and the corresponding catch block hashas 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 hashas matched.

Stmt 1 only will be executed.

Indicates Normal Termination.

158

Page 159: Core Java Meterial

Methods for displaying error info :

1 Throwable class contain the following 3 methods for displaying error info.

i) Print stack trace ( ) : We will get error info in the following format.

Name of the Exception : Description stack trace.

ii) to string ( ) method : This method displays error information in the

following format.

Name of the Exception : Description.

iii) get Message ( ) Method : This method displays error info

in the following format :

description

arithmetic

Eg : Catch (Exception e)

{

e. print Stack Trace ( );

SOP (e. to String( ));

SOP (e. get Message ( ));

}

try with multiple catch blocks :

1. It is a good programming practice to place a separate catch block for every

exception, because the way of handling the exception is varied from one

exception to another.

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 :

Exception has already been caught.

159

Page 160: Core Java Meterial

Eg: try try{ {SOP (10/0); SO(10/0);} }Catch (AE e) Catch (Exception e){ } { }Catch (Exception e) Catch (AE e){ } { }

CTE :NO CTE Exception : java. lang. AE

Has already been caught.

Control – flow in nested try - catch :

Eg : try Possible Combination of x and y :

{ x : AE E AE E

Stmt 1; y : E AE AE E

Stmt 2;

Stmt 3; In this pgm, we can’t compare the

Try order of inner and outer catches.

{ But either complete inner, (or)

Stmt 4; complete outer we can compare.

Stmt 5;

Stmt 6;

}

Catch (x e)

{

Stmt 7;

}

Stmt 8;

}

Catch (x e)

{

Stmt 9;

}

Stmt 10;

160

Page 161: Core Java Meterial

Case (i) : Exception raised at stmt 2 and corresponding catch block has found.

Flow : Stmt 1, 9 followed by 10

Normal Termination.

Case (ii) : If there is no exception

Flow : Stmt 1, 2, 3 , 4, 5, 6, 8 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 10Normal Termination.

Case (vi) : Exception raised at Stmt 5 but inner and outer catch blocks

r not matched.

Flow : 1,2,3,4

Abnormal Termination.

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.

161

Page 162: Core Java Meterial

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.

Case (x) : Exception raised at Stmt 9 (or) Stmt 10

Flow : 1,2,3,4,5,6

Abnormal Termination.

Note : We can place try block within catch block.

Generic : Wherever java code is present, we can place it

inside try – catch.

“Finally” : /* try

{

Open

read

close

}

Catch( )

{

}

1. Placing all these 3 in single try is not suggestible because there is no

guarantee that all the 3 stmts. Must be executed whenever an Exception is

occurred.

2. If U place that code in catch because no guarantee that catch executes

always.

3. We can’t keep in both because of redundancy.

162

Page 163: Core Java Meterial

1. For the graceful terminal of the program, we have to deal locate all the

resources like :

- Closing DB Connection,

- Closing N/W Streams…

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.

3. It is not suggestible to place clean-up code in catch blocks also because if an

exception not raised the corresponding catch block won’t execute. So we

need a place for keeping clean-up code which should always execute

whether an exception raised or not raised whether an exception is handled or

not handled.

Such place is “finally” 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;

Catch (AE e)

{

SOP(“Caught”);

}

Finally

{

SOP (“finally block”);

}

SOP(“Hello--------“);

}

}

163

Page 164: Core Java Meterial

O/P : 1. Hai finally block

2. Caught finally block

3. Finally block abnormal terminate

4. Finally block

5. RTE Exception

After execution of finally in case of abnormal termination no stmt. Would be

executed.

Note : If a stmt/. Outside try-catch-finally is causing exception then, because

try-catch is not concerned abt that stmt/. So finally block won’t be

executed.

‘return’ stmt, anywhere indicates stopping the execution of that method.

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.

/* Difference among : Final, finally and finalized.

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. */

164

Page 165: Core Java Meterial

$ final, finally and finalized :

Final : It is the modifier which can be applied for variables, methods and classes.

- Final variable means – Constant.

- Final method – It can’t be overridden.

- Final class – It can’t be inherited.

We can’t create child class.

Finally : This is the block associated with try-catd. For maintaining cleanup

code. This block will always execute whether an exception is

handled or not handled (or) an has raised or not.

Finalized ( ) : It is a method available in object class which contain clean-up

code, just before destroying any object, GC (Garbage Collector)

calls finalize ( ) method for releasing the resources associated with

that object.

When compared to finalize( ) method, finally block is always

suggestible bcoz when the Garbage Collector. Runs finalize( ) we

can’t predict (give any assurance).

Possible Combinations of try-catch-finally :

1. try

\ {

}

Catch ( )

{

}

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.

165

Page 166: Core Java Meterial

Saying :

(i) try without catch or finally

(ii) catch without finally. (Null Pointer Exception)

2. try{

} Catch ( )

{ }

VALID

No clean-up code, no finally block.

3. try{

} finally

{ }

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

Try must follow catch/finally. Otherwise CTE.

5. try{

}finally{}Catch( ){}

Order should be followed. Only 1 error occurs. Try finally cal ready there. Catch without finally – error.

Note : We can place try-catch in finally also.

166

Page 167: Core Java Meterial

Control flow in try-catch-finally :

1. try

{

Stmt 1;

Stmt 2;

Stmt 3;

}

Catch ( )

{

Stmt 4;

}

finally

{

Stmt 5;

}

Stmt 6;

Case (i) : If there is no exception.Flow : 1,2,3,5 & 6Normal Termination.

Case (ii) : Exception at Stmt 2 & corresponding catch matched.Flow : 1,4,5 & 6Normal Termination.

Case (iii) : Exception at Stmt 2 but corresponding catch not matched.Flow : 1, 5Abnormal Termination.

Case (iv) : Exception at Stmt 4.Flow : Exception at 1 (or) 2 (or) 3……. 5Abnormal Termination.

Case (v) : Exception at Stmt 5 (or) Stmt 6.Abnormal Termination.

167

Page 168: Core Java Meterial

Control flow in nested try-catch-finally blocks :

1. try{Stmt 1;Stmt 2;Stmt 3;try

{ Stmt 4;Stmt 5;Stmt 6;}Catch ( )

{Stmt 7;

}finally{Stmt 8;}Stmt 9;}Catch ( ){Stmt 10;}finally ( ){Stmt 11;}Stmt 12;

Case (1) : If there is no exception.Flow : 1,2,3,4,5,6,8,9, 11 & 12Normal Termination (N.T)

Case (2) : An Exception at Stmt 2 and Corresponding catch block has foundFlow : 1,10,11 & 12Normal Termination.

Case (3) : Exception at Stmt 2 and Corresponding catch has not matched.Flow : 1, 11Abnormal Termination (A.T)

Case (4) : Exception at Stmt 5 and corresponding inner catch has matched.

Flow : 1,2,3,4,7,8,9, 11 and 12Normal Termination.

168

Page 169: Core Java Meterial

Case (5) : Exception at Stmt 5, but inner catch has not matched, out catch matched.

Flow : 1,2,3,4, 8,10, 11 and 12Normal Termination.

Case (6) : Exception at Stmt 5, inner & catch did not match. Flow : 1,2,3,4,8,11 followed by (A.T)

Case (7) : Exception at Stmt 7 and corresponding catch (outer) has matched.Flow : 1,2,3,4,5,6,8,10, 11 and 12Normal Termination.

Case (8) : Exception at Stmt 7, but catch (outer) has not matched.Flow : 1,2,3,4,5,6,8,11 Abnormal Termination.

Case (9) : Exception at Stmt 8, Stmt 9, Stmt 10, Stmt 11, Stmt 12.

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 ( ){SOPln (“Hi”);thread.sleep (2000);}}

CTE : Unreported exception, java.lang.IE.

Must be caught or declared to be thrown.

Sleep method rises exception IE, because it is predictable that while it is sleeping any one can interrupt checked exception.

1. “throws” clause is used for legating the responsibility of handling exception to the caller.

169

Page 170: Core Java Meterial

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);}}

Here, Sleep method throws a checked “Interrupted Exception”. V should handle this exception by using try-catch (or) V can deligate that responsibility to the caller, by using “throws”. But v didn’t perform anything, hence it is a CTE.

CTE : Unreported Exception : java.lang. Interrupted Exception;

Must be caught or declared to be thrown.

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);}}

“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 ( );

170

Page 171: Core Java Meterial

} }

throw = Handover that object to JVMArithmetic Exception ( ); = Creation of Exception Object

2. After throw, v r not allowed to keep any statement directly, violation leads to CTE, saying:

Unreachable Statement.

Eg : class test{P S V M(S[ ] a) {throw new Arithmetic Exception ( ); SOP (“Hai”);} }

CTE : Unreachable Statement

3. In real-time it is not allowed to throw default exception objects, generally throw customized object.

4. V can throw any “throw able” instance (any exception or error) by using throw keyword.

Eg : class test{Static Arithmetic Exception e;P S V M(S[ ] a) {throw e; // throwing null to JVM but not object} }

CTE : Null Pointer Exception.

CTE (4) : (New Point)

If the try block doesn’t have any chance to throw some fully checked exception,

then v r not allowed to place catch block for such fully checked exceptions. Violation

leads to CTE, saying.

Exception is never thrown in body of corresponding try statement, i.e. v r not allowed to keep for catch blocks for fully checked exceptions unnecessary.

171

Page 172: Core Java Meterial

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.

Eg : Class too young exception extends.

{

Too Young Exception (String S)

{

Super(S);

}

}

class sample{P S V M (S[ ] arg) throws exception{int age = Integer. Parse Int (args[0]);

172

Page 173: Core Java Meterial

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”);

}

}

10 Standard Java Exceptions :

1) Some Exceptions automatically raised by JVM, which r considered as JVM Exceptions.

Eg : Arithmetic Exception.

2) Some Exceptions may be thrown explicitly by the application programmatically. Such type of exceptions r called programmatic exceptions.

1. Null Pointer Exception :

- It is unchecked exception thrown by the JVM.

- This Exception occurs when attempting to access an object with a reference variable whose current value is null.

Eg: Class Sample

{

Static Arithmetic Exception e;

P S V M(S[ ] args)

{

throw e; - null pointer exception

}

}

2. Stack Overflow Error :

- This is unchecked by compiler and is thrown raised by JVM (recursive method invocation).

173

Page 174: Core Java Meterial

Eg: Class Sample

{

P S V M(String[ ] args)

{

M1( );

}

P S V M1 ( )

{

M1( );

}

}

3. Array Index Out of Bounds Exception :

- It is unchecked Exception raised or thrown by the JVM, whenever v r accessing an array element with out of range index.

Eg: Class Sample

{

P S V M(S[ ] args)

{

int[ ] a = new int [10];

SOPln(a[11]; // AIOOBE

}

}

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

}

174

Page 175: Core Java Meterial

}

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 :

- 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.

175

Page 176: Core Java Meterial

8. Number Format Exception :

- It is direct child class of “Illegal Argument Exception” and is unchecked exception.

- It is thrown programmatically to indicate that the application has attempted to convert a string to numeric type but the string does not have appropriate format.

Eg: int i = Integer.parseInt (“10”);

jnt i = Integer.parseInt (“TEN”)

java.lang. Number Format Exception : For input : “ten”

9. Illegal State Exception :

It is the child class of run-time exception. It indicates that a method has been invoked at an illegal or inappropriate time, thrown by API Developer.

Eg : After Starting the thread, restarting the same thread once again will cause Illegal State Exception.

10. Assertion Error :

- It extends Error thrown programmatically when an “assert” statement fails.

Summarization Table

Exception / Error Thrown by

1. Null Pointer Exception

2. Stack Overflow Error

3. Array Index Out of Bounds JVM

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

176

Page 177: Core Java Meterial

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

time there won’t be memory for the creation of new objects, hence the program will

fail.

2. But in Java, creation of objects is responsibility of programmer but destruction of

objects can be performed by garbage collector which is always running in the

background. Hence in most of the cases java program never fails because of

memory problems. Hence GC is one of the reasons for calling java as robust.

/* 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.*/

177

Page 178: Core Java Meterial

3. The negative side of Garbage Collector is :

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.

2. Ways of Making an object eligible for GC : (good programming practice)

1. The programmer is not responsible for destruction of objects, but is recommended to make an object eligible for GC, if it is no longer use.

2. Ways of making an obj eligible for GC :

a) Nullifying the reference variable :

By assigning null to the reference variable V can make explicitly an object eligible for GC.

Eg : Student S = new Student ( ); ----------- ----------- Code using content of student object with’s’. -----------

S = null

Now, the object eligible for GC.v r reducing the GC.

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

3. The objects which r created as part of method execution r by default eligible

for GC after method completion, except that method doesn’t return any object. If the method returns an object and allocating a new reference variable for that won’t make that object eligible for GC.

Eg 1: Class Sample{P S V M(S[ ] a){M1( );At this line 2 objs (referred by S1, S2) eligible}P S V M1( ){

178

Page 179: Core Java Meterial

Student S1 = new student( );Student S2 = new student( );}}

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*/

/* 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 iTest t2 = new test( );Test t3 = new test( ); No obj eligible for GC}} t3 i=*/

Eg : Class test

179

Page 180: Core Java Meterial

{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 GCt3 = 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.

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)

5. Ways of requesting JVM to run GC :

We are not allowed to destroy the objects, but v can request JVM to run GC.

We are this, v have the following 2 possibilities :

i) System.gc( ); (Recommended because no need of object creation)

System class contains a static gc( ) method for requesting JVM to run GC.

ii) By using Runtime Class :

/* r. free memory ( ); gives the empty heap memory

r. total memory ( ); to know the total memory

r. gc( ); */

By using runtime object a Java application can communicate with JVM. It contains the following instance methods. Java application JVM

i. free memory ( ) : Returns the free memory of the JVM heap in bytes.

ii. Total memory( ) : Returns the total heap size in bytes.

180

Page 181: Core Java Meterial

iii. gc( ) : Requesting JVM to run GC.

Runtime class is a singleton class, (only 1 instance can be created) we can create the object by using the static method get Run time( );

i.e Run time r = new Runtime ( );

Run time r = Runtime. get Run time ( );

// Run time n = Runtime. get Run time ( );

r.gc ( );

By using gc( ) method, v can request JVM to run Garbage Collector, but it is upto JVM to accept our request or not, v can’t give any assurance.

Eg : describing GCclass 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 bytesSOPln (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( )) ;}}

80-100 because gc instantly work (or) not> 100 because gc not only destroys date objects but also other objs which v un referred if precent.

O/P :2031616190890418842081943840 (> 2nd one) Other unreferred objs may also deleted.512 kb is the default JVM heap memory. V can increase it.

IDE - ?Heap Memory - ?Static Method / Factory meth both r same.

181

Page 182: Core Java Meterial

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( );Thread.sleep (3000);SOPln (“End of Main”);}Public Void finalize( ){SOPln (“Finalize Method Called”);}}

O/P : End of main.

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( )

182

Page 183: Core Java Meterial

{SOPln (“Finalize Method Called”);}}

O/P : End of main Finalize method called [before introducing sleep( )]Finalize method called end of main [after introducing sleep( )]

/* For every object destroying, gc calls finalize( ) method every time */

Case 1 : for (int I = 0; I<100000; I++){Test S = new Test( );S = null;}// System.g ( );thread.sleep (3000);

/* Once main thread completed GC stops, won’t run */

Case 2 :

/* v can call finalize method explicitly as v r calling any other method */

/* Class Test{ Public void finalize ( )P S V M(S[ ] a) {{ SOPln (“Finalize Method”);Test t = new Test( ); SOPln (10/0);t.finalize( ); }}}

O/P : Finalize Method.Exception : java. lang. AE : / by zeroAbnormal Termination.

O/P Finalize Called Public void finalize ( )

Caught {Normal termination. try

{ {Test t = new Test( ); SOPln (“Finalize Method”);t.finalize( ); SOPln (10/0);} }} Catch (Fle e)

{SOPln (“Caught”);

183

Page 184: Core Java Meterial

}}

/* 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(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.

184

Page 185: Core Java Meterial

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 = nullSystem.g( );Thread.sleep (2000);SOPln (S.hash Code ( ));S = null;System.gc ( );Thread. Sleep (3000); SOP (“Hi, end of main”);}}

Public void finalize( ){SOP (“Hi Finalize Called”);S = this;}

O/P : 2 8 1 6 8 9 2 5

Hi, finalize called same

2 8 1 6 8 9 2 5

Hi, end of main

By this time object destroyed.

/* If pgmgr calls finalize( ) the GC won’t consider this count, it considers only its own count*/

Multi – Threading :

185

Page 186: Core Java Meterial

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.

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

Process based Multi-taksing Thread-based Multi-tasking

i. Writing Java Pgm

ii. Listening to songs

iii. Downloading a file from Net

- Multi-tasking is divided into 2 categories :

i. process-based multi-tasking

186

Page 187: Core Java Meterial

ii. thread-based multi-tasking

Process based multi-taksing :

i. Executing Several tasks simultaneously, where each task is a separate

independent process is known as “Process – based Multi taksing”.

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.

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).

ii. Non-Oop langs like ‘c’ donot have this feature.

iii. Compared to c++, Java thread based MTK is easy.

Java provides in.built support for multi-threading by introducing a rich set of

library, programmer can easily develop thread based applns.

Code (based on thread-based MTK)

187

Page 188: Core Java Meterial

C++ 100 to 150 lines Java 5 to 10 lines(Everything has to be implemented programmatically)

iv ) The main objective of multi-threading is decrease response-time of an appln/.. and

increase the performance of the system.

/* Java is simple because, java pgms, can be implanted easily, because knowing how to

use libraries is enough, v never bother about internal implention */

/* Memory areas of 2 different processes r entirely different. Because of seperation

heavy weight switching b/w one process to the other is difficult & costly. Where as

multiple threads of same process share common memory and shifting is easy so light

weight.

Process : A separate independent task

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.

188

Page 189: Core Java Meterial

Sirs experience reg M.td :

Project 300 applns telecom– connecting call, – calculating (counting) time, – calculating bill.

Maintainance (24x7 sqmr) – needs smooth execution of 300 appln is verymuch needed.

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.

300 apgb – 70 ppe – each has 10 appli in nand

They should be responsible for 24 x 7 smmt 12 hrs by 2 code

Horrible increase resources 240

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;

i) Defining Thread by Extending Thread Class :

/* 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 */

/* Eg : IO Print 20 times GM.

Class sample { } main( ) { for (int i = 0; i<20; i++);

SOPln (“God Morning”);

189

Page 190: Core Java Meterial

}

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 */

/* If U want to divede a task into 2 go for threads conept */

/* Because processor allocates a single stmt at am fine, gow reltine by maintaining

threads ? Ans : thread makes the processor to not to be in idle state. Eg : An applnt

neanes user defaults, while enteris data by user, until be entered data main( ) in ideal to

process the U allocate that to other task */

Eg : Class Mythread extends thread{Public Void run( ){for (int i = 0; i<10; i++){SOPln (“GM : Child thread”);}}

Eg : Class Thread Demo{P S V M (S[ ] args){At this point only 1 thread main is running my thread t = new mythread( );Same, I thread main is runningt.start ( ); starting a threadthreads startedfor (int i = 0; i < 10; i ++){SOPln (“GM : Main thread”);}}

O/P : V Can’t predict the O/P

190

Page 191: Core Java Meterial

/* Even though threre is no start( ) in Mythread, how can v call. Because start( ) present

in thread class vr extending thread class v can call that method. */

O/P : GM : Main Thread scheduler followsGM : Chil Round-RobinGM : Main Algorithm / Shortest job first.

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.

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 ( ){

191

Page 192: Core Java Meterial

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).

Case (iv) : If V r overriding start( ) method:

Eg : Class Mythread extends thread

{

Public Void run( )

{

SOPln (“run”);

}

Public Void Start( )

{

SOPln (“Start”);

}

}

Eg : Class Thread Demo

{

P S V M (S[ ] args)

{

Mythread t = new Mythread( );

t.start( );

}

}O/P : Start

When v override start( ) method, no new thread is created, it won’t call run( )

method, it will execute as a normal method.

192

Page 193: Core Java Meterial

Case (v) :

Eg : Class Mythread extends thread

{

P V run( ) {SOPln (“run”);}

P V Start( ) (Super.Start( ); SOPln (“Start”);}

}

Class Thread Demo

{

P S V M (S[ ] a)

{

Mythread t = new Mythread( );

t.start( );

}

}

O/P : v can’t predict. Start (by main thread)

Run (by Child Thread)

Main (by Main Thread)

Explanation of execution of above pgm’s :

Whenever the run emthod completes, thread expires :

Case (vi) : Overload a run( ) Method :

V can overload run method, but thread class start ( ) method will always call nen( )

method without any arguments.

Eg : Class Mythread extends thread

{

P V run( ) { SOP (“Run Method”);

P V run(int i) { SOP (“Run Method int”);

}

Class TDemo

193

Page 194: Core Java Meterial

{

PS V Main (S[ ] a)

{

Mythread t = new Mythread( );

t.start( );

}

}

Just like a normal method, v can call explicitly overloaded run( ) method.

/* Every thread is created to do a particular task, which is defined in run( ) method */

Life Cycle of a thread :

/* 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”.

Defining, Instantiating and Starting a Threads by “implements Runnable” interface:

1. The Runnable interface present in java.lang package contains only one method :

run( )

interface runnable

{

Public void run( );

}

2. Thread implements runnable

194

New/Born

t.start ( ) Ready/Runnable (Ready to run)

Thread scheduler allocates CPU

Running (Executing run method)

If run( ) method completed Dead

state

Page 195: Core Java Meterial

extends

Mythread

Instead of doing above one indirectly, follow the below one :

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.

Eg : Class Myrunnable implements runnable

{

Public void run( );

{

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 */

// Thread t = new thread( ); t.start( );

/* v can’t write above stmts, because t.start( ) calls run( ) method of thread class which

does nothing */

Thread t = new thread ( r); (r ) – target runnable

t.start( );

195

Page 196: Core Java Meterial

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.

Case (i) : t.start( ) method :

i) Thread class start( ) method will execute, which calls, Myrunnable, run( )

method. In this case, a new separate thread created.

Case (ii) : t.run( ) method :

(Almost similar to overriding concept)

thread t = new thread ®;

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.

Case (iii) : r.run( ) method :

MyRunnable run( ) method will execute just like a normal method. No new thread

will be created.

O/P : Run Main Thread.

Case (iv) : r.start( ) method :

MyRunnable class doesn’t contain any start( ) method, hence it is a CTE.

196

Page 197: Core Java Meterial

CTE : Can’t resolve symbol

Symbol : Method start( )

Location : Class My Runnable

r.start( );

Comparison b/w extends thread class and implements runnable :

- In the 1st approach (extending thread class) our class has to extend thread class, it is

not allowed to extend any other hence v r missing the key benefit of Oop –

Inheritance. Hence this approach is not suggestible in the real-time.

- 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.

Thread class constructors :

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);

Case – Study (Mix of – extends, implements) :

Class Myrunnable extends thread

197

Page 198: Core Java Meterial

{

P V run( );

{

SOP (“Run”);

}

}

Class Thread Demo

{

P S V M (S [ ] args)

{

Mythread t = new Mythread( );

Thread t1 = new Thread( t );

t1.run( ); run method of mythread as a simple method, but a new thread won’t created

t1.start( ); run method of mythread will be executed, a new thread is also created.

SOPln (“Main – Thread”);}}

Set and Get the name of the thread :

For every thread, r can assign the name, thread class contain the following methods for

setting and getting the name of a thread.

Setting and getting

1. Public final void setName (String Name)

2. Public final string getName ( )

Demo on Setter & Getter Methods :

198

Page 199: Core Java Meterial

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”).

// SOP (10/0); Exception in thread karthikeya.

}

}

O/P : Karithikeya

Thread Priorities :

/* Every thread in Java has by default has priority.

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

1 is having LEAST Priority

10 is having HIGHEST Priority

2. For defining standard priorities, thread class has the following constants. They are :

Thread. MAX – PRIORITY 10

199

Page 200: Core Java Meterial

Thread. MIN – PRIORITY 1

Thread. NORM – PRIORITY 5

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 :

i. Public final void setPriority (int i)

The valid range for ‘i’ is 1 – 10

If v give value for argument not within the range 1-10, v will get a Runtime

Exception Saying : “Illegal Argument Exception”.

// 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( )]; //

}

}

Class Mythread extends thread

{

Public void run( )

{

for (int i = 10; i < 10; i++)

{

SOP (“Child Thread”);

}

}

200

Page 201: Core Java Meterial

}

Class Thread Demo

{

P S V M (S[ ] a)

{

// Thread.current Thread( ). SetPriority (10);

// SOPln (Thread.current Thread( ).getPriority( ));

// Mythread t = new Mythread( );

// SOPln (t.getpriority); // 5 x 10

Mythread t = new Mythread ( );

t.start( );

for (int i = 0; i<10; i++)

{

SOPln (“Main Thread”);

}

Mythread t = new Mythread( );

t.setpriority (10);

t.start( );

for (int i=0; i<10; i++)

SOPln (“Main Thread”);

}

}

O/P : Child Thread (10 times)

Main Thread (10 times) //

Conclus :

201

Page 202: Core Java Meterial

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 :

// There is no concept of default priority for bulling every thread as ‘5’.

The default priority for only main thread is 5 and for all the remaining threads,

priority is inherited from parent. I.e. whatever the priority parent has, child also

having the same 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