You are on page 1of 212

Java Features:

To show the nature of java programming language, JAVA has provided the following features.

1. Simple

2. Object Oriented

3. Platform independent

4. Arch Nuetral

5. Portable

6. Robust

7. Secure

8. Dynamic

9. Distributed

10. Multi Threadded

11. Interpretive

12. High Performance

1. Simple:

Java is simple programming language, because,

1. Java applications will take less memory and less execution time.

2. Java has removed all most all the confusion oriented features like pointers, multiple-inheritance,.....

3. Java is using all the simplified syntaxes from C and C++.

2. Object Oriented:

Java is an object oriented programming language, because, JAVA is able to store data in the form of Objects
only.

3. Platform Independent:

Java is platform independent programming Language, because, Java allows its applications to compile on one
operating system and to execute on another operating system.

4. Arch Neutral:

Java is an Arch Neutral Programming language, because, Java allows its applications to compile On one H/W
Arch and to execute on another H/W Arch.

5. Portable:

Java is a portable programming language, because, JAVA is able to run its applications under all the operating
systems and under all the H/W Systems.

1
6. Robust:

Java is robust programming language, because,

1. Java is having very good memory management system in the form of heap memory Management
System, it is a dynamic memory management system, and it allocates and de-allocates memory for the
objects at runtime.
2. JAVA is having very good Exception Handling mechanisms, because, Java has provided very good
predefined library to represent and handle almost all the frequently generated exceptions in java
applications.

7. Secure:

Java is very good Secure programming language, because,

1. JAVA has provided an implicit component inside JVM in the form of "Security Manager" to

provide implicit security.

2. JAVA has provided a separate middleware service in the form of JAAS [Java Authentication

And Authorization Service] in-order to provide web security.

3. Java has provided very good predefined implementations for almost all well-known network

security alg.

8. Dynamic:

If any programming language allows memory allocation for primitive data types at RUNTIME then that
programming language is called as Dynamic Programming Language.

JAVA is a dynamic programming language, because, JAVA allows memory allocation for primitive data types
at RUNTIME.

9. Distributed:

By using JAVA we are able to prepare two types of applications

a). Standalone Applications

b). Distributed Applications

a). Standalone Applications:

If we design any java application with out using client-Server arch then that java application is

called as Standalone application.

b). Distributed Applications:

If we design any java application on the basis of client-server arch then that java application is called
as Distributed application.

To prepare Distributed applications, JAVA has provided a separate module that is "J2EE/JAVA EE".

10. Multi-Threaded:

Thread is a flow of execution to perform a particular task.

There are two thread models

a). Single Thread Model


2
b). Multi Thread Model

a). Single Thread Model:

It able to allow only one thread to execute the complete application, it follows sequential execution,

it will take more execution time, it will reduce application performance.

b). Multi Thread Model:

It able to allow more than one thread to execute application, It follows parallel execution, it will

reduce execution time, it will improve application performance.

JAVA is following Multi Thread Model, JAVA is able to provide very good environment to create

and execute more than one thread at a time, due to this reason, JAVA is Multi-threaded
Programming Language.

11. Interpretive:

JAVA is both completive programming language and interpretive programming language.

1. To check developers mistakes in java applications and to translate java program from High

Level representations to low level representation we need to compile java programs

2. To execute java programs, we need an interpreter inside JVM.

12. High Performance:

JAVA is high performance programming language due to its rich set of features like Platform independent,
Arch Neutral, Portable, Robust, Dynamic,......

3
Language Fundamentals:
1. Variables/identifiers

2. Reserved keywords

3. Datatypes

4. literals

5. pillars of object orientations

1. Identifiers:

A name in java program is called as Identifier.This may be class name method name.....

int x=10;

int virat=18;

int --> datatype

x --> identifier/variable

= --> operator

10 --> data (constant)/literal

; --> terminator

Rules to define the identifiers:

1. The only allowed characters in java is:

1. a to z

2. A to Z

3. 0-9

4. _

5. $

Note: If we are using any other character we will get compile time error

2. Identifiers should never starts with the digits.

Ex: virat18 -->(valid)

18virat -->(invalid)

3. Java is case sensitive in case of identifiers it will threat the name as new one..!

int virat=18;

int VIRAT=19;

int Virat=20;

4. There is no length limit for java identifers but it just recommeded that in and around

4
15 chacters are sufficent.

5. We cannot use reserved keyword as 'identifiers'

Now let us see what this reserved keywords..is!

2. Reserved Keyword:

In java some identifiers are reserved. Hence to associate some data and these words can not be considered as
identifiers in general programs.

Reserved keyword[53]

-->Actual RK [3] --> true, false, null

keywords

-->used keywords[48]

-->unused keywords[3] -->goto, const

used keywords:

SINO Reserved Reserved Reserved Reserved Reserved Reserved


Keywords keywords for keywords for keywords for keywords for keywords for
for flow control modifiers exception classes classes
Datatypes handling

01 byte if public try class new


02 short else private catch package instanceOf
03 int switch protected finally import super
04 float case static throw implements this
05 duble default final throws interface
06 char for abstract assert
07 long do synchronized
08 boolean while native
09 break strictfp
10 continue transient
11 return volatile

abstract : abstract class and methods

*enum: for grouped constants

void: return type

Excerise:

1. java2session --> valid

2. sumof# --> invalid

3. Integer --> valid

4. int --> invalid

5. _$_ --> valid

6. sachin Tendulker -->inVALID

7. sachinTendulker -->VALID

8. sachin_Tendulker -->VALID
5
9. sachin$Tendulker -->VALID

List of all Java keywords:

Keywords or Reserved words are the words in a language that are used for some internal process some
predefined actions. These words are therefore not allowed to use a variable names or objects. Doing this will
result into compile time error.

Java also contains a list of reserved words or keywords. These are:

1. abstract: Specifies that a class or method will be implemented later, in a subclass


2. assert: Assert describes a predicate (a true–false statement) placed in a Java program to indicate that the
developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an
assertion failure results, which typically causes execution to abort.

3. boolean: A data type that can hold True and False values only

4. break: A control statement for breaking out of loops

5. byte: A data type that can hold 8-bit data values

6. case: Used in switch statements to mark blocks of text

7. catch: Catches exceptions generated by try statements

8. char: A data type that can hold unsigned 16-bit Unicode characters

9. class: Declares a new class

10. continue: Sends control back outside a loop

11. default: Specifies the default block of code in a switch statement

12. do: Starts a do-while loop

13. double: A data type that can hold 64-bit floating-point numbers

14. else: Indicates alternative branches in an if statement

15. enum: A Java keyword used to declare an enumerated type. Enumerations extend the baseclass.

16. extends: Indicates that a class is derived from another class or interface

17. final: Indicates that a variable holds a constant value or that a method will not be overridden

18. finally: Indicates a block of code in a try-catch structure that will always be executed

19. float: A data type that holds a 32-bit floating-point number

20. for: Used to start a for loop

21. if: Tests a true/false expression and branches accordingly

22. implements: Specifies that a class implements an interface

23. import: References other classes

24. instanceOf: Indicates whether an object is an instance of a specific class or implements an interface

25. int: A data type that can hold a 32-bit signed integer

26. interface: Declares an interface

27. long: A data type that holds a 64-bit integer

28. native: Specifies that a method is implemented with native (platform-specific) code

6
29. new: Creates new objects

30. null: Indicates that a reference does not refer to anything

31. package: Declares a Java package

32. private: An access specifier indicating that a method or variable may be accessed only in the class it’s declared in

33. protected: An access specifier indicating that a method or variable may only be accessed in the class it’s declared
in (or a subclass of the class it’s declared in or other classes in the same package)

34. public: An access specifier used for classes, interfaces, methods, and variables indicating that an item is
accessible throughout the application (or where the class that defines it is accessible)

35. return: Sends control and possibly a return value back from a called method

36. short: A data type that can hold a 16-bit integer

37. static: Indicates that a variable or method is a class method (rather than being limited to one particular object)

38. strictfp: A Java keyword used to restrict the precision and rounding of floating point calculations to ensure
portability.

39. super: Refers to a class’s base class (used in a method or class constructor)

40. switch: A statement that executes code based on a test value

41. synchronized: Specifies critical sections or methods in multithreaded code

42. this: Refers to the current object in a method or constructor

43. throw: Creates an exception

44. throws: Indicates what exceptions may be thrown by a method

45. transient: Specifies that a variable is not part of an object’s persistent state

46. try: Starts a block of code that will be tested for exceptions

47. void: Specifies that a method does not have a return value

48. volatile: Indicates that a variable may change asynchronously

49. while: Starts a while loop

** The keywords const and goto are reserved, even they are not currently in use.

const -Reserved for future use

goto – Reserved for future use

** true, false and null look like keywords, but in actual they are literals. However they still can’t be used as identifiers
in a program.

7
4. Identifiers should not be duplicated with in the same scope, identifiers may be duplicated in two

different scopes.

Example:

class A{

int i=10; --> Class level

short i=20; --> Error

double f=33.33 --> No Error

void m1(){

float f=22.22f; --> local variable

double f=33.33; --> Error

long i=30; --> No Error}

5. In java applications, we can use all predefined class names and interface names as identifiers.

Ex 01:

int Exception=10;

System.out.println(Exception);

Status: No Compilation Error

Output: 10

Ex 02:

String String="String";

System.out.println(String);

Status: No Compilation Error

Output: String

Ex 03:

int System=10;

System.out.println(System);

Status: COmpilation Error

Reason: Once if we declare "System"[Class Name] as an integer variable then we must use that

"System" name as integer variable only in the remaining program, in the remaining program if we use

"System" as class name then compiler will rise an error.

In the above context, if we want to use "System" as class name then we have to use its fully qualified.

8
2 Literals:

Literal is a constant assigned to the variables .

Ex:

int a=10;

int ----> data types

a ------> variables/ identifier

= ------> Operator

10 -----> constant[Literal].

; ------> Special symbol.

To prepare java programs, JAVA has provioded the following set of literals.

1. Integer / Integral Literals:

byte, short, int, long ----> 10, 20, 30,....

char -----> 'A','B',.....

2. Floating Point Literals:

float ----> 10.22f, 23.345f,.....

double----> 11.123, 456.345,....

3. Boolean Literals:

boolean -----> true, false

4. String Literals:

String ---> "abc", "def",......

Note: JAVA7 has given a flexibility like to include '_' symbols in the middle of the literals inorder to

improve readability.

Ex:

float f=12345678.2345f;

float f=1_23_45_678.2345f;

If we provide '_' symbols in the literals then compiler will remove all '_' symbols which we provided,

compiler will reformate that number as original number and compiler will process that number as original number.

9
Number Systems in Java:

IN general, in any programming language, to represent numbers we have to use a particular system .

There are four types of number systems in programming languages.

1. Binary Number Systems[BASE-2]

2. Octal Number Systems[BASE-8]

3. Decimal Number Systems[BASE-10]

4. Hexa Decimal Number Systems[BASE-16]

In java , all number systems are allowed, but, the default number system in java applications is

"Decimal Number Systems".

1. Binary Number Systems [BASE-2]:

If we want to represent numbers in Binary number system then we have to use 0's and 1's, but, the

Number must be prefixed with either '0b' or '0B'.

int a=10;-----> It is not binary number, it is decimal num.

int b=0b10;---> valid

int c=0B1010;---> valid

int d=0b1012;---> Invalid, 2 symbol is not binary numbers alphabet.

Note: Binary Number system is not supported by all the java versions upto JAVA6, but , JAVA7 and

Above versions are supporting Binary Number Systems, because, it is a new feature introduced in JAVA7 version.

2. Octal Number Systems [BASE-8]:

If we want to prepare numbers in octal number System then we have to use the symbols like

0,1,2,3,4,5,6 and 7, but, the number must be prefixed with '0'[zero].

Ex:

int a=10; ------> It is decimal nhumber, it is not octal number.

int b=012345;---> Valid

int c=O234567;---> Invalid, number is prefixed with O, not zero

int d=04567;----> Valid

int e=05678;----> Invalid, 8 is not octal number systems alphabet.

10
3. Decimal Number Systems[BASE-10]:

If we want to represent numbers in Decimal number system then we have to use the symbols like

0,1,2,3,4,5,6,7,8 and 9 and number must not be prefixed with any symbols.

Ex:

int a=10;----> Valid

int b=20;----> Valid

int c=30;----> valid

4. Hexa Decimal Number Systems[BASE-16]:

If we want to prepare numbers in Hexa decimal number system then we have to use the symbols like

0,1,2,3,4,5,6,7,8,9, a,b,c,d,e and f, but the number must be prefixed with either '0x' or '0X'.

Ex:

int a=10;-----> It is not hexa decimal number, it is decimal number.

int b=0x102345;---> Valid

int c=0X56789;---> Valid

int d=0x89abcd;---> valid

int e=0x9abcdefg;----> Invalid, 'g' is not in hexa decimal alphabet.

Note: If we provide numbers in all the above number systems in java applications then compiler will

Recognize all the numbers and their number systems on the basis of their prefix values, compiler will

Convert these numbers into decimal system and compilers will process that numbers as decimal

Numbers.

Operators:

Operator is a symbol, it will perform a particular operation over the provided operands.

To prepare java applications, JAVA has provided the following list of operators.

Arithmetic Assignment Comparison Boolean Bitwise Short – Ternary Operators


Operators Operators Operators Logical Logical Circuit
Operator Operators Operators
s
Expr1? Expr2:
+, -, *, /, %, + =, +=, -=, ==, !=, <, >, <=, &, |, ^ &, |, ^, <<, &&, || Expr3;
+, -- *=, /=, %=,..... >=,..... >>,...

11
Ex 01:

class Test

public static void main(String[] args)

int a=10;

System.out.println(a);

System.out.println(a++);

System.out.println(++a);

System.out.println(a--);

System.out.println(--a);

System.out.println(a);

Status: No Compilation Error

Output: 10

10

12

12

10

10

Ex 02:

class Test

public static void main(String[] args)

int a=5;

System.out.println(++a-++a);

Status: No Compilation Error

12
Output: -1

Ex 03:

class Test

public static void main(String[] args)

int a=5;

System.out.println((--a+--a)*(++a-a--)+(--a+a--)*(++a+a++));

Status: No Compilation Error

Output: 16

5. Data Types:

Java is strictly a typed programming language, where in java applicatins before representing data

first we have to confirm which type of data we representing. In this context, to represent type of

data we have to use "data types".

Ex:

i = 10;----> invalid, no data type representation.

int i=10;--> Valid, type is represented then data is rpersented.

In java applications , data types are able to provide the following advatages.

1. We are able to identify memory sizes to store data.

Ex: int i=10;--> int will provide 4 bytes of memory to store 10 value.

2. We are able to identify range values to the variable to assign.

Ex: byte b=130;---> Invalid

byte b=125;---> Valid

Reason: 'byte' data type is providing a particular range for its variables like -128 to 127, in

this range only we have to assign values to byte variables.

13
To prepare java applications, JAVA has provided the following data types.

1. Primitive Data Types / Primary Data types

2. Non-primitive datatypes / secondary data types

1. Numeric Data Types

1. Integral data types/ Integer Data types:

byte ------> 1 bytes ----> 0

short------> 2 bytes ----> 0

int--------> 4 bytes ----> 0

long-------> 8 bytes ----> 0

2. Non-Integral Data Types:

float------> 4 bytes ---> 0.0f

double-----> 8 bytes ---> 0.0

1. Non-Numeric Data types:

char ---------> 2 bytes---> ' ' [single space]

boolean-------> 1 bit-----> false

3. User defined data types / Secondary Data types


