Core Java Meterial
March 28, 2017 | Author: Pravallika Repana | Category: N/A
Short Description
Core Java Material...
Description
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
1
8. Object – Oriented Concepts ……………………………111 9. Overriding…………………………………………………120 10. Constructor ……………………………...………………144 11. Exception Handling …………………………………….155 12. Garbage Collector ………………………………………176 13.Multi Threading ………………………………………….185
2
SCJP Syllabus 1.
Language Fundamentals.
2.
Operators and Assignment ***
3.
Declaration and Access Control
4.
Oops
5.
Multi-Threading (15 to 20 hrs.)
6.
Java. Lang –
7.
Exception Handling (10 hrs.)
8.
Assertions [used for debugging purposes (5hrs)]
9.
Garbage Collection
10.
File I/O & Serialization Customized (4hrs)
11.
Auto boxing & Auto unboxing, static impolts, var-arg method, num
12.
Collection framework (25 to 30 hrs). Generics. (40 – 50 days)
13.
Development
–
Encapsulation, Inheritance, Aggregation (Composition) Polymorphism Coupling & Cohesion. Object Class String String butter String builder Wrapper classes
Exam Pattern : 72 QS (Multiple Choice) & (Drag and Drop) → 43 QS ⇒ 59% Most of the Indian Projects are “Maintenance” only.
3
I.
Language Fundamentals a) Identifier b) Keywords c) Data types d) Literals e) Arrays f) Types of variables - Instance - Local - Static g) Main Method h) Var-arg Methods (in Notes No. 3)
(a)
Identifiers : A name in any program is called “identifier” which can be used for identifying classes, methods, variables and labels. Eg : Class Sample { P S V Main( ) [String args( )] { into x = 100; : : } }
No. of identifiers : - 4 – Sample, main, args, x 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.
4
3.
We r not allowed to use keywords as identifiers violation leads to compile-time error.
4.
There is no length limit for java identifiers. But Sun highly recommends upto 15 characters suggestable for identifiers. (In C++ 256 is max. length)
5.
The java identifiers are case sensitive. i.e. Number, NUMBER, number can be used as different identifiers within the same program and all are legal.
6.
All the pre-defined Java Classes and inter fore name we are allowed to be used as 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 can’t 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)
Used Key Words (48)
Un-used (2) goto, const.
Reserved literals (3) true, false → to represent boolean value null → for representing object references
Primitive Keywords for data types : (8) byte short int long
float double char boolean (logical)
5
Keywords for flow control : (11) if else
for do while
switch case default
return
break continue
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
6
Void return type keyword : (1) -
indicates no return type by a void method. (We should declare return type for a method)
-
Indicates nothing returned by a method. (If void is not mention for a method returning nothing, it gives compile time error).
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 don’t 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
:
All the keywords (reserved words) in java contain only alphabet symbols and all are in lower case.
Note 2
:
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 : var iable
- Every exp ression has the type - Compiler always searches for type compatibility Boolean b = o;
7
(c) Data types : 2Q** -
In java, every variable / expression has a type and every type is strictly defined (i.e. min & max sizes…..) The compiler strongly checks for type compatibility. Hence Java is considered as “strongly – typed” language. boolean b = o; int i = 10.5;
-
Data types 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.
8
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 2’s complement.
-
In general, Range : -2n-1 to 2 n-1 – 1
-
If U want to save data in a file, to transfer across a network, to handle data interns of streams (iron a N/W or from the file) this “byte” data type is the best suitable.
Note :
Compiler also checks for the assignments. Eg : byte b = 130; byte b = 127; Comp Error : Possible loss of precision required : byte found : int.
2. Short : -
Size
:
2 bytes
-
Range
:
-215 to 215 –1 (-32.768 to 32767)
-
Short
S = 32768;
Comp. Error : PLP found : int required : short -
Rarely used data type. But where it is used ?
When Java was introduced in 1995, processors are of 16-bits, they used short data type. But now, 16 – bit processors are outdated, the short data type is also outdated (almost). This is why is rarely used in regular pgmg.
Short d.t is best used for 16-bit processors like 8086.
9
3. int : -
The most commonly used datatype in Java is ‘int’ type. Java is ‘Robust’ in the sense, the chances of getting o/p of java program failed are low w.r.t p/f to p/f. In ‘C’ – int - 2 byte (16 – processor), 4 byte (32 – processor) The pgm written in ‘C’ on 16-bit proc can be executed on 32-bit processor but vice-versa is not possible. ⇒ ‘C’ is non-robut language.
-
The size of ‘int’ is always 4-bytes irrespective of platform. But in case of ‘C’ the size of int varies from p/f to p/f ⇒ chance of failing ‘C’ pgm from p/f to p/f is very high. This behavior is known as non-roburt behavior. But in case of Java, size of any d.t is fixed and it won’t vary from p/f to p/f. Hence the chance of failing the java pgms is very very less and hence it is considered as robutst language.
-
Because there are no memory problems in java because of Garbage collector, it is considers as robust.
-
Size : 4 – bytes
-
Range : -231 to 231 - 1 (-2147483648 to 2147483647)
-
Because our required values are only in the range of int it is most widely used.
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
Double
Size : 4-byte
Size : 8-byte
This is suitable if U want to consider 6 to 7 fractional digits of accuracy is required.
This is suitable if U want to consider 14 to 15 fractional digits of accuracy is required.
This is single – precision (6 to 7) ⇒ Less accurate. Range : -1.4e –45 to 3.4 e 38
This is double – precision (14 to 15) ⇒ More accurate. Range : 4.9 e –324 to 1.8 e 308
“Char” data type : -
Size
: 2 – bytes
-
Range : 0 to 65, 535 characters (language independent) Unicode ⇒ Unique code for every world wide character.
-
Java uses Unicode for representing characters. In order to cover all world-wide character sets, 8-bits (1 byte) are not enough, that is why we should go for 16-bits (2 byte).
Note : Unicode: Unique code for every character irrespective of language and irrespective of platform. But ‘c’ pgm can be developed only in English. Boolean type : -
In case of C, C++ size of Boolean is fixed, but in Java, size for Boolean is not applicable (JVM dependant)
-
Size : Not applicable Range : Not applicable, but allowed values are true and false.
Eg : boolean b = true; boolean b = TRUE; boolean b = false; boolean b= FALSE; Comp error : Cannot resolve symbol TRUE, FALSE
11
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
Range
Wrapper class
Default value
1. byte
1
–128 to 127
Byte
0
2. short
2
–32768 to 32767
Short
0
3. int
4
–231 to 231 –1
Integer
0
4. long
8
–263 to 263 –1
Long
0
5. float
4
–3.4e38 to 3.4e38
Float
0.0
6. double
8
–1.7e308 to 1.7e308
Double
0.0
7. char
2
Unicode values : 0 to 65, 535
Character
0[indicates blank space character]
NA (allowed values are true / false)
Boolean
false (but in C, C++ (1) i.e True)
8. boolean NA
Literals : ** A literal represents the constant value which can be assigned for the variable Eg.
Int
x
datatype keyword
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
a−f A −F
Allowed literals : 0 to 9 and
This is one of the very few areas, where java is not case – sensitive. OX 10;
-
Eg : int y = OX 10; ; (‘x’ in any case) (Any case is allowed) The number must be prefixed with either ox (or) OX.
We can’t assign binary literals for integral data types.
Eg :
Class Test { Public Static Void Main (String args [ ]) { int x = 10; int y = 010; int z = 0X10; S.O.Pln (x + “……….” + y + “…..” + z); } }
O/P : 10…8…..16. Note :
We can give i/ps to JVM in decimal, octal and hexadecimal but the O/P of JVM is always in decimal form. O/P can be displayed as binary, Oct & Hex by using methods (to Octal String ( ) etc) in Util Package. By default all the integral literals (either decimal / octal / hexa decimal) are of ‘int’ type. We can specify explicitly a long literal by suffixing either ‘l’ (or) ‘L’. Eg : long y = 10 l; int x = 10 l; comp error : PLP found : long
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 can’t assign a floating – point literal directly to the float variable. Eg : double d = 123.456; float f = 123.456; Comp. Error : Possible Loss of Precision (PLP) found : double required : float
-
We can specify explicitly a floating point literal of float type by suffixing with ‘f’ (or) ‘F’. 123.456 f ;
Eg : float f = 123.456 F ; @@ -
We can’t specify a floating – point literal by using base-8 [octal] (or) base – 16 [Hexa decimal] notation. i.e. The only possible way to specify floating point literals is base – 10 [Decimal] notation only. Note :
int x = 10.5; com. error : PLP found : double; required : int.
- ⇒ We can’t assign floating point literals for integral types @@ - We can directly assign an integral literal to the float data type.
14
Eg : float f = 10; S.O.P(f); O/P : 10.0 Note :
No need of Suffix ‘f/F’ For integral literal when assigned to floating point data types.
Exercise : 1. float
f
=
123.456;
2. float
f
=
123.456f;
3. double
d
=
123.456d;
4. double
d
=
123.456;
5. double
d
=
123.456D;
6. float
f
=
123;
#7. float
f
=
0123;
#8. float
f
=
0X123;
7., 8., are valid 0123, 0x123 constitue only integer literals, they are converted to integer decimal type and stored in & l – literals. Note : @@
@@
We can specify explicitly a floating point literal is of double type by specifying ‘D’ (or) ‘d’ at suffix (of course not required, because floating – point literal is of double type by default).
An integral literal can be assigned to floating point data type whether it is expressed in decimal / octal / hexadecimal form Eg : float f = 123; float f = 0123; float f = 0X123;
9. float f = 123e2(f); Note : For integer data type we shouldn’t age 123e2 assigned to int variable. Eg: int i = 123e2; 10. double d = 123e2; 123456e98;
15
Possible assignment : byte → short
int → long → float → double
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 : ------
Eg :
boolean b = 1; in case of C, C++ boolean b = 1; in case of Java. Comp. Error : In compatible type Fount : int Required : bodlean.
Here we don’t get PLP error, be cause we are not storing the literal value in its equally compatible data type but of entirely different data type. But in case of; int i = 23.45; Error : PLP because both found & required data types are compatible with each other, but not equally compatible. Eg :
int x = 10; if(x) { SOPln (“Hello”); } else { SOPln(“Hi”) } (Code is valid in IO but valid in Java) O/P : Comp. Error : Incompatible types 16
Exercise : 1.
boolean boolean boolean boolean boolean
b b b b b
= = = = =
true; FALSE; O; yes; (10>20); (x > y);
-
Can’t resolve symbol Incompatible types Can’t 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
Unicode Value
Character
\b
\u0008
Backspace
\t
\u0009
Horizontal tab
\n
\u000a
New line
\r
\u000d
Carriage return
\f
\u000c
Form feed
\’
\u0027
Single quote
\”
\u0022
Double quotes
\\
\u005c
Backspace
big farms
need
red
tractors
18
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
Can’t increase or we can’t decrease size. Hence, memory point of view arrays r not good. Solution is : Collections
Arrays r fixed in size but Array list is not fixed in size. The collection objects (Array list) r growable in nature but performance wise these r not good. These collection show worst performance, because they create a new copy of all the existing objects.
3. There is no under lying data structure present for arrays. Hence we r unable to represent array information in some sorting order we can’t avoid duplicate object insertion by default. Agenda (Arrays) 1. Arrays Intro 2. ↓
Declaration
3. ↓
Construction
4. ↓
Initilization
5. ↓
Declaration, Construction & Initialization in a single line.
6. Length vs length (
)
7. Anonymous arrays (Nameless) 8. Array element Assignments 9. Array variable Assignments
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 b
short s = 100; int[ ] an = new int [ s ]; i
int i long l = 10L; int[ ] arz = new int = [ l ]; Error : PLP -
chart ch = ‘a’; int [ ] i = new int [ ch ]; ⇒ array size is ‘97’ ints. int[ ] i = new int [ ‘a’ ];
-
int [ 10 ] a = new int [ 10 ]; ↓ At the time of declaration we shouldn’t mention the size.
2 – D arrays construction : -
2-D arrays r known as Matrices. These matrices form is in C, c++ but in Java there is no matrices concept. It stores every thing in a single row. 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[1]
a[2]
a→
- base array
int [ ] [ ] a = new int [ 3 ] [ ]; ([3] – optional, [ ] – compulsory) a[ 0 ] = new int[ 2 ]; a[ 1 ] = new int [ 1 ]; a[ 2 ] = new int [ 3 ]; Note : At the time of construction of multi-dim arrays, the base-dimension should be compulsorily specified otherwise compile-time error. i.e. int[ ] [ ] a = new int [ ] [ ]; because base size is not mentioned. Exercise : int [ 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[2]
a→ a[0] [0] a[0] [1]
a[0] [0] [0 ]
24
Code : int[
][
][
]
a
= new int [ 3 ] [
][
a[ 0 ]
= new int [ 2 ] [
];
];
a [ 0 ] [ 0 ] = new int [ 3 ] ; a [ 0 ] [ 1 ] = new int [ 2 ] ; Exercise : 1. int [ 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 [
][
][
] a = new int [ 3 ] [ 4 ] [ 1 ];
5. int [
][
][
] a = new int [ 2 ] [ 3 ] [ 1 ];
Structure : a→
6. int [
][
][
] a = new int [ 2 ] [ 0 ] [ 3 ];
Array Initialization : -
Once we constructed an array, all the elements will get default values automatically. Eg : int [
] a = new int [ 3 ];
S.O.Pln (a[0]); //O.P. = O -
If we r performing any initialization explicitly, the default values will be over ridden with our specified values.
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
reference of d[1] [0]
d [0] [2] 0.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 won’t be any value for d [ 0 ] [ 1 ] ⇒ Null pointer exception.
Eg.3 : int [ ] a = new int [100]; a[ 0 ] = 10; a[10] = 100; S.O.Pln (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 can’t create an array of ur own size with some values of ur own and some with default values.
-
Declaration, construction & Initialization is a single line. If U r dividing into 2 nd line, it results in a compile – time error.
Eg : int [ ] a = { 10, 20, 30}; int [ ] a; a = {10, 20, 30}; (C.E. Illegal Start of expression)
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.
int [ ] a = new int [ 6 ]; S.O.Pln (a length); // O.P : 6
2.
int [ ] [ ] a = new int [ 2 ] [ 3 ]; a.length = 6 a.length = 2 (size of base array) a[ 0 ].length = 3 -
There is no direct method which represents, the total no. of elements of 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}; (shouldn’t 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 can’t be promoted to int)
-
If an array is declared of type “Object” class, we allowed to give any kind of objects as elements. i.e In the cause of array of reference type it can take the declared type objects and its child class objects also as array elements. Eg : Object [ ] ob = new object [ 3 ]; ob [ 0 ] = “Pavan”; ob [ 1 ] = new object ( ); ob [ 2 ] = new integer (10);
30
Array variable assignments : -
While performing assignment of one array to another array, we have to check the declared types, not its sizes. Eg : int [ ] a = {10,20,30};
int [ ] a = {10,20,30,40,50,60,70,80};
int [ ] b = {40,50,60}; a = b;
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 can’t be promoted to into array but we can promote a char value to the int value at array element level. Eg : char [ ] ch = {‘a’,’b’,’c’};
-
int [ ] i = {10,20,30}; i = ch; comp. Error : Incompatible types. found : char [ ] req : int [ ] In the case of reference arrays for the parent type array, we can assign child array type. Eg.1 : string[ ] s = {‘A’,’B’ }; object [ ] ob = s; Eg.2 : car [ ] c = new car [ 3 ]; zen [ ] z = new zen [ 3 ]; c = z;
-
In place of I-D array, U can’t provide value. Int [ ] [ ] a = new int [ 3 ] [ 2 ]; a [ 0 ] = new int [ 2 ]; a [ 0 ] = new int [ 100 ]; a [ 1 ] = 10;
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’ can’t be referenced from a static text.
-
There is no need to perform initialization for the instance variables, by default instance variables, will always get default values.
-
Observe the above eg.
-
Values varying from obj to obj, we will declare them as instance vary.
2. Static variables : Eg : class student { string sname; int rollno; string coll-name; } -
In the above class, even though u create a lot of objects, all of them having same 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 : Don’t assume, because static variables r declared within class they r called as “class variables”. Because, though instance variables r created within the class – they r called as “instance variables” but not class level variables. 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 won’t be the concept of “Default Initilization”. It is programmer’s responsibility to perform initialization for local variables explicitly.
-
Before using a local variable, we should perform initialization, otherwise compile time error. Eg : class sample { P.S.V.M (S[ ] a) { int i; Sopln (“Don’t Sleep”); } }
O/P : Don’t sleep (no comp. error. ‘i’ is not used till now)
35
Eg : class sample { P.S.V.M (S[ ] a) { int i; if (args.length > 0) { i = 10; } Sopln (i); } } O/P : Comp. error : V ‘i’ m n h i. Note : Initialization is not suggestable in the conditional blocks. Eg :
class sample { P.S.V.M (S[ ] a) { int i; if (args.length > 0) { i = 10; } else; { i = 20; } SOP (i); } }
O/P : No compile time & run-time error.
36
Conclusions : -
If U R not performing initialization, for the static and instance variables, default values will come. But for the local variables, default values will come. But for the local variables, there is no concept of default initialization we should perform initialization before using local variable.
-
Local variables, the only allowed modifier is “final”. i.e. the following local variable declarations. Invalid
-
Error : illegal start of expression
Public
int i = 10;
final int i = 10;
Private
int i = 10;
int i = 10;
Static
int i = 10;
Local variables can’t be static because static variables can be accessed with classname and object of class outside the methods also, but local variables can’t be used outside the block.
Un initialization in Arrays : Eg : class sample { int [ ] a; P S V M (S[ ] a) { Sample S = new sample ( ); Sopln (s.a.); // null Sopln (s.a[ 0 ]); // Null pointer exception (Run time exception) } } At the instance level : 1.
int [ ] a
sopln (obj. a); null. sopln (obj. a [ 0]); NPE
2.
int [ ] a = new int [ 6 ];
sopln (obj.a); i@ 12D34 sopln (obj.a[ 0]); O
37
Static : 1.
int [ ] a;
sopln (a); null. sopln (a [ 0]); NPE
2.
int [ ] a = new int [ 6 ];
sopln (a); i@ 1add 2dd sopln (a[ 0]); O
‘Local’ level : 1.
int [ ] a;
sopln (a); CE No need of its components
2.
int [ ] a = new int [ 4 ];
sopln (a); // i@ 1add 2dd sopln (a[ 0]); O
-
Whether an array is declared instance static (or) local its elements always assigned with default values. When arrays r declared at static / instance level, V can print the address (reference) of an array object as null, but V can’t print a3[ 0 ], results in CJE because null object points to nothing. Where as if V declare an array as local, then, V can’t print reference of an array object, Vget CTE : variable might not have been initialized.
Signature (or) Complete Declaration of Main Method : -
Public static void main (String[ ] args) { ----------}
Public
: To call this method by JVM from anywhere (JVM is configured in such a way that it finds the main method in its defined signature.
Static
: Without object also we can in invoke this method.
Void
: This method doesn’t return anything to JVM.
Main
: Name of the method.
String[ ] args : Command line arguments array. *
If there is no main method, in run-time while executing we get error : No such method error.
38
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 won’t 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
20
[2]
[3]
30
40
Command-line arguments
If U access args [ 4 ] – error. -
args [ 0 ] – 1st Gmd line argument args [ 1 ] – 2nd Gmd line argument args.length – the no. of command-line args. Args [ 4 ] – 5th Gmd line arg, but there is no such args results in “Array Index Out Of Bounds” Exception.
-
WAP to display all Gmd and line args. Class test { P S V M (S[ ] a) { for (int i = o; i < args.length; i + +) S.O.Pln (i); } }
Public,
Static, Void } 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 javap jav.lang. Float
46
Double Integer -
For representing infinity, there r constants defined in the Float and Double wrapper classes. They r: public static final positive infinity public static final negative infinity
But there is no such arrangement in the case of Integral types (Byte, Short, Int and Long) represent infinity. Hence “Division by zero AE” results only in case of integral types but not in floating point data types. int 10/0
→ int (but no const in Integer class)
double 10.0/0
→ double (there is a const / defined in double class for representing infinity) → (-Infinity)
-10.0/0 3.
Nan / (Not a Number) SOP (0/0) ; A.E : / by zeror (RTE) SOP (0.0/0) ; NaN If the result of an Arithmetic Expression is underfined, there is no way to represent that undefined values in the integral arithmetic. Hence it results in Arithmetic Exception. Eg : SOP (0/0); CTE : A.E. : / by zero But in the case of floating point arithmetic, if the result is undefined, there is a constant available for representing undefined results. (NaN). Hence, Eg : SOP (0.0/0); O/P : NaN (No Compile & Runtime Errors)
Consolidated : 10/0
⇒ A.E
10.0/0
⇒ Infinity
-10.0/0
⇒ −Infinity
47
-0/0
⇒ AE
-0.0/0
⇒ NaN
There is no math class in 1.5 but there in 1.4 3.
1.4 : S.O.Pln (Math. Sq.rt (4)); O/P : 2.0 SOPln (Math. Sq.rt (-4)); O/P : NaN 4.
For any ‘x’ value including NaN, the following statements results. x > Float NaN x<
“
x>
“
x<
“
x==
“
O/P : False [SODln (x ! = Float.NaN), O/P : true] But, the result of below stmt is true. Float.Non! = Flat.NaN → O/P; True SOPl (Float.Non! = Flat.NaN); → True SOPln (Float.Non! = Flat.NaN); → False. Conclusion : Arithmetic Exception : - meant for only integral types not for float, double - only & operators (/, %) cause their exception. 4.
String Concatenation Operator : Till 1.4, only ‘+’ operator is overloaded. But in 1.5, ‘%’ operator is also overloaded. ‘+’ Operator is the overloaded operator in Java. Sometimes it acts as Addition operator and sometimes it acts as String Concatenation Operator. If atleast one of the operands is the string type, then ‘+’ oprator simply acts as “Concatenation” operator. If both operands are numbers then ‘+’ acts as Arithmetic Addition operator. Eg 1: 2 + 3 = 5 “ab” + “cd” = abcd “ab” + 3 = ab3
48
Eg 2: int
a = 10;
int
b = 20;
int
c = 30;
String
d = “durga”;
SOPln
(a+b+c+d); // 60 durga (a+d+b+c); // 10 durga 2030 (d+a+b+c); // durga 102030 (c+d+a+b); // 30 durga 1020 (a+b+d+c); // 30 durga 30
Note : If same operator is more than once; then associatively arises and for ‘+’ it is L→R associativity. 6.
Equality Operator : byte → short → int → long → float → double chart 1.
Only z : = = and ! = return type is “Boolean”. Eg :
SOP (10 = = 20); // false SOP (10.0 = = 10); // true
Note : Before comparing 10.0, 10, JVM promotes lower type into higher type. SOP (97 = = ‘a’); // true Char can be promoted to int SOP (‘a’ = = true); // CTE CTE : Operator = = cannot be applied to char and boolean. 2.
We can apply “Equality Operators” for both primitive types and object references. In case of primitive data types, these operators check magnitudes. Eg :
Sample S1 = new sample ( ); Sample S2 = new sample ( ); Sample S3 = S1; SOPln (S1 = = S2); // false SOPln (S1 = = S3); // true
In case of object references, ‘ = =’ operator always checks for address comparison. i.e. (S1 = = S2) is true, if and only if both S1 & S2 pointing to the same object (observe above eg). Eg : Sopln (“durga” = = “xxxyyy”); // flase Sopln (“durga” = = new Integer (10)); C..T.E. : Incomparable types.
49
Note : We can’t use = = operator for different type of objects. Violation leads to compile-time error, saying “Incomparable types”. -
For any object reference ‘S’, S = = null, the result is always false. String S = null; Object O = null; Integer i = null; SOP (null = = “durga”); // false SOP (new integer (10) == “null”);
-
null = = null always results in (true).
-
10 = = 20 // flase 10 = = 20 = = 30 L→R CTE : = = Cannot be applied to Boolean, int
5.
Comparison Operator : They are = Always return boolean type. These can be applicable only for primitives except boolean. Eg :
10 < 20 → true 30 > 15 → true 30 < = 15 → false “durga” < “xxxyyy”. CTE : Operator < cannot be applied to string and string. 10 < 20 < 30 CTE : Operator < cannot be applied to boolean, int.
7.
Bit-wise Operator : 1.
They r &, |, ∧ AND ← & - If both r true then only true. OK
←|
XOR ← ∧
- If atleast one is true then result is true. - If both are different, then only true. If both r same, then false. 50
Exercise : TθF→F T | F→T T ∧ F→T 2.
4θ 5→4
4 – 0100 5 – 0101 & - 0100 → 4
4| 5→5
4 – 0100 5 – 0101 | - 0101 → 5
4∧5→1
4 – 0100 5 – 0101 ∧ - 001 → 1
3.
We can apply for bolean & Integral types, not applicable to floating point and char types. Eg : 1.5 & 2.6 CTE : ‘θ’ operator cannot be applied to double and double.
4.
Bit-wise complement operator : ( ~ ) -
We can apply Bit-wise complement operator, only for integral types but not for Boolean types.
Eg : ~ 4 ~ true CTE : Operator ~ cannot be applied to boolean. SOP (~4); // -5
51
4 → 0000 0000 …….. 0100 ~4 →1111 111……… 1011 =-
000 000......0100 5 01015
= -5 15 → 0000 …… 1111 ~15 →1111 …… 0000 → 000 …… 1111 10000 - 16 SOP (~15); // -16 5.
Boolean - complement operator : (!) ! true → false ! flase → true ! 3 → CTE CTE : Operator ! cannot be applied to int. Conclusion : & | ∧ - can be applied for both integral & boolean types. ~ → Only for integral types. ! → Only for boolean types.
8.
Short – Circuit Operators : if
( x1 + .... + x n ) ( y1 + .... + y n ) & 10 min 10 min
{ 52
L1min → total 21 min
// } else
if
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 (&, |)
Short-circuit (&&, ||)
1. Can be applicable for both boolean & integral types
1. Applicable only for boolean types.
2. Both operands must be evaluated
2. Evaluation of 2nd argument is optional. (x && y → if x is true. then only y will be calculated) (x || y → if x is false, then only y will be calculated)
3. Performance is low
Eg:
3. Performance is high.
int x = 10; int y = 15; if (++x < 10 & + +16y > 10) {
53
++x; Sopln(x); Sopln(y); } else { ++y; Sopln(x); Sopln(y); } x
y
&
11
17
|
12
16
&&
11
16
||
12
15
if (10=,
a = a & 5;
&=, |=, ∧=
a& = 5;
Adv : Implicit type-casting Chained ass Operators : Eg : int a,b,c,d; a = b = c = d = 40; int a = b = c = d = 40; CTE (a,b,c,d not declared – No seperator b/w 2 variables) New Operator : 1. This can be used for creation of objects 2. New and instance of are both keywords as well as operators. [ ] Operator : 1. This can be used for declaration and construction of arrays. Note :
Chained assignment is not allowed at the time of declaration. int a,b,c,d; a = b = c = d = 40; a+ = b* = c| = d = 10 → a = 80, b = 40, c = 1, d = 30. All compound operators have called precedence. Assignment always takes place from R → L.
Precedence of Java Coperators : 1.
Unary Operators : i) [ ], x ++, x – ii) +=x, --x, ~, ! iii) new, - type-casting operator)
59
2.
Arithmetic Operators (binary operators): i) *, /, % ii) +, -
3.
Shift Operators : i) , >>>
4.
Comparison Operators : =, instance of
5.
Equality Operators : ==, !=
6.
Bitwise Operators : &, ∧, |
7.
Short-circuit Operators : && ||
8.
Conditional Operators : ?:
9.
Assignment Operators : =, +=, -=, *=, /=, %=, >>=, >=, &=, | =, ∧=
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.
Curly braces { }, and else part both are optional.
2.
The valid argument for the if-statement is always Boolean, violation leads to CTE.
61
Case 1 : int i = 10; if (i) { SOP (“Hi”) } else { SOP (“Hello”); } 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.
Curly braces are mandataory, violation leads to CTE.
2.
Both case and default are optional Eg.
int x = 4; switch (x) { } - No case and default statements No CTE, NO RTE
3.
Valid arguments for switch statement are : byte short → unitl 1.4 version chart int From 1.5 version onwards, the corresponding wrapper class objects (Byte, Short, Character and Integer) are also allowed. Switch can take an enum object also as argument. Eg :
Integer i = new intger (10); Switch (i) { } valid in 1.5 Invalid upto 1.4
4.
If us want to keep any statement inside switch, it must be under some case of default. Otherwise compile time error. Eg :
int x = 4; Switch (x) { SOP (“Pandu”); } CTE : ‘Case’, ‘default’ (or) ‘}’ expected.
5.
Case Labels : All the case labels must be compile time constants otherwise CTE. Saying constant expression required. Eg :
int x = 10; int y = 40; // final y = 40 Switch (x) { case 10; case 20; 64
case 30; case y : } CTE : Constant expression required. 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
⇒ ⇒ ⇒ ⇒
0,1 1 2 default
x-1 x-2 x – 3 …. R also final.
Iteration Statements : 1.
‘While’ loop : If we don’t know the number of iterations in advance, then we should go for “while” loop. The valid argument for the while loop is Boolean. Curly braces are optional, without curly braces only one statement is allowed, that statement should not be declarative statement. If the controller never reaches any statement then compiler gives an error saying. “Unreachable Statement” Eg.1 : while (true)
(compile – time constants)
{ SOP (“Hi”); } SOP (“Hello”); Eg.2 : while (false)
(unreachable stmt) (compile – time constants)
{ SOP (“Hi”);
(unreachable stmt)
} SOP (“Hello”);
67
Eg.3 : int a = 10; int b = 20; while (b > a) { SOPln (“Hi”); } SOPln (“Hello”); Here there won’t be any CTE, (b > a) expression is executed at run-time 10g JVM but not by compiler. If compiler couldn’t resolve expression then it won’t check for unreachable stmts/. Hence no CTE. Eg.4 : final int a = 10; final int b = 20; while (b > a)
(compile-time comparison)
{ SOP (“Hi”); } SOPln (“Hello”); CTE : Unreachable stmt/2.
do – while : If the loop body has to be executed at least once, go for do-while loop. Syntax : do { ---------------} while (b); Omission of ; results in compile time error. Curly braces r optional but b/w do and while there should be atleast a single statement. i.e. do-while with zero. Statements in b/w results in CTE. The single stmt b/w do-while might be empty statement.
68
do while (b); do ; while (b);
CTE : while expected.
No CTE
do
do ; ; while(b);
{ } while (b);
CTE (; expected) ;
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”);
NO Unreachable stmt
do { SOPln (“Hi”); } while (true); SOPln (“Hello”);
Unreachable stmt.
int a = 10, b = 20; do { SOPln (“Hi”); } while (a javac sample.java ⇒ sample. class will be generated and placed in current working directory. But if we r using package declaration, it is suggestible to place generated class file in the corresponding package structure. We can achieve this by using –d flag of javac. > javac – d . sample.java ⇒ create sample. class in the current working directory inside a package -d → specifies where to place generated class files ⇒ destination. → Current working directory. If the needed package structure is not available, this command automatically creates the required package structure. Instead of , we can use
C: E: D:
⇒ > javac –d C : sample.java ⇒ Need not be always. The compiler can create needed folder structure but it cannot create destination structure. If the specified destination is not available, we will get a compile-time error saying : The system cannot find the path specified. Eg : > javac –d z : sample.java.
(error in writing)
Run : > java com/durga/sample. Hi >java com.durga.sample Inside a java program, we r not allowed to get more than one package statement. Violation leads to compile-time error. Saying : “class” or ‘interface’ expected.
82
If we r not specifying any package statement, the generated class file will be placed in the default package, which is nothing but “current working directory”.
The package, import and class statements must be placed in following order. 1. package statement – Atmost one 2. import statements – Any number 3. Class / interface declarations – Any Conclusions : i. 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
(top level classes & inner classes)
iv. abstract v. strctfp If we use any other modifier, we will get a compile-time error. Saying: - modifier < modifier-name> not allowed. Public : Public classes : 1.
If a class declared as public, we can access that class from anywhere ie within or from outside the package or even from the N/W also . ⇒ from remote area also we can access. Eg :
Package pack 1 ;
Compile : >javac –d A.java.
/* Public */ class A { Public void M1( ) {
83
SOP (“In A’S M1”) } } Package Pack 2; // import Pack 1. A;
Compile : >javac –d B.java.
class B { P S V M (S[ ] a) { A al = new A( ); A1.Ml( ); } } If class A in pack 1 is not declared as ‘public’, then while compiling class B, we will get a CTE, Saying : Pack 1. A in pack 1 is not public and cannot be accessed from outside package. (Class A if not mentioned as public will be treated as default and default classes can’t be accessed from outside the package). Issue can be resolved by mentioning class A in pack 1 as public Run : > java pack 2/B. O/P. in A’s M1. Default Classes : 1. If a class is declared as the default, we r allowed to access that class from within the package only, if we r trying to access from outside package, it results in CTE. 2. Default access is also known as “Package Level Access” 3. There is no default keyword for class level modifiers. But “default” keyword is there for switch statement. Abstract Classes : 1. Would be used for good programming practice. Most used by real-time experts. 2. “abstract” is a keyword which can be applied for classes and methods. i.e we can’t apply abstract keyword for variables. 3. If we don’t know about implementation of a method, still we r allowed to declare such type of methods in our classes by using abstract modifier.
84
4. if a method is declared as abstract in a class, it indicates that we don’t know about implementation, child class is responsible for providing implementation. The following is the valid abstract method declaration abstract int no of wheels ( ); 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 doesn’t contain a single abstract method.
What is d use of creating HhpServlet as abstract class ? 8. If u don’t want to create an instance of the class, declare that class as abstract class; whether it contains abstract methods or not. 9. Inside abstract classes we r allowed to keep constructors, i.e an abstract class may contain constructors but the programmer is not allowed to create an object of abstract class, but internally JVM is allowed to create an instance. 10. The 1st child class extending an abstract class is responsible to provide implementation for all the abstract methods present in the parent class, otherwise the child class should also be declared as “abstract”. Final Classes : 1. ‘final’ is a keyword which can be applied for the classes methods and variables. 2. final methods : If a method declared as final, we r not allowed to over side this method in the child class violation leads to CTE. Eg :
Public class A { final public void M1( ) { SOP (“A’s M1 Method”); } } Class B extends A { Public void M1( ) { SOP (“B’s M1 Method”); } }
CTE : M1( ) in B can’t override M1( ) in A.; Overridden Method is final 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
class B extends A
{
{ };
P V M1( )
CTE : Can’t inherit from final ‘A’.
{ SOP (“Pandu”); } } Note : Until & unless there is no specific requirement, don’t use final keyword in the real-time coding, because the programmer is missing the wonderful key concept of object – oriented programming – INHERITANCE Eg :
for final classes : String, Wrapper Classes, Math…..etc String Buffer, String Builder…..
Comparison between final and abstract : 1. An abstract method means : it never talks about implementation. A final method means its implementation is final. No one allowed to override this method. Hence, final and abstract combination is illegal combination, for the methods. 2. An abstract class means, we should create the child class to provide implementation for the abstract methods. But, final class means, we should not create the child class because parent class implementation is final. Hence final and abstract combination is illegal for classes also. 3. A final class never allows to constrain abstract methods but an abstract class may contain final methods. Eg :
final class A
abstract class A
{
{
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.
abstract –final
→
Illegal for methods Illegal for classes
2.
abstract – strictfp
→
Illegal for methods Legal for classes
88
Member Modifiers (Variable + Method) 1.
Member Modifiers : 1) public 2) 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, 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 : Can’t be accessed because class A is default and from outside package. (Issue can be resolved by declaring class A is public). Suppose class A is public but member M1( ) is not public then also we can’t access we get CTE : M1( ) is not public in pack 1.A; can’t be acened from outside the package. ⇒ A class member both should be declared as public to be act. essed from outside the package. Default Members : If a member declared as default, we can access that member, within the current package only i.e. if we r trying to access from outside package, we will get a compile-time error. Private Members : If a member declared as private, we can access that member only in current class, i.e. from outside the class if u r trying to access we will get a 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 = + kids. (Default – within current package, Kids – within subclasses in outside package) The most misunderstood modifier in java is ‘Protected’ (cattle sierra statement) Eg 1 : Package Pack 1; Public class A { Protected void M1( ) { SOP (“M1 in A”); } } Class B extends A { P S V M (SC) args) { 90
A a1 = new A( ); a1.M1( ); // M1 in A B b1 = new B( ); b1.M1 ( ) // M1 in A A a2 = new B( ); A2.M1( ); //M1 in A } } Eg 2 :
II
Package Pack 2; I 1. result in CTE : M1( ) has protected access in pack 1.A; 2. No CTE 3. result in CTE Conclusion : If u want to access protected member, within the current package either by using parent class reference (or) by using child class reference. But from outside package if u want to access protected member, we should access by using child class reference only. i.e. by using parent class reference we r not allowed to access protected members from outside package. Violation leads to compile-time error. If we place class B in pack 1 all combinations are legal. Summarization table : Visibility
Private
Protected
Public
within the class
YES
YES
YES
YES
within the current package either from
NO
YES
YES
YES
child / non-child from outside package but in child class
NO
NO
YES (But it must be invoked on child class ref)
YES
from outside package in non-child class
NO
NO
NO
YES
* Private < javac
p.java
{ P S V M(S[ ] a)
p.class
d.class
{ SOPln (“parent main”); } } Class C extends P { };
> java p 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 won’t be executed. We can’t override static methods. It seems to be overriding applicable but it is method hiding ⇒ changing the implementation of a class by using other classes makes no sense. But overloading applicable for the static methods. ⇒ Inheritance Overriding Overloading
(explanation later)
Transient : (Interviews) 1. “transient” is the keyword which can be applied only for variables. We can’t apply transient for methods and classes. (Process of saving object (values in object) into a file is known as serialization. If we don’t want to store some of the values of object into a file we go for transient). 2. transient means → not to serialize i.e. while saving the state of object to a file, (this process is called serialization) JVM ignores the values of transient variables. Instead of original value, JVM stores default values. Eg : class account { string accname; string accno; string UID; string PWD; }
97
OOS i = 10 j = 20
FOS →
Sample S
i = 10 j = 20 abc.tx+
FOS – File O/P Stream. OOS – Object O/P stream (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) // 0……0 (I,j-tray)
‘Static’ variables never participated in the serialization process because these r not part of object state. If we r declaring static variable as the transient there is no effect at all. All the object can’t be serialized, only objects of class implementing serializable interface can be serialized. Hence we provide implements serializable in the above example. If we declare a final variable as transient, there is no effect at all. Before Serialization
After Serialization
1.
int i = 10; int j = 20;
i = 10; j = 20;
2.
transient int i = 10; int j = 20;
i = 0; j = 20;
3.
transient int i = 10; transient int j = 20;
i = 0; j = 0;
4.
transient static int i = 10; transient int j = 10;
i = 10; j = 0;
5.
transient final int i = 10; transient int j = 20;
i = 10; j = 0;
6.
transient static int i = 10; transient final int j = 20;
i = 10; j = 20;
transient static final int i = 10; i = 10 “Native” Modifier : 1.
“native” is the keyword which can be applied only for methods. i.e we r not allowed to use native keyword for the classes and variables.
2.
If a method is implemented in non-java (like C, C++ mostly) is called native method (or) foreign method. In olden days, java is performance very poor when compared to C/C++. But later because of advs of Java slowly shifting to java. But now also performance wise not that much good.
99
Now – a days 10% real-time projects are with C/C++ with Unix called open systems, - C/C++ code is M/c understandable in a higher level than compared to Java. Native keyword is breaking Java’s p/f independent concept. Java code is easily understood by pgmgs when compared to C code but perf wix slow and java pgm should be converted to .class 1st and then to .exe files. 3.
The main objective of using native keyword in java is i) to improve performance of the ii) to communicate with language code, (using code developed in any lang. as it is)
4.
The use of native keyword breaks p/f I feature of java.
5.
Pseudo code for using native libraries in java : If want to lodd some libraries during the time of loading the class, we put it in static block. Class native
6.
{ 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.
7.
The ‘native’ and ‘strictfp’ combination is also illegal for the methods. - follows IEEE 754 standards but may or may not IEEE 754 stds.
8.
We CAN OVERRIDE !!! a native method. It is recommended to override a native hash code method available in the object class.
9.
Inheritance & overloading possible for native methods.
100
Synchronized Keyword 1.
“Synchronized” is the keyword which can be applied for methods and blocks. i.e we can’t apply synchronized keyword for a variable and class.
2.
If a method declared as synchronized, at a time only one thread is allowed to execute, that method on the given specified common object.
3.
Adv. Of synchronization : i. Security ii. Prevent data corruption and increase data consistency. Disadvantage : i. It slows down the and results low performance. Until & unless required don’t go for synchronized like final.
Volatile : (Ameerpet student mentality) 1.
“Volatile” is a keyword which can be applied only for variables.
2.
If a variable value keep on changing by multiple threads it will create data inconsistency problems. To over come this, we have to declare such type of variables as volatile variables.
3.
If a variable declared as volatile, JVM will create separate private copy for every thread. The thread is allowed to read the value from its local copy so that there won’t be any inconsistent problems.
4.
To achieve this, the JVM has to create so many local copies of the same variable. Creating and maintaining multiple copies is very difficult and creates big performance problems. hence, volatile concept is completely outdated now a days and it is replaced with synchronization.
5.
We can’t declare a final variable as a volatile. Violation leads to compile time error. (Final const and volatile ⇒ variable, both r contradictory)
1.
What is an I ?
2.
Importance of an I ?
3.
I declaration
Interfaces
methods in I declaration variables declaration 4.
Tag or marker interfaces
5.
Interface Naming conflicts.
101
1.
What is an I ? 1. From the client point of view an I, defines set of services what the client is expecting. 2. From the service provider point of view an I defines the set of services what service provider is providing. Hence an I is nothing but contract b/w the client and service provider. Advantages : 1. Security : As we r not highlighting our internal implementation, outside person is not able to iee or get the internal formulae. 2. Enhancement is very easy ⇒ without effecting outside person, we r allowed to check our internal implementation. As the I doesn’t contain any implementation, it is considered as 100% pure abstract class.
Declaring an (I) : Eg : interface transferable { public void transfer( ); } ⇒ we can declare an interface by using “interface” keyword. The allowed modifiers for the top level interface are : Public, , 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 can’t implement any interface.
104
1.
After installing jdk 1.5/1.4, type javac in and prompt. If U get “bad command”, then type set path = “c:\jdk1.4\bin”. Type again javac.u% get it
2.
The above process has to be repeated every time U closes & opens the command prompt which is a tedious process.
3.
To avoid this, My computer properties → Advanced tab → Environment variables → User variables for pandu → New variable → Variable name : Path → O.K → O.K. Variable value : C:\jdk1.4\bin. Now, no need of repeating 1) every time cond prompt opens. Koooooo1….. The variable name should be : path (irrespective of case) no other name is allowed.
Note : 1. No need, of setting this path in system variables if U have set in user variables. 2. Otherwise (i.e. if U didn’t set in), in system variables there will be a variable ‘path’ by default click eqlit button after clicking (selecting) variable. 3. In that, variable name : path variable value : …… ; c:\jdk1.4\bin o.k → o.k. 4. This will also result in the same. 5. No need of setting path in both variables. Interface naming Conflicts : Case 1: 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:
Eg :
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.
Case 3: Eg :
interface Left {void M1( );} interface Right { int M1(
);}
Class Test implements Left, Right { Public Void M1( ) { } Public Void M1( ) { } Public V Left M1( ) { } Public I Right M1( ) { } } Note : If 2 interfaces contain methods with same name same arguments but with different return types, IT IS NOT POSSIBLE to implement & interfaces simultaneously in the same class. Case 4: 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 } }
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.
According to coding standards, the class names must be nouns. Eg ; class Dog { }; class Account { };
2.
The first letter should be capitalized and if several words are linked together to form the name, the 1st letter of inner world should be upper case . (known as “Camel Case”) Eg :
Class Dog Sample { }; Class Student Info { }; Class Account Details { };
Interfaces : 1.
Interface names should be adjectives and the remaining rules are exactly similar to that of class names (camel case format) Eg :
Serializable ; Resizable Transferable Cloneable.
Methods : The method names usually verb-noun pairs. Method name must start with lower case letter and every inner word starts with capital letter (camel case). Eg :
get Details ( ) Print Details ( ) get Balance ( ) get Customer Name ( )
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 get ( ) (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 (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 ;
(Properties must be private)
Private int rollno; Public string get Name ( )
(Setter & getter must be public)
{ return name ; } Public void set Name (String name)
(Setter & getter must be public)
{ this.name = name; } } Listeners Naming Conventions : For registering a listener : Public void
add My Action Listener My Action Listener l
Exercise : Valid way of registering a listener according to coding standard. 1.
Public void set My Action Listener (My Action Listener l);
2.
add My Action Listener (My Listener l);
3.
add My Action Listener (My Listener l);
For unregistering a listener : Public void remove My Action Listener (MyActionListener l); The method name must be public with void return type and the method name must be prefixed with ‘remove’. Var-arg Methods: Eg : If there is a sum method with 2 args, then we can call it with sum (10, 20). If 3 nos. are there to add we should create another sum method with 3 args and so on… to avoid this we go for var-arg.
109
1.
This concept was introduced in 1.5 version, we can declare a method that can take variable number of arguments which is called var-arg method. Eg : M1(int…a) Calling M1: M1( ); M1(10); M1(10,20,30) any no.
WAP by using var-arg method for printing the sum of any number of integers. Class test { public static void sum (int….a) { int total = 0; for (int x : a) { total = total + x; } SOP (“Sum is:” + total); P S V M (S[ ] a) { Sum ( ); // Sum is : O Sum (10); Sum (10, 20); Sum (10, 20, 30); } } By using var-arg method display the elements of 2-D array : (single-D array of another 1) Class test { public static void meth (int[ ]….x) { for (int[ ] y : x) { for (int z : y) { SAOPln (z); } 110
} } P S V M (String[ ] args) { int( ) a = {1,2,3,4}; int( ) b = {4,5,6}; (a,b); (both r 1-D arrays) } } Conclusions : 1.
We should keep… after the type only not after the name of the variable. i.e. Sum (int[ ] a) = sum (int a[ ]) ↓ equals to Sum (int… a) = Sum (int + a….) (bade syntax)
2.
We can mix a normal argument with var-org arguments. But in that case, the vararg parameter must be the last parameter. i.e.
Sum (float f, int….a); Sum (int….a, float f);
3.
We can’t keep more than one var-arg parameter in var-arg methods. i.e.
Sum (int… a, int….b); Sum (int… a, float….f);
Exercise :
4.
1.
Void M1 (int….a){ }
2.
Void M1 (int a…){ } (Bad syntax)
3.
Void M1 (float f, int….a){ }
4.
Void M1 (int….a, flat f){ }
5.
Void M1 (double d float….a, char…ch) { }
Eg :
class test { P S V M1 (int I) {
111
SOPln (“General Method”); } P S V M1 (int…a) { SOPln (“var-arg method”); } P S VM (String[ ] args) { M1( ); // Var-arg M1 (10); // General – method } } Var-arg methods will always get least preference. We can declare main method in one of the following possible : Public static void main (String[ ] args) { } Public static void main (String….. args) { } Object – Oriented Concepts : 1.
Data - Hiding
2.
Abstraction
3.
Encapsulation
4.
Inheritance. (IS-A relationship)
5.
Aggregation (HAS – A relationship)
6.
Method signature
7.
Polymorphis M Overloading Overrding Methodhding
8.
Coupling and
9.
Cohesion
10.
Static control flow
11.
Instance control flow
12.
Constructors
(1.5 features)
112
I.
II.
Data Hiding : 1.
It means, the data should not go out directly. We can achieve this by declaring data members as private. (providing security)
2.
The outside person is allowed to access data through methods only.
Abstraction : 1.
Hiding implementation details is called “abstraction”. Eg : Generation of a car 1.men 2. rod. 3. key 4. touch screen only by owner. Abstraction may be comfortable but too much cause – ve serve.
Advantages : 1.
As we r not highlighting our internal implementation; we can get more security.
2.
Without affecting outside word, v r able to change internal implementation. Hence, enhancement is easy.
We can achieve abstraction by providing a public interface for the end user. Eg : Keyboard is an interface for us, the internal implementation is always hided III. Encapsulation : (key benefit of is security i.e. data hiding) 1.
If a class follows – Data Hiding and Abstraction, that class is said to be encapsulated class. Encapsulation : data hiding + abstraction
Note : The getter and setter methods, in real-time contain code regarding authentication. 2.
Hiding data behind methods is the central concept of encapsulation. Advantages : i. Security ii. Enhancement iii. Maintainability (of code) iv. Modularity Disadv : The –ve side of encapsulation is : It increases the length of code (because for every property (data member) we have to write getter & setter methods) and slows down the execution.
Note : In encapsulation, data hiding has more importance.
113
Tightly Encapsulated Class : 1.
A class is said to be tightly encapsulated if and only if all the data members are declared as “private”. Eg : which of the following classes r tightly encap sulted ? i.
class x { private int i = 10; (Tightly encapsulated – data member declared as private) public int get i ( ) { return i; } public void set i (int i) { this. i = i; } }
ii.
class x { private int i = 10; public void set i (int i) { this. i = i; } } (Outside person can’t access (i) directly i.e. data not going out directly ⇒ tightly encapsulated)
iii.
class x { private int i = 10; } class y extends x { int j = 10; 114
} (class y is not T.E. – there is no rule that if parents is T.E., Child also has to be T.E., - Y data member is not P.Vote it is not T.E.) iv.
class x { int i = 10; x is not T.E. } class x extends { private int j = 20; } class z extends { private int k = 30; } (Y is extending x, the non-private data of x is available to ‘y’ also) (Generally in java class itself indicates encapsulation)
Conclusion : If the parent is not tightly encapsulated then no child class is tightly encapsulated Note : The protected member is available to the child class directly but not at all available to its sub child classes. 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)
↓
C – 12
(10+2+1)
↓
D ↓
E ↓
F ↓
G We think ‘C’ has all the methods and it is advs. This is tve side But –ve side is : To create child class obj all its parent class objs have to be created, but obj. creation is always. Costliest ⇒ performance issue.
116
4. According to real-time coding standard, 8-10 levels of inheritance is acceptable, beyond that it is not suggestible because it may create performance problems; for every child class object creation all the parent class objects we have to create. Eg :
class parent { public void M1( ) { SOPln (“parent”); } } Class child extends parent { Public void M2( ) { SOPln (“Child”); } P S V M (String args[ ]) }
Case 1 :
Parent P = new parent ( ); P.M1 ( ); // Parent P.M2( ); // Parent has no idea of what child class has, with parent clan ref. Child clam can’t be called.
Case 2 :
Child C = new child( ); C.M1( ); // Parent →
no such mett (M1) by in child clam, it executes parent class methods.
C.M2( ); // Child
Case 3 :
Parent P = new child( ); →
Runtime object is child.
P.M1( ); // Parent P.M2( ); // CTE } 117
} (Parent class ref. Can hold child clan obj but by using that ref we can’t call child clay specific methods.) (Child class ref can’t hold parent class object) Conclu : 1.
The parent never aware of child-class specific. Methods. Parent.M2( );
2.
Child aware of all the parent class methods. Child.M1 ( );
3.
Child class reference can never hold parent class object. Child C = new parent ( );
4.
The parent class ref can be used to hold child class instances. But by using that reference we r allowed to call only parent class methods. We r not allowed to call child class specific methods. Violation leads to CTE. If parent class method is overridden in child class, and if v calling that parent method with children clan reference then the overridden method is executed but not the parent clan method.
V.
Aggregation (Has A relationship): (We use this concept in general but we don’t know) Note : Also known as composition. Eg :
Car contains (cabiposed of) engine, steer, seats – etc. ⇒ Car has Engine
1.
HAS – A relationship also known as composition or aggregation. By using several objects, we can compose an object. Eg :
Class Engine
Class Car
{
{
M1( )
Engine C = new Engine( );
M2( )
}
M3( ) } ⇒ A car HAS-A Engine reference. 2.
The advantage of HAS-A relationship is reusability.
3.
No keyword for mentioning HAS-A relationship.
118
4.
HAS – A relationship increases the dependency between components which results in maintenance and enhancement problems. Eg : without engine there is no car ⇒ dependency Eg : class sample { P S V M (String[ ] args) { system out print in (“Kiran”); } }
Method Signature : In C, C++ method signature refers to return type + method name + arguments list. Eg ; Void M1( ) 1.
In Java, method signature consists of method name followed by arguments (the order of arguments is also important) Eg : M1( ) Eg : Public Void M1( ) Meth. Signature → M1( ) Public int M2 (int i, float f) → M2 (int i, float f) Note : Return type is not part of method signature in java.
2.
class test { P Void M1( ) { } P void M2 (int I) { } P void M3 (int I, float f) { } }
For the above class, compiler creates a table containing method signatures. Test: 1
M1( )
2
M2 (int)
3
M3 (int, float)
class client { P S V M (S[ ] a) {
119
Test t = new Test( ); t.M1( ); → compiler checks; t.M2(10); t.M3(23); } (CTE : can’t resolve symbol M3 (double) method signature) (‘t’ which class ref – test then it cheking M1( ) signature in table, if it matches the corresponding method is executed). 3.
2 methods with same signature is not possible in Java. Violation leads to compile time error. (Because compiler finds it ambiguous which method has to be executed). CTE : M1() is already defined in test Class test { P V M1( ){ } P int M1( ) { } return 10; }
4.
In order to link method calls with corresponding implementations, compiler checks the method signature.
Overloading : 1.
Overloading & overriding, both comes under polymorphism. In C, to find absolute value of an integer we have a method abs (int). To find abs value of long int we can’t use we have labs (long int) for floating point abs value fabs (float f) ⇒ For every data types we have separate type we have to remember all the in.. & code is complex. It is because 2 methods with same signature is not possible. This problem is resolved in oops by using over OR.
2.
In C, 2 methods with same name is not allowed. Eg : If u want to find absolute value we have the following methods: abs ( ) – int labs ( ) – long fabs ( ) – float…etc For every data type, declaring anew method is always problem and it increases the complexity of the programming.
120
3.
To resolve this, in the object oriented pgmg we can declare more than one method with the same sname (which is nothing but method over leading) so that the programming becomes very simple: Eg :
‘max’ method in math Class Max (int i, int j) Max (long l, long m) Max (double d, double e)
Method Overloading : 1.
Two methods with the same method name but different arguments (atleast order) r said to be over loaded methods.
2.
In case of overloading, the method names must be same, the arguments list must be different, never consider return type/access modifiers throws clause. Eg 1 :
class test { P V M1( ) { SOPln (“No arg”);} P V M1 (int i) { SOPln (“inte”);} }
CTE :
P V M1( ) P int M1( )
Eg 2:
class test 1 { P V M1( ) { SOPln (“No arg”);} P V M1 (int i) { SOPln (“inte”);} P S V M (S[ ] args) { Test 1 t1 = new test ( ); t1.M1( ); // No-arg t1.m1(10); // Inte } }
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”); }
Perfectly Overloaded. (Only order of arguments is changed)
P V M1(float f, int i) { SOPln (“float, int”); } P S V M (S[ ] a) { test t = new test ( ); t1.M1(10, 10.5f); // Int, Float t1.M1(10.5f, 10); // Float, Int t1.M1(10, 10); // CTE : Ambiguous reference to M1 is ambiguous. } } Note :
float, int
float, float
float, int 123
t.M1 (10,10)
int, float
float, int
int, int
CTE
float, 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)
Class Animal
{
{
SOP (“Animal Version”);
}
}
Class Monkey
Public Void M1(Monkey M)
Extends Animal
{
{
SOP (“Monkey Version”);
}
}
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 doesn’t want to use a particular method of the parent class it is allowed to provide its own implementation by overriding parent class method. While overriding we have to follow certain rules : Overriding Rules : 1.
Method names and the argument list order also must be same. i.e. signature of the methods must be same. Eg : Class P {
Class C extends P { 125
Public Void MIC ------------}
2.
Public Void MIC { ------- ⇒Overriding ------} }
If parent class method, doesn’t want to allow child class to override, declare that as ‘final’ (security purpose). The final methods cannot be overridden. Eg : Class P { Final Public Void M1( ) { SOP(“Parent”); }
CTE : 3.
Class C extends P { Public Void M1( ) { SOP(“Child”); } ------} }
M1 in C can’t 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.
4.
Private methods will not be available for the child class and hence overriding concept is not applicable for the private methods.
5.
If u want, we can declare exactly similar parent class method in the child class, but these methods r not overriding methods. Eg : Class P { Private Void M1( ) {SOP (“Parent”);}; } Class C extends P
These r not overriding methods.
{ Private void M1( ) {SOP(“Child”);} } No CTE 6.
In the case of overriding, the return types must be same. This rule is applicable until 1.4 version, violation leads to CTE.
126
Eg : Class P { Public Void M1( ) {SOP (“Parent”);}; } Class C extends P
different return types.
{ Public int M1 ( ) {SOP(“Child”);} } CTE Saying :
M1( ) in C can’t override M1( ) in P; attempting to use incompatible return types. found : int required : void
7.
But from 1.5 version onwards covariant return types r also allowed. Co-variant return type means, need not be parent class return type its child classes also allowed as the return type.
Eg : If the return type of parent class method is object then the return type of child class method must be object until 1.4 version. But in 1.5 version, need not be object may be its child class like string is also allowed. Eg : Class P { Public Object M1( ) } return new object ( ); } }
Co-variant return type
Class C extends P
allowed in 1.5 but not in
{ Public String M1( ) 127
{ return “Kiran”; } } Note :
P = Object C = String
P = String C = Object
Co-variant return types
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
B
Overridding C
8.
(Child of A) (Child of B)
While overrding, weakering the access specifier is not allowed. Violation leads to CTE. Parent : Public
Protected
Default
Private
Child : Public Protected Default Private Note : Same Private methods in parent, child class r not considered as overridden methods but treated as separate methods. Eg : Class P { Public Void M1( ) { SOP(“Parent”);
CTE : M1( ) in C cannot Override M1( ) in } P Attempting to
assign } Class C access decreased { Private Void M1( ) { SOP(“Child”) }
weaker access pri vileges; was public.
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
Void M1( ) {
}
Void M1( ) {
}
Void M1( ) {
}
Protected Void M1( ) {
}
Private } 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.
Whether an exception is checked or unchecked it is always occur at Run-time only.
4.
Checked Exceptions r again divided into partially checked and fully checked. A checked exception is called fully checked exception if and only if all its child classes also checked other wise considered as partially checked exception. Eg : for fully checked : IO Exception Eg : for partially checked ; Exception
1.
In the case of overriding v r not allowed to increase the size of the checked exceptions. But there is no rule for unchecked exceptions. We can decrease (or) remain same the checked exception.
129
Import java 10-*;
Eg : Class P { Public Void M1( ) { SOPln(“Parent”); } } Class C extend P { Public Void M1( ) { SOP(“Child”) } }
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
> javac c.java 2.
Results in CTE : (The size of checked exception is increased) M1( ) in C can’t override M1( ) in ‘P’; overridden method does not throw java.lang. exception.
Exercise : Already mentioned in the pgm. 2.
We can override a synchronized method as non-synchronized and a non synchronized method as the synchronized.
3.
We can override a native method as non-native and non-native method as a native. Eg : It is recommended to override native has a code method in our classes.
4.
We can override an abstract method as non-abstract method to provide implementation we can also override a non-abstract method to abstract. In that case, the child classes of child class r responsible to provide implementation abstract. Eg1 : Class P { abstract void M1( ); }
Generic abstract to non-abstract
130
class C extends P { Void M1( ) { } } Eg2 : Class P { void M1( ) { } }
non-abstract to abstract (SUPERUUU)
abstract class C extends P { abstract void M1( ); } 5. Class P { Public Void M1( ) { SOPln (“Parent”); } } Class C extends P { Public Void M1( ) { SOPln (“Child”); } P S V M (String[ ] args) } Case 1 :
P P1 = new P( ); P1.M1( ); // Parent
Case 2 :
C C1 = new C( ); C1.M1( ); // Child 131
Case 3 :
P P = new d( ); P.M1( ); // Child
/* Note :
Parent class reference can hold child class instance. At compile time compiler checks the reference type P and checks whether M1 ( ) is present or not if not them CTE once it is satisfied, later at rum-time JUM checks which run-time (child class) object is that, once it is decided whether method M1( ) is overridden, then child class method is called, it not a then parent class method is executed because parent class members r by default available for child class */ In case of overriding, the method resolution taken case by JVM based on run-time object this process is also known as : “Dynamic method dispatch” (or) “Dynamic Polymorphism” (or) “Runtime Polymorphism” (or) “Last binding”.
Overriding in the case of static methods A static method cannot be overridden as non-static method (class level behavior can’t be changed). We can’t override a non-static method as static. Method Hiding : (Child class method is hidden by parent class method) 1.
All the rules of method hiding r exactly similar to overriding rules except both methods declared as static.
2.
In the method hiding, the method resolution takes care by compiler based on reference type. (Irrespective of run-time object). Eg : for method hiding Class P { Public Static Void M1( ) { SOP (“Parent”); } } Class C extends P { Public Static Void M1( ) 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 :
P P1 = new P( ); SOP(P(i); //10.
Case 2 :
( C1 = new (( ); SOP(C1.i); // 20
Case 3 :
P P1 = new (( ); SOP(P1.i); // 10 (Overriding not applicable for variables and compile check the ref type only)
⇒
Overriding concept is not applicable for variables. The variable resolution always taken care by compiler based on reference type. Variable hiding is possible, not overriding.
Comparison b/w Overloading & Overriding : Property
Overloading
Overriding
1. Method Names
Must be same
Must be same
2. Arguments
Must be different (at least order)
Must be same
3. Signature
Must be different
Must be same
4. Access Modifiers
No restrictions
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.
7. Final
We CAN (⇒Yes)
We CAN (⇒No)
8. Private
We CAN (⇒Yes)
No
9. Static
We CAN
We cannot but method hiding is possible.
We CAN
We CAN
10.
Native synchronized abstract
SCJP ‘Q’ regarding Overloading and Overriding : Class B { Public Void M1( ) { } } Which of the following methods r allowed in the derived class ? 1.
Public void M1 (int i) { }
Overloading
2.
Private void M1 (double d)
throws exception overloading
3.
Public void M1 ( ) {
}
overriding
4.
Private void M1 ( ) {
}
CTE : M1( ) is already declared.
5.
Public void M1( ) throws AE { } Overriding Not in SCJP, But in real time
Static Control Flow : Eg : Class Base { i = O (RIWO) Static int i = 10; Static
134
{ M1( ); SPOln (“First Static Block”); } Public Static Void Main (String[ ] args) { M1 ( ); SOPln (“Main Method”); } Public Static void M1( ) { SOPln (j); // j = 0
// j = 20
} Static { SOPln (“Second Static Block”); } j = 0 (RIWO) static int j = 20; } NO CTE,
RTE
O/P : 20 (Mine) FSB SSB 20 Main Method 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
SSB 20 Main Method Note : ⇒ Variables can be declared at the last place (or) any where. Static blocks r executed while class is loading in to the memory. Eg :
After loading driver registering the driver stuff is written in static block of the driver class. 1. Load driver, 2. Connection, 3. State, 4. Execute, 5. Result set
Static blocks : 1. Syntax : Static { } 2. Static blocks executed while the class is loaded into the memory. 3. If u want to perform any activity while can be executed while loading the class that activity should be defined inside static block. Eg1 : Loading native libraries must be performed while the class is loaded into the memory. Hence this activity should be declared inside static block. Eg2 :Registering database driver with Driver Manager can be performed by executing static block available in driver class. 1. If a variable is just identified by JVM but the proper explicit assignment not takes place then that variable is in the mode of RIWO (State – Read Indirectly Write Only) and assigned with default values. If a variable is in RIWO State, we r not allowed to perform read operation directly, violation leads to compile – time error saying : Illegal forward reference. Eg.1 : Static { // M1( ); SOP (j); // SOP (Base.j); SOP (“First Static Block”); } 2. Later variable comes into R&W State, then we can read & write values directly. Eg.2 : Static { // M1( ); 136
SOP (i); SOP (“First Static Block”); }
3. Static blocks should be declared only at class level, but shouldn’t be declared inside methods. Printing a statement to the console without using main( ) and static block. Class Google – 3rd - Round { Static int i = M1( ); P Static int M1( ) { SOPln (“Hi I can Print….”); return 10; } } O/P : Hi I can Print…. No Such Method Error. 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
: Derived. java
Compile
: Derived. Class Base.class
Run
: java derived
O/P : O
Correct O/P :
DFSB
O
DSSB
Base SB
200
O
D Main Method
Derived FSB Derived SSB 200 Derived Main 138
Flow : 1.
Identification of static members from parent to child (I) to (II)
2.
Execution of static variable assignments and static blocks from. Parent
3.
Executive of Derived class main method.
Case 1:
Suppose in the derived class if there is no main method, then the parent class main method will execute because static members can be inherited.
Case 2:
> java base 1 O/P : O Base static block Base Main Method. ⇒ Derived Class won’t be loaded.
Instance Control Flow : 1.
Non-static variable can’t be referred from static context directly because they may not be identified by the JVM. Eg 1: Class Sample { int i = 10; P S V M (String[ ] args) { SOPln (i); } } CTE : Non-static variable ‘i’ can’t be referred from static context (directly). Eg 2: Class Parent { int i = 10; { M1( ); SOP (“First Instance Init Block”); } Parent ( ) { SOPln (“Constructor”);
139
}
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
Repeats for every child object creation.
CSIB C Constructor Main Method
142
Suppose if parent class one more parent & etc. suppose there r 8 levels the for creation of child obj all remaining parent class objs should be created ⇒ performance problem.
Exercise : What is the O/O when u compile & run the following code ? Public Class Myclass { P S V M (S[ ] args) { My Class Obj = new My Class (i) } Static int i = 5; Static int l; Int j = 7; Public Myclass (int M) { SOP(i+”,” + j + “,” + k + “,” + l + “,” + m); } { j = 70; // Instance initializer block l = 20; } Static { i = 50; // Static initializer block } } O/P : 50, 70, 0, 20, 0 Trace : i = 0 (RIWO) l = 0 (RIWO) i = 5 (R/W) i = 50 My class (0) J=0
143
k=0 j=7 j – 70 l – 20
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.
At the time of declaration only. But, all d objects have same no and name not. (not suggestible.
2.
Giving values in invoice initialization block also results in same above problem.
3.
In main method, s.name = “Ki”; S.rollno = 701; For 600 obj 1200 lines of Code ⇒ cumbeyone code ⇒ Not suggestible.
145
4.
So we will pay values as arguments to the constructor.
*/ 2.
The main objective of constructor is to parlor initialization. /* The main objective of constructor is it takes parameters */
3.
Whenever we r creating an object, the constructor will execute automatically to perform initialization.
Eg :
Class Student { String Sname; Int rollno; Studnet (Sname, int rollno) { this.sname = sname; this.rollno = rollno; { P S V M (S[ ] arg) { Student S1 = new student (“Kiran”, 101); Student S2 = new student (Karthikeya”, 102); } }
4.
The main difference b/w instance initialization block and constractors is . Constructor can take arguments but instance initialization block won’t take any arguments. Hence common initialization for all the object inside instance initialization block, where as object specific initialization we can perform inside constructor.
Rules for Writing Constructors : 1. Constructor is the concept applicable for every class including abstract classes also, but interfaces don’t have any constructors concept. 2. The name of the constructor must be same as class name. (for compilation understanding purpose). 3. The only allowed modifiers for the constructors are : Public, Protected, and private. If v r declaring constructors with any other modifiers v will get a compile time exception saying :
146
Modifier not allowed here. Eg :
Class Test { Static Test( ) { } }
CTE : Modifier Static not allowed here. 4.
Return type is not applicable/allowed for the constructors. By mistake, if U keep return type compiler treats it as a method instead of constructor but there is no compile time error. Eg : Class Test { Void Test ( ) { SOPln (“Constructor”); } P S V M (S[ ] args) { Test t = new Test( ); } }
⇒ It is legal (but stupid) to have a method whose name is same as class name. 5. Default Constructor : Every class should have the constructor that may be written by programmer (or) generated by compiler. If the programmer is not placing any constructor, then only compiler places (or) generates “Default Constructor”. If the programmes already provided any constructor, then the compiler won’t general any default constructor. I.e. Either programmer provided constructor (or) compiler generated constructor is possible but not both simultaneously. Proto type of Default Constructor : -
The access modifier of the default constructor is same as access modifier of the class (either public or default).
147
-
Default constructor is always no argument constructor only.
-
The Default constructor contains only one line i.e. a no argument call to the super class constructor. [Super ( );] Eg : Public Class Test { Public Test ( ) { Super( ); } }
Programmer’s Code 1. Class Test { }
2. Public Class Test { }
Compiler General Code Class Test { Test( ) {Super( ); } } Public Class Test { Public Test ( ) { Super( ); } } Class Test
{ Test ( ) { } }
{ Test ( ) { Super( ); } }
4. Class Test
Class Test
{ Test (int i) { Super( ); } }
{ Test (int i) { Super ( ); } }
Class Test
Class Test
5.
3. Class Test
148
{ Void Test (int i) { }
{ Void Test (int i) { } Test ( ) { Super ( ); } }
Overloaded Constructors : 1.
For any class we can write any number of constructors and are considered as overloaded constructors.
2.
By using “Super” and “this”, we will invoke other constructors. “Super” can be used for calling (invoking) parent class constructor and “this” can be used for invoking overloaded constructors of the same class. Eg : Class Test { Test ( ) { // Super( ); SOP (“No arg constructor”); } Test (int i) { This ( ); SOPln (“Int Constructor”); } Test (double d) { This (10); SOPln (“Double Constructor”); } P S V M(S[ ] args) { Test t = new Test (10.6);
149
} } O/P : No arg constructor Int Constructor Double Constructor this. i 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 can’t invoke a constructor directly from a method. ii. We should use only one but not both. iii. We can use either super( ) (or) this( ) must be as the 1 st statement only. iv. If U don’t keep Super ( ) (or) this( ), then compiler always places no argument Super( ) as the 1st Statement in a Constructor. Eg : Class Test { Test ( ) { Super( ); this ( ); } Void M1( ) { this ( ); } CTE : Call to this( ) must be the 1st stmt in a constructor.
150
5.
We can overload a constructor but inheritance and overriding is not possible. ⇒ Parents class variables & method r available to child class, but constructors won’t be available. Case (i): Recursive method call is always a run problem. JVM rises Stack Over Flow Error. But, compiler point of view there is no problem at all. Eg : Class Test { Void M2( ) { M1( ); } Void M1( ) { M2 ( ); } P S V M(String[ ] args) { Test t = new Test( ); t.M1( ); } } NO CTE RTE : Java.lang. Stack Over Flow Error
6.
But in case of constructors, recursive constructor invocation is a compile time error. Compiler is responsible for checking everything related to constructors. Eg : Class Test { Test( ) { this(10); } Test (int i) { 151
this( ); } P S V M(S[ ] a) { SOP(“Hello”); } } CTE : Recursive constructor invocation. Compiler checks about constructor because if pgmgr didn’t provide, compiler has to provide default constructor. Case (ii) :
Compiler’s Code Class P { } Class C extends P { }
Class P { P ( ) {Super( );} } Class C extends P { (C) {Super( );} }
NO CTE : Compiles Successfully. Case (iii) :
Compiler’s Code Class P { P(int I) { } Class C extends P { }
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 won’t generate any default constr./ So, Super( ) ⇒ calling which is not present. P (int) in P can’t be applied to ( ) C extends P.
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).
Eg: Class P { P( ) throws exception{ } } Class C extends P { C ( ) {Super( );} }
1
C ( ) throws Exption { Super( ); NOCTE }
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:
1.
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
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.
3.
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
4.
5.
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.
6.
7. 8.
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
Error
(We can handle) (recoverable)
(We can’t handle) (irrecoverable) Linkage Error
Assertion 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.
Virtual Mk Error
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
1
We can implement Exception – Handling by using try – catch statements. The risky code we keep in inside ‘try’ block and the corresponding handlers, we can keep inside ‘catch’. Eg: Class Test { P S V M(S[ ] args) { SOPln(“Stmt1” ); try { SOP (10/0); } Catch (Arithmetic Exception) { SOPln(“Stmt2”); } } O/P : Stmt 1 5 Stmt 2 Eg: try { Stmt 1; Stmt 2; Stmt 3; } Catch (X e) { Stmt 4; } Stmt 5 ;
Case (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) { }
try { SO(10/0); } Catch (Exception e) { } Catch (AE e) { } CTE : Exception : java. lang. AE Has already been caught.
NO CTE
Control – flow in nested try - catch : Eg :
try
Possible Combination of x and y :
{
x : AE
E
Stmt 1;
y:
AE AE E
E
AE E
Stmt 2; Stmt 3;
In this pgm, we can’t compare the
Try
order of inner and outer catches.
{
But either complete inner, (or) Stmt 4;
complete outer we can compare.
Stmt 5; Stmt 6; } Catch (x e) { 160
Stmt 7; } Stmt 8; } Catch (x e) { Stmt 9; } Stmt 10; Case (i) :
Exception raised at stmt 2 and corresponding catch block has found. Flow : Stmt 1, 9 followed by 10 Normal Termination.
Case (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.
If U place that code in catch because no guarantee that catch executes always.
3.
We can’t 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 won’t execute. So we need a place for keeping clean-up code which should always execute whether an exception raised or not raised whether an exception is handled or not handled. Such place is “finally” block. Hence finally block will always execute even in the case of abnormal termination also.
Eg :
Class Test { P S V M (String[ ] args) { SOP (“Hai”); System.exit(O); // SOP (10/0); return;
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 won’t be executed.
‘return’ stmt, anywhere indicates stopping the execution of that method. Suppose if u place return stmt in try block, finally executes first then return stmt is executed. The finally will always executed once u entered into the try block, even in the case of return statement also. But, if v r calling explicitly system.exit(O), Method, (⇒shutdown JVM Programme) the finally won’t execute. This is the only exceptional case where the finally block won’t execute.
/* Difference among : Final, finally and finalized.
164
Final : is a modifier applicable to variables, methods and classes. Finally : To execute clean-up code irrespective of exception occurrence / handling we keep that code in finally block. Finalized : It is also for maintaining clean-up code only, (just before destroying unreferred obj). .finalized( ) Finally & Finalized : is better be finally always executes where as we don’t know when GC occurs. */
$ final, finally and finalized : Final : It is the modifier which can be applied for variables, methods and classes. -
Final variable means
–
Constant.
-
Final method
–
It can’t be overridden.
-
Final class
–
It can’t be inherited. ⇒ We can’t create child class.
Finally
: This is the block associated with try-catd. For maintaining cleanup code. This block will always execute whether an exception is handled or not handled (or) an has raised or not.
Finalized ( ) : It is a method available in object class which contain clean-up code, just before destroying any object, GC (Garbage Collector) calls finalize ( ) method for releasing the resources associated with that object. When compared to finalize(
) method, finally block is always
suggestible bcoz when the Garbage Collector. Runs finalize( ) we can’t predict (give any assurance). Possible Combinations of try-catch-finally : 1.
try \{ } Catch ( )
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.
Case (ii) :
Exception at Stmt 2 & corresponding catch matched. Flow : 1,4,5 & 6 Normal Termination.
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)
Case (2) :
An Exception at Stmt 2 and Corresponding catch block has found Flow : 1,10,11 & 12 Normal Termination.
Case (3) :
Exception at Stmt 2 and Corresponding catch has not matched. Flow : 1, 11 Abnormal Termination (A.T)
Case (4) :
Exception at Stmt 5 and corresponding inner catch has matched. Flow : 1,2,3,4,7,8,9, 11 and 12 Normal Termination.
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.
Case (6) :
Exception at Stmt 5, inner & catch did not match. Flow : 1,2,3,4,8,11 followed by (A.T)
Case (7) :
Exception at Stmt 7 and corresponding catch (outer) has matched. Flow : 1,2,3,4,5,6,8,10, 11 and 12 Normal Termination.
Case (8) :
Exception at Stmt 7, but catch (outer) has not matched. Flow : 1,2,3,4,5,6,8,11 Abnormal Termination.
Case (9) :
Exception at Stmt 8, Stmt 9, Stmt 10, Stmt 11, Stmt 12. Abnormal Termination.
“throws” clause : class test { P S V M(S[ ] args) { do stuff ( ); } P S V do stuff( ) { do more stuff ( ); } P S V do more stuff ( {
)
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 didn’t perform anything, hence it is a CTE. CTE : Unreported Exception : java.lang. Interrupted Exception; Must be caught or declared to be thrown. Eg : class test { P S V M(S[ ] args) throws IE { do stuff ( ); } P S V do stuff( ) throws IE { do more stuff ( ); } P S V do more stuff( ) throws IE { thread.sleep (1000);
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.
In real-time it is not allowed to throw default exception objects, generally throw customized object.
4.
V can throw any “throw able” instance (any exception or error) by using throw keyword. Eg : class test { Static Arithmetic Exception e; P S V M(S[ ] a) { throw e; // throwing null to JVM but not object }
171
} CTE : Null Pointer Exception. CTE (4) : (New Point) If the try block doesn’t have any chance to throw some fully checked exception, then v r not allowed to place catch block for such fully checked exceptions. Violation leads to CTE, saying. Exception is never thrown in body of corresponding try statement, i.e. v r not allowed to keep for catch blocks for fully checked exceptions unnecessary.
Eg : try { SOPln(“Hi”); } Catch (AE e) Catch (Exception e) { } Catch (IO Exception e) CTE :
Exception java. io. IO Exception is never thrown in body of corresponding try statement.
Consolidated CTES in Exception Handling : 1.
Exception has already been caught.
2.
Unreported Exception must be caught or declared to be thrown.
3.
Unreachable stmt.
4.
Exception is never thrown in the body of corresponding try statement. 5 keywords, 4 CTEs
Customized Exceptions : Eg : Entering age in matri mony.com. If ventered 90 (or) 13 then that site should throw exception age too low / too high ⇒ customized exception. 1.
Based on our programming requirement, V have to create our own customized exceptions like [Too Young exception (in Matrimony.com), Insufficient Funds Exception….. etc) using ‘throw’ key word.
172
Eg : Class too young exception extends.
RuntimeException Exception
{ Too Young Exception (String S) { Super(S); } } class sample { P S V M (S[ ] arg) throws exception { int age = Integer. Parse Int (args[0]); if (age>40) { throw new Too Young Exception (“P/S wait some more time, U will get best match”); } else if (age 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 (
) throws throw able.
2.
GC calls finalize( ) method just before destroying any object to perform clean-up activities. /* When gc thread is called from main thread, but which thread executes v can’t give assurance, because both r threads */ Eg 1 : Class test { Public Static V M (S[ ] a) throws Interrupted Exception { String S = new String (“Kiran”); S = null; Sytem.gc( ); 182
Thread.sleep (3000); SOPln (“End of Main”); } Public Void finalize( ) { SOPln (“Finalize Method Called”); } } 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
View more...
Comments