Vous êtes sur la page 1sur 203

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 9. Overriding120 10. Constructor ...144 11. Exception Handling .155 12. Garbage Collector 176 13.Multi Threading .185

SCJP Syllabus 1. 2. 3. 4. Language Fundamentals. Operators and Assignment *** Declaration and Access Control Oops Encapsulation, Inheritance, Aggregation (Composition) Polymorphism Coupling & Cohesion. Object Class String String butter String builder Wrapper classes

5. 6.

Multi-Threading (15 to 20 hrs.) Java. Lang

7. 8. 9. 10. 11. 12. 13.

Exception Handling (10 hrs.) Assertions [used for debugging purposes (5hrs)] Garbage Collection File I/O & Serialization Customized (4hrs) Auto boxing & Auto unboxing, static impolts, var-arg method, num Collection framework (25 to 30 hrs). Generics. (40 50 days) Development

Exam Pattern : 72 QS (Multiple Choice) & (Drag and Drop) 43 QS 59% Most of the Indian Projects are Maintenance only.

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 : abc123 123abc abc @ 123 .etc. 2. No identifier in Java Starts with the digit.

3. 4. 5. 6.

We r not allowed to use keywords as identifiers violation leads to compile-time error. There is no length limit for java identifiers. But Sun highly recommends upto 15 characters suggestable for identifiers. (In C++ 256 is max. length) 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. All the pre-defined Java Classes and inter fore name we are allowed to be used as identifiers. There is no
Compile time errors. Run time

Eg. : int String = 10; (Pre-defined class name but not the keyword). S.O.P(string); O/P : 10. Note : (b) But take care of ambiguity problem because in some cases U cant distinguish String (A class name) as predes class (or) identifier name.

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) true, false to represent boolean value null for representing object references

Used Key Words (48)

Un-used (2) goto, const.

Primitive Keywords for data types : (8) byte short int long float double char boolean (logical)

Keywords for flow control : (11) if else switch case default for do while break continue return

Keywords for exception - handling : (6) try catch finally throw throws assert (introduced in 1.4) Mainly used as tool for debugging purposes. Keywords for modifiers : (11) Public Protected Private Static Abstract Final Synchronized (not synchronize) Volatile Transient Native Strictfp (not Strict Fp)

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) Class Interface Extends (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) Super this

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 final goto 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 dont want to miss the wonderful enumeration concept. Eg. : enum month { JAN, FEB, MAR.. etc. } Reserved Words for defining literals : (3) true false null Note 1 Note 2 : : All the keywords (reserved words) in java contain only alphabet symbols and all are in lower case. assert introduced in 1.4 enum introduced in 1.5 No 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 exp ression has the type - Compiler always searches for type compatibility Boolean b = o;
var iable

(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 Numeric types For representing whole numbers. 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 byte short int long float double char boolean Corresponding Wrapper class Byte Short Integer Long Float Double Character Boolean

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

1. byte : ** Size : 8 - bits Range : - 128 (min) to 127 (max)

(MSB) Sign bit 0 +ve 1 -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 2s 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. 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 Range Short : : 2 bytes -215 to 215 1 (-32.768 to 32767) S = 32768;

Note :

Comp. Error : PLP found : int required : short Rarely used data type. But where it is used ?

When Java was introduced in 1995, processors are of 16-bits, they used short data type. But now, 16 bit processors are outdated, the short data type is also outdated (almost). This is why is rarely used in regular pgmg. Short d.t is best used for 16-bit processors like 8086.

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

Floating Point d.types :

Float Size : 4-byte This is suitable if U want to consider 6 to 7 fractional digits of accuracy is required. This is single precision (6 to 7) Less accurate. Range : -1.4e 45 to 3.4 e 38 Char data type : Size : 2 bytes

Double Size : 8-byte This is suitable if U want to consider 14 to 15 fractional digits of accuracy is required. This is double precision (14 to 15) More accurate. Range : 4.9 e 324 to 1.8 e 308

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

Eg : int x = 0 if (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 1. byte 2. short 3. int 4. long 5. float 6. double 7. char 1 2 4 8 4 8 2 Range 128 to 127 32768 to 32767 231 to 231 1 263 to 263 1 3.4e38 to 3.4e38 1.7e308 to 1.7e308 Unicode values : 0 to 65, 535 NA (allowed values are true / false) Wrapper class Byte Short Integer Long Float Double Character Default value 0 0 0 0 0.0 0.0 0[indicates blank space character] false (but in C, C++ (1) i.e True)

8. boolean NA

Boolean

Literals : ** A literal represents the constant value which can be assigned for the variable Eg. Int datatype keyword x name of variable identifier = 10; constant value literal

12

Integral literals : Literals that are assigned to Integral data types such as int, long, short and byte. For the integral types, we are allowed to specify the value by using one of the following possible literals. i) Decimal literals : Allowed digits 0-9 Eg : int x = 10; 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


OX 10;

This is one of the very few areas, where java is not case sensitive. Eg : int y = OX 10; ; (x in any case) (Any case is allowed) The number must be prefixed with either ox (or) OX.

af A F

We cant assign binary literals for integral data types. Class Test { Public Static Void Main (String args [ ]) { int x = 10; int y = 010; int z = 0X10; S.O.Pln (x + . + y + .. + z); } } 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 found : long

Eg :

O/P : 108..16. Note :

13

req : int. ** There is no direct way to specify an integral literal is of byte type (or) short type. We can assign an int value to the byte or short variables but it should be within the range supported by the. Corresponding data type. Eg : byte b = 10; 10 is also int type, but because 10 is within range of byte, it is considered as byte.

byte b = 10b; This is similar to short also. Short S = 10; Short S = 10s; Floating Point Literals : @@ By default, floating point literal is of double type we cant 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 = 123.456 F ; @@ We cant 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.
123.456 f ;

- We cant assign floating point literals for integral types @@ - We can directly assign an integral literal to the float data type.

14

Eg : float f = 10; S.O.P(f); O/P : 10.0 Note : No need of Suffix f/F For integral literal when assigned to floating point data types.

Exercise : 1. float 2. float 3. double 4. double 5. double 6. float #7. float #8. float f f d d d f f f = = = = = = = = 123.456; 123.456f; 123.456d; 123.456; 123.456D; 123; 0123; 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 shouldnt age 123e2 assigned to int variable. Eg: int i = 123e2; 10. double d = 123e2; 123456e98;

15

Possible assignment : byte short char 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 symbol Symbol : Variable TRUE Location : -----boolean b = 1; in case of C, C++ boolean b = 1; in case of Java. Comp. Error : In compatible type Fount : int Required : bodlean. int long float double

Eg :

Here we dont 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

Exercise : 1. boolean boolean boolean boolean boolean b b b b b = = = = = true; FALSE; O; yes; (10>20); (x > y); Cant resolve symbol Incompatible types Cant resolve symbol 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; Char ch = 3I47; SOP(ch); O/P : a

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)s Char Ch = 0x61; Char Ch = \u0061;

17

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 Sequence \b \t \n \r \f \ \ \\ big farms Unicode Value \u0008 \u0009 \u000a \u000d \u000c \u0027 \u0022 \u005c need red tractors Character Backspace Horizontal tab New line Carriage return Form feed Single quote Double quotes Backspace

18

String literals : A sequence of characters within double quotes is considered as a string literal. Eg : Strings = Cognizant Technology Solution. Sopln(s); String Si = cognizant\n Technology \n Solution; \u0009 \u00a Note : Instead of \n and \r we are not allowed to use the corresponding unicodes (\u000a and \u000d). Violation leads to compile time error. The above unicodes r not allowed even in the comments also. The error appears for the next line.

19

(2-3 Qs) Arrays 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

Cant increase or we cant 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 cant avoid duplicate object insertion by default. Agenda (Arrays) 1. Arrays Intro 2. 3. 4. 5. Declaration Construction Initilization Declaration, Construction & Initialization in a single line. )