 All classes, all abstract classes, all interfaces, all arrays,......
 No fixed memory allocation for User defined data types
 If we want to identify range values for variables on the basis of data types then we have to use the

following formula.

n-1 n-1s

-2 to 2 - 1

Where 'n' is no of bits.

Ex: Data Type: byte, size= 1 byte = 8 bits.

8-1 8-1

-2 to 2 - 1

77

-2 to 2 - 1

14
-128 to 128 - 1

-128 to 127

Note: This formula is applicable upto Integral data types, not applicable for other data types.

To identify "min value" and "max value" for each and every data type, JAVA has provided the

following two constant variables from all the wrapper classes.

MIN_VALUE and MAX_VALUE

Note: Classes representation of primitive data types are called as Wrapper Classes

Primitive data types Wrapper Classes

byte --------------------> java.lang.Byte

short -------------------> java.lang.Short

int ---------------------> java.lang.Integer

long --------------------> java.lang.Long

float -------------------> java.lang.Float

double-------------------> java.lang.Double

char---------------------> java.lang.Character

boolean------------------> java.lang.Boolean

Example:

class Sample{

public static void main(String[] args){

System.out.println(Byte.MIN_VALUE+"----->"+Byte.MAX_VALUE);

System.out.println(Short.MIN_VALUE+"---->"+Short.MAX_VALUE);

System.out.println(Integer.MIN_VALUE+"----->"+Integer.MAX_VALUE);

System.out.println(Long.MIN_VALUE+"----->"+Long.MAX_VALUE);

System.out.println(Float.MIN_VALUE+"----->"+Float.MAX_VALUE);

System.out.println(Double.MIN_VALUE+"----->"+Double.MAX_VALUE);

System.out.println(Character.MIN_VALUE+"----->"+Character.MAX_VALUE);

//System.out.println(Boolean.MIN_VALUE+"----->"+Boolean.MAX_VALUE);--->
Error }}

Type Casting:
The process of converting data from one data type to another data type is called as "Type Casting".

There are two types of type castings are existed in java.


15
1. Primitive data Types Type Casting

2. User defined Data Types Type Casting

1. Primitive data Types Type Casting:

The process of converting data from one primitive data type to another primitive data type is

called as Primitive data types type casting.

There are two types of primitive data types type castings.

1. Implicit Type Casting

2. Explicit Type Casting

1. Implicit Type Casting:

The process of converting data from lower data type to higher data type is called as Implicit Type

Casting.

To cover all the possibilities of implicit type casting JAVA has provided the following chart.

124848

byte ---> short ---> int ---> long ---> float ---> double

^|

char

If we want to perform implicit type casting in java applications then we have to assign lower data type

variables to higher data type variables.

Example:

byte b=10;

int i = b;

System.out.println(b+" "+i);

Status: No COmpilation Error

OP: 10 10

 If we compile the above code, when compiler encounter the above assignment statement then

compiler will check whether right side variable data type is compatible with left side variable data type

or not, if not, compiler will rise an error like "possible loss of precision". If right side variable data

type is compatible with left side variable data type then compiler will not rise any error and compiler

will not perform any type casting.

 When we execute the above code, when JVM encounter the above assignment statement then JVM

16
will perform the following two actions.

1. JVM will convert right side variable data type to left side variable data type implicitly

[Implicit Type Casting]

2.JVM will copy the value from right side variable to left side variable.

Note: Type Checking is the responsibility of compiler and Type Casting is the responsibility of JVM.

Example 01:

class Sample

public static void main(String[] args)

int i=10;

byte b=i;

System.out.println(i+" "+b);

Status: Compilation Error, Possible loss of precision.

Example 02:

class Sample

public static void main(String[] args)

byte b=65;

char c=b;

System.out.println(b+" "+c);

Status: Compilation Error

17
Example 03:

class Sample

public static void main(String[] args)

char c='A';

short s=c;

System.out.println(c+" "+s);

Status: Compilation Error, Possible loss of precision.

Reason: byte and short internal data representations are not compatible to convert into char.

Example 04:

class Sample

public static void main(String[] args)

char c='A';

int i=c;

System.out.println(c+" "+i);

Status: No Compilation Error

OP: A 65

Reason: Char internal data representation is compatible with int.

Example 05:

class Sample

public static void main(String[] args)

18
byte b=128;

System.out.println(b);}}

Status: Compilation Error,possible loss of precision.

Reason: When we assign a value to a variable of data type, if the value is greater the max limit of the

left side variable data type then that value is treated as of the next higher data type value.

Note: For both byte and short next higher data type is int only.

Example 06:

class Sample

public static void main(String[] args)

byte b1=60;

byte b2=70;

byte b3=b1+b2;

System.out.println(b3); }}

Status: Compilation Error, possible loss of precision.

Example 07:

class Sample

public static void main(String[] args)

byte b1=30;

byte b2=30;

byte b3=b1+b2;

System.out.println(b3);

Status: Compilation Error, Possible loss of precision.

Reason: X,Y and Z are three primitive data types.

X+Y=Z

1. If X and Y belongs to {byte, short, int} then Z should be int.


2. If either X or Y or both X and Y belongs to {long, float, double} then Z should be higher(X,Y).
19
byte+byte=int

byte+short=int

short+int=int

byte+long=long

long+float=float

float+double=double

Example 08:

class Sample

public static void main(String[] args)

long l=10;

float f=l;

System.out.println(l+" "+f);

Status: No Compilation Error

OP: 10 10.0

Example 09:

class Sample

public static void main(String[] args)

float f=22.22f;

long l=f;

System.out.println(f+" "+l);

Status: Compilation Error, possible loss of precision.

2. Explicit Type Casting:

The process of converting data from higher data type to lower data type is called as Explicit Type

Casting.

20
To perform explicit type casting we have to use the following pattern.

P a = (Q) b;

(Q)----> Cast operator

Where P and Q are two primitive data types, where Q must be either same as P or lower than P as

per implicit type casting chart.

Example 01:

class Sample

public static void main(String[] args)

int i=10;

byte b=(byte)i;

System.out.println(i+" "+b);

Status: No Compilation Error

OP: 10 10

Example 02:

class Demo

public static void main(String[] args)

int i=130;

byte b=(byte)i;

System.out.println(i+" "+b);

Status: No Compilation Error

OP: 130 -126

When we compile the above code, when compiler encounter the above assignment statement, compiler

will check whether cast operator provided data type is compatible with left side variable data type or

21
not, if not, compiler will rise an error like "Possible loss of precision". If cast operator provided data

type is compatible with left side variable data type then compiler will not rise any error and compiler

will not perform type casting.

When we execute the above program, when JVM encounter the above assignment statement then JVM

will perform two actions.

1.JVM will convert right side variable data type to cast operator provided data type.

2.JVM will copy value from right side variable to left side variable

Java Statements:

Statement is the collection of expressions.

To design java applications JAVA has provided the following statements:

1. General Purpose Statements

 Declaring variables, methods, classes,....


 Creating objects, accessing variables, methods,.....

2. Conditional Statements:

 if
 switch

3. Iterative Statements:

 for
 while
 do-while

4. Transfer statements:

 break
 continue
 return

5. Exception Handling statements:

 throw, try-catch-finally

6. Synchronized statements:

1.synchronized methods

2.synchronized blocks

Conditional Statements:

These statements are able to allow to execute a block of instructions under a particular condition.

Example:

1. if

22
2. switch

1. if:

Syntax 01:

if (condition)

{ instructions--- }

Syntax 02:

if(condition)

{ ---instructions---- }

else

{ ----instructions--- }

Syntax 03:

if(condition)

{ ---instructions---- }

else if(condition)

{ ---instruction---- }

else if(condition)

{ ---instructions---- }

else

{ ----instructions---- }

Example 01:

class Test

public static void main(String[] args)

int i=10, j;

if(i==10)

j=20;

else

j=30;

23
System.out.println(j); } }

Status: No Compilation Error

OP: 20

Example 02:

class Demo

public static void main(String[] args)

int i=10, j;

if(i==10)

j=20;

else if(i==20)

j=30;

else

j=40;

System.out.println(j);

Status: no Compilation Error

OP: 20

Example 03:

class Test

public static void main(String[] args)

final int i=10;

24
int j;

if(i == 10)

j=20;

System.out.println(j); } }

Status: No Compilation Error

OP: 20

Example 04:

class Demo

public static void main(String[] args)

int j;

if(true)

j=20;

System.out.println(j); } }

Status: No Compilation Error

Reasons:

1. In java applications, only class level variables are having default values, local variables are not

having default values. If we declare local variables in java applications then we must provide

initializations for that local variables explicitlty, if we access any local variable with out having

initialization explicitly then compiler will rise an error like "Variable x might not have been

initialized".

class Demo

public static void main(String[] args)

int j;

if(false)

25
{ j=20; }

else

{ j=30; }

System.out.println(j); } }

Status: No Compilation Error

OP: 30

Example 01:

class A{

int i;-----> class level variable, default value is 0..

void m1(){

int j;---> local variable, no default value.

System.out.println(i);// OP: 0

//System.out.println(j);--> Error

j=20;

System.out.println(j);---> No Error

Note: Local variables must be declared in side methods, blocks, if conditions,... and these variables are

having scope upto that method only, not having scope to outside of that method. Class level variables

are declare at class level that is in out side of the methods, blocks,.... these variables are having scope

through out the clsas that is in all methods, in all blocks which we provided in the respective class.

2. switch

'if' is able to provide single condition checking bydefault, but, switch is able to provide multiple

conditions checking’s.

Syntax:

switch(Var)

case 1:

-----instructions-----

break;

case 2:

----instructions------

26
Break;

case n:

----instructions-----

break;

default:

----instructions-----

break;

Example:

class Demo

public static void main(String[] args)

int i=10;

switch(i)

case 5: System.out.println("Five");

break;

case 10: System.out.println("Ten");

break;

case 15: System.out.println("Fifteen");

break;

case 20: System.out.println("Twenty");

break;

default: System.out.println("Default");

break;

Output:Ten

Rules to write switch:

1. switch is able to allow the data types like byte, short, int and char.

Example 01:

27
byte b=10;

switch(b) { ---- }

Status: No Compilation Error

Example 02:

long l=10;

switch(l)

{ ---- }

Status: Compilation Error.

Example 03:

class Demo

public static void main(String[] args)

char c='B';

switch(c)

case 'A': System.out.println("Five");

break;

case 'B': System.out.println("Ten");

break;

case 'C': System.out.println("Fifteen");

break;

case 'D': System.out.println("Twenty");

break;

default: System.out.println("Default");

break;

Status: no Compilation Error

1. *Upto JAVA6 version, switch is not allowing "String" data type as parameter, "JAVA7" version

28
onwards switch is able to allow String data type.

Example 04:

class Demo

public static void main(String[] args)

String str="BBB";

switch(str)

case "AAA": System.out.println("AAA");

break;

case "BBB": System.out.println("BBB");

break;

case "CCC": System.out.println("CCC");

break;

case "DDD": System.out.println("DDD");

break;

default: System.out.println("Default");

break;

Status: No Compilation Error

OP: BBB

2. In switch, all cases and default are optional, we can write switch without cases and with default, we

can write switch with cases and without default, we can write switch without both cases and default.

Example 05:

int i=10;

switch(i)

{}

Status: No Compilation Error

OP: No Output.

29
Example 06:

class Demo

public static void main(String[] args)

int i=10;

switch(i)

default: System.out.println("Default");

break;

Status: No Compilation Error

OP: Default

3. In switch, "break" statement is optional, we can write switch with out break statement, in this

context, JVM will execute all the instructions continuously right from matched case until it

encounter either break statement or end of switch.

Example 07:

class Demo

public static void main(String[] args)

int i=10;

switch(i)

case 5: System.out.println("Five");

case 10: System.out.println("Ten");

case 15: System.out.println("Fifteen");

case 20: System.out.println("Twenty");

default: System.out.println("Default");

30
}

}}

Status: No Compilation Error

Output: Ten

Fifteen

Twenty

Default

4. In switch, all case values must be provided with in the range of the data type which we provided as

parameter to switch.

Example 08:

class Demo

public static void main(String[] args)

byte b=126;

switch(b)

case 125: System.out.println("125");

break;

case 126: System.out.println("126");

break;

case 127: System.out.println("127");

break;

case 128: System.out.println("128");

break;

default: System.out.println("Default");

break;

Status: Compilation Error

31
Iterative Statements:

These statements are able to allow JVM to execute a set of instructions repeatedly on the basis of a

particular condition.

Example 01:

1. for

2. while

3. do-while

1. for

Syntax:

for(Expr1; Expr2; Expr3)

{ ----instructions----- }

Example 01:

class Demo

public static void main(String[] args)

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

{ System.out.println(i); }

Status: No Compilation Error

Output: 0

---

---

Expr1-----> 1 time

Expr2-----> 11 times

Expr3-----> 10 times

Body -----> 10 times

32
Example 02:

class Demo

public static void main(String[] args)

int i=0;

for(;i<10;i++)

{ System.out.println(i); }

Status: No Compilation Error

OP: 0 ---- 9

Example 03:

class Demo

public static void main(String[] args)

int i=0;

for(System.out.println("Hello");i<10;i++)

{ System.out.println(i); }

Status: No Compilation Error

OP: Hello 0 1 ---- 9

Reason:

In for loop, Expr1 is optional, we can write for loop even with out Expr1 , we can write any statement

like System.out.println(--) as Expr1, but, always, it is suggestible to provide loop variable declaration

and initialization kind of statements as Expr1

33
Example 04:

class Demo

public static void main(String[] args)

for(int i=0, float f=0.0f ;i<10 && f<10.0f; i++,f++)

{ System.out.println(i+" "+f); }

Status: Compilation Error

Example 05:

class Demo

public static void main(String[] args)

for(int i=0, int j=0 ;i<10 && j<10; i++,j++)

{ System.out.println(i+" "+j); }

Status: Compilation Error

Example 06:

class Demo

public static void main(String[] args)

for(int i=0, j=0 ;i<10 && j<10; i++,j++)

{ System.out.println(i+" "+j); }

Status: No Compilation Error

OP: 0 0

34
11

22

Reason:

In for loop, Expr1 is able to allow almost one declarative statement, it will not allow more than one

declarative statement, we can declare more than one variable with in a single declarative statement.

Example 07:

class Demo

public static void main(String[] args)

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

{ System.out.println(i); }

Status: No Compilation Error

OP: Infinite Loop

Example 08:

class Demo

public static void main(String[] args)

for(int i=0; System.out.println("Hello") ;i++)

{ System.out.println(i); }

Status: Compilation Error

Reason: In for loop, Expr2 is optional, we can write for loop even with out Expr2, if we write for loop

with out Expr2 then for loop will take "true" value as Expr2 and it will make for loop as an infinite

loop. If we want to write any statement as Expr2 then that statement must be boolean statement, it

must return either true value or false value.

35
Example 08:

class Demo

public static void main(String[] args)

System.out.println("Before Loop");

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

{ System.out.println("Inside Loop"); }

System.out.println("After Loop");

Status: Compilation Error, Unreachable Statement

Reasons:

In java applications, if we provide any statement immediately after infinite loop then that statement is

called as "Unreachable Statement". If compiler identifies the provided loop as an infinite loop and if

compiler identifies any followed statement for that infinite loop then compiler will rise an error like

"Unreachable Statement". If compiler does not aware the provided loop as an infinite loop then there is

no chance for compiler to rise "Unreachable Statement Error".

Note: Deciding whether a loop as an infinite loop or not is completely depending on the conditional

expression, if the conditional expression is constant expression and it returns true value always then

compiler will recognize the provided loop as an infinite loop. If the conditional expression is variable

expression then compiler will not recognize the provided loop as an infinite loop even the loop is

really infinite loop.

int i=0;

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

{}

36
Example 09:

class Demo

public static void main(String[] args)

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

System.out.println(i);

i=i+1;

Status: No Compilation Error

OP: 0,1 ..... 9

Example 10:

class Demo

public static void main(String[] args)

for(int i=0;i<10;System.out.println("Hello"))

System.out.println(i);

i=i+1;

}}}

Status: No Compilation Error

Output: 0

Hello

Hello

----

----

37
9

Hello

Note: In for loop, Expr3 is optional, we can write for loop with out expr3, we can provide any

statement as expr3, but, it is suggestible to provide loop variable increment/decrement kind of

statements as expr3.

Example 11:

class Demo

public static void main(String[] args)

for(;;)

Status: Compilation Error

Example 12:

class Demo

public static void main(String[] args)

for(;;);

Status: No Compilation Error

OP: No Output, but, JVM will be in infinite loop

Example 13:

class Demo

public static void main(String[] args)

for(;;)

{}

38
}}

Status: No Compilation Error. Output: No Output, but, JVM will be in infinite loop

Reason: In for loop, if we want to write single statement in body then curly braces [{ }] are optional , if we dont want
to write any statement as body then we must provide either ; or curly braces to the for loop.

In general, we will utilize for loop when we aware no of iterations in advance before writing loop.

2. While loop:

In java applications, when we are not aware the no of iterations in advance before writing loop there

we have to utilize 'while' loop.

Syntax:

while(Condition)

{ ---instructions----- }

Example 01:

class Test

public static void main(String[] args)

int i=0;

while(i<10)

System.out.println(i);

i=i+1;

