You are on page 1of 131

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

Output: -1

12
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

-128 to 128 - 1

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

1. Primitive data Types Type Casting


15
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

will perform the following two actions.

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

byte b=128;

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

byte+byte=int
19
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

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

21
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

2. switch

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

System.out.println(j); } }

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

int j;

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

{ j=20; }

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

Break;

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

byte b=10;

27
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

onwards switch is able to allow String data type.

28
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

11

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

System.out.println(i);
39
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)

break;
42
}

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

87 92 37 59 64

57
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

Enter the marks of the students: 50

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

} } Output: 10 20 30 40 50

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

}}

OUTPUT: 10 30 the total sum is 30

69
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
abstraction
}
70
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

CREATION OF OBJECT USING 'new' KEYWORD:


71
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

NOTE: 1.Always program execution starts from the class where main method is present.
72
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();
l1.run();

73
}
}

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

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

83
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

public static void main(String[] args)

Plane ref = new Plane();

//CargoPlane cp =new CargoPlane(); //[child refernce to child object]

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

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

{
85
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");

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

87
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

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

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

void CarryPassenger()

System.out.println("Passengerplane is carrying the people");

class FighterPlane extends Plane

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

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

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

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

91
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 Airport

void allow(CargoPlane ref)

ref.takeOff();

ref.fly();

ref.land();

92
}

void allow(PassengerPlane ref)

ref.takeOff();

ref.fly();

ref.land();

void allow(FighterPlane ref)

ref.takeOff();

ref.fly();

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;

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

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

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

---------

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

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

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

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

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.
98
Example:

class A

void fun1()

System.out.println("inside the parent class");

class B extends A

static void fun1()

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.

99
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

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

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

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

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

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

102
class B extends A

void fun2() //IM

System.out.println("inside the fun2");

class Demo

public static void main(String[] args)

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

103
void fun2()

System.out.println("inside the fun2");

class Demo

public static void main(String[] args)

B b= new B();

b.fun2();

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;

104
class B extends A

B() //UDDC

super();

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

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;

105
class B extends A

B()

super();

void display()

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

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

106
//super();

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

class B extends A

B() //UDDC

super();

B(int i, int j) //UDPC

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

107
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

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

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

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

{
109
int i =20;

class C extends A,B

void display()

System.out.println(i);

class Demo

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

110
class C extends B

void fun3()

System.out.println("inside the fun3 method");

class Demo

public static void main(String[] args)

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

111
}

class Demo

public static void main(String[] args)

B b1 =new B();

b1.fun1();

b1.fun2();

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

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

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

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

EXECUTION OF THE INSTANCE MEMBERS IN INHERITANCE:

EXAMPLE:

class Parent

int x = 10; //IV

//IB

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

114
}

//IB

fun2();

System.out.println("child class second instance block");

Child() //UDDC

System.out.println("child class constructor");

void fun2() //IM

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

115
EXECUTION OF THE STATIC MEMBERS IN INHERITANCE:

EXAMPLE:

class Parent

static int x = 10;

static

System.out.println("parent class first static block");

static

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

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

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.

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

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

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

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

119
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

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

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

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


121
}

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

public static void main(String[] args)

CargoPlane cp =new CargoPlane();

PassengerPlane pp = new PassengerPlane();

FighterPlane fp = new FighterPlane();

cp.takeOff();

cp.fly();

122
cp.land();

cp.CarryCargo();

pp.takeOff();

pp.fly();

pp.land();

pp.CarryPassenger();

OUTPUT: plane is taking off

Cargoplane is flying with the low speed

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

123
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

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

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

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

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

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

126
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

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.

127
EXAMPLE:

class os

String name;

int size;

public os(String name, int size)

this.name=name;

this.size=size;

public String getName()

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

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

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

129
130
131

You might also like