6. Length vs length (

7. Anonymous arrays (Nameless) 8. Array element Assignments 9. Array variable Assignments

20

Array Declaration : (1 1 arr decl) Eg : int[ ] a; {int (datatype), [ ] (dimension), a; (Name of array)} This approach is suggestible because, by seeing the stmts only we can say a is a single dimensional array of int type. int a[ ]; It is valid that we can place the dimension even beside the name of the array. At the time of declaration, we are not allowed to specify the size, violation leads to fompile time error. I.e. Eg : int[6] a; L dimensional array declaration : Eg : The dimension can be specified after the name (or) after the type. 1. Int[ ] [ ] 2. Int 3. Int [ ] 4. Int[ ] a; a[ ] [ ]; a[ ]; [ ] 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. Arrays int[ ] [ ]a,b; a 2-D b 2-D int[ ] [ ]a, [ ]b; Comp. Error.

Becoz the dimension should not be preceded before the 2 nd variable, it is only & only for the 1st variable. int[ ] [ ]a, b[ ] a 2D b 3D Exercise : int[ ] [ ] [ ] int[ ] [ ] int [ ] [ ] int [ ] [ ] int [ 6 ] 3-D array declaration: int [ ] [ ] [ ] int int [ ] int [ ] [ ] int [ ] int int [ ] int [ ]

a; a 3D [ ] a, b; a,b 3D [ a ] a, b [ ] [ ]; a 3D, b 5D [ ]a, [ ]b; a; a; a[ ] [ ] [ ]; a [ ] [ ]; a[ ]; [ ] [ ] a; [ ] [ ] [ ]a; [ ]a; [ ]a [ ], [ ] b [ ]; 21

Construction of Arrays : (1-D array Construction) - An array itself is an object in Java, whether it may be of any dimension. 1. Construction : 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
Canbepromoted

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

22

6. We can assign the size of the array even with a realizable also. Eg : byte b short s = 100; int[ ] an = new int [ s ];
i b

int i long l = 10L; int[ ] arz = new int = [ l ]; Error : PLP chart ch = a; int [ ] i = new int [ ch ]; array size is 97 ints. int[ ] i = new int [ a ]; int [ 10 ] a = new int [ 10 ]; At the time of declaration we shouldnt 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.

23

Eg : My req; a[0] a a[1] a[2] - 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 [ int [ int [ int [ ][ ][ ][ ][ ] a = new ] a = new ] a = new ] a = new int [ ] [ ]; Missing base size int [ 2 ] [ 3 ]; int [ ] [ 3 ]; (Specify size from L R) int [ 1 ] [ ] [ ] [ 4 ]; Comp. Error

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

a[2]

a[0] [0] [0 ]

24

Code : int[

][

][

= new int [ 3 ] [ = new int [ 2 ] [

][ ];

];

a[ 0 ]

a [ 0 ] [ 0 ] = new int [ 3 ] ; a [ 0 ] [ 1 ] = new int [ 2 ] ; Exercise : 1. int [ 2. int [ 3. int [ ][ ][ ][ ][ ][ ][ ] a = new int [ 3 ] [ ] [ ]; ] a = new int [ ] [ 4 ] [ 5 ]; ] a = new int [ 3 ] [ ] [ 6 ];

*** If u have given value for any dimension, all its previous dimensions must be defined. 4. int [ 5. int [ Structure : a ][ ][ ][ ][ ] a = new int [ 3 ] [ 4 ] [ 1 ]; ] a = new int [ 2 ] [ 3 ] [ 1 ];

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.

25

Eg.1 : double [ ] [ ] d = new double [ 2 ] [ 3 ]; Internal Structure : d[ 0 ] d[ 1 ] d reference of d[0] [0] d [0] [0] d [0] [1] Object array 0.0 0.0 d [0] [2] 0.0 reference of d[1] [0] d [1] [0] d [1] [1] d [1] [2] 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 wont 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 (a


[ 0] [1] [ 2] [10] +a +a + ...... + a ); 10 0 0 100

[(0, 0 = default values) (10, 100 Over hidden values)] O.P. = 110/

26

Eg.4 : int [ ] a = new int [ 3 ]; a [ 1.5 ] = 60; a [ 0 ] = 10; a [ 1 ] = 20; a [ 2 ] = 30; a [ 3 ] = 40; AIOOBE (Run time Error) a [ -1 ] = 50; AIOOBE If we r accessing an array element, with ve index (or) an index value which is in out of range, we will get a run-time exception saying Array Index Out Of Bounds Exception along with index number. Declaration, Construction and Initialization in a Single line : Eg : int[ ] a; a = new int [ 3 ]; a [ 0 ] = 10; a [ 1 ] = 20; a [ 2 ] = 30; Sphagetti Code String [ ] str = {xxx, yyy, zzz}; Char [ ] ch = {a, a, c}; int [ ] a = {10, 20, 30}; (Internally JVM creates an array object of size 3) Real time code

In the above approach U cant 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)

27

- D,C,I of Multi D array in a single row. Eg : int [ ] [ ] a = {{10,20}, {30,40,50}, {60}};

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

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

28

Exercise : 1. 2. int [ ] a = new int [ 6 ]; S.O.Pln (a length); // O.P : 6 int [ ] [ ] a = new int [ 2 ] [ 3 ]; a.length = 6 a.length = 2 (size of base array) a[ 0 ].length = 3 There is no direct method which represents, the total no. of elements of multidimensional 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 :

29

new int [ ] [ ] {{10,20}, {30,40}}; ** -

While Declaring anonymous arrays, we r not allowed to specify the size. Violation leads to compile time error. i.e. new int [ ] {10,20,30}; new int [ 3 ] {10,20,30}; Eg : Expected.

int [

] a = new int [ 2 ] {10,20}; (shouldnt be mentioned)

in general, all the static methods are utility methods. int i = a; SOP (i); //97 float f = 10; 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 cant 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);

30

Array variable assignments : While performing assignment of one array to another array, we have to check the declared types, not its sizes. Eg : int [ ] a = {10,20,30}; int [ ] b = {40,50,60}; a = b; int [ ] a = {10,20,30,40,50,60,70,80}; int [ ] b = {100}; 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 cant 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 cant provide value. Int [ ] [ ] a = new int [ 3 ] [ 2 ]; a [ 0 ] = new int [ 2 ]; a [ 0 ] = new int [ 100 ]; a [ 1 ] = 10;

31

comp. error :

Incompatible types. found : int req : int [ ]

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 variables 2. Reference variables. 1. Primitive variables : These variables can be used for holding primitive values Eg : int a = 10; (a = P.V.) 2. Reference Variables : These variables can be used for refereeing objects. Eg String S = kiran; (S = R.V.) Based on the position and the purpose, variables are divided into the following 3 categories : 1. Instance variables 2. Static variables and 3. Local variables

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.

32

These instance variables will be created when the corresponding object is created. If the object is destroyed by the Garbag. Collector (GC), automatically the corresponding instance variables will also be destroyed. Instance variables exist as long as the corresponding object present on the heap. We have to declare instance variables within the class, outside of any method or constructor. Eg : Class Test { int i; P S V M(S[ ] a) { SOPln (i); // we should create object first. } } Test t = new test( ); SOP (t.i); CTE : non-static variable i cant 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 collname duplicated in all object which is of no use. So, U maintain that value in a single variable of type static which is a class level variable. If the value of a variable, is same for all objects, such type of variables not suggestable to declare at object level. We have to declare these variables at class level so that a single copy is shared by all instances. Such type of variable we have to declare by using keyword static.

33

i.e. Instance variables are object level variables but static variables are class level variables.

Note : Dont 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. 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

34

Local Variables : Also known as Temporary Variables (or) Stack Variables (or) Automatic Variables. Within a block if we declare any variable, for temporary purpose, such type of variables are called Local variables. The Scope (where these can be present) of is where they are declared within a block. Eg : class sample { P.S.V.M (S[ ] a) { int i; Sopln (i); } } O/P : Comp. Error : Variable i might not have been initialized. For the local variables, there wont be the concept of Default Initilization. It is programmers 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 (Dont Sleep); } } O/P : Dont sleep (no comp. error. i is not used till now)

35

Eg : class sample { P.S.V.M (S[ ] a) { int i; if (args.length > 0) { i = 10; } Sopln (i); } } O/P : Comp. error : V i m n h i. Note : Initialization is not suggestable in the conditional blocks. Eg : class sample { P.S.V.M (S[ ] a) { int i; if (args.length > 0) { i = 10; } else; { i = 20; } SOP (i); } } O/P : No compile time & run-time error.

36

Conclusions : If U R not performing initialization, for the static and instance variables, default values will come. But for the local variables, default values will come. But for the local variables, there is no concept of default initialization we should perform initialization before using local variable. Local variables, the only allowed modifier is final. i.e. the following local variable declarations. Invalid Public Private Static int i = 10; int i = 10; int i = 10; Error : illegal start of expression final int i = 10; int i = 10;

Local variables cant be static because static variables can be accessed with classname and object of class outside the methods also, but local variables cant 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. 2. int [ ] a int [ ] a = new int [ 6 ]; sopln (obj. a); null. sopln (obj. a [ 0]); NPE sopln (obj.a); i@ 12D34 sopln (obj.a[ 0]); O

37

Static : 1. 2. int [ ] a; int [ ] a = new int [ 6 ]; sopln (a); null. sopln (a [ 0]); NPE sopln (a); i@ 1add 2dd sopln (a[ 0]); O Local level : 1. 2. int [ ] a; int [ ] a = new int [ 4 ]; sopln (a); CE No need of its components 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 cant print a3[ 0 ], results in CJE because null object points to nothing. Where as if V declare an array as local, then, V cant 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 Static Void Main * : 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. : Without object also we can in invoke this method. : This method doesnt return anything to JVM. : 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

Different cases w.r.t. main ( ) : 1. class test { --------} > javac test > java test No such method error. Compiler never checks whether class contain main method or not but at run-time JVM checks for the main method with the specified signature. If it is not finding any method with the specified signature, it lises no-such method error. Note : It is run-time error only, but not compile time error. 2. Class test { Private static void main (String[ ] args) { --------} } Run time error : Main Method not public. In java, a method is not allowed to be declared within another method. 3. Class test { Public void main (String[ ] args) { SOP (.); } } O/P: Run time error : No such method error.

39

4.

Class test { Public static int main (String[ ] args) { SOP (.); return 10; } } RJE : No such method error.

5.

Class test { Public static void main (String[ ] args) { SOP (.); } } NO CTE, RTE; No such method error.

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 wont over write main method. } }

40

7. Public static synchronized void main (String [ ] args) { 8. Public static void main (String args) { } RTE ; No such method error. 9. Public static void main (String [ ] Pavan Kiran) { 10. Public static void main (String args) { } Command line arguments : Arguments passed during run-time in command prompt Eg : java test arg [ 0 ] [ 1 ] 10 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. 20 [2] 30 [3] 40 }

Command-line arguments

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 } String } Args, Main } Keywords Class name Not keywords

41

Eg : Public class A { P S V M (S[ ] args) { String [ ] [ ] argcopy = new string [ 2 ] [ 2 ]; int x; argcopy [ 0 ] = args; x = argcopy [ 0 ].length; for (int y = 0; y<x; y ++) { SOP ( +argcopy[ 0 ] [ y ]); } } } java A 1 2 3 O/P : 1 2 3

42

Operators & Assignments


Agenda : 1. 2. Increment / Decrement Operators. 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

Decrement Operators : y - -; Post Decrement - - y; Post Decrement Table : Expression Initial Value of x 4 4 4 4 Final Value of x 5 5 3 3 Initial Value of y 5 4 3 3 Final Value of y 5 4 3 4

y = ++x y = x++ y = --x; y = x --; Conclusions w.r.t. SCJP : 1. int y = + + 4; compile-time error : required found * 2. : :

un excepted value variable value

x = 5; int y = ++ x;

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

Nesting of Increment / Decrement Operators is not allowed violation leads to CTE int x = 4; int y = + + (++x) CTE found : : required : variable value (returns a const. But not variable and ++ (const) is invalid) Unexpected value.

3.

We cant apply Increment / Decrement Operators for the final variables. Violation leads to compile time error. Eg : final int x = 4; ++x; // x ++ (Here re-initialization for x after increment done but in is final) SOP (x);

44

CTE : Cant 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 short + short int + long float + double int + byte int + int int int long double 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

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 float + double short + float 2. S.O.Pln (10/0) RE : Arithmetic Exception : / by zero S.O.Pln (10./0) O/P : Infinity > javap jav.lang. Float int double float.

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

46

Double Integer For representing infinity, there r constants defined in the Float and Double wrapper classes. They r: public static final positive infinity public static final negative infinity But there is no such arrangement in the case of Integral types (Byte, Short, Int and Long) represent infinity. Hence Division by zero AE results only in case of integral types but not in floating point data types. int 10/0 double 10.0/0 -10.0/0 3. int (but no const in Integer class) double (there is a const / defined in double class for representing infinity) (-Infinity)

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 10.0/0 -10.0/0 A.E Infinity Infinity

47

-0/0 -0.0/0 3. 1.4 :

AE NaN

There is no math class in 1.5 but there in 1.4 S.O.Pln (Math. Sq.rt (4)); O/P : 2.0 SOPln (Math. Sq.rt (-4)); O/P : NaN 4. For any x value including NaN, the following statements results. x > Float NaN x< x> x< x==

O/P : False [SODln (x ! = Float.NaN), O/P : true] But, the result of below stmt is true. Float.Non! = Flat.NaN O/P; True SOPl (Float.Non! = Flat.NaN); True SOPln (Float.Non! = Flat.NaN); False. Conclusion : Arithmetic Exception : - meant for only integral types not for float, double - only & operators (/, %) cause their exception. 4. String Concatenation Operator : Till 1.4, only + operator is overloaded. But in 1.5, % operator is also overloaded. + Operator is the overloaded operator in Java. Sometimes it acts as Addition operator and sometimes it acts as String Concatenation Operator. If atleast one of the operands is the string type, then + oprator simply acts as Concatenation operator. If both operands are numbers then + acts as Arithmetic Addition operator. Eg 1: 2 + 3 = 5 ab + cd = abcd ab + 3 = ab3

48

Eg 2: int int int String SOPln

a = 10; b = 20; c = 30; d = durga; (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.

49

Note : We cant use = = operator for different type of objects. Violation leads to compile-time error, saying Incomparable types. For any object reference S, S = = null, the result is always false. String S = null; Object O = null; Integer i = null; SOP (null = = durga); // false SOP (new integer (10) == null); null = = null always results in (true). 10 = = 20 // flase 10 = = 20 = = 30 LR 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. - If both are different, then only true. If both r same, then false. 50 XOR

Exercise : TFF T | FT T FT 2. 4 54 4 0100 5 0101 & - 0100 4 4| 55 4 0100 5 0101 | - 0101 5 451 4 0100 5 0101 - 001 1 3. We can apply for bolean & Integral types, not applicable to floating point and char types. Eg : 1.5 & 2.6 CTE : operator cannot be applied to double and double. 4. Bit-wise complement operator : ( ~ ) We can apply Bit-wise complement operator, only for integral types but not for Boolean types.

Eg : ~ 4 ~ true CTE : Operator ~ cannot be applied to boolean. SOP (~4); // -5

51

4 0000 0000 .. 0100 ~4 1111 111 1011 =000 000......0100 5 01015

= -5 15 0000 1111 ~15 1111 0000 000 1111 10000 - 16 SOP (~15); // -16 5. Boolean - complement operator : (!) ! true false ! flase true ! 3 CTE CTE : Operator ! cannot be applied to int. Conclusion : & | - can be applied for both integral & boolean types. ~ Only for integral types. ! Only for boolean types.

8.

Short Circuit Operators : if { 52


( x1 + .... + x n ) ( y1 + .... + y n ) & 10 min 10 min

// } else { // } if

L1min total 21 min


false 10 min 10 min

In the normal logical operators & and | we have to calculate both arguments (expression values). Compulsorily sometimes, it may create performance problems. To improve the performance, short-circuit operators were introduced. They are && and || Comparison b/w biterise and short circuit operators : Bit-wise (&, |) 1. Can be applicable for both boolean & integral types 2. Both operands must be evaluated Short-circuit (&&, ||) 1. Applicable only for boolean types. 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) {

53

++x; Sopln(x); Sopln(y); } else { ++y; Sopln(x); Sopln(y); } x & | && || 11 12 11 12 y 17 16 16 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

54

ii) Explicit typecasting i) Compiler responsible for Implicit typecasting. Keeping small value in a big container, is called Implicit typecasting No loss of information Also known as Widening All possible implicit type castings byte short int long float double 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 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 1: int i = 130;

Eg 2: int i = 150; byte b = (byte) i; short S = (short) i; Sopln (b); -106 55