Example 02:

class Demo

public static void main(String[] args)

int i=0;

while()

{
39
System.out.println(i);

i=i+1;

Status: Compilation Error

Reason: Conditional Expression is mandatory.

Example 03:

class Demo

public static void main(String[] args)

System.out.println("Before Loop");

while(true)

System.out.println("Inside Loop");

System.out.println("After Loop");

Status: Compilation Error, Unreachable Statement

3. do-while:

Q) What are the differences between while loop and do-while loop?

Ans:

1. While loop is not giving any guarantee to execute loop body minimum one time. do-while loop will
give guarantee to execute loop body minimum one time.

2. In case of while, first, conditional expression will be executes, if it returns true then only loop body
will be executed.

In case of do-while loop, first loop body will be executed then condition will be executed.

3 .In case of while loop, condition will be executed for the present iteration.

In case of do-while loop, condition will be executed for the next iteration.

40
Syntaxes:

while(Condition)

---instructions-----

do

---instructions---

While(Condition);

Example 01:

class Demo

public static void main(String[] args)

int i=0;

do

System.out.println(i);

i=i+1;

while (i<10);

Status: No Compilation Error

OP: 0, 1, 2,.... 9

41
Example 02:

class Demo

public static void main(String[] args)

System.out.println("Before Loop");

do

System.out.println("Inside Loop");

while (true);

System.out.println("After Loop");

Status: Compilation Error, Unreachable Statement

Transfer Statements:

These statements are able to bypass flow of execution from one instruction to another instruction.

Example:

1. break
2. 2.continue
3. 3.return
1. break:

break statement will bypass flow of execution to outside of the loops or outside of the blocks by skipping the
remaining instructions in the current iteration and by skipping all the remaining iterations.

Example 01:

class Demo

public static void main(String[] args)

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

if(i==5)

{
42
break;

System.out.println(i);

Status: No Compilation Error

OP: 0

1234

Example 02:

class Demo

public static void main(String[] args)

System.out.println("Before loop");

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

if(i==5)

System.out.println("Inside loop, before break");

break;

System.out.println("Inside loop, after break");

System.out.println("After Loop");

Status: Compilation Error, unreachable Statement

Reason: If we provide any statement immediately after break statement then that statement is

Unreachable Statement, where compiler will rise an error.

43
Example 03:

class Demo

public static void main(String[] args)

for(int i=0;i<10;i++)// Outer loop

for(int j=0;j<10;j++)// Nested Loop

if(j==5)

break;

System.out.println(i+" "+j);

// Out side of nested Loop

Status: No Compilation Error

OP: 0 0

01

02

Note: If we provide "break" statement in nested loop then that break statement is applicable for only nested loop, it
will not give any effect to outer loop.

In the above context, if we want to give break statement effect to outer loop, not to the nested loop then we have to
use "Labelled break" statement.

Syntax:

break label;

Where the provided label must be marked with the respective outer loop.

Continue…..

44
Example 01:

class Demo

public static void main(String[] args)

l1:for(int i=0;i<10;i++)// Outer loop

for(int j=0;j<10;j++)// Nested Loop

if(j==5)

break l1;

System.out.println(i+" "+j);

// Out side of nested Loop

//Out side of outer loop

Status: no Compilation Error

OP: 0 0

01

02

03

04

2. Continue:

This transfer statement will bypass flow of execution to starting point of the loop by skipping all the

Remaining instructions in the current iteration in-order to continue with next iteration.

Continue….

45
Example 01:

class Demo

public static void main(String[] args)

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

if(i == 5)

{ continue; }

System.out.println(i);

Status: No Compilation Error

OP:

012346789

Example 02:

class Demo

public static void main(String[] args)

System.out.println("before Loop");

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

if(i == 5)

System.out.println("Inside Loop, before continue");

continue;

System.out.println("Inside Loop, After continue");

46
}

System.out.println("After loop");

Status: Compilation Error, Unreachable Statement.

Reason: If we provide any statement immediately after continue statement then that statement is unreachable
statement, where compiler will rise an error.

Example 03:

class Demo

public static void main(String[] args)

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

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

if(j==5)

continue;

System.out.println(i+" "+j);

Status: No Compilation Error

OP:

If we provide continue statement in netsted loop then continue statement will give effect to nested loop

only, it will not give effect to outer loop

47
Example 04:

class Demo

public static void main(String[] args)

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

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

if(j==5)

continue;

System.out.println(i+" "+j);

In the above context, if we want to give continue statement effect to outer loop, not to the nested loop

then we have to use labelled continue statement.

Syntax:

continue label;

Where the provided label must be marked with the respective outer loop

Example:

class Demo

public static void main(String[] args)

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

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

48
{

if(j==5)

continue l1;

System.out.println(i+" "+j);

Status: No Compilation Error

Output:

00

01

02

03

04

10

11

12

13

14

---

---

90

01

92

93

94

OO

49
ARRAYS
 Whenever we try to store large amount of data in a variable we will face readability issue.
 In order to store small amount data we can use variables but if we want to store large amount of data then we
must use ARRAYS.
 An array is an indexed collection of fixed number of homogeneous data elements.
 The main disadvantage of array is we can present only homogeneous type of data.
 The main advantage of array is we can represent multiple values under the same variable. Hence we can achieve
readability.
 Once the array is created with some size we can not alter that during execution.
 We can use concept called as COLLECTIONS to solve the above mentioned problem.

TYPES OF ARRAYS:

1. SINGLE DIMENSION ARRAY

2. MULTI DIMENSION ARRAY

1. SINGLE DIMENSION ARRAY [1-D]

In this type the data can be stored in the single row/column.

SYNTAX:

There are 3 steps in order to create 1d array.

1. Declaration of a array variable. ( eg: int a[]; )

2. Creation of array object. ( eg: int a = new int[5]; )

3. Initilization of a array. ( eg: a[0] = 10;

a[1] = 20; )

Note: int a[] = new int[5];

Single line (declare create initilize)

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

NOTE: Array is an obejct since it is created using new keyword. The Super class of array is Object.

WHERE DOES THE MEMORY ALLOCATED FOR ARRAYS?

The arrays are created inside the object hence the memory is allocated in heap memory segment.

Note: Whenever array is created the default values will be added based on the datatype.

Example:

int a[] = new int[5] --> 0 0 0 0 0

float a[] = new float[5] --> 0.0 0.0 0.0 0.0 0.0

50
ARRAY DECLARATION:

The declaration of the array can be done in nay one of the way:

1. int a[];

2. int []a;

3. int[] a; -->{recommended}

Example 01 : Demo1.java

class Demo1

public static void main(String[] args)

int a[];

a = new int[5];

a[0] = 10;

a[1] = 20;

System.out.println(a[0]);

System.out.println(a[1]);

System.out.println(a[2]);

System.out.println(a[3]);

System.out.println(a[4]);

//System.out.println(a[5]); --> error: ArrayIndexOutOfBoundsException: 5

Output: 10

20

51
Example 02: Demo1.java

class Demo1

public static void main(String[] args)

int a[] = new int[5];

a[0] = 10;

a[1] = 20;

System.out.println(a[0]);

System.out.println(a[1]);

System.out.println(a[2]);

System.out.println(a[3]);

System.out.println(a[4]);

//System.out.println(a[5]);

Output: 10

20

Example 03: Demo1.java

class Demo1

public static void main(String[] args)

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

System.out.println(a[0]);

System.out.println(a[1]);

System.out.println(a[2]);

System.out.println(a[3]);

System.out.println(a[4]);

//System.out.println(a[5]);

52
}}

Output: 10

20

30

40

50

Class name for different array types:

ARRAY TYPE CLASS TYPE


int[] [I
byte[] [B
short [S
long[] [J
float[] [F
double[] [D
char[] [C

Example 04: Demo1.java

class Demo1

public static void main(String[] args)

//float a[] = new float[5]; --> [F

//int a[] = new int[5]; --> [I

short s[] = new short[5]; --> [S

System.out.println(s.getClass());

NOTE: At the array declaration Size should not be specified. Size should be mentioned only during creation of aaray.

Example 05:

int a[5]; --> invalid

int a[]; --> valid

It is valid to create array with size zero

int a[] = new int[0]; --> valid.

An array size can not be mentioned as negative value. If we do so during compilation we will not get any problem but
during execution we will get error

--> int a[] =new int[-5]; --> error NegativeArraySizeException


53
Examples for 1D (Single Dimension) array:

Example 01: Demo.java

//Write a program to store and print marks of 5 students.

import java.util.*; // package

class Demo

public static void main(String[] args)

int a[] = new int[5];

Scanner sc = new Scanner(System.in);

System.out.println("Enter the marks:");

a[0]= sc.nextInt();

System.out.println("Enter the marks:");

a[1]= sc.nextInt();

System.out.println("Enter the marks:");

a[2]= sc.nextInt();

System.out.println("Enter the marks:");

a[3]= sc.nextInt();

System.out.println("Enter the marks:");

a[4]= sc.nextInt();

System.out.print(a[0]+ " ");

System.out.print(a[1]+ " ");

System.out.print(a[2]+ " ");

System.out.print(a[3]+ " ");

System.out.print(a[4]+ " ");

Output:

Enter the marks:

87

Enter the marks:

92

54
Enter the marks:

37

Enter the marks:

59

Enter the marks:

64

87 92 37 59 64

Example 02: Demo1.java

// Write a Program to store and print marks of 5 students.

import java.util.*; // package

class Demo1

public static void main(String[] args)

int a[] = new int[5];

Scanner sc = new Scanner(System.in);

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

System.out.println("Enter the marks:");

a[i]= sc.nextInt();

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

{ System.out.print(a[i]+" "); }

Output:

Enter the marks: 87

Enter the marks: 92

Enter the marks: 37

Enter the marks: 59

Enter the marks: 64

87 92 37 59 64

55
Example 03: Demo1.java

//Write a Program to store and print marks of 5 students.

import java.util.*; // package

class Demo1

public static void main(String[] args)

int a[] = new int[5];

Scanner sc = new Scanner(System.in);

int i;

i=0;

while(i<=4)

System.out.println("Enter the marks:");

a[i]= sc.nextInt();

i++;

i=0;

while(i<=4)

System.out.print(a[i]+" ");

i++;

Output:

Enter the marks: 87

Enter the marks: 92

Enter the marks: 37

Enter the marks: 59

Enter the marks: 64

87 92 37 59 64

56
Example 04: Demo1.java

//Write a Program to store and print marks of 5 students.

import java.util.*; // package

class Demo1

public static void main(String[] args)

int a[] = new int[5];

Scanner sc = new Scanner(System.in);

int i;

i=0;

do

System.out.println("Enter the marks:");

a[i]= sc.nextInt();

i++;

while(i<=4);

i=0;

do

System.out.print(a[i]+" ");

i++;

while(i<=4);

Output:

Enter the marks: 87

Enter the marks: 92

Enter the marks: 37

Enter the marks: 59

Enter the marks: 64

57
87 92 37 59 64

Example 05: Demo1.java

//Write Program to store and print marks of n number of students.

import java.util.*; // package

class Demo1

public static void main(String[] args)

System.out.println("Enter the length/size of the array:");

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int a[] = new int[n];

System.out.println("the length of the array is: "+a.length);

for (int i =0;i<=a.length-1 ;i++)

System.out.println("Enter the marks of the students");

a[i] = sc.nextInt();

for (int i =0;i<=a.length-1 ;i++)

System.out.print(a[i]+ " ");

Output:

Enter the marks: 87

Enter the marks: 92

Enter the marks: 37

Enter the marks: 59

Enter the marks: 64

87 92 37 59 64

58
Example 06: Demo1.java

//Write Program to store and sum the values and print sum value.

import java.util.*; // package

class Demo1

public static void main(String[] args)

System.out.println("Enter the length/size of the array:");

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int a[] = new int[n];

System.out.println("the length of the array is: "+a.length);

for (int i =0;i<=a.length-1 ;i++)

System.out.println("Enter the marks of the students");

a[i] = sc.nextInt();

int sum = 0;

for (int i=0;i<=a.length-1 ;i++)

sum = sum+a[i];

System.out.print(a[i]+ " ");

System.out.print("The sum of values is : "+ sum);

Output:

Enter the length/size of the array: 10

The length of the array is: 10

Enter the marks of the students: 10

Enter the marks of the students: 20

Enter the marks of the students: 30

Enter the marks of the students: 40

59
Enter the marks of the students: 50

Enter the marks of the students: 60

Enter the marks of the students: 70

Enter the marks of the students: 80

Enter the marks of the students: 90

Enter the marks of the students: 100

10 20 30 40 50 60 70 80 90 100 The sum of values is : 550

2. MULTI-DIMENSIONAL ARRAY

Multi-dimensional arrays are such arrays whose data can be stored in multiple row/columns.

1D array: single row/column

Multi-dimensional arrays are classified into two types:

1. 2-Dimensional array [2D array]

2. 3-Dimensional array [3D array]

1. 2D array [refer the diagram]

Declaring the 2D array:

int a[][];

int [][]a;

int[][] a;

int[] []a;

int[] a[];

Note: all the above combinations are valid.

1. int[] a,b; a->1D b->1D

2. int a[],b; a->1D b-> it is just a variable

3. int a[],b[]; a->1D b->1D

4. int[] a[],b[]; a->2D b->2D

5. int[][] a[],b; a->3D b->2D

6. int[][] []a,b[]; a->3D b->3D

7. int[][] []a,[]b; compilation error

Creation of 2D array:

declaration: int a[][];

60
Create: a = new int[2][3];

initilize: a[0][0] = 10;

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

a[0][1]=20;

Single line(declare,Create, initilize)

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

2D arrays are classified into two types:

1. 2D regular array

2. 2D jagged array

1. 2D regular array:

In this regular array all the rows will have same number of columns.

Example:1

Write a Program to store and print the marks of students from 3 class rooms where in each class 5
students are presents.

import java.util.*;

class Demo

public static void main(String[] args)

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

Scanner sc = new Scanner(System.in);

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

for (int j=0;j<=4;j++)

System.out.println("Enter the marks of student " + j +"of classroom "+i);

a[i][j]= sc.nextInt();

61
for (int i=0;i<=2;i++)

for (int j=0;j<=4;j++)

System.out.print(a[i][j] + " ");

System.out.println(" ");

Output: 10 20 30 40 50

60 70 80 90 100

110 120 130 140 150

NOTE:

int a[] = new int[5];

a.length -> 5

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

a.length ->3

a[i].length ->5

int a[][][] = new int[3][4][5];

a.length -> 3

a[i].length -> 4

a[i][j].length ->5

2. 2D jagged array:

If the number of columns is not same in each rows then it is called as Jagged array.

2D regular array: 2D jagged array:

co -> s0 s1 s2 s3 s4 c0 -> s0 s1 s2

c1 -> s0 s1 s2 s3 s4 c1 -> s0 s1

c2 -> s0 s1 s2 s3 s4 c2 -> s0 s1 s2 s3

62
Example for 2D jagged array:

import java.util.*;

class Demo

public static void main(String[] args)

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

a[0] = new int[3];

a[1] = new int[2];

a[2] = new int[4];

Scanner sc = new Scanner(System.in);

for (int i=0;i<=a.length-1;i++)

for (int j=0;j<=a[i].length-1;j++)

System.out.println("Enter the marks of student " + j +"of classroom "+i);

a[i][j]= sc.nextInt();

for (int i=0;i<=a.length-1;i++)

for (int j=0;j<=a[i].length-1;j++)

System.out.print(a[i][j] + " ");

System.out.println(" ");

Output: 10 20 31

41 51

61 71 81 91

63
Example:

class Demo1

public static void main(String[] args)

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

System.out.println(a.length); --> 3

System.out.println(a[0].length); --> 5

System.out.println(a[1].length); --> 5

System.out.println(a[0][0].length); --> error

2.3(Three Dimension) Dimensional array [3D array]

Declaration of 3D array:

int [][][] a;

int a[][][];

int[][] a[];

int[] [][]a;

int[] []a[];

Note: all the above mentioned declarations are valid.

Creation of 3D array:

Declaration : int a[][][];

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

initilize: a[0][0][0]=10;

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

Single line (declare, create , initilize)

int a[][][] = {{{10,20},{30,40},{50,60}} ,{{70,80},{90,100},{110,120}} ,{{130,140},{150,160},{170,180}}}

64
Example for 3D regular array:

import java.util.*;

class Demo

public static void main(String[] args)

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

Scanner sc = new Scanner(System.in);

for (int i=0;i<=a.length-1;i++)

for (int j=0;j<=a[i].length-1;j++)

for (int k=0;k<=a[i][j].length-1;k++)

System.out.println("Enter the marks of student " + k +"of the


classroom "+j+" from the school " +i);

a[i][j][k]= sc.nextInt();

for (int i=0;i<=a.length-1;i++)

for (int j=0;j<=a[i].length-1;j++)

for (int k=0;k<=a[i][j].length-1 ;k++ )

System.out.print(a[i][j][k] + " ");

System.out.println(" ");

}
65
Output: 10 20 30

40 50 60

70 80 90

100 11 12

13 14 15

16 17 18

Example for 3D jagged arrary:

import java.util.*;

class Demo

public static void main(String[] args)

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

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

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

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

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

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

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

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

Scanner sc = new Scanner(System.in);

for (int i=0;i<=a.length-1;i++)

for (int j=0;j<=a[i].length-1;j++)

for (int k=0;k<=a[i][j].length-1;k++)

System.out.println("Enter the marks of student " + k +"of the


classroom "+j+" from the school " +i);

a[i][j][k]= sc.nextInt();

}
66
}

for (int i=0;i<=a.length-1;i++)

for (int j=0;j<=a[i].length-1;j++)

for (int k=0;k<=a[i][j].length-1 ;k++ )

System.out.print(a[i][j][k] + " ");

System.out.println(" ");

Output: 10 20

30 40 50

60 70

80 90 100

110 120 130 140

for-each loop/enhanced loop

Example: Demo.java

// using for loop

class Demo

public static void main(String[] args)

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

for (int i=0;i<=x.length-1;i++)

System.out.println(x[i]);

67
} } Output: 10 20 30 40 50

Example: Demo.java

// using for-each loop / enhanced loop

class Demo

public static void main(String[] args)

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

for (int i : x)

System.out.println(i);

Output: 10 20 30 40 50

with the above program we can see that same task can be achvied using for each loop aswell.

Syntax of for-each loop:

for(datatype variable : array )

statements

Continue statement:

Continue is a control statement which is used to skip the current iteration and move to the next iteration
.Continue can be used only with the loops.

Example: Demo.java

// Continue Statement

class Demo

public static void main(String[] args)

int x[] = {10,20,30,40,50,60,70,80,90,100};

68
for (int i : x)

if(i==70)

continue;

System.out.println(i);

Output: 10 20 30 40 50 60 80 90 100 --> 70 is skiped

ANONYMOUS ARRAY

Anonumous array are such array which doesnt have name . It can be declared and initilized in single line.

Anonumous array can be 1D or 2D or 3D and can be passed as arguments to the methods.

Example: Demo1.java

// ANONYMOUS ARRAY

class Addition

int sum;

void add( int[] x )

for (int i=0;i<=x.length-1 ;i++ ){

sum=sum+x[i];

System.out.println(sum);

System.out.println("the total sum is :" + sum);

}}

class Demo1

public static void main(String[] args)

Addition a = new Addition();

a.add(new int[]{10,20});

}}

69
OUTPUT: 10 30 the total sum is 30

OBJECT ORIENTATION:
ORIENTATION  view point.

OBJECT  Real time entity.

RULES OF OBJECT ORIENTATION [FEATURES]

1. The world is a collection of objects.


2. Every object is useful, no object is useless.
3. Every object is in constant interaction with another object.
4. Every object belongs to a type, but type does not exist in reality only are exist. Object type is technically called as
CLASS.
5. Every object will have two parts one is ‘has’ part also called as ‘properties’ and second one is ‘does’ part also called
as ‘behaviour.’
6. Has part of a object is handled using ‘datatype and variables’ whereas does part is handled by ‘methods’.

WHY WE NEED OBJECT ORIENTATION?

 To solve real time problems we need object orientation.


Example: BOOKMYSHOW application.

SINO offline online


01 customer customer
02 counter counter
03 money money
04 ticket ticket
05 theatre theatre
06 seat seat
07 movie movie
08 snacks snacks
09 [black market] not applicable

PILLARS OF OBJECT ORIENTATION:


1. CLASS
2. OBJECT
3. POLYMORPHISM
4. ENCAPSULATION
5. ABSTRACTION
6. INHERITANCE

1. CLASS: Class is a blueprint/template which does not exist in reality.


SYNTAX OF THE CLASS:

access modifier Class Classname


{
variable
methods
blocks
constructors
interface
nested class
70
abstraction
}

SYNTAX OF A METHOD:
access modifier returnType methodName (parameter)
{
---------------
--------------- --> body
---------------
}

example for blueprint[class]


Class Lion
{
String name;
String breed;
String gender;

eat()
{
------
------
}

sleep()
{
-------
-------
}

run()
{
-------
-------
}

CREATION OF OBJECT:
An object can be created in 5 differnt ways:
1. using 'new' keywords
2. using newInstance()
3. using clone()
4. using FactoryMethod
5. using deserialization

71
CREATION OF OBJECT USING 'new' KEYWORD:
To create an object using 'new' keyword we must fallow 3 steps:
1. Declaration: declare a variable to a type(class) eg: Lion l1
2. Instantiation : allocate the memory (new) memory is pointed by reference variable eg: new Lion();
3. Initilization : variables and methods will be loaded to the memory.

ex: Lion l1 = new Lion();

example1: LionApp.java

class Lion
{
String name;
String breed;
String gender;

void eat()
{
System.out.println("lion always eats non-veg");

}
void sleep()
{
System.out.println("lion sleeps 10 hr per day...!");
}
void run()
{
System.out.println("lion runs faster than human being");

}
}

class LionApp
{
public static void main(String[] args)
{
Lion l1 = new Lion();
l1.eat();
l1.sleep();
l1.run();

}
}

Output:
-------
lion always eats non-veg
lion sleeps 10 hr per day...!
lion runs faster than human being
72
NOTE: 1.Always program execution starts from the class where main method is present.
2.To access the variables and methods present in differnt class we will make use of reference varibale.

OBJECT VALUES CAN BE INITILIZED USING 3 WAYS:

1. using reference varibale


2. using methods
3. using the constructor

1. initilizing the object value using refernce variable


Example: LionApp.java
------------
class Lion
{
String name;
String breed;
String gender;

void eat()
{
System.out.println("lion always eats non-veg");

}
void sleep()
{
System.out.println("lion sleeps 10 hr per day...!");
}
void run()
{
System.out.println("lion runs faster than human being");

}
}
class LionApp
{
public static void main(String[] args)
{
Lion l1 = new Lion(); // object creation is done using new keyword

l1.name = "simba"; // values for objects is given using ref variables


l1.breed = "Asiatic";
l1.gender = "male";
System.out.println(l1.name);
System.out.println(l1.breed);
System.out.println(l1.gender);

l1.eat(); // methods are called with the help of ref variable.


l1.sleep();
73
l1.run();

}
}
Output:simba
Asiatic
male
lion always eats non-veg
lion sleeps 10 hr per day...!
lion runs faster than human being

VARIABLES:
Variables are classified into two types based on:
1. Data representation
2. Positional declaration

1.Data representation: Depending on what type of data we will assign to a variable.


It has been classified into two types:

1.1 Primitive variable: If a variable holds primitive data then such variables are called Primitive varaible.
Ex: int a = 46;
1.2 Reference variable: If a variable holds address of the memory location of an object then such type of
variables are called as ref variable.
Ex: Lion l1 = new Lion();

2. Positional declaration: based on where we declare the varibales it has been classified into 3 types.
2.1 Instance variable
2.2 Static variable
2.3 Local variable
2.1 INSTANCE VARIABLE:
WHAT IS AN INSTANCE VARIABLE?

Value of a variable if it changes from object to object then such variables are called as Instance
Variables.

NOTE:
--> For every object separate copy of instance variables is created.

WHERE THE INSTANCE VARIABLES ARE DECLARED?

Example:

Class Demo
{
int x;
float y;
boolean z;

void method1()
74
{

}
}

Instance Variables are declared within the class but outside the methods/blocks.

WHERE DOES INSTANCE VARIABLES ARE LOCATED IN MEMORY?


Instance variables present within the object inside the 'heap' memory. Hence it is also called object varible or
attribute.

WHAT IS THE SCOPE OF THE INSTANCE VARIABLE ?

Scope refers to memory allocation and deallocation.

For instance variable memory will be allocated during object creation and deallocation will occur during
object destruction. Hence scope of instance variable is same as object scope.
HOW WE CAN ACCESS THE INSTANCE VARIBLES?
Instance variables can not be accessed from static area.
Ex:
class Demo
{

int x =25;
public static void main(String[] args)
{
System.out.println(x);
}
}

because: jvm will not allow to access instance variable in static region.

Instance variables can be accessed by using refernce variable.


example:
--------
class Demo
{

int x =25;
public static void main(String[] args)
{

Demo d1 = new Demo();


System.out.println(d1.x); --> using object reference

}
}

NOTE: JVM always gives default values for Instance variables


Ex:
75
class Demo2
{
byte b;
short s;
int i;
long l;
float f;
double d;
boolean bo;
char ch;
String st;

public static void main(String[] args)


{
Demo2 d1 = new Demo2(); --> 0
System.out.println(d1.b); --> 0
System.out.println(d1.s); --> 0
System.out.println(d1.i); --> 0
System.out.println(d1.l); --> 0
System.out.println(d1.f); --> 0.0
System.out.println(d1.d); --> 0.0
System.out.println(d1.bo); --> false
System.out.println(d1.ch); --> space
System.out.println(d1.st); --> null
}
}
IS JAVA IS PURELY (100%) OBJECT ORIENTED PROGRAMMING LANGUAGE ?

YES, when compared with previous programming languages.


NO, considering only java it does not support few features operator overloading, multiple inheritance hence
it is not 100% object oriented.
Also, if a programming language is 100% object oriented then everything in the program must be considered
as object. But, in java we have primitive datatypes (non-object)

We can make our project 100% object oriented by using wrapper classes.
Example
byte b = 10; Byte b = new Byte(10);
int x = 25; Int i = new Int(25);

NOTE: The disadvantage with wrapper class is that it will occupy more memory.

2.2 STATIC VARIABLE:


1. WHAT IS STATIC VARIABLE?
The value of a variable does not change from object to object such variables are called as STATIC VARIBALES.

2. WHERE THE STATIC VARIABLES ARE DECLARED?


Static variables are declared within the class but outside the methods or block.
Example:
class People
{
String name; IV
final int addhar_no; IV
static String nationality; SV
76
}

NOTE: For all the objects only one copy of static variable is created and it is shared by every object.

3. WHERE DOES THE MEMORY ALLOCATED FOR STATIC VARIABLES?


Static variables always present in method area [static memory segment] inside the memory.

4. WHAT IS THE SCOPE OF THE STATIC VARIABLE?


Scope refers to the memory allocation and deallocation
For the static variable memory will be allocated during loading of class file and deallocated while unloading the class
file.
Hence scope of the static variable is same as the .class file.

5. HOW WE CAN ACESS THE STATIC VARIABLE


We can access the static variable using:
directly we can use within the static method
using the object reference
using class name {recommeded}

Example: People.java
class People
{
String name;
int addhar_no;
static String nationality="Indian";

public static void main(String[] args)


{
People p1 = new People();

System.out.println(nationality); // directly we can access


System.out.println(p1.nationality); // using object reference
System.out.println(People.nationality); // using class name [recommended]
}
//System.out.println(nationality);

}
Output:
-------
Indian
Indian
Indian

6. JVM always gives default values for the static variables:


Example: Demo2.java
class Demo2
{
static byte b;
static short s;
static int i;
static long l;
static float f;
77
static double d;
static boolean bo;
static char ch;
static String st;

public static void main(String[] args)


{
Demo2 d1 = new Demo2();
System.out.println(d1.b); --> 0
System.out.println(d1.s);` --> 0
System.out.println(d1.i); --> 0
System.out.println(d1.l); --> 0
System.out.println(d1.f); --> 0.0
System.out.println(d1.d); --> 0.0
System.out.println(d1.bo); --> false
System.out.println(d1.ch); --> space
System.out.println(d1.st); --> null
}
}

NOTE: If the values of static variable is modified then it will be reflected on all the objects

Example: Demo.java
class Demo
{
static int x = 25;
int y = 50;
public static void main(String[] args)
{

Demo d1 = new Demo();


System.out.println(d1.x); // 25
System.out.println(d1.y); // 50

d1.x = 143;
d1.y = 420;
System.out.println(d1.x); // 143
System.out.println(d1.y); // 420

Demo d2 = new Demo();


System.out.println(d2.x); // 143
System.out.println(d2.y); // 50

}
}

2.3 LOCAL VARIABLE:


1. WHAT IS LOCAL VARIABLE?
78
Local Variables are temporary variables which are used by programmers to meet temporary requirements.

2. WHERE THE LOCAL VARIABLES ARE DECLARED?


Local Variables are always declared within the method or block.
Example:
Class Demo
{
p s v m(String []args)
{
int x =10; #LV
for(int i=0;i<10;i++)
{
s.o.p(i);
}
}
}

3. WHERE DOES LOCAL VARIABLES ARE LOCATED IN THE MEMORY?


Local Variables are always present in stack memory hence it is also called as stack variable.

4. WHAT IS THE SCOPE OF THE LOCAL VARIABLE?


Scope refers to memeory allocation and deallocation.
memory will be allocated when ever control enters the method/block.
memory will be deallocated when ever control leaves the method/block.
Hence the scope of Local variables is same as the method scope.
Example:
class Demo
{
public static void main(String[] args)
{
int x = 10;
System.out.println(x); // valid
for (int i=0;i<10 ;i++ )
{
System.out.println(i); // valid
System.out.println(x); // valid
}
//System.out.println(i); // error[invalid]
}

}
5. HOW WE CAN ACCESS THE LOCAL VARIABLES?
Local Variables can be accessed only within the method/block. Outside the method we cannot access.
Example: refer above example

6. DOES THE JVM PROVIDE DEFAULT VALUES FOR LOCAL VARIBALES?


NO, Programmer must initialize the values to the local variable.

Example: 01 Demo.java
class Demo
{
public static void main(String[] args)
{
79
int x;
System.out.println("java");
//if local variables are not used then we won’t get compilation error
}

Output:
java
Example: 02 Demo.java
class Demo
{
public static void main(String[] args)
{
int x;
System.out.println("java");
System.out.println(x);
//if we try to use local variables with out initilization then we will get compilation error.
}
}

Output:
Error

Example: 03
NOTE: jvm will not provide default values to the local variables hence it is recommended to the programmer to give
default values

Demo.java
class Demo
{
public static void main(String[] args)
{
int x = 0;
System.out.println("java");
System.out.println(x);
}

}
Output:
java
0

1. VALUE TYPE ASSIGNMENT


2. REFERNCE TYPE ASSIGNMENT

80
1. VALUE TYPE ASSIGNMENT: Whenever value of one variable is assigned to another variable is called as value type
assignment.
Example: Demo.java
class Demo
{
public static void main(String[] args)
{
int x = 10;
int y;
y = x;
System.out.println(x);
System.out.println(y);

}
}

Output:
-------
10
10

2. REFERENCE TYPE ASSIGNMENT: Whenever the address of the one variable is assigned to another variable then it
is called as reference type assignment.
After the assignment all the ref variable would be pointing to the same object.
Modification done by any one of the reference variable would affect the same
object.

NOTE: In java one object can have multiple reference variables.

Example: Demo.java
class Demo
{
String name;
int roll_no;
public static void main(String[] args)
{
Demo d1 = new Demo();
d1.name = "sagar";
d1.roll_no = 24;
System.out.println(d1.name);
System.out.println(d1.roll_no);

Demo d2;
d2 = d1;
d1.name = "sandesh";
d1.roll_no = 25;
System.out.println(d2.name);
System.out.println(d2.roll_no);
81
System.out.println(d1.name);
System.out.println(d1.roll_no);
}
}

Output: sagar
24
sandesh
25
sandesh
25

82
ABSTRACTION
Abstraction is one of the important object oriented features in java. It is process of hiding the internal
implementation and sharing only the related functionality to the user.

ABSTRACTION: It is all about hiding the implementation (body) of an overridden method.

ENCAPSULATION: It is all about hiding the data members (variable and methods).

In java abstraction can be achieved in two ways:

1. Abstract class [0-100%]

2. Interface

EXAMPLE: PROGRAM WITHOUT ABSTRACTION

class Vehicle

void Move() //IM --> sp m

System.out.println("vehicle is moving");

void Start() //IM -->sp m

System.out.println("vehicle is started");

class Car extends Vehicle

void Start() //IM -->OM

System.out.println("self start or auto start");

class Bike extends Vehicle

83
{

void Start()

System.out.println("kick start");

class Demo

public static void main(String[] args)

Vehicle V = new Vehicle();

Car C = new Car();

Bike B = new Bike();

V.Move();

V.Start();

C.Move();

C.Start();

B.Move();

B.Start();

EXAMPLE: PROGRAM WITH ABSTARCTION

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

abstract class Vehicle

void Move()

84
System.out.println("vehicle is moving"); // concrete method

abstract void Start(); // abstract method

class Car extends Vehicle

void Start()

System.out.println("self start or auto start");

class Bike extends Vehicle

void Start()

System.out.println("kick start");

class Demo

public static void main(String[] args)

//Vehicle V = new Vehicle();

Car C = new Car();

Bike B = new Bike();

C.Move();

C.Start();

B.Move();

B.Start();

85
}

NOTE 1

1. ABSTRACT METHOD: Abstract methods are overridden methods where it will be not have implementation.

2. abstract is a non-access modifier keyword which used as prefix for abstract methods and classes.

3. If any method is abstract in a class then that class is also considered as abstract class and prefixed with abstract
keyword.

4. For abstract classes we cannot create the object (not required to create).

5. All the abstract methods should end with the semicolon

6. The inherited method from the parent class is also called as 'concrete method'.

EXAMPLE:

abstract class Bank

abstract void roi(); // 100% abstraction

class Sbi extends Bank

void roi()

System.out.println("intrest rate is 7.5%");

class Hdfc extends Bank

void roi()

System.out.println("intrest rate is 8.5%");

class Icici extends Bank

void roi()

{
86
System.out.println("intrest rate is 9.5%");

class Demo1

public static void main(String[] args)

//Bank b =new Bnak();

Bank b;

b = new Sbi(); // upcasting

b.roi();

b = new Hdfc(); // upcasting

b.roi();

b = new Icici(); // upcasting

b.roi();

NOTE 2

1. For abstract class we cannot create object but we can have reference

2. by parent reference we can perform up casting and polymorphism can be achieved .

3. abstract class which consist of only abstract methods is considered as 100% abstraction.

DIFFERENCE B/W NORMAL CLASS AND ABSTRACT CLASS.

EXAMPLE FOR NORMAL CLASS WITHOUT OBJECT OREIENTATION FEATURES:

class Calc

int a;

int b;

void add() // concrete method

a=10;

87
b=20;

int c=a+b;

System.out.println(c);

void sub() // concrete method

a=20;

b=10;

int c=a-b;

System.out.println(c);

class Demo2

public static void main(String[] args)

Calc c = new Calc();

c.add();

c.sub();

EXAMPLE FOR ABSTRACTION CLASS:

// normal class

abstract class Calc

int a;

int b;

abstract void add(); // abstract method

abstract void sub(); // abstract method

class Demo2

88
public static void main(String[] args)

//Calc c = new Calc();

//c.add();

//c.sub();

ABSTRACTION USING THE ABSTRACT CLASS

abstract class remote

abstract void On();

abstract void Off();

class Tv extends remote

void On()

System.out.println("the TV is on");

void Off()

System.out.println("the TV is off");

class Demo3

public static void main(String[] args)

remote r;

r = new Tv();

r.On();

r.Off();

89
}

RULES W.R.T ABSTRACTION:

RULE 1

If a method is made as abstract then compulsory the child class should override the method.

If the child class does not override the abstract method then error is displaced during compilation

EXAMPLE:

CASE 1

abstract class Sample

abstract void fun1();

class Demo4 extends Sample

void fun1()

System.out.println("inside fun1");

public static void main(String[] args)

System.out.println("inside main method");

CASE 2

abstract class Sample

abstract void fun1();

class Demo4 extends Sample

public static void main(String[] args)

90
{

System.out.println("inside main method");

NOTE: Abstract keyword can be used with following members:

1. class

2. methods

3. Interface (methods)

4. Inner class (classes)

NOTE: Illegal combination of using abstraction

1. static

2. final

3. private

legal combinations are:

1. Strictfp

2. Synchronized

3. native

--> INTERFACE is a specification.

refer fig:2

--> Interface promotes standardization using which we can achieve polymorphism.

INTERFACE
Interface is collection of abstract methods using interface 100% abstraction can be achieved because inside the
interface methods declaration are allowed

SYNTAX:

interface interface_Name

abstract method(); --> method

Constants; --> variables(final)

91
ADVANTAGE OF INTERFACE:

1. Using the interface standardization is achieved.

eg: pi value

2. It promotes polymorphism

3. 100% abstraction can be achieved

4. multiple inheritance can be achieved.

NOTE: By default all the data members (variable) present in the interface are 'public static final' in nature.

Also by default all the methods present in the interface is 'public abstract' in nature.

EXAMPLE 1

interface Test

float pi = 3.14f;

void fun();

compile:

interface Test

public static final float pi = 3.14f;

public abstract void fun();

RULES OF INTERFACE:

RULE 1

When a class is implementing the interface the methods access modifiers should be made as public because by
default all the abstract method in interface are public in nature.

EXAMPLE

interface Calculate

/* public abstract */void add();

class Calculator implements Calculate


92
{

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

class Demo

public static void main(String[] args)

Calculator c = new Calculator();

c.add();

/*

public

protected weaker access modifiers can be given

default

private

*/

OUTPUT: 30

RULE 2

If a class implements the interface then it should provide the body for all the methods present in the interface class.

If the class is not in a position to provide the body for all the method then class should be made as abstract.

EXAMPLE 1

interface Calculate

93
{

void add();

void mul();

class Calculator implements Calculate

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

class Demo

public static void main(String[] args)

Calculator c = new Calculator();

c.add();

OUTPUT: Calculator is not abstract and does not override abstract method mul() in Calculate

class Calculator implements Calculate

Note:The above problem can be overcome by making class as abstract and method where class is not in a position to
provide the body then it should be made as abstract.

EXAMPLE 2

interface Calculate

void add();

void mul();

}
94
abstract class Calculator implements Calculate

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

abstract public void mul();

class Demo

public static void main(String[] args)

//Calculator c = new Calculator();

//c.add();

RULE 3

An object of abstract class cannot be created

ex: refer above program

An object of interface cannot be created

EXAMPLE:

interface Calculate

void add();

void mul();

class Demo

95
p s v m (---)

Calculate c = new Calculate();

OUTPUT: ERROR

--> Object can not be instantiated.

RULE 4

Though we cannot create the object for interface its reference can be created.

EXAMPLE:

interface Calculate

void add();

void mul();

class Demo

p s v m (---)

//Calculate c = new Calculate();

Calculate c; --> parent refernce

RULE 5

A class and interface cannot be related using the extends keyword

EXAMPLE:

interface Calculate

void add();

class Calculator extends Calculate

96
public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

class Demo

public static void main(String[] args)

Calculator c = new Calculator();

c.add();

OUTPUT: ERROR

RULE 6

Using the interface ref (parent ref) the implemented methods of a class can be accessed and using interface ref
polymorphism can be achieved

EXAMPLE:

interface Bank

void ROI();

class SBI implements Bank

public void ROI()

System.out.println("sbi --> 7.5%");

class AXIS implements Bank


97
{

public void ROI()

System.out.println("AXIS --> 9.5%");

class CANARA implements Bank

public void ROI()

System.out.println("CANARA --> 8.5%");

class Calculate

public void allow(Bank ref)

ref.ROI();

class Demo1

public static void main(String[] args)

SBI s = new SBI();

AXIS a = new AXIS();

CANARA c = new CANARA();

Calculate c1= new Calculate();

c1.allow(s);

c1.allow(a);

c1.allow(c);

98
OUTPUT: sbi --> 7.5%

AXIS --> 9.5%

CANARA --> 8.5%

AMBIGUITY PROBLEMS WITH INTERFACE VARIABLES:

EXAMPLE:

interface calculate1

int min = 10;

interface calculate2

int min = 20;

class Test implements calculate1,calculate2

public void disp()

System.out.println(min);

class Ambiguity

public static void main(String[] args)

Test t = new Test();

t.disp();

OUTPUT: error: reference to min is ambiguous

System.out.println(min);

both variable min in calculate1 and variable min in calculate2 match

99
NOTE: The above problem can be overcome by accessing the interface variable with the interface name.

EXAMPLE:

interface calculate1

int min = 10;

interface calculate2

int min = 20;

class Test implements calculate1,calculate2

public void disp()

System.out.println(calculate1.min);

System.out.println(calculate2.min);

class Ambiguity

public static void main(String[] args)

Test t = new Test();

t.disp();

OUTPUT: 10

20

100
RULE 7

An interface can extend any number of interface.

EXAMPLE:

interface calculate1

void add();

interface calculate2

void sub();

interface calculate3 extends calculate1,calculate2

void mul();

class Test implements calculate3

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

public void sub()

int a,b,c;

a=20;

b=05;

c=a-b;

101
System.out.println(c);

public void mul()

int a,b,c;

a=20;

b=05;

c=a*b;

System.out.println(c);

class Rule14

public static void main(String[] args)

Test t = new Test();

t.add();

t.sub();

t.mul();

OUTPUT: 30

15

100

DOES JAVA ALLOW MULTIPLE INHERITANCE?

Multiple inheritance through classes cannot be achieved in java because of ambiguity problem (diamond shape
problem).

But multiple inheritance can be achieved through interface as shown below:

EXAMPLE:

interface A

int i =10;

}
102
interface B

int i = 20;

interface C extends A,B

class Test

public void disp()

System.out.println(A.i);

System.out.println(B.i);

class Demo

public static void main(String[] args)

Test t = new Test();

t.disp();

OUTPUT: 10

20

103
ACCESS_MODIFIERS
These are the keywords in object oriented language that set the accessibility of classes, methods and other
members.

In Java having a keyword before the class, method or variable is considered as 'modifiers'.

NOTE: In java there is not concept of access_specifiers.

Access_specifiers are available in c,c++ languages.In java Acess_modifiers are available.

ACCESS_MODIFIERS IN JAVA:

1. public

2. protected

3. default

4. private

5. final

6. abstract

7. static

8. synchronized

9. native

10. strictfp

11. transient

12. volatile

SINO ACCESS_MODIFIERS available for ACCESS MODIFIERS for inner


user-defined classes classes
01 public public
02 default default
03 final final
04 abstract abstract
05 strictfp strictfp
06 public private
07 protected
08 static

104
PUBLIC/DEFAULT access_modifiers w.r.t classes:

--> If a UDC is declared as 'public' then we can access that class from anywhere.

EXAMPLE:

package pack1;

public class A

public void fun1()

System.out.println("inside pack1");

package pack2;

import pack1.A;

class B

public static void main(String[] args)

A a = new A();

a.fun1();

System.out.println("inside pack2 of class B");

OUTPUT: inside pack1

inside pack2 of class B

NOTE: If we want to use methods of a class in another package then we must make the UDC as 'public'.

If UDC is public in nature then members of that class can be accessed within the same package and also from
different packages.

105
EXAMPLE:

class Demo

public void fun1()

System.out.println("inside class Demo");

class Demo1

public static void main(String[] args)

Demo d = new Demo();

d.fun1();

System.out.println("inside class Demo1");

OUTPUT: inside class Demo

inside class Demo1

NOTE: If we want to use methods of a class in the same package then we must make the UDC as 'default'.

If UDC is default in nature then members of that class can be accessed within the same package and cannot be
accessed from different packages.

ABSTRACT [non-access_modifiers] w.r.t. methods:

abstract modifier is only applicable for classes and methods and it is not applicable for variables

(refer class notes(abstract concept))

NOTE: If any method present in the class is abstract in nature then the class should be prefixed with abstract
keyword.

106
NOTE: Illegal combinations with abstarct keyword:

1. final

2. synchronized[multithreading]

3. private

4. native

5. static

6. strictfp

strictfp [strict floating point] ACCESS_MODIFIER:

--> This modifier is applicable for classes and methods and not applicable for variables.

Example: 10/3 --> 3.33333

the result w.r.t floating point is always machine dependent

ie, based on 16 bit 32 bit 64bit we will get different floating point.

To strandarize the result and to achive platform independent strictfp is used w.r.t floating point calculations.

strictfp w.r.t methods:

--> If strictfp is used on methods then all the floating points in the methods should fallow "IEE754" format. To
achieve standardization and platform independence

strictfp w.r.t classes:

--> If a UDC is declared as strictfp then every floating point within the class is calculated for concrete methods as per
IEE754 format.

Note: abstract and strictfp is a illegal combination

EXAMPLE:

abstract strictfp class Demo2

abstract strictfp void fun1()

public void fun100()

107
{

abstract void method1();

abstract void method2();

OUTPUT: illegal combination

METHOD LEVEL AND VARIABLE LEVEL ACCESS MODIFIERS:

1. public methods and variables:

--> public members can be accessed from any where but, its corresponding class should public.

2. default members:

--> default members can be accessed only within the current package.

3. private members:

--> if a members is private we can use only within the current UDC.

4. protected members:

--> can be accessed within the current package but, only in child classes of outside package.

EXAMPLE:

package p1;

public class sample

protected void fun1()

System.out.println("inisde pack p1 and class sample and method fun1");

package p2;

import p1.sample;

class sample2 extends sample

108
{

public static void main(String[] args)

//sample s = new sample();

//s.fun1();

//sample s = new sample2();

//s.fun1();

sample2 s2 = new sample2();

s2.fun1();

System.out.println("inside sample2 and pack p2 ");

OUTPUT: inside pack p1 and class sample and method fun1

inside sample2 and pack p2

static access-modifier:
static access modifiers is applicable only on methods and variables and not applicable on top level classes.

static can be used for inner classes [static nested class]

legal combinations:

static variable

static block

static method

static nested class

native access_modifier:

native access_modiers are applicable only to methods. It is not applicable to variables, inner class, top-level class.

native keyword is used because:

1. to improve the performance of the program.

2. to achieve the memory level communication.

3. to use already existing legacy non-java code from C++.

109
syntax for native keyword is:

1. load the native libraries

2. declare a native method

3. invoke a native method

EXAMPLE:

class Demo

static

System.out.println("native libraries path:");

public native void fun1();

// implementation is already available

class Demo1

public static void main(String[] args)

Demo d = new Demo();

d.fun1();

OUTPUT: native libraries path:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Demo.fun1()

at Demo.fun1(Native Method)

at Demo1.main(Demo1.java:15)

illegal combinations with native:

native and abstract

native and strictfp

110
adv: performance of the program

dis_adv: program may become platform dependent.

transient access_modifier:

--> this access_modifier is only applicable for variables. It is used only during the process of 'serialization mechanism'.

serialization : saving the data of an object in a file.

de-serialization : taking the object data from the file.

note: for sensitive data in a object we must use transient keyword.

Volatile access-modifiers:

It is applicable only to variable.

int a = 25; --> p1/t1

int a = 25; --> p2/t2

int a = 25; --> p3/t3

but, creation of separate local copies every time leads to complexity of program execution.

and also memory usage will be inefficient.

the problem of 'data consistency ' can be solved.

note: it is almost deprecated modifier in java.

111
112
113
METHODS:

114
The does part or behaviour of an object is handled in the programming using methods.

Syntax of method:

access_modifier returntype methodName(parameter)

method body

access_modifier --> optional

returnType --> compulsory

methodName --> compulsory

parameter --> optional

Example:

public void add(int x, int y)

int z;

z=x+y;

s.o.p(z);

TYPES OF METHODS BASED ON PARAMETER AND RETURN VALUE.

1. NO PARAMETER AND NO RETURN VALUE

2. PARAMETER AND NO RETURN VALUE.

3. PARAMETER AND RETURN THE VALUE.

4. NO PARAMETER AND RETURN THE VALUE.

Example: 1

1. NO PARAMETER AND NO RETURN VALUE

Demo.java

// no passing the input and no returning the output.

class Demo

public static void main(String[] args)

115
Addition a1=new Addition();

a1.add();

class Addition

void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

Output: 30

Example: 02

2. PARAMETER AND NO RETURN VALUE

Demo.java

// passing the input and no returning the output.

class Demo

public static void main(String[] args)

Addition a1=new Addition();

int x=12;

int y=8;

a1.add(x,y);

class Addition

void add(int a,int b)

116
{

int c;

c=a+b;

System.out.println(c);

Output: 20

Example: 3

3. PARAMETER AND RETURN VALUE

Demo.java

// passing the input and returning the output.

class Demo

public static void main(String[] args)

Addition a1=new Addition();

int x=12;

int y=12;

int res = a1.add(x,y);

System.out.println(res);

class Addition

int add(int a,int b)

int c;

c=a+b;

return c;

Output: 24

117
Example: 4

4. NO PARAMETER AND RETURN VALUE

Demo.java

// no passing the input and returning the output.

class Demo

public static void main(String[] args)

Addition a1=new Addition();

int res = a1.add();

System.out.println(res);

int res = a1.add();

System.out.println(res);

class Addition

int add()

int a,b,c;

a=14;

b=14;

c=a+b;

return c;

OUTPUT: 28

118
Example

// Write a Program to return the array.

class Demo

public static void main(String[] args)

ArrayRetrun ar=new ArrayRetrun();

int[] x = ar.fun();

for (int i=0;i<=x.length-1;i++)

System.out.println(x[i]);

class ArrayRetrun

int[] fun()

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

return a;

Output: 10 20 30 40

CONSTRUCTORS

119
Constructor is a special block or method where name of the constructor is same as the class name.

It is a specialized setter to initialize the object.

Constructor does not have any return type. The access modifier allowed for the Constructor method is public,
private, protected, default.

Constructor are always called during the object creation.

There are 3 ways to intilize the object.

1. using the reference variable

2. using the methods

3. using the constructors

1. using the reference variable:

EXAMPLE:

class Student

String name;

int roll_no;

class Demo2

public static void main(String[] args)

Student s1 = new Student();

s1.name ="raju";

s1.roll_no = 84;

System.out.println(s1.name);

System.out.println(s1.roll_no);

OUTPUT: raju

84

120
2. using the methods

EXAMPLE:

class Student

String name;

int roll_no;

public void SetData(String sname, int sroll_no)

name=sname;

roll_no=sroll_no;

public String getName()

return name;

public int getRoll_no()

return roll_no;

class Demo2

public static void main(String[] args)

Student s1 = new Student();

s1.SetData("somu",89);

System.out.println(s1.getName());

System.out.println(s1.getRoll_no());

OUTPUT: somu

89

121
3. using the constructors

EXAMPLE:

class Student

String name; //IV

int roll_no; //IV

Student(String sname,int sroll_no) sname -->LV

name=sname;

roll_no=sroll_no;

System.out.println(name);

System.out.println(roll_no);

class Demo

public static void main(String[] args)

Student s1 = new Student("bheem",28);

//Student s2 = new Student("somu",89);

OUTPUT: bheem

28

somu

89

122
EXAMPLE: 2

// SHADOWING PROBLEM

class Student

String name; //IV

int age; //IV

Student(String name,int age) //name age --> LV

name=name;

age=age;

public String getName()

return name;

public int getAge()

return age;

class StudentApp

public static void main(String[] args)

Student s1= new Student("ramu",21);

System.out.println(s1.getName());

System.out.println(s1.getAge());

OUTPUT: null

123
Whenever local variable name is same as the instance variable then the priority is given to local variable. Because of
this problem object initialization

Will not happen in the proper way.

This problem is called as Shadowing problem.

Solution to the above problem is:

1. use the 'this' keyword to differentiate b/w instance and local variable.

EXAMPLE:

// solution to the SHADOWING PROBLEM by using 'this' keyword.

class Student

private String name;

private int age;

Student(String name,int age)

this.name=name;

this.age=age;

public String getName()

return name;

public int getAge()

return age;

class StudentApp

public static void main(String[] args)

Student s1= new Student("ramu",21);


124
System.out.println(s1.getName());

System.out.println(s1.getAge());

Student s2= new Student("somu",22);

System.out.println(s2.getName());

System.out.println(s2.getAge());

OUTPUT: ramu

21

somu

22

NOTE: 'this' keyword is used to solve the shadowing problem.

this keyword always points the currently executing object and also brings the difference b/w local and instance
variable.

TYPES OF CONSTRUCTOR

The types of constructors are:

1. default constructor

2. user defined default constructor

3. parameterized constructor

1. DEFAULT CONSTRUCTOR:

In a class if constructor is not present during the compilation compiler will add default constructor.

The default constructor is no argument or zero parameterized in nature.

The only one line of code present within the default constructor is super() method.

Whenever compiler adds the default constructor the access modifier of the constructor will be same as that of class.

In the above example void Demo() is not a constructor it is a method.

If user has provided the constructor within a class then during compilation compiler will add a super() method to the
body of the Constructor.

125
2. USER DIFINED DEFAULT CONSTRUCTOR:

In a class if a programmer adds a constructor then compiler will not add the default constructor.

UDC is always added by the user with no args/zero parameter.

In a class there would be either UDC or DC. Both of them will never occur simultaneously in the class.

EXAMPLE:

class Student

String name;

int age;

Student()

name="ramu"; // USER DIFIEND DEFAULT CONSTRUCTOR

age=21;

public String getName()

return name;

public int getAge()

return age;

class Demo

public static void main(String args[])

Student s1 = new Student();

System.out.println(s1.getName());

System.out.println(s1.getAge());

OUTPUT: ramu 21

126
THE DIFFERENCE B/W CONSTRUCTOR AND METHOD

EXAMPLE:

class A

A()

System.out.println("Inside the constructor");

void A()

System.out.println("Inside the method");

class Demo1

public static void main(String[] args)

A a1= new A();

a1.A();

a1.A();

OUTPUT:

Inside the constructor

Inside the method

Inside the method

SI NO CONSTRUCTOR METHOD
01 Constructor should be same as class name. Method name can anything.
02 They don’t have return type. return type is compulsory.
03 Constructor calling implicit. method calling is explicit.
04 Constructor will be called only one during the object method can be called n number times..
creation.
05 Access modifier permitted are: public, private, protected. We can also use static, final. Etc.
06 Constructor cannot be initiated. Methods can be inherited.

127
3. PARAMETERIZED CONSTRUCTOR:

Constructors with the parameter is called as parameterized constructor. It is a user defined constructor.

PC is used to initialize the object by the user input.

EXAMPLE:

class Student

String name;

int age;

Student(String name)

this.name=name; // PARAMETERIZED CONSTRUCTOR

public String getName()

return name;

class Demo

public static void main(String args[])

Student s1 = new Student("RAMU");

System.out.println(s1.getName());

OUTPUT: RAMU

128
EXAMPLE 2

class Student

String name;

int age;

Student(String name)

this.name=name; // PARAMETERIZED CONSTRUCTOR

public String getName()

return name;

class Demo

public static void main(String args[])

Student s1 = new Student();

System.out.println(s1.getName());

OUTPUT: COMPILATION ERROR

NOTE: In the above program we are trying to call the parameterized constructor without passing the argument
hence we will get compilation error.

129
CONSTRUCTOR OVERLOADING:

Defining more than one constructor in a class by changing the :

1. number of parameter

2. type of parameter

3. order of parameter

EXAMPLE:

class Employee

private String name;

private int id;

private float salary;

public Employee(String name) //PC

this.name = name;

public Employee(String name,int id)

this.name = name;

this.id = id;

public Employee(String name,int id,float salary)

this.name = name;

this.id = id;

this.salary = salary;

public String getName()

return name;

public int getId()

return id;

130
}

public float getSalary()

return salary;

class Demo

public static void main(String[] args)

Employee e1 = new Employee("ramu");

System.out.println(e1.getName());

Employee e2 = new Employee("ramu",124);

System.out.println(e2.getName());

System.out.println(e2.getId());

Employee e3 = new Employee("ramu",124,50.45f);

System.out.println(e3.getName());

System.out.println(e3.getId());

System.out.println(e3.getSalary());

OUTPUT: ramu

ramu

124

ramu

124

50.45

NOTE: Constructor overloading is used to extend the functionality of the constructor .It exhibits virtual
polymorphism.

131
this() constructor call:

this: this keyword is used which will internally points to the currently executing object.

this(): this() method is a constructor call within the same class.

Calling the constructor within another constructor of a same class can be achieved using this()

EXAMPLE:

class A

A()

System.out.println("inside default constructor");

A(int x)

this();

System.out.println("inside parametrized constructor");

class Demo

public static void main(String[] args)

A a = new A(18);

OUTPUT: inside default constructor

inside parametrized constructor

132
EXAMPLE 2

class A

A()

this("ramu");

System.out.println("inside default constructor");

A(int x)

this();

System.out.println("inside parametrized constructor");

A(String s)

System.out.println("inside String parametrized constructor");

class Demo1

public static void main(String[] args)

A a = new A(18);

OUTPUT: inside String parameterized constructor

inside default constructor

inside parameterized constructor

133
MUTATORS or SETTERS and ACCESSOR or getters
Based on the object state modification methods can be classified into two types:
1. MUTATORS/SETTER: These are used to set or modify the value in the object.
2. ACCESSOR/GETTERS: These are used to get the value from the object.

Example 1: MUTATORS/SETTERS and ACCESSORS/GETTERS


class Credentials
{
private String un;
private String pwd;
void setUn(String username)
{
un=username;
}
void setPwd(String password)
{
pwd=password;
}
String getUn()
{
return un;
}
String getPwd()
{
return pwd;
}
}
class Demo
{
public static void main(String[] args)
{

134
Credentials c = new Credentials();

c.setUn(" ");
c.setPwd("3443");

System.out.println(c.getUn());
System.out.println(c.getPwd());
}
}
Output : 34343

Example 2: MUTATORS/SETTERS and ACCESSORS/GETTERS


class Student
{
private String name;
private int age;
private float height;

void setName(String sname)


{
name=sname;
}
void setAge(int sage)
{
age=sage;
}
void setHeight(float sheight)
{
height=sheight;
}

135
String getName()
{
return name;
}
int getAge()
{
return age;
}
float getHeight()
{
return height;
}
}
class Demo
{
public static void main(String[] args)
{
Student s = new Student();
s.setName("Subbu");
s.setAge(24);
s.setHeight(6.1f);
System.out.println(s.getName());
System.out.println(s.getAge());
System.out.println(s.getHeight());
}
}
Output: subbu
24
6.1

136
PASS BY VALUE
In java the parameter can be passed only in the value mode. Java does not support the any other passing
techniques other than pass by value.
In c programming language it has both pass by value and pass by reference, but java does not support
concept of pointer hence pass by reference is ruled out in java.
Example: PASS BY VALUE IN JAVA.
class Test
{
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
}
class Demo
{
public static void main(String[] args)
{
int a=10; //LV
int b=20; //LV
Test t = new Test();

System.out.println("before swapping:");
System.out.println("the value of a is :" + a);// 10
System.out.println("the value of b is :" + b);// 20

t.swap(a,b);
System.out.println("after swapping:");
System.out.println("the value of a is :" + a); // 20
System.out.println("the value of b is :" + b);// 10

137
}
}
Output: before swapping:
the value of a is :10
the value of b is :20
after swapping:
the value of a is :10
the value of b is :20

NOTE: Whatever the changes made in called method is reflected on calling method.

METHOD OVERLOADING IN JAVA


In c language we can write any number of functions but the functions name should be unique(no two
functions should have the same name).
Example of c language:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a=10, b=20, c=30;
float x=1.2, y=2.2, z=3.2;
double p=10.222, q=20.2433, r=30.3233;
printf(“%f”, add3(p,q));
printf(“%f”, add4(a,x));
printf(“%f”, add10(a,b,c));
int add1(int x, int y)
{
return x+y;
}
int add2(float x, float y)
{
return x+y;
138
}
int add3(double x, double y)
{
return x+y;
}
int add4(int x, float y)
{
return x+y;
}
int add5(int x, double y)
{
return x+y;
}
int add6(float x, double y)
{
return x+y;
}
int add7(float x, int y)
{
return x+y;
}
int add8(double x, int y)
{
return x+y;
}
int add9(double x, float y)
{
return x+y;
}
int add10(int x, int y, int z)
{
return x+y+z;

139
}
int add11(float x, float y, float z)
{
return x+y+z;
}
int add12(double x, double y, double z)
{
return x+y+z;

}
int add13(int x, float y, double z)
{
return x+y+z;
}
int add14(int x, float y, float z)
{
return x+y+z;
}
int add15(int x, double y, double z)
{
return x+y+z;
}
int add16(float x, int y, int z)
{
return x+y+z;
}
Note:
In the above c program even though we are properly performing addition operation but still we should
remember multiple functions name which is complex
The above problem can be overcome using the METHOD OVERLOADING concept in java.

140
Example: // METHOD OVERLOADING IN JAVA
class Demo
{
public static void main(String[] args)
{
Test t = new Test();
int a=10, b=20, c=30; // NAME OF THE METHOD
float x=1.2f, y=2.2f, z=3.2f; // NUMBER OF PARAMETER
double p=10.222, q=20.2433, r=30.3233; // DATATYPES OF THE PARAMETER

// ORDER OF THE PARAMETER


System.out.println(t.add(p,q));
System.out.println(t.add(a,x));
System.out.println(t.add(a,b,c));
System.out.println(t.add(a,p));
}
}
class Test
{
int add(int x, int y)
{
return x+y;
}
float add(float x, float y)
{
return x+y;
}
double add(double x, double y)
{
return x+y;
}

141
float add(int x, float y)
{
return x+y;
}
double add(int x, double y)
{
return x+y;
}
double add(float x, double y)
{
return x+y;
}
float add(float x, int y)
{
return x+y;
}
double add(double x, int y)
{
return x+y;
}
double add(double x, float y)
{
return x+y;
}
int add(int x, int y, int z)
{
return x+y+z;
}
float add(float x, float y, float z)
{
return x+y+z;
}

142
double add(double x, double y, double z)
{
return x+y+z;

}
double add(int x, float y, double z)
{
return x+y+z;
}
float add(int x, float y, float z)
{
return x+y+z;
}
double add(int x, double y, double z)
{
return x+y+z;
}
float add(float x, int y, int z)
{
return x+y+z;
}
}
Output: 30.4653
11.2
60
20.222

Multiple methods with the same name is called as method over-loading . Whenever call is made for
overloaded method the compiler will resolve the

method call in following ways:


1.NAME OF THE METHOD
2.NUMBER OF PARAMETER
143
3.DATATYPES OF THE PARAMETER
4.ORDER OF THE PARAMETER

TYPES OF METHODS OR BLOCKS


The types of methods or blocks are :
1. instance methods and instance block
2. static methods and static blocks

class Demo
{
int a = 10;
int b = 20; // instance variables
public static void main(String[] args)
{
Demo d1 = new Demo();
d1.fun();
}
void fun() // instance methods
{
int c=a+b;
System.out.println(c);
}
{
System.out.println("hello world"); // instance block
}
}
NOTE: Instance blocks are anonymous (nameless) blocks which are executed during the object creation
before the constructor call

144
EXAMPLE:
class A
{
A()
{
System.out.println("inside the default constructor");
}
A(int x)
{
System.out.println("inside the parametrized constructor");
}
{
System.out.println("inside the instance block");
}
}
class Demo2
{
public static void main(String []args)
{
A a =new A();
}
}
OUTPUT: inside the instance block
inside the default constructor

NOTE: A class can have any number of instance blocks the order of execution is always from top-bottom.

EXAMPLE:
class A
{
{

145
System.out.println("inside the first instance block");
}
{
System.out.println("inside the second instance block");
}
{
System.out.println("inside the third instance block");
}
}
class Demo2
{
public static void main(String []args)
{
A a =new A();
}
}
OUTPUT:
inside the first instance block
inside the second instance block
inside the third instance block

NOTE: The order of the memory allocation is 1. instance variables 2. instance blocks (non-static blocks) 3.
constructor

EXAMPLE:
class A
{
//int a=10;
A()
{
System.out.println("inside the constructor");
}

146
{
System.out.println("inside the instance block");
}
float f = 12.14f;
void fun()
{
System.out.println("inside the instance method");
}
}
class Demo2
{
public static void main(String []args)
{
System.out.println("inside the main method");
A a =new A();
}
}
OUTPUT: inside the main method
inside the instance block
inside the constructor

NOTE: Unlike constructors instance blocks are used to initialize the instance variables

EXAMPLE:
class A
{
int age; //IV
//IB
{
age=16;
System.out.println("the age is"+age);
}

147
}
class Demo2
{
public static void main(String []args)
{
System.out.println("inside the main method");
A a =new A();
}
}
OUTPUT: inside the main method
the age is 16

NOTE: Instance blocks are used to provide the logic which is common for all the objects. If the logic is
specific for different objects then we can use this code in the constructor.

EXAMPLE:
class Student
{
int register_number; //IV
//IB
{
System.out.println("WELCOME TO Java classes");
}
Student() //UDDC
{
register_number=20;
System.out.println("your registration number is :" +register_number);
}
Student(int x) //UDPC
{
register_number = x;
System.out.println("your registration number is :" +register_number);

148
}
}
class Demo
{
public static void main(String []args)
{
//System.out.println("inside the main method");
Student s1 =new Student();
Student s2 =new Student(21);
}
}
OUTPUT: WELCOME TO Java classes
your registration number is :20
WELCOME TO Java classes
your registration number is :21

NOTE: The memory for instance variables and methods and blocks are always given in the heap memory
segment.

import java.util.*;
class Student
{
private String name;
private int age;
private String schoolName;

public void setData()


{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER THE NAME : ");
name = sc.next();
System.out.println("ENTER THE AGE : ");
age = sc.nextInt();
149
System.out.println("ENTER THE SCHOOL NAME : ");
schoolName = sc.next();
}
public void display()
{
System.out.println("name is :"+name);
System.out.println("age is :"+age);
System.out.println("schoolname is :"+schoolName);
}
}
class Demo
{
public static void main(String[] args)
{
Student s1 = new Student();
s1.setData();
s1.display();
}
}
OUTPUT: sagar 25 jain

NOTE: Whenever the value is same for multiple objects instead of having multiple copies we can have a
single copy.
In the above program school-name is common for all the students hence we can have a single copy and it
can be shared among the objects
such common elements we should make it as static in the program to improve memory efficiency.

EXAMPLE 2
private String name;
private int age;
static private String schoolName = "jain";

150
NOTE: whenever java program stats executing always static members will execute first.

the order of execution is:


1. --> static variables
2. --> static blocks
3. --> static methods

STATIC METHODS:
Static methods are such methods present in the class where a method is prefixed with static keyword.
static methods are class methods which are shared by multiple objects. they are not associated with
objects.
They can be accessed using the reference variable or class name

EXAMPLE:
class Test
{
void fun1()
{
System.out.println("inside the instance method");
}
static void fun2()
{
System.out.println("inside the static method");
}
}
class Demo2
{
public static void main(String[] args)
{
Test t1 =new Test();
t1.fun1();
151
t1.fun2();

Test.fun2();
}
}
OUTPUT: inside the instance method
inside the static method
inside the static method
refer the fig:

EXAMPLE:
class Test
{
static int a,b,c;//SV
int x,y,z; //IV
static //SB
{
a=10;
b=20;
c=30;
}
static void fun1() //SM
{
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
{ //IB
x=40;
y=50;
z=60;
a=100;

152
b=200;
c=300;
}
void fun2() //IM
{
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
class Demo
{
public static void main(String[] args)
{
Test t1 = new Test();
Test.fun1();
Test t2 = new Test();
t2.fun2();
}
}
OUTPUT: 100
200
300
40
50
60
100
200
300

153
INSATNCE METHOD:
1. It is also called as non-static method.
2. If we want to call the method where objects should be created.
3. Can be accessed using the object reference variable
4. It is always deals with object level

STATIC METHOD:
1. It is also called as class method.
2. No need of object creation for method call
3. Can be accessed using the both object ref and class name
4. It is always deals with class level

STATIC BLOCKS:
Static blocks are executed during the class loading. There execution is before the execution of main
method.
They always initialize the static variables.
If a block is prefixed with static keyword then it is called as static block
Example:
static{ static
{

}
}

EXAMPLE: // Static blocks


class A
{
int x;
static int y;

{
x=10;
154
System.out.println("inside the instance block");
System.out.println(x);
}
static
{
y=20;
System.out.println("inside the static block");
System.out.println(y);
}
A()
{
System.out.println("iniside the constructor ");
}
}
class Demo1
{
public static void main(String[] args)
{
A a =new A();
}
}

INSTANCE BLOCK:
1. It is used to initialize the instance variable.
2. It will always executes during object creation and before the constructor call.
3. Memory will be allocated each time when a new object is created
STATIC BLOCKS:
1. It is used to initialize the static variable.
2. It is executed during the class loading and before the execution of main method
3. Memory will be allocated only once.

155
CAN WE EXECUTE A JAVA PROGRAM WITHOUT A MAIN METHOD?
Till java 1.6 version a java program can be executed without a main method.
From 1.7 version onwards main method is mandatory.

156
157
158
POLYMORPHISM

 Polymorphism is one of the importent object oriented feature in java.

 To achive polymorphism we need the concept of 'parent refernce to child object'.

 POLY means many MORPHS means forms. An object with many forms is called as POLYMORPHISM.

NOTE: In the above program v.Move() is polymorphic statement because it is providing 3 differnt outputs ---> 1:3

POLYMORPHISM is used to achive the 'code reduction' and flexibilty of the program.

EXAMPLE 1:

class Plane

String name;
159
int wheel;

void takeOff()

System.out.println("plane is taking off");

void fly()

System.out.println("plane is flying");

void land()

System.out.println("plane is landing");

class CargoPlane extends Plane

void takeOff()

System.out.println("Cargoplane is taking off");

void fly()

System.out.println("Cargoplane is flying with the low speed"); }

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane

void fly()

System.out.println("Passengerplane is flying with the medium speed");

160
void CarryPassenger()

System.out.println("Passengerplane is carrying the people");

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Demo

public static void main(String[] args)

Plane ref = new Plane();

//CargoPlane cp =new CargoPlane(); //[child refernce to child object]

ref = new CargoPlane();

ref.takeOff();

ref.fly();

ref.land();

//ref.CarryCargo();

ref = new PassengerPlane();

ref.takeOff();

ref.fly();

ref.land();

//ref.CarryPassenger();

ref = new FighterPlane();

161
ref.takeOff();

ref.fly();

ref.land();

//ref.CarryArms();

OUTPUT: Cargoplane is taking off

Cargoplane is flying with the low speed

plane is landing

plane is taking off

Passengerplane is flying with the medium speed

plane is landing

plane is taking off

Fighterlane is flying with the high speed

plane is landing

NOTE: In the above program we have achived polymorphism by using the concept of 'parent ref to child object' but
by this technique we cannot access the specialized methods.

EXAMPLE 2:

class Plane

String name;

int wheel;

void takeOff()

System.out.println("plane is taking off");

void fly()

System.out.println("plane is flying");

void land()

System.out.println("plane is landing");

}
162
class CargoPlane extends Plane

void takeOff()

System.out.println("Cargoplane is taking off");

void fly()

System.out.println("Cargoplane is flying with the low speed");

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane

void fly()

System.out.println("Passengerplane is flying with the medium speed");

void CarryPassenger()

System.out.println("Passengerplane is carrying the people");

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

163
void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Airport

void allow(Plane ref)

ref.takeOff();

ref.fly();

ref.land();

class Demo

public static void main(String[] args)

CargoPlane cp =new CargoPlane(); //[child refernce to child object]

PassengerPlane pp = new PassengerPlane();

FighterPlane fp = new FighterPlane();

Airport a = new Airport();

a.allow(cp);

a.allow(pp);

a.allow(fp);

OUTPUT: Cargoplane is taking off

Cargoplane is flying with the low speed

plane is landing

plane is taking off

Passengerplane is flying with the medium speed

plane is landing

plane is taking off

164
Fighterlane is flying with the high speed

plane is landing

STEPS TO ACHIEVE POLYMORPHISM:

1. INHERITANCE must be present.

2. classes must be related

3. METHOD OVERRIDING should be present

4. use the concept of 'PARENT REF TO CHILD OBJECT'

5. POLYMORPHISM

NOTE: To access the specialized methods we must perform 'DOWNCASTING'.

EXAMPLE:

class Plane

String name;

int wheel;

void takeOff()

System.out.println("plane is taking off");

void fly()

System.out.println("plane is flying"); }

void land()

System.out.println("plane is landing");

class CargoPlane extends Plane

void takeOff()

System.out.println("Cargoplane is taking off");

165
void fly()

System.out.println("Cargoplane is flying with the low speed");

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane

void fly()

System.out.println("Passengerplane is flying with the medium speed");

void CarryPassenger()

System.out.println("Passengerplane is carrying the people");

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Demo

166
public static void main(String[] args)

Plane ref = new Plane();

ref =new CargoPlane(); // DOWNCASTING

//ref = new CargoPlane(); ?/ UPCASTING

ref.fly();

ref.land();

((CargoPlane)(ref)).CarryCargo();

//ref = new PassengerPlane();

//ref = new FighterPlane();

OUTPUT: Cargoplane is flying with the low speed

plane is landing

Cargoplane is carrying the goods

UPCASTING and DOWNCASTING:

UPCASTING: upcasting refers to the creation of child object and assigning the ref to it.

advantage of upcasting is achieving the polymorphism.

DOWNCASTING: it means temporary converting the parent ref to child type to access the specialized method

WHAT IS RUNTIME POLYMORPHISM AND VIRTUAL POLYMORPHISM?

--> METHOD OVERLOADING --> VIRTUAL POLYMORPHISM --> STATIC POLYMORPHISM --> EARLY BINDING.

--> METHOD OVERRIDING --> RUNTIME POLYMORPHISM --> DYNAMIC POLYMORPHISM --> LATE BINDING.

1. VIRTUAL POLYMORPHISM USING THE METHOD OVERLOADING.

class Plane

String name;

int wheel;

void takeOff()

167
{

System.out.println("plane is taking off");

void fly()

System.out.println("plane is flying");

void land()

System.out.println("plane is landing");

class CargoPlane extends Plane

void takeOff()

System.out.println("Cargoplane is taking off");

void fly()

System.out.println("Cargoplane is flying with the low speed");

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane

void fly()

System.out.println("Passengerplane is flying with the medium speed");

168
void CarryPassenger()

System.out.println("Passengerplane is carrying the people");

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Airport

void allow(CargoPlane ref)

ref.takeOff();

ref.fly();

ref.land();

void allow(PassengerPlane ref)

ref.takeOff();

ref.fly();

ref.land();

void allow(FighterPlane ref)

ref.takeOff();

ref.fly();

169
ref.land();

class Demo

public static void main(String[] args)

CargoPlane cp = new CargoPlane();

PassengerPlane pp = new PassengerPlane();

FighterPlane fp = new FighterPlane();

Airport a = new Airport();

a.allow(cp);

a.allow(pp);

a.allow(fp);

2. RUNTIME POLYMORPHISM USING THE METHOD OVERRIDING.

class Plane

String name;

int wheel;

void takeOff()

System.out.println("plane is taking off");

void fly()

System.out.println("plane is flying");

void land()

System.out.println("plane is landing");

170
}

class CargoPlane extends Plane

void takeOff()

System.out.println("Cargoplane is taking off");

void fly()

System.out.println("Cargoplane is flying with the low speed");

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane

void fly()

System.out.println("Passengerplane is flying with the medium speed");

void CarryPassenger()

System.out.println("Passengerplane is carrying the people");

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

171
void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Airport

void allow(Plane ref)

ref.takeOff();

ref.fly();

ref.land();

class Demo1

public static void main(String[] args)

CargoPlane cp = new CargoPlane();

PassengerPlane pp = new PassengerPlane();

FighterPlane fp = new FighterPlane();

Airport a = new Airport();

a.allow(cp);

a.allow(pp);

a.allow(fp);

RULES OF METHOD OVERRIDING

RULE 1: In method overriding the method signature should be same. IE The method name and argument type should
be same in both parent and child class.

Example:

public void test(int a)

---------
172
}

--> test(int a) // method signature

FINAL KEYWORD:

This keyword can be used or applied on :

1. on class

2. on method

3. on variable

final keyword on class:

If a class is made as final then that class will not participate in inheritance.

Example:

final class A

void fun1()

System.out.println("INSIDE PARENT CLASS");

class B extends A

void fun1()

System.out.println("INSIDE child CLASS");

public static void main(String[] args)

A a = new A();

a.fun1();

B b = new B();

b.fun1();

173
}

final keyword on method:

The methods which are made as final can be inherited to the child class but can not be overridden.

Example:

class A

final void fun1()

System.out.println("INSIDE PARENT CLASS");

class B extends A

void fun1()

System.out.println("INSIDE child CLASS");

public static void main(String[] args)

//A a = new A();

//a.fun1();

B b = new B();

b.fun1();

//b.fun1();

final keyword on variable:

If the variable is made as final then the value of the variable can not be alterd in other words it will become
static in nature.

Example:

class A

final int speed = 300;


174
int fun1()

speed = 250;

//System.out.println(spped);

return speed;

class B

public static void main(String[] args)

A a = new A();

System.out.println(a.fun1());

RULE 2: METHOD OVERRIDING W.R.T STATIC METHODS:

non-static to static method overriding and static to non-static method overriding is not permited in java.

Example:

class A

void fun1()

System.out.println("inside the parent class");

class B extends A

static void fun1()

175
{

System.out.println("inside the child class");

public static void main(String[] args)

//A a = new A();

//a.fun1();

B b = new B();

b.fun1();

NOTE : STATIC members cannot be overriding.

INHERITANCE

 Inheritance is a process of a class acquiring the properties(variables) and behaviour (methods) from the other class.

 Inheritance can be achieved using extends keywords.

 Parent class is a class which gives the properties and behaviour to another class.

 child class is a class which inherit the properties and behaviour from its parent class.

ADVANTAGE OF INHERITANCE:

1. CODE REUSABLITY.

2. less time for developing the s/w.

Example:1

// unrelated classes
176
class visitor

String name;

int ph_no;

class Hospital

void Doctor_conslut()

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

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

NOTE 01: In order to relate two classes we can use extends keywords.

Example 02:

// related classes

class visitor

String name; // parent class or super class

int ph_no;

class Hospital extends visitor

void Doctor_conslut() // child class or sub class

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

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

NOTE 02:

Inheritance promotes IS- A relationship.

NOTE 03:

Whenever the object of child class is created the memory is not only allocated for the instance variable of a child class
but it also allocates the instance variable of the parent class.

EXAMPLE:
177
// note3

class A

int i =10; // parent class or super class

class B extends A

int j = 20;

class Demo

public static void main(String[] args)

B b= new B();

System.out.println(b.i);

System.out.println(b.j);

NOTE: 4

Private members will not participate in the inheritance. This rule is made to promote ENCAPSULATION

EXAMPLE:

// note4

class A

private int i =10; // parent class or super class

class B extends A

int j = 20;

178
}

class Demo

public static void main(String[] args)

B b= new B();

System.out.println(b.i);

System.out.println(b.j);

OUTPUT: i has private access in A

System.out.println(b.i);

NOTE 05:

Child class can call the instance method of parent class directly.

EXAMPLE:

// note5

class A

void fun1() //IM

System.out.println("inside the fun1");

class B extends A

void fun2() //IM

System.out.println("inside the fun2");

class Demo

public static void main(String[] args)

179
{

B b= new B();

b.fun2();

b.fun1();

OUTPUT:

inside the fun2

inside the fun1

NOTE 06:

The child class can call the inherited static methods directly.

EXAMPLE:

// note4

class A

static void fun1()

System.out.println("inside the fun1");

class B extends A

void fun2()

System.out.println("inside the fun2");

class Demo

public static void main(String[] args)

B b= new B();

b.fun2();

180
b.fun1();

OUTPUT: inside the fun2

inside the fun1

NOTE 07:

Unlike the private members constructors are also doesn’t participate in the inheritance.

i.e., parent class constructor would not be inherited to the child class rather the control from the child class will go
the super class(parent class)

constructor and the code will get executed.

EXAMPLE:

// note7

class A

int i; //IV

int j; //IV

A() //UDDC

//super();

i=1111;

j=2222;

class B extends A

B() //UDDC

super();

void display() //IM

System.out.println("i value is "+i);

System.out.println("j value is "+j);

}
181
}

class Demo

public static void main(String[] args)

B b= new B();

b.display();

OUTPUT: i value is 1111

J value is 2222

// note7 example:2

class A

int i;

int j;

A(int x)

super();

i=1111;

j=2222;

class B extends A

B()

super();

void display()

System.out.println("i value is "+i);

System.out.println("j value is "+j);

182
}

class Demo

public static void main(String[] args)

B b= new B();

b.display();

OUTPUT: COMPILATION ERROR

In the child class during the execution of super() a call is made to the default constructor (parent class) if the default
constructor is not present then we will get compilation error

NOTE 08:

Even though the parameterized constructor of a sub-class is called yet, the default constructor in the super class is
executed first then the parameterized constructor of the sub-class is executed.

// note8

class A

int i,j; //IV

A() //UDDC

//super();

System.out.println("inside the default constructor");

class B extends A

B() //UDDC

super();

B(int i, int j) //UDPC

183
{

super();

this.i=i;

this.j=j;

void display() //IM

System.out.println("i value is "+i);

System.out.println("j value is "+j);

class Demo

public static void main(String[] args)

B b= new B(10,20);

b.display();

OUTPUT: inside the default constructor

i value is 10

j value is 20

NOTE 09:

If the parameterized constructor of the super class has to be executed then parameter super should be used in the
sub-class

EXAMPLE:

// note9

class A

int i,j;

int a,b; //IV

A(int a,int b) //UDPC

{
184
this.a=a;

this.b=b;

System.out.println("inside the parent class constructor");

class B extends A

B(int i, int j) //UDPC

super(30,60);

this.i=i;

this.j=j;

void display()

System.out.println("i value is "+i);

System.out.println("j value is "+j);

System.out.println("a value is "+a);

System.out.println("b value is "+b);

class Demo

public static void main(String[] args)

B b= new B(10,20);

b.display();

OUTPUT:

-------

inside the parent class constructor

i value is 10

j value is 20

185
a value is 30

b value is 60

TYPES OF INHERITANCE:

1. SINGLE INHERITANCE

2. MULTI-LEVEL INHERITANCE

3. HIERARCHICAL INHERITANCE

4. MULTIPLE INHERITANCE

5. HYBRID INHERITANCE

6. CYCLIC INHERITANCE

NOTE: In Java single,multi-level and hierarchical inheritance is supported and other types are not supported.

Why in java multiple inheritance is not supported?

--> In case of multiple inheritance it will result in ambiguity(confusion).This problem is referred as 'DIAMOND
SHAPE' problem.

EXAMPLE:

class A

int i = 10;

class B extends A

int i =20;

class C extends A,B

void display()

System.out.println(i);

class Demo

{
186
public static void main(String[] args)

C c1 = new C();

c1.display();

OUTPUT: COMPILATION ERROR

2. EXAMPLE FOR MULTI-LEVEL INHERITANCE

class A

void fun1()

System.out.println("inside the fun1 method");

class B extends A

void fun2()

System.out.println("inside the fun2 method");

class C extends B

void fun3()

System.out.println("inside the fun3 method");

class Demo

public static void main(String[] args)

187
C c1 =new C();

c1.fun1();

c1.fun2();

c1.fun3();

OUTPUT: inside the fun1 method

inside the fun2 method

inside the fun3 method

6. EXAMPLE FOR CYCLIC INHERITANCE

class A extends B

void fun1()

System.out.println("inside the fun1 method");

class B extends A

void fun2()

System.out.println("inside the fun2 method");

class Demo

public static void main(String[] args)

B b1 =new B();

b1.fun1();

b1.fun2();

188
OUTPUT: error: cyclic inheritance involving A

class A extends B

super keyword

During the inheritance if the parent class and class having the variable name and the name clash would occur and
priority is given to child class.

instance variable.

In order to access the instance variable of parent class we will use super keyword.

// EXAMPLE FOR SUPER KEYWORD

class A

int x = 10;

class B extends A

int x=20;

void fun2()

System.out.println(x); // 20

System.out.println(this.x); // 20

System.out.println(super.x); // 10

class Demo

public static void main(String[] args)

B b1 =new B();

b1.fun2();

this keyword : it will alwys points the currently executing object.

this() : it is used to call the constructor within the same class.


189
super() : it is used to call the constructor of the parent class

super keyword : it is used to access the instance variable of parent class.

this() and super()

NOTE: Inside the constructor the first statement should be either this() or super(). If the user is not using either
super() or this() then compiler

by default will add super() to the constructor.

EXAMPLE:

class A

A()

super() --> added by the compiler

System.out.println("inside default constructor");

NOTE: super() and this() can not be placed in the same constructor.

EXAMPLE:

class A

A()

super();

this();

System.out.println("inside default constructor");

EXECUTION OF THE INSTANCE MEMBERS IN INHERITANCE:

EXAMPLE:

class Parent

int x = 10; //IV

//IB
190
{

System.out.println("parent class first instance block");

//IB

fun1();

System.out.println("parent class second instance block");

Parent() //UDDC

System.out.println("parent class constructor");

void fun1() //IM

System.out.println("parent class first instance method");

class Child extends Parent

int y=20; //IV

//IB

System.out.println("child class first instance block");

//IB

fun2();

System.out.println("child class second instance block");

Child() //UDDC

System.out.println("child class constructor");

void fun2() //IM

191
{

System.out.println("child class first instance method");

public static void main(String[] args)

Child c1= new Child();

OUTPUT: parent class first instance block

parent class first instance method

parent class second instance block

parent class constructor

child class first instance block

child class first instance method

child class second instance block

child class constructor

STEPS FOR EXECUTION OF INTANCE MEMBERS IN IN HERITANCE:

1. Identify all the instance members of the parent class

2. execute instance variable fallowed by instance blocks and method and finally execute parent class constructor

3. Identify all the instance members of the child class

4. execute instance variable fallowed by instance blocks and method and finally execute child class constructor

EXECUTION OF THE STATIC MEMBERS IN INHERITANCE:

EXAMPLE:

class Parent

static int x = 10;

static

System.out.println("parent class first static block");

static

192
{

fun1();

System.out.println("parent class second static block");

Parent()

System.out.println("parent class constructor");

static void fun1()

System.out.println("parent class first static method");

class Child extends Parent

static int y=20;

static

System.out.println("child class first static block");

static

fun2();

System.out.println("child class second static block");

Child()

System.out.println("child class constructor");

static void fun2()

System.out.println("child class first static method");

193
public static void main(String[] args)

Child c1= new Child();

OUTPUT: parent class first static block

parent class first static method

parent class second static block

child class first static block

child class first static method

child class second static block

parent class constructor

child class constructor

STEPS FOR EXECUTION OF STATIC MEMBERS IN INHERITANCE:

1. Identify all the static members of the parent class

2. execute static variable fallowed by static blocks and method.

3. Identify all the static members of the child class

4. execute static variable fallowed by static blocks and method.

5. then object is created during object creation constructor will be executed.

EXECUTION OF BOTH STATIC AND INSTANCE MEMBERS IN INHERITANCE:

EXAMPLE:

class Parent

static int x = 10; // static variable

int y = 20; // instance variable

static

System.out.println("parent class first static block");

194
// instance block

System.out.println("parent class first instance block");

// instance block

test1();

System.out.println("parent class second instance block");

// constructor

Parent()

System.out.println("parent class constructor");

// static method

static void fun1()

System.out.println("parent class first static method");

System.out.println(x);

// instance method

void test1()

System.out.println("parent class first instance method");

System.out.println(y);

class Child extends Parent

static int a=20;

int b=40;

static

System.out.println("child class first static block");

195
}

test2();

System.out.println("child class first instance block");

Child()

System.out.println("child class constructor");

static void fun2()

System.out.println("child class first static method");

System.out.println(a);

void test2()

System.out.println("child class first instance method");

System.out.println(b);

public static void main(String[] args)

System.out.println("inside the main method");

Child.fun1();

Child.fun2();

Child c1= new Child();

OUTPUT: parent class first static block

child class first static block

inside the main method

parent class first static method

10

child class first static method

196
20

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

parent class first instance block

parent class first instance method

20

parent class second instance block

parent class constructor

child class first instance method

40

child class first instance block

child class constructor

STEPS FOR EXECUTION OF STATIC MEMBERS AND INSTANCE MEMBERS IN INHERITANCE:

1. Identify the static members(both parent and child class)

2. execute the sv sb and sm of parent class and execute it in the top-bottom order

3. execute the main method

4. new keyword---> object creation

5. identify the instance members( of both parent and child class)

6. execute the iv ib im and constructor of parent class

7. execute the iv ib im and constructor of child class

INHERITED, OVERRIDDEN, SPECILIZED METHODS.

INHERITED METHOD : any method which is acquired by the child class from the parent class is called as inherited
method.

OVERRIDDEN METHOD : changes performed on inherited method is called as overridden methods

SPECIALIZED METHOD : methods which are unique to child class is called as specialized methods

EXAMPLE:

class Plane

String name;
197
int wheel;

void takeOff()

System.out.println("plane is taking off");

void fly()

System.out.println("plane is flying");

void land()

System.out.println("plane is landing");

class CargoPlane extends Plane

void fly()

System.out.println("Cargoplane is flying with the low speed");

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane

void fly()

System.out.println("Passengerplane is flying with the medium speed");

void CarryPassenger()

System.out.println("Passengerplane is carrying the people");

198
}

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Demo

public static void main(String[] args)

CargoPlane cp =new CargoPlane();

PassengerPlane pp = new PassengerPlane();

FighterPlane fp = new FighterPlane();

cp.takeOff();

cp.fly();

cp.land();

cp.CarryCargo();

pp.takeOff();

pp.fly();

pp.land();

pp.CarryPassenger();

OUTPUT: plane is taking off

Cargoplane is flying with the low speed

199
plane is landing

Cargoplane is carrying the goods

plane is taking off

Passengerplane is flying with the medium speed

plane is landing

Passengerplane is carrying the people

METHOD OVERRIDING

class Parent

void marry()

s.o.p("marry @ age of 26"); // overriden method w.r.t parent class

class Child extends Parent

void marry()

s.o.p("marry @ age of 30"); // overriding method w.r.t child class

void job() // SPECILIZED METHODS.

The method which is inherited by the child class from the parent class and if the child class modifies or implements
the inherited methods such

Process is called as METHOD OVERRIDING.

EXAMPLE:

class Vehicle

{
200
void Move()

System.out.println("vehicle is moving"); // overriden method w.r.t parent class

class Bike extends Vehicle

void Move()

System.out.println("bike is moving medium speed");


// overriding method w.r.t child class }

class Car extends Vehicle

void Move()

System.out.println("Car is moving high speed");


// overriding method w.r.t child class }

class Truck extends Vehicle

void Move()

System.out.println("Truck is moving low speed");


// overriding method w.r.t child class }

class Demo1

public static void main(String[] args)

Bike b = new Bike();

Car c = new Car();

201
Truck t = new Truck();

b.Move(); // 1:1

c.Move(); // 1:1

t.Move(); // 1:1

OUTPUT: bike is moving medium speed

Car is moving high speed

Truck is moving low speed

PARENT REFERENCE TO CHILD OBJECT:

Parent reference to child object in method overriding is all about proving the parent object reference to the child
object to achieve the POLYMORPHISM.

EXAMPLE:

class Vehicle

void Move()

System.out.println("vehicle is moving"); // overriden method w.r.t parent class

class Bike extends Vehicle

void Move()

System.out.println("bike is moving medium speed");


// overriding method w.r.t child class }

class Car extends Vehicle

void Move()

202
System.out.println("Car is moving high speed");
// overriding method w.r.t child class }

class Truck extends Vehicle

void Move()

System.out.println("Truck is moving low speed");


// overriding method w.r.t child class }

class Demo1

public static void main(String[] args)

Vehicle v = new Vehicle();

v = new Bike(); //[child object with parent refernce]

v.Move();

v = new Car();

v.Move();

v = new Truck();

v.Move(); // 1:3 } }

OUTPUT: bike is moving medium speed

Car is moving high speed

Truck is moving low speed

RELATIONSHIPS IN JAVA

As a part of java application development we have to use entities as per the requirement.

relationships are used to provide the optimization over memory utilization, code reusability, execution time, ease of
share ability.

TYPES OF RELATIONSHIPS IN JAVA:

1.IS-A relationship

203
2.HAS-A relationship

IS-A : by using this we can achieve the concept of inheritance by doing so we can perform 'code reusability'.

HAS-A : It defines associations b/w the entities to improve the communication b/w the entities for better data
navigation.

NOTE: has-A relationships is of two types:

1. COMPOSITION

2. AGGREGATION

WHAT IS THE DIFFERENCE B/W COMPOSITION AND AGGREGATION ?

-->Aggregation refers to weak relationship whereas composition refers to strong relationship.

aggregation will have less dependency with enclosed object whereas composition will have more dependency with
enclosed object

aggregation members can be accessed when without enclosed object.

composition members cannot be accessed without enclosed object.

aggregate object is independent in nature.

compostion objects are dependent in nature.

EXAMPLE:

class os

String name;

int size;

public os(String name, int size)

this.name=name;

this.size=size;

public String getName()

204
return name;

public int getSize()

return size;

class charger

String brand;

String color;

public charger(String brand, String color)

this.brand=brand;

this.color=color;

public String getBrand()

return brand;

public String getColor()

return color;

class mobile

os o = new os("android",125); //strong relationship

public void hasA(charger c) //weak relationship

System.out.println(c.getBrand());

System.out.println(c.getColor());

205
class Demo1

public static void main(String[] args)

mobile m = new mobile();

charger c1 = new charger("samsung","white");

//System.out.println(m.o.getName());

//System.out.println(m.o.getSize());

m.hasA(c1);

m=null;

//System.out.println(o.getName());

//System.out.println(o.getSize());

System.out.println(c1.getBrand());

System.out.println(c1.getColor());

OUTPUT: samsung

white

samsung

white

ADAPTER CLASS:
Adapter class is a normal class in java which as empty body for all the abstract methods of an interface.

EXAPLE:

interface compute

void fun1();

void fun2();

void fun3();

void fun4();

void fun5();

void fun6();

206
class Adapter implements compute

public void fun1()

public void fun2()

public void fun3()

public void fun4()

public void fun5()

public void fun6()

class Test1 extends Adapter

public void fun1()

System.out.println("inside fun1 method");

class Test2 extends Adapter

public void fun4()

System.out.println("inside fun4 method");

207
}

class Demo3

public static void main(String[] args)

Test1 t1 = new Test1();

t1.fun1();

Test2 t4 = new Test2();

t4.fun4();

OUTPUT: inside fun1 method

inside fun4 method

MARKER INTERFACE:

Marker interface is a empty interface which does not contain any abstract methods or fields.

If a class implements a marker interface then it acquires a special behaviour.

example: if a class implements cloneable interface then a duplicate object with the same behaviour can be created.

examples for marker interface are:

1. Cloneable

2. Serialization

3. Runnable

OBJECT CLONING:

-->The process of creating duplicate object for an existed object is called as Object Cloning.

-->If we want to perform Object Cloning in Java application then we have to use the following steps.

1. Declare an User defined Class.

2. Implement java.lang.Cloneable interface inorder to make eligible any object for cloning.

3. Override Object class clone() method in user defined class.

208
public Object clone() throws CloneNotSupportedException

4. In Main class, in main() method, access clone() method over the respective object

EXAMPLE:

class Demo5 implements Cloneable

int a = 10;

public static void main(String[] args) throws Exception

Demo5 d = new Demo5();

System.out.println(d.a);

Demo5 d1=(Demo5)d.clone();

System.out.println(d1.a);

OUTPUT: 10

10

Difference b/w extends and implements

extends:

1. A class can inherit other class using the extends keyword.An interface can inherit another interface using the
extends keyword.

2. A subclass which extends super class may or may not override all the methods of superclass

3. An interface can extends any number of interface

4. A class can extends only one super class.

implements:

1. A class can be implemented other interface using implements keyword.

2. class implementing interface should provide body for all methods of interface

3. An interface can never implements other interface

4. A class can implement multiple interface simultaneously.

209
Difference b/w interface and abstract class

interface:

1.100% abstraction is achieved

2. interface are used when we don't know complete implementation

3. only abstract methods are allowed

4. Every methods inside interface are by default public and abstract

5. Every variables inside interface are by default public static final

6. following modifiers are not allowed for abstract methods static, private,strictfp,protected,final

7. interface cannot have static blocks

8. interface cannot have instance blocks

9. constructors are not allowed

abstract class

1. 0-100% abstraction can be achieved

2. abstract class is used when we know parent implementation

3. both abstract and concrete methods are allowed

4. every method present in abstract class need not to be public and abstract

5. every variables present in abstract class need not to be public static final

6. no such restrictions for methods

7. abstract class can have static block

8. abstract class can have instance block

9. construced are allowed

210
211
212

You might also like