Sopln (s); 150 150 0000.. 1001 0110 -ve 110 1001 110 1010 b = -106 s = 150 Eg 3: float f = 123.456f; int i = (int) f; SOP (i); 123 If we type cast a float value into the int type, by explicit type casting the decimal part (digits after decimal point) will be lost. Object type casting pending. 9. Instance of Operator : We can use instance of operator to check whether the given object is an instance of the specified class / interface. a instance of x Object / Object reference Eg 1 : Class / Interface

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.

56

Conclusion : a instance of x The type of a and x must be related, otherwise compile time error saying inconvertible types. Object obj = new Object( ); Sopln (obj. instance of String); // false NO CTE. null instance of x result is always false Doubts : 1. A: 2. A: 3. A: 4. A: 5. 6. How to know the unicode value for a particular character. www.unicode.org What the diff b/w (char ch1 = Ox61; char ch2 = \u0061; Nothing but the representation. I think we have \v - vertical tab, what abt that ? No. That tab is present in C, C++. But not is Jav In comments, can we use escape seq other than unicodes of \n & \r yes, we can r both collections & arrays same ? a 2-D int b 1-D int b = a ? a = b No Error : Incompatible type Found : Z-D Req : 1 D

Eg :

57

Conditional Operator : The only available ternary operator is the conditional operator. Syntax : int a = (Boolean expression) ? (value if TRUE) : (value if FALSE) Eg : int a = (x > 20) ? z : y Int a = true ? 10 : 20; // a = 10 We can perform nesting of conditional operator also. Eg : int x = (false) ? 30 : ((true) ? 40 : 50); // x = 40 byte x = (true) ? 10 : 20; (true compile-time const/ - then compiler doc.print bother about type of operands) SOP (x) ; // x=10 byte x = (a<b) ? 10 : 20; (a<b expression executed by JVM, compiler bothers about types of operands) CTE : PLP required : byte found : int Assignment Operators : Divided into 3 categories : i) Simple assignment ( = ) Eg : I = 10; ii) Compound assignment iii) Chained - assignment ii) Compound assignment : int a = 10; a + = 10; SOP (a); (10) byte b = 20; b + = 30; 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; b = b+30; SOP (b); CTE byte b = 20; b + = 30; SOP (b); (50)

58

The following r all possible compound ass operators : + =, -=, *=, /=, %= >>=,<<=, >>>=, &=, |=, = 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) Eg : int a = 4; a = a & 5; a& = 5;

59

2.

Arithmetic Operators (binary operators): i) *, /, % ii) +, -

3. 4. 5. 6. 7.

Shift Operators : i) <<, >>, >>> Comparison Operators : <, <=, >, >=, instance of Equality Operators : ==, != Bitwise Operators : &, , | Short-circuit Operators : && ||

8. 9.

Conditional Operators : ?: 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

O/P :

123456

-3

1 + 2 * 3 / 4 5 % 6 1 + 6/4 5 % 6 1 + 1 5 2 5 = -3 Conclusion : Before applying any operator, first we have to evaluate all the operands. The order of evaluation of operators is always from L R After evaluation of operands, we have to apply the operators according to precedence. Control Flow : Flow control describes the order of execution of statements (code) at run-time i.e. it describes the order in which the statements will execute. Selection Statements Among Several choices u pick one i) if else Flow Control ii) switch

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. 2. Curly braces { }, and else part both are optional. The valid argument for the if-statement is always Boolean, violation leads to CTE.

61

Case 1 : int i = 10; if (i) { SOP (Hi) } else { SOP (Hello); } 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

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 = true if (b) { int x = 10; } Sopln (Hi);

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

63

Switch Statement : 1. 2. Curly braces are mandataory, violation leads to CTE. Both case and default are optional Eg. int x = 4; switch (x) { } - No case and default statements No CTE, NO RTE 3. Valid arguments for switch statement are : byte short unitl 1.4 version chart int From 1.5 version onwards, the corresponding wrapper class objects (Byte, Short, Character and Integer) are also allowed. Switch can take an enum object also as argument. Eg : Integer i = new intger (10); Switch (i) { } valid in 1.5 Invalid upto 1.4 4. If us want to keep any statement inside switch, it must be under some case of default. Otherwise compile time error. Eg : int x = 4; Switch (x) { SOP (Pandu); } CTE : Case, default (or) } expected. 5. Case Labels : All the case labels must be compile time constants otherwise CTE. Saying constant expression required. Eg : int x = 10; int y = 40; // final y = 40 Switch (x) { case 10; case 20; 64

case 30; case y : } CTE : Constant expression required. 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

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

Once any case or default is matched, then all the stmts will be executed from top to bottom until break (or) end of switch stmts. This is called fall through inside switch. int x = switch (x) { default : SOPln (default); Case 0 : SOPln (0); 66

Case 1 : SOPln (1); Case 2 : SOPln (2); } x=0 x= 1 x=2 x=4 If x is final then x-1 x-2 x 3 . R also final. Iteration Statements : 1. While loop : If we dont 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) { SOP (Hi); } SOP (Hello); Eg.2 : while (false) { SOP (Hi); } SOP (Hello); (unreachable stmt) (unreachable stmt) (compile time constants) (compile time constants) 0,1 1 2 default

67

Eg.3 : int a = 10; int b = 20; while (b > a) { SOPln (Hi); } SOPln (Hello); Here there wont be any CTE, (b > a) expression is executed at run-time 10g JVM but not by compiler. If compiler couldnt resolve expression then it wont check for unreachable stmts/. Hence no CTE. Eg.4 : final int a = 10; final int b = 20; while (b > a) { 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. (compile-time comparison)

68

do while (b); do ; while (b); do { } while (b);

CTE : while expected. do ; ; while(b); CTE (; expected) ;

No CTE

without curly braces only | stmt/ is allowed, but it should not be declarative statement. do int i = 10; while (b); do { SOPln (Hi); } While (false); SOPln (Hello); do { SOPln (Hi); } while (true); SOPln (Hello); int a = 10, b = 20; do { SOPln (Hi); } while (a<b); SOPln (Hello);

NO Unreachable stmt

Unreachable stmt.

NO CTE (Hi) infinite times

69

final int a = 10; final int b = 20; do { SOPln (Hi); } while (a<b); SOPln (Hello); 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. CTE Unreachable

70

5. Increment / Decrement Part : Here we r allowed to give any valid Java statement including SOP also. Case 1 : for (; ; ); (valid). All the 3 parts of for loop and curly braces { } are optional. for (; ; ); indicates infinite loop. (condition is always true) Case 2 : for (int i = 0; ; i ++) { SOPln (i); } SOPln (Hello); (CTE unreachable stmtl) Case 3 : for (int i = 0; false; i ++) { SOPln (i); } SOPln (Hi); Case 4 : int a = 10; int b = 20; for (int i = 0; a < b ; i ++) { SOPln (i); } SOPln (Hello) O/P : 0 1 2 (because of i ++ no problem of type casting) (CTE Entire loop body is unreachable)

71

For each loop : 1. Introduced in 1.5, more convenient loop for iterating elements of arrays and collections. Eg : int[ ] a = {10, 20, 30, 40}; for (int i = 0; i<a.length; a++) { SOP (a[i]); } for-each int[ ] a = {10, 20, 30, 40}; for (int x : a) { SOP (x); } The main limitation of for each loop is that it cant 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. ii. iii. within the loops to come out of the loop In the switch statement to come out of switch block In the labeled block to come out of the label block (for each every element x in a) (older versions)

72

If we use break other than in above mentioned cases, we will get compile time error saying break outside switch or loop. Eg : int x = 10; if (x = = 10) { break; } 2. Continue Statement : We can use continue statement only in loops, to skip the current iteration and continue for the next iteration. Eg : int i = 10; do { i ++; SOPln (i); if (i<16) Continue; SOPln(i); } while (++i<20); In the do-while, continue statement will shift the transfer to conditional checking. Eg : int x = 10; if (x > 10) Continue; 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 (---------) { --------CTE : Continue outside of loop.

73

L3 : for (---------) { break L2; continue; } } } Eg : L1: for (int i = 0; i<5; i++) { L2: for (int j = 0; j<5; j++) { if (i = = j) break : //continue//break L1; SOPln (i+ +j); } }

74

III. Declarations & Access Control


1. 2. 3. 4. Java source file structure Class level access modifiers Member (variable + Method) Modifiers 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 Public Class Class A { }; B { }; C { }; Saved with name A.java

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 Class A { }; 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

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 : Cant resolve symbol Symbol : Method Array list ( ) 1 SOP (Array list); CTE : Cant resolve symbol Symbol : Variable Array list. 1 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; l = new java. Util Array List ( );

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 *; Shouldnt be used because it decreases the readability. In the util package, which class we r using we dont know.

76

IDE always use java.util.ArrayList but not Java.util * Instead of specifying fully qualified name every time, we can use import statements once and the corresponding classes by short name (or) (by its own name only) i.e. import statement is mean for typing short cut. It is not equal to c language # include < > statement. import java.util. Array List considered as Explicit class inport (ECI) considered a Implicit class import; (ICI)

import java.util *

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

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) ii) iii) ECI is always convenient The classes present in current working directory no need of import 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 wont be loaded only the required classes will be loaded) Import statements totally effect or compile time not on runtime. I.e. more no. of import statements will increase the time for compilation but no effect on time to run (or) execute.

78

Illegal : import import java.util; java.util.Array List. *;

import java.util.Array List, java. util.Date; > java c verbose sample.java Note : If we r using ECI, then the corresponding class files will be loaded even we r not using those classes in our code. U can seen them with the command > javac verbose <sample>.java. Static imports : Math is a utility class which provides all static methods. This feature was introduced in 1.5 version. According to sun people, static imports improves the readability of the code. But, world wide java experts r not accepting this conclusion. It increases the confusion instead of readability. So, sun people told that to not to use static imports not very frequently. Static imports can be used to import static members of a class. But this static imports should be used only when it is compulsion. Usually, static members can be accessed by using class name. But, if we r using static import, no need to use class name. i.e. static imports can be used for importing static members of the class. Eg 1 : Class sample { P S V M(String[ ] args) { SOPln (math.sqrt(9)); SOPln (math.random( )); } }

79

Eg 2 : import static math . ; (using static import) import static java.lang.math.; class sample 2 { P S V M(String[ ] args) { SOPln (sqrt(9)); SOPln (random( )); } } The following static import statements r illegal : Illegal : 1. Import static java.lang.math; Reason : Static import should end with a method but not with a class name. 2. Import static java.lang.math.sqrt.*; Reason : Either <method name> (or) * Should be there If our class also contain a static method with the same name, then the local method will get priority. Eg : import static java.lang.integer.*; import static java.lang.* ; class sample { P S V M (String args[ ]) { SOPln (MAX-VALUE); } } CTE : Reference to MAX_VALUE is ambiguous. Case 1 : In the above eg, declare a local static variable with name MAX_VALUE Class containing our own static MAX_VALUE then local variable will get the chance. Case 2 : Among static imports the Explicit static import will get the precedence.

80

import static java.lang.system.out; class sample { P S V Main (S [ ] a.) { Out.Println (Hi); } } O/P : Hi

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

81

} Compiling : > javac d (destination . sample.java) We can declare a package stmt. By using the keyword Package. Above eg. Compilation : If U use > javac sample.java sample. class will be generated and placed in current working directory. But if we r using package declaration, it is suggestible to place generated class file in the corresponding package structure. We can achieve this by using d flag of javac. > javac d . sample.java create sample. class in the current working directory inside a package -d specifies where to place generated class files destination. Current working directory. If the needed package structure is not available, this command automatically creates the required package structure. Instead of , we can use C: E: D: > javac d C : sample.java Need not be always. The compiler can create needed folder structure but it cannot create destination structure. If the specified destination is not available, we will get a compile-time error saying : The system cannot find the path specified. Eg : > javac d z : sample.java. 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. (error in writing)

82

If we r not specifying any package statement, the generated class file will be placed in the default package, which is nothing but current working directory.

The package, import and class statements must be placed in following order. 1. package statement Atmost one 2. import statements Any number 3. Class / interface declarations Any Conclusions : i. 2. Almost 1 package stmt is allowed and it must be the non-comment statement in the program.

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 iv. abstract v. strctfp If we use any other modifier, we will get a compile-time error. Saying: - modifier < modifier-name> not allowed. (top level classes & inner classes)

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 ; /* Public */ class A { Public void M1( ) { Compile : >javac d A.java.

83

SOP (In AS M1) } } Package Pack 2; // import Pack 1. A; 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 cant 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 As 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 cant apply abstract keyword for variables. 3. If we dont know about implementation of a method, still we r allowed to declare such type of methods in our classes by using abstract modifier. Compile : >javac d B.java.

84

4. if a method is declared as abstract in a class, it indicates that we dont 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. 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.

85

Eg :

HhpServlet class is an abstract class which doesnt contain a single abstract method.

What is d use of creating HhpServlet as abstract class ? 8. If u dont want to create an instance of the class, declare that class as abstract class; whether it contains abstract methods or not. 9. Inside abstract classes we r allowed to keep constructors, i.e an abstract class may contain constructors but the programmer is not allowed to create an object of abstract class, but internally JVM is allowed to create an instance. 10. The 1st child class extending an abstract class is responsible to provide implementation for all the abstract methods present in the parent class, otherwise the child class should also be declared as abstract. Final Classes : 1. final is a keyword which can be applied for the classes methods and variables. 2. final methods : If a method declared as final, we r not allowed to over side this method in the child class violation leads to CTE. Eg : Public class A { final public void M1( ) { SOP (As M1 Method); } } Class B extends A { Public void M1( ) { SOP (Bs M1 Method); } } CTE : M1( ) in B cant override M1( ) in A.; Overridden Method is final Disadvantage of final Classes :

86

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 { P V M1( ) { SOP (Pandu); } }

class B extends A { }; CTE : Cant inherit from final A.

Note : Until & unless there is no specific requirement, dont 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 {

87

abstract void M1( ); }

final void M1( ); final void M1( ) { }; }

Strict fp : (floating point) 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. 2. abstract final abstract strictfp Illegal for methods Illegal for classes Illegal for methods Legal for classes

88

Member Modifiers
(Variable + Method) 1. Member Modifiers : 1) public 2) <default> 3) private 4) protected 5) native 6) abstract 7) strictfp 8) final 9) static 10) synchronized Variable Modifiers : 1) Volatile 2. 2) transient

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; Class A { Public void M1( ) { SOP(M1); } } >javac d. A.java package pack 2; import pack1.A; class B { Public void M2( ) { SOP(M2) } P S V M ([SC] a) { A a1 = new A( ); a1.M1( ) } } >>javac d B.java

89

CTE : Cant 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 cant access we get CTE : M1( ) is not public in pack 1.A; cant 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 compiletime error. Protected Members : If a member declared as protected, we can access that member within the current package anywhere but in outside package, only in child classes we can access. So, Protected = <default> + kids. (Default within current package, Kids within subclasses in outside package) The most misunderstood modifier in java is Protected (cattle sierra statement) Eg 1 : Package Pack 1; Public class A { Protected void M1( ) { SOP (M1 in A); } } Class B extends A { P S V M (SC) args) { 90

A a1 = new A( ); a1.M1( ); // M1 in A B b1 = new B( ); b1.M1 ( ) // M1 in A A a2 = new B( ); A2.M1( ); //M1 in A } } Eg 2 : II

Package Pack 2; I 1. result in CTE : M1( ) has protected access in pack 1.A; 2. No CTE 3. result in CTE Conclusion : If u want to access protected member, within the current package either by using parent class reference (or) by using child class reference. But from outside package if u want to access protected member, we should access by using child class reference only. i.e. by using parent class reference we r not allowed to access protected members from outside package. Violation leads to compile-time error. If we place class B in pack 1 all combinations are legal. Summarization table : Visibility within the class within the current package either from child / non-child from outside package but in child class from outside package in non-child class Private <default> YES NO NO YES YES NO Protected YES YES YES (But it must be invoked on child class ref) NO Public YES YES YES

NO

NO

YES

* Private < <default> <protected < public.

91

It is recommended (by default) that declare data members as private and the methods as public. final Variables : 1. final instance variables : i. Instance variables generally will get default values, but final instance variables wont 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. iii. Whether we r using or not, for the final instance variables, we should perform initialization, otherwise CTE. Initialization for the final instance variable may be completed before object creation. i.e. we can perform initialization for the final instance variables in one of following places. a) At the time of declaration b) Inside contractor c) Inside instance initialization block (will be executed before executing constructor only. before creating object) They r : final int i = 10; test ( ) { i = 10; } { i = 10; } 92

2.

final static variables : i. Static variables generally get default values. But final static variables wont 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 wont 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( ) { final int i; } No CTE PSVM( ) { final int i; SDP (i); } CTE 93

iii. For the local variables, the only allowed modifier is final. if v r using any other modifier we will get a compile time error. Saying : illegal start of expression iv. formal arguments : The variables which are declared as the arguments of a method are simply act as local variables of that method. We r allowed to declare a formal parameter as final. If it is declared as the final, then v r not allowed to perform any reassignment within the method. Eg 1: class test { public static void M1(int i int j) { 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) { 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. (formal parameter as final) (I = local variables) (J = formal arguments )

94

Static : i. Static is a keyword, which can be applied for variables and methods. We cant apply static keyword for the top level classes but we can apply for inner classes. (Such type of inner classes are called static nested classes). Necessity of static : Class student { String name : Instance variables Int rollno; Static String College name; static variables } Conclu : In the case of instance variables, for every object a separate copy will be created. But in the case of static variables, a single global copy will be creates and shared by all instances. Eg: class test { int i = 10; static int j = 20; P S V M (String[ ] args) { Test t1 = new test ( ); t1.j = 100; t1.j = 200; Test t2 = new test ( ); t2.j = 300; t2.j = 3000; SOPln (t1.i + . +t1.j); SOPln (t2.i + . +t2.j); } }

95

Disadv of Static : As all the objects are sharing single global copy of the static variable, if any object changes its value (by using ob; ref), that changed value will be reflected for all the objects. Hence, security is the major problem in the case of static variables. Hence, there is no thread safety for the static variables. To overcome this problem, usually static variables always associated with final keyword. Eg: class test { int i = 10; P S V M (String args [ ]) { SOPln (i); } } CTE : non-static variable i cannot be referenced from a static context. Static members can be referenced from anywhere i.e. either from static or instance area but non-static members can be accessed only from instance area. Eg : Consider the following 4 declarations : i) int i = 10; ii) static int i = 10; iii) public void M1( ) {SOPln (i)}; iv) public static void M1( ) { SOPln (i)}; Which of the following 2 is allowed within a single class : a) i & iii b) i & iv c) ii & iii d) ii & iv (instance var can be accessed from instance method). CTE : instance non-static variables, cant be referenced from static context. (static variables can be referenced from anywhere) Static is nothing but utility and can be used from anywhere by anyone. Static means complete implementation available but abstract means no implementation available. Hence static, abstract combination is illegal in the case of methods.

96

Eg : class P { P S V M(S[ ] a) { SOPln (parent main); } } Class C extends P { };

> javac p.class > java p

p.java d.class

parent main > java c parent main

The static methods can be inherited only main method will be executed but any stmtsl. Present in child class wont be executed. We cant override static methods. It seems to be overriding applicable but it is method hiding changing the implementation of a class by using other classes makes no sense. But overloading applicable for the static methods. Inheritance Overriding Overloading Transient : (Interviews) 1. transient is the keyword which can be applied only for variables. We cant apply transient for methods and classes. (Process of saving object (values in object) into a file is known as serialization. If we dont 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; } (explanation later)

97

OOS i = 10 j = 20 Sample S FOS File O/P Stream. OOS Object O/P stream

FOS

i = 10 j = 20 abc.tx+

(the process of writing an object to a file is called serialization) OIS i = 10 j = 20

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

98

SOPln (t1.i + .. +t1.j); } }

// 10..20 (same as before) // 10. 0 (j-tray) // 00 (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 cant 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 Serialization 1. 2. 3. 4. 5. 6. int i = 10; int j = 20; transient int i = 10; int j = 20; transient int i = 10; transient int j = 20; transient static int i = 10; transient int j = 10; transient final int i = 10; transient int j = 20; transient static int i = 10; transient final int j = 20; transient static final int i = 10; i = 10 Native Modifier : 1. 2. 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. 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. After Serialization i = 10; j = 20; i = 0; j = 20; i = 0; j = 0; i = 10; j = 0; i = 10; j = 0; i = 10; j = 20;

99

Now a days 10% real-time projects are with C/C++ with Unix called open systems, - C/C++ code is M/c understandable in a higher level than compared to Java. Native keyword is breaking Javas 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) The use of native keyword breaks p/f I feature of java. 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) 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. The native and strictfp combination is also illegal for the methods. - follows IEEE 754 standards but may or may not IEEE 754 stds. We CAN OVERRIDE !!! a native method. It is recommended to override a native hash code method available in the object class. Inheritance & overloading possible for native methods.

4. 5.

6.

7. 8. 9.

100

Synchronized Keyword
1. 2. 3. Synchronized is the keyword which can be applied for methods and blocks. i.e we cant apply synchronized keyword for a variable and class. If a method declared as synchronized, at a time only one thread is allowed to execute, that method on the given specified common object. 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 dont go for synchronized like final. Volatile : (Ameerpet student mentality) 1. 2. Volatile is a keyword which can be applied only for variables. 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. 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 wont be any inconsistent problems. 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. We cant declare a final variable as a volatile. Violation leads to compile time error. (Final const and volatile variable, both r contradictory)

3.

4.

5.

Interfaces
1. 2. 3. What is an I ? Importance of an I ? I declaration methods in I declaration variables declaration 4. 5. Tag or marker interfaces Interface Naming conflicts.

101

1.

What is an I ? 1. From the client point of view an I, defines set of services what the client is expecting. 2. From the service provider point of view an I defines the set of services what service provider is providing. Hence an I is nothing but contract b/w the client and service provider. Advantages : 1. Security : As we r not highlighting our internal implementation, outside person is not able to iee or get the internal formulae. 2. Enhancement is very easy without effecting outside person, we r allowed to check our internal implementation. As the I doesnt contain any implementation, it is considered as 100% pure abstract class.

Declaring an (I) : Eg : interface transferable { public void transfer( ); } we can declare an interface by using interface keyword. The allowed modifiers for the top level interface are : Public, <default>, abstract & strictfp. Implementing an interface : 1. We can implement an (I) by using implements keyword. The class which implements an interface must be responsible to provide implementation for all the interface methods, otherwise the class must be declared as abstract violation leads to CTE. 2. In the implementation class, every interface method must be declared as the public.

102

Eg : class test implements transferable 1 { public void transfer ( ) { ;;;;;; } Interface 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.

103

Exercise : 1. int i = 10; 2. int i ; (default values r not applicable for final static, initialization must be done) 3. volatile int i = 10; CTE : ---- expected. 4. Transient int i = 10; 5. Public final static int i = 10; 6. Private final static int I = 10; Note : Inside an interface, for the variables we should perform initialization at the declaration time only. otherwise compile time error. Static { } r not allowed in interfaces. 4. All the interface variables, by default available in the implemented classes, but they will get only read access. The implemented class is not allowed to change the value of interface variables, violation leads to CTE. Eg : interface x { int i = 10; } class test implements x { P S V M (S[ ] a) { i = 100; // CTE SOP (i); } } CTE : Cannot assign a value to the final variable i A class can extend only one class at a time, but an interface can extend any number of (I)s. A class can implement any no. of interfaces, but an interface cant implement any interface.

104

1.

After installing jdk 1.5/1.4, type javac in and prompt. If U get bad command, then type set path = c:\jdk1.4\bin. Type again javac.u% get it <path where jdk installed> The above process has to be repeated every time U closes & opens the command prompt which is a tedious process. 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.

2. 3.

Note : 1. No need, of setting this path in system variables if U have set in user variables. 2. Otherwise (i.e. if U didnt 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: Eg : If 2 interfaces contain methods with the same signature and same return type in the implementation class one method implementation is enough. interface Left {void M1( );} interface Right { void M1( );} Class Test implements Left, Right { Public Void M1( ) { } }

105

Case 2:

If 2 interfaces contain methods with the same names, return type but with different signatures implementation class has to provide implementation for both methods. 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.

Eg :

Case 3: Eg : interface Left {void M1( );} interface Right { int M1( { 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: Eg : Variable naming conflicts 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); // 100 SOP (Right i); // 20 } } );} Class Test implements Left, Right

106

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

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. 2. According to coding standards, the class names must be nouns. Eg ; class Dog { }; class Account { }; 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 ( )

107

Variables : The variable names r usually nouns at class level starts with lower case letter and then normal camel case follows. Eg : balance, bandwidth, customer name. etc. Constants : Usually we can declare constants with static and final keywords. All the letters must be in capital and if it is a multiple words, the words r separated with ( ). Eg : MAX VALUE MAX PRIORITY MIN PRIORITY Java Bean Standards : 1. Java Beans are simple java classes that have private properties. We can access the private properties by using getter and setter methods. Syntax of getter method : Public <return type of property> get <property name>( ) (should start with a capital letter) It should be public. It the property is not Boolean, the prefix of the method name must be get followed by property. Eg : Public String get Name( ); If the property is Boolean, we may use either get (or) is as the prefix. Eg : public Boolean is Empty ( ); For the getter methods, we should not pass any arguments.

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

108

Java Bean Class : Class Student Bean { Private String name ; Private int rollno; Public string get Name ( ) { return name ; } Public void set Name (String name) { this.name = name; } } Listeners Naming Conventions : For registering a listener : Public void Exercise : Valid way of registering a listener according to coding standard. 1. 2. 3. Public void set My Action Listener (My Action Listener l); add My Action Listener (My Listener l); add My Action Listener (My Listener l); add My Action Listener My Action Listener l (Setter & getter must be public) (Setter & getter must be public) (Properties must be private)

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

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(inta) Calling M1: M1( ); M1(10); M1(10,20,30) any no.

WAP by using var-arg method for printing the sum of any number of integers. Class test { public static void sum (int.a) { int total = 0; for (int x : a) { total = total + x; } SOP (Sum is: + total); P S V M (S[ ] a) { Sum ( ); // Sum is : O Sum (10); Sum (10, 20); Sum (10, 20, 30); } } By using var-arg method display the elements of 2-D array : (single-D array of another 1) Class test { public static void meth (int[ ].x) { for (int[ ] y : x) { for (int z : y) { SAOPln (z); } 110

} } P S V M (String[ ] args) { int( ) a = {1,2,3,4}; int( ) b = {4,5,6}; (a,b); (both r 1-D arrays) } } Conclusions : 1. We should keep after the type only not after the name of the variable. i.e. Sum (int[ ] a) = sum (int a[ ]) equals to Sum (int a) = Sum (int + a.) (bade syntax) 2. We can mix a normal argument with var-org arguments. But in that case, the vararg parameter must be the last parameter. i.e. 3. Sum (float f, int.a); Sum (int.a, float f); We cant 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. 2. 3. 4. 5. 4. Eg : Void M1 (int.a){ } Void M1 (int a){ } (Bad syntax) Void M1 (float f, int.a){ } Void M1 (int.a, flat f){ } Void M1 (double d float.a, charch) { } class test { P S V M1 (int I) {

111

SOPln (General Method); } P S V M1 (inta) { 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. 2. 3. 4. 5. 6. 7. Data - Hiding Abstraction Encapsulation Inheritance. (IS-A relationship) Aggregation (HAS A relationship) Method signature Polymorphis M Overloading Overrding Methodhding Coupling and Cohesion Static control flow Instance control flow Constructors 112 (1.5 features)

8. 9. 10. 11. 12.

I.

Data Hiding : 1. 2. It means, the data should not go out directly. We can achieve this by declaring data members as private. (providing security) The outside person is allowed to access data through methods only. 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. 2. As we r not highlighting our internal implementation; we can get more security. Without affecting outside word, v r able to change internal implementation. Hence, enhancement is easy.

II.

Abstraction : 1.

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.

113

Tightly Encapsulated Class : 1. A class is said to be tightly encapsulated if and only if all the data members are declared as private. Eg : which of the following classes r tightly encap sulted ? i. class x { private int i = 10; (Tightly encapsulated data member declared as private) public int get i ( ) { return i; } public void set i (int i) { this. i = i; } } ii. class x { private int i = 10; public void set i (int i) { this. i = i; } } (Outside person cant access (i) directly i.e. data not going out directly tightly encapsulated) iii. class x { private int i = 10; } class y extends x { int j = 10; 114

} (class y is not T.E. there is no rule that if parents is T.E., Child also has to be T.E., - Y data member is not P.Vote it is not T.E.) iv. class x { int i = 10; x is not T.E. } class x extends { private int j = 20; } class z extends { private int k = 30; } (Y is extending x, the non-private data of x is available to y also) (Generally in java class itself indicates encapsulation) Conclusion : If the parent is not tightly encapsulated then no child class is tightly encapsulated Note : The protected member is available to the child class directly but not at all available to its sub child classes. 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( ); 115

string sleep( ) } Eg 2: class SWEngg extends person { string devignation; float salary; float code ( ); float dance ( ); float play ( ); float sleep ( ) } Eg 3: Amitab

Abishek Suggestible

Chetab Eg 4: A has 10 methods

B 12

(10 + 2) (10+2+1)

C 12

G We think C has all the methods and it is advs. This is tve side But ve side is : To create child class obj all its parent class objs have to be created, but obj. creation is always. Costliest performance issue.

116

4. According to real-time coding standard, 8-10 levels of inheritance is acceptable, beyond that it is not suggestible because it may create performance problems; for every child class object creation all the parent class objects we have to create. Eg : class parent { public void M1( ) { SOPln (parent); } } Class child extends parent { Public void M2( ) { SOPln (Child); } P S V M (String args[ ]) } 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 cant be called. Case 2 : Child C = new child( ); C.M1( ); // Parent C.M2( ); // Child Parent P = new child( ); P.M1( ); // Parent P.M2( ); // CTE } 117 no such mett (M1) by in child clam, it executes parent class methods.

Case 3 :

Runtime object is child.

} (Parent class ref. Can hold child clan obj but by using that ref we cant call child clay specific methods.) (Child class ref cant hold parent class object) Conclu : 1. 2. 3. 4. The parent never aware of child-class specific. Methods. Parent.M2( ); Child aware of all the parent class methods. Child.M1 ( ); Child class reference can never hold parent class object. Child C = new parent ( ); 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 dont know) Note : Also known as composition. Eg : 1. Car contains (cabiposed of) engine, steer, seats etc. Car has Engine HAS A relationship also known as composition or aggregation. By using several objects, we can compose an object. Eg : Class Engine { M1( ) M2( ) M3( ) } A car HAS-A Engine reference. 2. 3. The advantage of HAS-A relationship is reusability. No keyword for mentioning HAS-A relationship. Class Car { Engine C = new Engine( ); }

118

4.

HAS A relationship increases the dependency between components which results in maintenance and enhancement problems. Eg : without engine there is no car dependency Eg : class sample { P S V M (String[ ] args) { system out print in (Kiran); } }

Method Signature : In C, C++ method signature refers to return type + method name + arguments list. Eg ; Void M1( ) 1. In Java, method signature consists of method name followed by arguments (the order of arguments is also important) Eg : M1( ) Eg : Public Void M1( ) Meth. Signature M1( ) Public int M2 (int i, float f) M2 (int i, float f) Note : Return type is not part of method signature in java. 2. class test { P Void M1( ) { } P void M2 (int I) { } P void M3 (int I, float f) { } } For the above class, compiler creates a table containing method signatures. Test: 1 2 3 { P S V M (S[ ] a) { M1( ) M2 (int) M3 (int, float)

class client

119

Test t = new Test( ); t.M1( ); compiler checks; t.M2(10); t.M3(23); } (CTE : cant 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 cant 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 ( ) floatetc For every data type, declaring anew method is always problem and it increases the complexity of the programming.

120

3.

To resolve this, in the object oriented pgmg we can declare more than one method with the same sname (which is nothing but method over leading) so that the programming becomes very simple: Eg : max method in math Class Max (int i, int j) Max (long l, long m) Max (double d, double e)

Method Overloading : 1. 2. Two methods with the same method name but different arguments (atleast order) r said to be over loaded methods. In case of overloading, the method names must be same, the arguments list must be different, never consider return type/access modifiers throws clause. Eg 1 : class test { P V M1( ) { SOPln (No arg);} P V M1 (int i) { SOPln (inte);} } CTE : P V M1( ) P int M1( ) Eg 2: class test 1 { P V M1( ) { SOPln (No arg);} P V M1 (int i) { SOPln (inte);} P S V M (S[ ] args) { Test 1 t1 = new test ( ); t1.M1( ); // No-arg t1.m1(10); // Inte } }

121

3.

Compiler is checking (or) resolve methods based on reference type (not based on runtime objects) in case of overloading, which is also known as Compile-time resolution of overloaded methods.

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

122

P V M1(String S) {SOPln (String Version);} P V M1(Object O) {SOPln (Object Version);} P S V M(S[ ]a) { Test t = new Test ( ); t1.M1(Pandu); // String Version t1.M1(new Object( )); // Object Version t1.M1(new Thread( )); // Object Version, Thread is implicitly promoted to object. t1.M1(null); // NO CTE. O/P : String Version } } Case 2 : Class test { P V M1(int i, float f) { SOPln (int, float); } 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, int 123 Perfectly Overloaded. (Only order of arguments is changed)

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

float, int float, int

int, int int, int

Always child level data types get priority. (done by compiler). Case 3 : Class test { 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) { SOP (Animal Version); } Public Void M1(Monkey M) { SOP (Monkey Version); } Class Animal { } Class Monkey Extends Animal { }

124

P S V M(S[ ]a) }

Case 1 : Test t = new Test ( ); Monkey M = new Monkey ( ); 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 { Gold Land Money Subbu( ) } Class child extends father

Available {different implementation}

1. Whatever the parent has by default available for the child classes. If the child class doesnt want to use a particular method of the parent class it is allowed to provide its own implementation by overriding parent class method. While overriding we have to follow certain rules : Overriding Rules : 1. Method names and the argument list order also must be same. i.e. signature of the methods must be same. Eg : Class P { Class C extends P { 125

Public Void MIC ------------}

Public Void MIC { ------- Overriding ------} }

2.

If parent class method, doesnt want to allow child class to override, declare that as final (security purpose). The final methods cannot be overridden. Eg : Class P { Final Public Void M1( ) { SOP(Parent); } Class C extends P { Public Void M1( ) { SOP(Child); } ------} }

CTE : 3.

M1 in C cant override M1 in P; Overridden method is final.

A final method cannot be overridden but a non-final method can be overridden as final. i.e. declaring M1( ) of C as final. Private methods will not be available for the child class and hence overriding concept is not applicable for the private methods. 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 { Private void M1( ) {SOP(Child);} } No CTE These r not overriding methods.

4. 5.

6.

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

126

Eg : Class P { Public Void M1( ) {SOP (Parent);}; } Class C extends P { Public int M1 ( ) {SOP(Child);} } CTE Saying : M1( ) in C cant 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 ( ); } } Class C extends P { Public String M1( ) 127 Co-variant return type allowed in 1.5 but not in different return types.

{ return Kiran; } } Note : P = Object C = String Co-variant return types P = String C = Object Not co-variant

The concept of co-variant return types application for only object/reference types but not for primitive types. A Overriding Not overriding 8. B C (Child of A) Overridding (Child of B) While overrding, weakering the access specifier is not allowed. Violation leads to CTE. Parent : Public Child : Public Protected Default Private Note : Same Private methods in parent, child class r not considered as overridden methods but treated as separate methods. Eg : Class P { Public Void M1( ) { SOP(Parent); assign } Class C access decreased { Private Void M1( ) { SOP(Child) } weaker access pri vileges; was public. CTE : M1( ) in C cannot Override M1( ) in } P Attempting to Protected Default Private

128

9.

Inside interface all the methods r by default public and abstract. 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 Private } Void M1( ) { Void M1( ) { 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 Runtime Exception and its subclasses r considered as unchecked exceptions

and all the remaining by default considered as checked exceptions. 3. 4. Whether an exception is checked or unchecked it is always occur at Run-time only. Checked Exceptions r again divided into partially checked and fully checked. A checked exception is called fully checked exception if and only if all its child classes also checked other wise considered as partially checked exception. Eg : for fully checked : IO Exception Eg : for partially checked ; Exception 1. In the case of overriding v r not allowed to increase the size of the checked exceptions. But there is no rule for unchecked exceptions. We can decrease (or) remain same the checked exception.

129

Import java 10-*;

Eg : Class P { Public Void M1( ) { SOPln(Parent); } } Class C extend P { Public Void M1( ) { SOP(Child) } } > javac c.java 2. Results in CTE : (The size of checked exception is increased)

1 throws IO Exception 2 throws IO Exception 3 throws IO Exception 4 Exception 5 throws IO Exception 6 throws IO Exception 1 throws IO Exception 2 throws IO Exception 3 throws IO Exception 4 throws IO Exception 5 throws IO Exception 6 throws IO Exception

M1( ) in C cant override M1( ) in P; overridden method does not throw java.lang. exception. Exercise : Already mentioned in the pgm. 2. 3. 4. We can override a synchronized method as non-synchronized and a non synchronized method as the synchronized. 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. 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

130

class C extends P { Void M1( ) { } } Eg2 : Class P { void M1( ) { } } 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 : Case 2 : P P1 = new P( ); P1.M1( ); // Parent C C1 = new C( ); C1.M1( ); // Child 131 non-abstract to abstract (SUPERUUU)

Case 3 : /* Note :

P P = new d( ); P.M1( ); // Child Parent class reference can hold child class instance. At compile time compiler checks the reference type P and checks whether M1 ( ) is present or not if not them CTE once it is satisfied, later at rum-time JUM checks which run-time (child class) object is that, once it is decided whether method M1( ) is overridden, then child class method is called, it not a then parent class method is executed because parent class members r by default available for child class */ In case of overriding, the method resolution taken case by JVM based on run-time object this process is also known as : Dynamic method dispatch (or) Dynamic Polymorphism (or) Runtime Polymorphism (or) Last binding.

Overriding in the case of static methods


A static method cannot be overridden as non-static method (class level behavior cant be changed). We cant override a non-static method as static. Method Hiding : (Child class method is hidden by parent class method) 1. 2. All the rules of method hiding r exactly similar to overriding rules except both methods declared as static. 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( ) 132

} SOP (Child); } P S V Main (String[ ]args) { P P1 = new C ( ); P1.M1( ); // Parent Note : If it is overriding, child class method has to execute, since it is method hiding parent class method is executed. Overrding in case of variables : Eg : Class Class P { int i = 10;} C extends P { int i = 20}; P S V M (String[ ] args) { Case 1 : Case 2 : Case 3 : P P1 = new P( ); SOP(P(i); //10. ( C1 = new (( ); SOP(C1.i); // 20 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 1. Method Names 2. Arguments 3. Signature 4. Access Modifiers Overloading Must be same Must be different (at least order) Must be different No restrictions Overriding Must be same Must be same Must be same Weakering the access opecifier is not allowed

133

5. Return type

No restrictions

Must be same until 1.4 / from 1.5, covariant return types also allowed.

6. Throws clause

No restrictions

Increasing size of checked exceptions is not allowed, but there r no restrictions for unchecked exceptions. We CAN (No) No We cannot but method hiding is possible. We CAN

7. Final 8. Private 9. Static 10. Native synchronized abstract

We CAN (Yes) We CAN (Yes) We CAN We CAN

SCJP Q regarding Overloading and Overriding : Class B { Public Void M1( ) { } } Which of the following methods r allowed in the derived class ? 1. 2. 3. 4. 5. Public void M1 (int i) { } Private void M1 (double d) Public void M1 ( ) { Private void M1 ( ) { } } Overloading throws exception overloading overriding CTE : M1( ) is already declared.

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

134

{ M1( ); SPOln (First Static Block); } Public Static Void Main (String[ ] args) { M1 ( ); SOPln (Main Method); } Public Static void M1( ) { SOPln (j); // j = 0 } Static { SOPln (Second Static Block); } j = 0 (RIWO) static int j = 20; } NO CTE, 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 135 RTE // j = 20

SSB 20 Main Method Note : Variables can be declared at the last place (or) any where. Static blocks r executed while class is loading in to the memory. Eg : After loading driver registering the driver stuff is written in static block of the driver class. 1. Load driver, 2. Connection, 3. State, 4. Execute, 5. Result set

Static blocks : 1. Syntax : Static { } 2. Static blocks executed while the class is loaded into the memory. 3. If u want to perform any activity while can be executed while loading the class that activity should be defined inside static block. Eg1 : Loading native libraries must be performed while the class is loaded into the memory. Hence this activity should be declared inside static block. Eg2 :Registering database driver with Driver Manager can be performed by executing static block available in driver class. 1. If a variable is just identified by JVM but the proper explicit assignment not takes place then that variable is in the mode of RIWO (State Read Indirectly Write Only) and assigned with default values. If a variable is in RIWO State, we r not allowed to perform read operation directly, violation leads to compile time error saying : Illegal forward reference. Eg.1 : Static { // M1( ); SOP (j); // SOP (Base.j); SOP (First Static Block); } 2. Later variable comes into R&W State, then we can read & write values directly. Eg.2 : Static { // M1( ); 136

SOP (i); SOP (First Static Block); }

3. Static blocks should be declared only at class level, but shouldnt 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; 137

} Class Derived Extends Base { Static int x = 100; Static { M2( ); SOP (Derived First Static Block); } P S V M (S[ ] args) { M2 ( ); SOP (Derived Main Method); } P S V M2 ( ) { SOPln ( y ); y = 0; y = 200; } Static { SOP (Derived Second Static Block); } Static int y = 200; @ : Whenever Derived class is loaded base class should also be already loaded. Save Compile Run O/P : O DFSB DSSB 200 D Main Method : Derived. java : Derived. Class Base.class : java derived Correct O/P : O Base SB O Derived FSB Derived SSB 200 Derived Main 138

Flow : 1. 2. 3. Case 1: Case 2: Identification of static members from parent to child (I) to (II) Execution of static variable assignments and static blocks from. Parent Executive of Derived class main method. 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. > java base 1 O/P : O Base static block Base Main Method. Derived Class wont be loaded. Instance Control Flow : 1. Non-static variable cant 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 cant be referred from static context (directly). Eg 2: Class Parent { int i = 10; { M1( ); SOP (First Instance Init Block); } Parent ( ) { SOPln (Constructor);

139

P S V M(String[ ] args) { Parent P = new Parent( ); // of Case (ii) SOPln (Main Method); Parent P1 = new parent( ); } P V M1( ) { SOPln (j); } { SOPln (Second Instance Init Block); } int j = 20; } 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 140

FIIB SIIB Constructor Flow : 1. Whenever we r creating an object, the instance control flow will start. For every, object creation instance control flow will be repeated. The following is the sequence of events in the instance control flow : a. Identification of instance members of the class. (From T to B) b. Execution of instance variable assignments and instance blocks (From T to B) c. Execution of the constructor. (That is why object creation is costliest) d. Main Method. 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; {

141

M2( ); SOPln (Child First Instance Init Block) } Child ( ) { SOPln (Child Constructor) } P S V M(String[ ] args) { Child C = new child( ); SOPln (Child Main Method) } Public Void M2( ) { SOPln (y); } { SOPln (Child SIIB); int y = 200; } } Flow : a. Identification of instance members from parent to child. b. Execution of instance variable assignments and instance blocks only in parent class. c. Execution of parent class constructor. d. Execution of instance variable assignments and instance blocks in the child class. e. Execution of child class constructor. > java child O/P : O PIIB P Constructor O CIIB CSIB C Constructor Main Method Repeats for every child object creation.

142

Suppose if parent class one more parent & etc. suppose there r 8 levels the for creation of child obj all remaining parent class objs should be created performance problem.

Exercise : What is the O/O when u compile & run the following code ? Public Class Myclass { P S V M (S[ ] args) { My Class Obj = new My Class (i) } Static int i = 5; Static int l; Int j = 7; Public Myclass (int M) { SOP(i+, + j + , + k + , + l + , + m); } { j = 70; // Instance initializer block l = 20; } Static { i = 50; // Static initializer block } } O/P : 50, 70, 0, 20, 0 Trace : i = 0 (RIWO) l = 0 (RIWO) i = 5 (R/W) i = 50 My class (0) J=0

143

k=0 j=7 j 70 l 20

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

144

Static String M = MSG(1); { M = MSG (2); } Static { M = MSG(3); } P S V M (String[ ] args) { Object obj = new Initialization ( ); } } Constructors : Eg : Class Student { String Sname; int rollno; P S V M (S[ ]a) { Student S1 = new student( ); } } * 1. 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. 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. 2. 3. At the time of declaration only. But, all d objects have same no and name not. (not suggestible. Giving values in invoice initialization block also results in same above problem. In main method, s.name = Ki; S.rollno = 701; For 600 obj 1200 lines of Code cumbeyone code Not suggestible.

145

4. */ 2. 3.

So we will pay values as arguments to the constructor.

The main objective of constructor is to parlor initialization. /* The main objective of constructor is it takes parameters */ Whenever we r creating an object, the constructor will execute automatically to perform initialization.

Eg :

Class Student { String Sname; Int rollno; Studnet (Sname, int rollno) { this.sname = sname; this.rollno = rollno; { P S V M (S[ ] arg) { Student S1 = new student (Kiran, 101); Student S2 = new student (Karthikeya, 102); } }

4.

The main difference b/w instance initialization block and constractors is . Constructor can take arguments but instance initialization block wont 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 dont have any constructors concept. 2. The name of the constructor must be same as class name. (for compilation understanding purpose). 3. The only allowed modifiers for the constructors are : Public, Protected, <default> and private. If v r declaring constructors with any other modifiers v will get a compile time exception saying :

146

Modifier <other than above 4> not allowed here. Eg : Class Test { Static Test( ) { } } CTE : Modifier Static not allowed here. 4. Return type is not applicable/allowed for the constructors. By mistake, if U keep return type compiler treats it as a method instead of constructor but there is no compile time error. Eg : Class Test { Void Test ( ) { SOPln (Constructor); } P S V M (S[ ] args) { Test t = new Test( ); } } It is legal (but stupid) to have a method whose name is same as class name. 5. Default Constructor : Every class should have the constructor that may be written by programmer (or) generated by compiler. If the programmer is not placing any constructor, then only compiler places (or) generates Default Constructor. If the programmes already provided any constructor, then the compiler wont general any default constructor. I.e. Either programmer provided constructor (or) compiler generated constructor is possible but not both simultaneously. Proto type of Default Constructor : The access modifier of the default constructor is same as access modifier of the class (either public or default).

147

Default constructor is always no argument constructor only. The Default constructor contains only one line i.e. a no argument call to the super class constructor. [Super ( );] Eg : Public Class Test { Public Test ( ) { Super( ); } }

Programmers Code 1. Class Test { }

Compiler General Code Class Test { Test( ) {Super( ); } } Public Class Test { Public Test ( ) { Super( ); } } Class Test { Test ( ) { Super( ); } } Class Test { Test (int i) { Super ( ); } } Class Test

2. Public Class Test { }

3. Class Test { Test ( ) { } } 4. Class Test { Test (int i) { Super( ); } } 5. Class Test

148

{ Void Test (int i) { }

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

Overloaded Constructors : 1. 2. For any class we can write any number of constructors and are considered as overloaded constructors. By using Super and this, we will invoke other constructors. Super can be used for calling (invoking) parent class constructor and this can be used for invoking overloaded constructors of the same class. Eg : Class Test { Test ( ) { // Super( ); SOP (No arg constructor); } Test (int i) { This ( ); SOPln (Int Constructor); } Test (double d) { This (10); SOPln (Double Constructor); } P S V M(S[ ] args) { Test t = new Test (10.6);

149

} } O/P : No arg constructor Int Constructor Double Constructor this. i this ( ) super. i super ( ) 3. invoking a member (variable / method) invoking a constructor invoking parent class member invoking a parent class constructor

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 cant invoke a constructor directly from a method. ii. We should use only one but not both. iii. We can use either super( ) (or) this( ) must be as the 1 st statement only. iv. If U dont keep Super ( ) (or) this( ), then compiler always places no argument Super( ) as the 1st Statement in a Constructor. Eg : Class Test { Test ( ) { Super( ); this ( ); } Void M1( ) { this ( ); } CTE : Call to this( ) must be the 1st stmt in a constructor.

150

5.

We can overload a constructor but inheritance and overriding is not possible. Parents class variables & method r available to child class, but constructors wont be available. Case (i): Recursive method call is always a run problem. JVM rises Stack Over Flow Error. But, compiler point of view there is no problem at all. Eg : Class Test { Void M2( ) { M1( ); } Void M1( ) { M2 ( ); } P S V M(String[ ] args) { Test t = new Test( ); t.M1( ); } } NO CTE RTE : Java.lang. Stack Over Flow Error

6.

But in case of constructors, recursive constructor invocation is a compile time error. Compiler is responsible for checking everything related to constructors. Eg : Class Test { Test( ) { this(10); } Test (int i) { 151

this( ); } P S V M(S[ ] a) { SOP(Hello); } } CTE : Recursive constructor invocation. Compiler checks about constructor because if pgmgr didnt provide, compiler has to provide default constructor. Case (ii) : Class P { } Class C extends P { } Compilers Code Class P { P ( ) {Super( );} } Class C extends P { (C) {Super( );} }

NO CTE : Compiles Successfully. Case (iii) : Class P { P(int I) { } Class C extends P { } Compilers Code Class P { P (int i) { Super( ); } } Class C extends P { C ( ) {Super( ); } }

But parent class already contain constructor with int argument, - already 1 contest is present compiler wont generate any default constr./ So, Super( ) calling which is not present. P (int) in P cant be applied to ( ) C extends P.

152

Conclu : If the parent class has same argument constructor, it is suggestible to place always no argument constructor also, otherwise, while writing child class constructors, we should take care of calling super class constructor properly. Class P { P(int i) { } } Class C extends P { C (int i) } } } Class P { P (int i) { Super( ); } } Class C extends P } 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). 1 C ( ) throws Exption { Super( ); NOCTE }

Eg: Class P { P( ) throws exception{ } } Class C extends P { C ( ) {Super( );} }

2 C( ) { tru { Catch (Exception C) { } CTE : Super must be stmt.

CTE : Unreported exception java.lang. Exception, must be caught or declared to be thrown. Exception Handling : 1. Exception :

153

An Exception is an unexpected event which disturbs entire flow of the program. Eg : Arithmetic Exception Null Pointer Exception File not Found Exception 2. If an exception occurred, the program terminates abnormally, which is not at all suggestible because it may effect the performance of the system. To overcome this problem, we should handle the exception for graceful termination of your program. 3. Exception Handling means V r providing alternative possibility but it does not mean that v r repairing the exception.

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

154

{ P S V M(S[ ] args) { do stuff( ); } P S V do stuff( ) } do more stuff( ); } P S V do more stuff( ); { SOP (Hi, h r u); } } 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);} } 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 Exception Where it is occurred What is the reason

1.

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 Exception ii) Description of the Exception iii) Location where it occurred (stack trace) After creation of Exception object, the method hand over the object to the JVM. 155

3.

4.

5.

6.

7. 8.

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. 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. 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. JVM hand over the responsibility of exception handling to the Default Exception Handler. The Default Exception Handler just displays the error info on the console, nothing more.

RTE for pgm 2 : Exception in thread main : Arithmetic Exception : / by zero at 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 in i) do stuff method ii) main method and see the O/P. Exception Handling : Throwable

Exception (We can handle) (recoverable) Linkage Error Assertion Error

Error (We cant handle) (irrecoverable) Virtual Mk Error

Verify No Class Def Out of Memory Error Found Error Error Can be handled by pgmgr. 1. Errors r irrecoverable where as Exceptions r recoverable.

Stack Over flow error

156

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

Run time Exception

IO Exception

IO Exception

SQL Exception

Remote Exception

Arithmetic Exception Null Pinter Exception

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 :

157

We can implement Exception Handling by using try catch statements. The risky code we keep in inside try block and the corresponding handlers, we can keep inside catch. Eg: Class Test { P S V M(S[ ] args) { SOPln(Stmt1 ); try { SOP (10/0); } Catch (Arithmetic Exception) { SOPln(Stmt2); } } O/P : Stmt 1 5 Stmt 2 Eg: try { Stmt 1; Stmt 2; Stmt 3; } Catch (X e) { Stmt 4; } Stmt 5 ;

Case (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 has 158

has matched. Stmt 1,4 followed by 5 will be executed. Indicates Normal Termination. Case (iii) : An exception raised at Stmt 2 and the corresponding catch block has has matched. Stmt 1 only will be executed. Indicates Normal Termination.

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

2.

If V have multiple catch blocks, the order of catch blocks is very important. V should take child to parent, violation leads to CTE saying : Exception has already been caught.

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

try { SO(10/0); } Catch (Exception e) { } Catch (AE e) { } CTE : Exception : java. lang. AE Has already been caught.

Control flow in nested try - catch : Eg : try { Stmt 1; Stmt 2; Stmt 3; Try { Stmt 4; Stmt 5; Stmt 6; } Catch (x e) { 160 In this pgm, we cant compare the order of inner and outer catches. But either complete inner, (or) complete outer we can compare. Possible Combination of x and y : x : AE y: E E AE E AE AE E

Stmt 7; } Stmt 8; } Catch (x e) { Stmt 9; } Stmt 10; Case (i) : Exception raised at stmt 2 and corresponding catch block has found. Flow : Stmt 1, 9 followed by 10 Normal Termination. Case (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 10 Normal Termination. Case (vi) : Exception raised at Stmt 5 but inner and outer catch blocks r not matched. Flow : 1,2,3,4 Abnormal Termination.

161

Case (vii) : Exception raised at Stmt 8, the corresponding catch block has matched. Flow : 1,2,3,4,5,6,9 and 10 1,2,3,4,5,7,9 and 10 1,2,3,4,5,7,9 and 10 1,2,3,4,5,6,9 and 10 Normal Termination.

Case (viii) : If an Exception raised at Stmt 7 and the corresponding catch block has matched. Flow : 1,2,3,4,5,6,7,9 and 10 Normal Termination. Case (ix) : Exception raised at Stmt 7 but the corresponding catch block has not matched. Flow : 1,2,3,4,5,6 Abnormal Termination. 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( ) {

162

} / 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. 3. If U place that code in catch because no guarantee that catch executes always. We cant keep in both because of redundancy.

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

163

Catch (AE e) { SOP(Caught); } Finally { SOP (finally block); } SOP(Hello--------); } } 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 wont 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 wont execute. This is the only exceptional case where the finally block wont execute.

/* Difference among : Final, finally and finalized.

164

Final : is a modifier applicable to variables, methods and classes. Finally : To execute clean-up code irrespective of exception occurrence / handling we keep that code in finally block. Finalized : It is also for maintaining clean-up code only, (just before destroying unreferred obj). .finalized( ) Finally & Finalized : is better be finally always executes where as we dont know when GC occurs. */

$ final, finally and finalized : Final : It is the modifier which can be applied for variables, methods and classes. Final variable means Final method Final class Constant. It cant be overridden. It cant be inherited. We cant 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 cant predict (give any assurance). Possible Combinations of try-catch-finally : 1. try \{ } Catch ( )

165

{ } finally { } VALID B/W try and catch (or) b/w catch block (or) b/w catch and finally. V r not allowed to keep any stmt, violation leads to compile-time error.

Saying : (i) try without catch or finally (ii) catch without finally. (Null Pointer Exception) 2. try { } Catch ( ) { } VALID 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.

166

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. 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 & 6 Normal Termination. Exception at Stmt 2 & corresponding catch matched. Flow : 1,4,5 & 6 Normal Termination.

Case (ii) :

Case (iii) : Exception at Stmt 2 but corresponding catch not matched.

167

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

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

Case (1) :

If there is no exception. Flow : 1,2,3,4,5,6,8,9, 11 & 12 Normal Termination (N.T) An Exception at Stmt 2 and Corresponding catch block has found Flow : 1,10,11 & 12 Normal Termination. Exception at Stmt 2 and Corresponding catch has not matched. Flow : 1, 11 Abnormal Termination (A.T) Exception at Stmt 5 and corresponding inner catch has matched. Flow : 1,2,3,4,7,8,9, 11 and 12 Normal Termination.

Case (2) :

Case (3) :

Case (4) :

Case (5) :

Exception at Stmt 5, but inner catch has not matched, out catch matched. Flow : 1,2,3,4, 8,10, 11 and 12 Normal Termination. Exception at Stmt 5, inner & catch did not match. Flow : 1,2,3,4,8,11 followed by (A.T) Exception at Stmt 7 and corresponding catch (outer) has matched. Flow : 1,2,3,4,5,6,8,10, 11 and 12 Normal Termination. Exception at Stmt 7, but catch (outer) has not matched. Flow : 1,2,3,4,5,6,8,11 Abnormal Termination. Exception at Stmt 8, Stmt 9, Stmt 10, Stmt 11, Stmt 12. Abnormal Termination.

Case (6) : Case (7) :

Case (8) :

Case (9) :

throws clause : class test { P S V M(S[ ] args) { do stuff ( ); } P S V do stuff( ) { do more stuff ( ); } P S V do more stuff ( {

169

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

170

} } throw Keyword : 1. We can use throw keyword for hand over exception object to the JVM. Some times, it is required to create our own customized exception objects and we have to handover to the JVM we can achieve this by using throw keyword. Eg : class test { P S V M(S[ ] args) { throw new Arithmetic Exception ( ); } } throw = Handover that object to JVM Arithmetic 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. 4. In real-time it is not allowed to throw default exception objects, generally throw customized object. 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 }

171

} CTE : Null Pointer Exception. CTE (4) : (New Point) If the try block doesnt 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.

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. 2. 3. 4. Exception has already been caught. Unreported Exception must be caught or declared to be thrown. Unreachable stmt. Exception is never thrown in the body of corresponding try statement. 5 keywords, 4 CTEs Customized Exceptions : Eg : Entering age in matri mony.com. If ventered 90 (or) 13 then that site should throw exception age too low / too high customized exception. 1. Based on our programming requirement, V have to create our own customized exceptions like [Too Young exception (in Matrimony.com), Insufficient Funds Exception.. etc) using throw key word.

172

Eg : Class too young exception extends. { Too Young Exception (String S) { Super(S); } }

RuntimeException Exception

class sample { P S V M (S[ ] arg) throws exception { int age = Integer. Parse Int (args[0]); if (age>40) { throw new Too Young Exception (P/S wait some more time, U will get best match); } else if (age<15) { throw new Too Young Exception (Ur age is already crossed); } else { SOPln (U will get match info by mail very soon); } } 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. 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 173

1. Null Pointer Exception : -

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

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 }

174

} 4. Class Cast Exception : It is child class of Runtime Exception and it is unchecked exception. This is thrown by the JVM, when attempting to cast a reference variable to a type that fails Is A test. Eg: Class Sample { P S V M(S[ ] args) { Object O = new object( } } 5. 6. 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. 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 : 7. Exception in Initializer Error Caused by : java.lang. Arthmetic Exception / by zero. ); String S = (String) O; // CCE, fails IS -A

Illegal Argument Exception :

175

It is a child class of Runtime Exception and is unchecked exception thrown by API developer to indicate that a method has been called with in appropriate argument. Eg: Class Sample { P S V M(String[ { thread. Current thread( ). Set priority ( // priority range 1 to 10 } } ); ] args)

RTE Error : java.lang. Illegal Argument Exception.

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 1. Null Pointer Exception 2. Stack Overflow Error 3. Array Index Out of Bounds JVM Thrown by

176

Exception 4. Class Cast Exception 5. No Class Def Found Error 6. Exception in Initializer Error 7. Illegal Argument Exception 8. Number Format Exception 9. Illegal State Exception 10. Assertion Error Thrown Programatically by the Programmer / API Developer

Garbage Collector :
1. 2. 3. 4. Introduction Ways of making object eligible for GC The ways of requesting JVM to run GC 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/. Wont fail because of memory problems. Java is robust because of this GC. */ 1. Most of old OOP languages like C++ the programmer is responsible for both creation and destruction of objects. But the pgmgr is very much interest for creation of object but be usually neglects the destruction of objects. As a result, at certain

177

time there wont 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/- wont 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.*/ 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. 2. 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. 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 withs. ----------S = null Now, the object eligible for GC. v r reducing the GC.

178

b) Reassigning the reference variable : By reassigning the reference variable, v can make objects eligible for GC. Eg : Student S1 = new Student ( ); Student S2 = new Student ( ); No obj. eligible for GC S2 = 21; 1 obj. eligible for GC

3.

The objects which r created as part of method execution r by default eligible for GC after method completion, except that method doesnt return any object. If the method returns an object and allocating a new reference variable for that wont 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( ) { 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 dont know when JVM does this process*/ /* Whenever main ( ) method over, then GC wont run JVM shutdown*/ 179

/* The thread which is running in the background is considered as Demon thread. Eg : GC */ 4. Island of Isolation : SCJP /* Class Test { Test i; P S V M(S[ ] a) { Test t1 = new test( ); Test t2 = new test( ); Test t3 = new test( ); No obj eligible for GC } } */ t1 i=

t2

t3

i=

Eg :

Class test { Test i; P S V M(S[ ] args) { Test t1 = new test( ); Test t2 = new test( ); Test t3 = new test( ); t1.i = t2; t2.i = t3; t3.i = t1; t1 = null; t2 = null; At this line also no object is eligible for GC t3 = null; Test t4 = t2.i; Nullptr } } At this point all d 3 objs eligible for GC, even though the objects having internal references, this group of objs. Doesnt have any reference from live thread, hence eligible for GC.

180

If a group of objects dont 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 doesnt 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. 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 cant give any assurance. Eg : describing GC class run time demo { (Free memory varies from run to run) P S V M(String[ ] args) { Runtime r = Run time . get Runtime ( ); SOPln (r. total memory( )) ; 23222596 bytes 181

SOPln (r. free memory( )) ; 12345 bytes , (total bytes) for (i = 0; i < 1000; i ++) { java.util.date d = new java.util.Date( ); d = null; } SOPln (r. free memory( )) ; r.gc( ); //System.gc( ); SOPln (r. free memory( )) ; } } 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 : 2031616 1908904 1884208 1943840 (> 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. 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 ( 2. ) throws throw able.

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 cant give assurance, because both r threads */ Eg 1 : Class test { Public Static V M (S[ ] a) throws Interrupted Exception { String S = new String (Kiran); S = null; Sytem.gc( ); 182

Thread.sleep (3000); SOPln (End of Main); } Public Void finalize( ) { SOPln (Finalize Method Called); } } 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( ) { 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, wont run */ Case 2 : /* v can call finalize method explicitly as v r calling any other method */ /* Class Test 183

{ P S V M(S[ ] a) { Test t = new Test( ); t.finalize( ); } } O/P : Finalize Method. Exception : java. lang. AE : / by zero Abnormal Termination. O/P Finalize Called Caught Normal termination. { Test t = new Test( ); t.finalize( ); } }

Public void finalize ( ) { SOPln (Finalize Method); SOPln (10/0); }

Public void finalize ( )

{ try { SOPln (Finalize Method); SOPln (10/0); } Catch (Fle e) { SOPln (Caught); } } /* Thumb rule : If I made a mistake it is blunder, if my dad did that ignorable. */ /* Generally, v dont put SOP stmts/.., v put cleanup code (DB Closing, N/W closing etc)*/ Eg 1 : Class test { P S V M (S[ ] args) { Test t = new. Test ( ); t = finalize ( ); } P Void Finalize( ) { SOP (F Method); SOP (10/0) } } O/P : Finalize Method. Exception thrown followed by

184

(Abnormal Termination) Note : We are allowed to call finalize( ) method explicitly. At that time if any exception raised in finalize( ) method, the corresponding catch block will execute. If there is no catch block then it is abnormal termination. Eg 2 : Class test { P S V M (S[ ] a) throws IE { Test t = new. Test ( ); t = null; System.g( ); Thread.sleep (3000); } Public Void Finalize ( ) { SOPln (Finalize Called); SOP (10/0); // SOP (Hai); } }

O/P : Finalize Called. Note : While executing finalize( ) method which is called by GC any uncaught exceptions are simply ignored by the JVM. Once an exception rises; JVM ignores and remaining code wont execute. Case 3 : Going till the edges of hell & coming back. Once an object eligible for Garbage College, it may not be always destroyed by GC (Some times it is save), i.e. even after an object eligible for farbage collection, it may get the reference, then that object is not eligible for Garbage Collection. /* And later if that object loses its ref, GC comes & now, it wont execute finalize( ) method, directly deletes that object */ Case 3 Eg Pgm : Class Finalize Demo { Static Finalize Demo S; // Static since I want to access from everything P S V M (String[ ] args) { Finalized Demo S1 = new Finalize Demo ( ); SOPln (S1.hashCode( )); S1 = null System.g( ); Thread.sleep (2000); SOPln (S.hash Code ( ));

185

S = null; System.gc ( ); Thread. Sleep (3000); SOP (Hi, end of main); } } Public void finalize( ) { SOP (Hi Finalize Called); S = this; } O/P : 2 8 1 6 8 9 2 5 Hi, finalize called same 28168925 Hi, end of main By this time object destroyed. /* If pgmgr calls finalize( ) the GC wont consider this count, it considers only its own count*/

Multi Threading :
1. 2. 3. 4. 5. Introduction (Terminology) Define a thread, Instantiate & Start extens thread implements runable a thread. Set & get the name of a thread. Thread priorities. How v can prevnt a thread from exfution ? i. Yield ( ) ii. Sleep ( ) iii. Join ( ) 6. 7. 8. 9. Synchronized Keyword Inter-thrad communication [wait( ), notify( ), notify all ( )] Dead lock Daemon threads (1/2 hr)

10% of real-time java projs r of core java, where multi threading is important.

186

Introduction : /* Mult-tasking : Doing multiple tasks simultaneously. Eg : Human being sleeping, listening, writing */ 1. Multi - Tasking : Executing several tasks simultaneously is considered as Multi-tasking. The main motto of multi-tasking is to improve the performance (of an appln). The taks in multi-tasking rexecuted independent of each other. Multi tasking

Process based Multi-taksing i. Writing Java Pgm ii. Listening to songs iii. Downloading a file from Net

Thread-based Multi-tasking

- Multi-tasking is divided into 2 categories : i. process-based multi-tasking 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 dont make sense. So this type of MTK is not at all signifible. /* Consider the following Process : Java 10000 pgm independent parts (threads) light weight process is a process (or) execution of stmts. 187

Main is default 10000 b in java pgm Motto : Calculating temp. Cpgm : O/P after 1 hr., since line by line execution at last it finds temp after 1 hr. Jpgm : It divides pgm into no. independent parts and executes simultaneously. This individual part is known as thread. Because of this response time decrease and pert incs. */ Thread-based MTK : i. Executing several independent tasks simultaneously where each task is a separate independent part of the same program is considered as : thread-based MTK. (Wonderful feature of OOP). ii. iii. Non-Oop langs like c donot have this feature. 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) C++ 100 to 150 lines (Everything has to be implemented programmatically) iv ) Java 5 to 10 lines

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

188

Thread : Part of Process */ /* In CGI, process-based MTK, For every request a separate process is created after the use destroyed creation & deletion is costly CGI fails to deliver scalable applns.. So creation of thread instead of process came into pecture which made the CGI outdated. CGI is outdated because of Multi-threading. Adv : in CGI is no problem of symchronitation. */ In process based MTK, all d processes r using their own memory areas hence there is no question of synchronization problems. But in case of thrad based MTK, all d threads r using the same common memory, hence synchronization (concurrency) problems vil come. /* Movie : All these parts of movie rexecuted 1 after the other then that movie would be reality horrible, so because M.td can into picture & made all party of movie executed simultaneouls. */ The major appln area of multi-threading is multi-media and graphics like implementing video games, simulators etc. 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

189

2. Defining, Instantiating and Starting a Thread: 1. V can define a thread in the following ways : i) By extending thread class. ii) By implementing Runnable interface; 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 cant 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); } 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 */

190

Eg :

Class Mythread extends thread { Public Void run( ) { for (int i = 0; i<10; i++) { SOPln (GM : Child thread); } } 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 running t.start ( ); starting a thread threads started for (int i = 0; i < 10; i ++) { SOPln (GM : Main thread); } }

Eg :

O/P : V Cant predict the O/P /* 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 GM : Chil GM : Main 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 cant 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. Thread scheduler follows Round-Robin Algorithm / Shortest job first.

191

Marathi Movies : Case (i) : Defference b/w t.start( ) and t.run( ). In the case of t.start( ) a new thread vil create and that thread is responsible for the execution of run( ) method. But in the case of t.run( ), no new thread vil create and the main thread is wholely responsible for execution fo run( ) Method also i.e. run( ) will execute like a normal method instead of a thread. Eg : Replace t.start( ) with t.run( ) in above pgm the following is the O/P : GM : Child thread (10 times) GM : Mainthread (10 times) - Entire O/P produced by Main( ) thread. Case (ii) : Importance of thread class start method. Once v created a thread, v r responsible for registering our own created thread with the threat scheduler. This activity will be performed by start( ) method available in the thread class. Hence, for starting a new thread, v have to call start( ) method instead of run( ) method. After completing, joining formalities for our thread, start method will invoke run( ) method. Public Void Start ( ) { 1. Joning formalities for our thread like : Registering the thread with the thread scheudler 2. Invoke (call) run( ) method. } Case (iii) : If v r not overriding run method : t.Start( ) internally calls, thread class run( ) method who has empty ) method to define, our job (Strictly implentation, which is doing nothing. v.Should override run( recommended). Case (iv) : If V r overriding start( ) method: Eg : Class Mythread extends thread { Public Void run( ) {

192

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 wont call run( ) method, it will execute as a normal method. 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( ); }

193

} O/P : v cant predict. Start (by main thread) Main (by Main Thread) Explanation of execution of above pgms : 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 { 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 : New/ Born t.start ( )
Ready/ Runnabl e (Ready to run)

Run (by Child Thread)

);

);

Thread scheduler allocates CPU

Running (Executi ng run method)

If run( ) method completed

Dead state 194

/* Once V start a thread, restarting the same is foolish as similar to assign brachure to make us born once again */ In the program, write t.start( ) 2 times. No CTE, but RTE : Illegalthread State Exception. 1. Once a thread is started, V r not allowed restart the same thread again. Violation leads to Run time Exception Saying : - Illegal thread state exception. 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 extends Mythread

implements

runnable

Instead of doing above one indirectly, follow the below one : Runnable Mythread 1. Is not suggestible because once v rextending thread class v cant 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( );

195

{ SOPln (Run); } } Class Thread Demo { P S V M (String[ ] a) { Myrunnable r = new Myrunnable ( );

/* V wnt write r.start( ), (CTE) because. My Runnable class is not extending Thread class */ // Thread t = new thread( ); t.start( ); /* v cant 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( ); 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 :

196

(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 doesnt contain any start( ) method, hence it is a CTE. CTE Symbol : : Cant resolve symbol Method start( ) 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.

Location :

Thread class constructors : 197

1. 2.

No-arg constructor : Thread t = new thread ( ); Constructor with argument as string object (so that v can give our own name to the thread) Thread t = new thread (string name); Constructor with argument as any runnable interface refeence Thread t = new thread (Runnable r); Constructor with Runnable, string args. Thread t = new thread (runnable r, string sname) Thread grouping : (very rarely used in real-time) not i.e. SCJP Thread t = new thread (thread group g, string name); Thread t = new thread (thread group of, runnbale r); Thread t = new thread (threadgroup of runnable r, string name);

3. 4. 5. 6. 7.

Case Study (Mix of extends, implements) : Class Myrunnable extends thread { 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 wont created

198

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. 2. Public final void setName (String Name) Public final string getName ( )

Demo on Setter & Getter Methods : Eg : Class Sample { P S V M(S[ ] args) { SOPln (thread current thread ( ).get Name ( )); } } O/P : Main Eg : Class Sample { P S V M(S[ ] args) { Threadd.currentthread( ).setName (Karthikeya).

199

// SOP (10/0); Exception in thread karthikeya. } } O/P : Karithikeya Thread Priorities : /* Every thread in Java has by default has priority. If all the threads have same priority, which thread vil execute v cant 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 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.

200

// Demo pgm on Thread Priorities : Class Sample Thread t = thread current thread( ); { Public Static Void Main (String[ ] args) { SOPln [Thread.currentThread( ).getpriority()]; Thread.current thread.setpriority (10); // Thread current thread. Set priority (thread. MAX PRIORITY); SOPln [Thread. Current thread( ).getpriority( )]; // } }

Class Mythread extends thread { Public void run( ) { for (int i = 10; i < 10; i++) { SOP (Child Thread); } } } 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( ); 201

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 : 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 cant change the damon nature of a thread once it is started. ***

202

203