You are on page 1of 316

CORE JAVA NOTES

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

15 chacters are sufficent.

5. We can not use reserved keyword as 'identiers'

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

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:

Reserved keywords for datatypes:

1.byte

2.short

3.int

4.float

5.double

6.char

7.long

8.boolean

Reserved keywords for flow control:

1.if

2.else

3.switch

4.case

5.default

6.for

7.do
8.while

9.break

10.continue

11.return

Reserved keywords for modifiers:

1.public

2.private

3.protected

4.static

5.final

6.abstract

7.synchronized

8.native

9.strictfp

10.transient

11.volatile

Reserved keywords for exception handling:

1.try

2.catch

3.finally

4.throw

5.throws

6.assert

Reserved keywords for classes:

1.class

2.package

3.import

4.extends

5.implements

6.interface

Reserved keywords for classes:

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

1.new
2.instanceOf

3.super

4.this

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

9. sachin$Tendulker -->VALID

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

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

Java is an Arch Nuetral 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.

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, it allocates and deallocates 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 seperate middleware service in the form of JAAS [Java Authetication

And Autherization Service] inorder 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 seperate module that is "J2EE/JAVA EE".

10. Multi Threadded:

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

There are two thread models

a)Single Thread Model

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 compilative 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 interpretor inside JVM.

12. High Performance:

JAVA is high performance programming language due to its rich set of features like Platform

independent, Arch Nuetral, Portable, Robust, Dynamic,......

List of all Java Keywords

Keywords or Reserved words are the words in a language that are used for some internal process or represent some
predefined actions. These words are therefore not allowed to use as a variable names or objects. Doing this will result
into a 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

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.

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.

EX1:

int Exception=10;

System.out.println(Exception);

Status: No Compilation Error

OP: 10

EX2:

String String="String";

System.out.println(String);

Status: No Compilation Error


OP: String

EX3:

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 .

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.

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.

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.

1. Arithmetic Operators:

+, -, *, /, %, ++, --

2. Assignment Operators:

=, +=, -=, *=, /=, %=,.....

3. Comparision Operators:

==, !=, <, >, <=, >=,.....

4. Boolean Logical Operators:

&, |, ^

5. Bitwise Logical Operators:

&, |, ^, <<, >>,...

6. Short-Circuit Operators:

&&, ||

7. Ternary Operator:

Expr1? Expr2: Expr3;

Ex1:

-----

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

OP: 10

10

12

12

10

10

EX:

----

class Test

public static void main(String[] args)

int a=5;

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

Status: No Compilation Error

OP: -1

EX:

----

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

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

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

2. 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 variablers onthe basis of data types then we have to use the

following formula.

n-1 n-1

-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

-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

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

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:

--------

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:

class Sample

public static void main(String[] args)

byte b=65;

char c=b;

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

}
Status: Compilation Error

Example:

--------

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:

--------

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:

class Sample

public static void main(String[] args)

byte b=128;

System.out.println(b);

Status: Compilation Error,possible loss of precision.

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

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

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

Example:

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:

---------

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

byte+short=int

short+int=int

byte+long=long

long+float=float

float+double=double

Example:

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:

---------

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.

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:

--------

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:

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

-->1. if

-->2. switch

3. Iterative Statements:

-->1. for

-->2. while

-->3. do-while

4. Transfer statements:
-->1. break

-->2. continue

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

1. if:

------

syntax-1:

---------

if(condition)

---instructions----

Syntax-2:

---------

if(condition)

---instuctions----

else

{
----instructions----

Syntax-3:

---------

if(condition)

---instructions----

else if(condition)

---instruction----

else if(condition)

---instructions----

----

----

else

----instructions----

Example:

--------

class Test

public static void main(String[] args)

int i=10;

int j;
if(i==10)

j=20;

else

j=30;

System.out.println(j);

Status: No Compilation Error

OP: 20

Example:

---------

class Demo

public static void main(String[] args)

int i=10;

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

--------

class Test

public static void main(String[] args)

final int i=10;

int j;

if(i == 10)

j=20;

System.out.println(j);

}}

Status: No Compilation Error

OP: 20

EX6:

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;

else

j=30;

System.out.println(j);

Status: No Compilation Error

op : 30

EX:

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.

switch

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

conditions checkings.

Syntax:

--------

switch(Var)

case 1:

-----instructions-----

break;

case 2:

----instructions------

break;

----

----

case n:

----instructions-----

break;

default:

----instructions-----

break;

Example:

---------
class Demo

public static void main(String[] args)

int i=10;

switch(i)

case 5:

System.out.println("Five");

break;

case 10:

System.out.println("Ten");

break;

case 15:

System.out.println("Fifteen");

break;

case 20:

System.out.println("Twenty");

break;

default:

System.out.println("Default");

break;

Op:Ten

Rules to write switch:

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

---------

byte b=10;

switch(b)

----

Status: No Compilation Error

Example:

---------

long l=10;

switch(l)

----

Status: Compilation Error.

Example:

---------

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

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

onwards switch is able to allow String data type.

Example:

---------

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 with out cases and with default, we

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

Example:

---------

int i=10;

switch(i)

{}

Status: No Compilation Error

OP: No Output.

Example:

--------

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 continously right from matched case untill it

encounter either break statement or end of switch.

Example:

---------

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

Status: No Compilation Error

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

---------

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

------------------------------------------------------------------------------------------------------------------------
Iterative Statements:

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

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

particular condition.

Example:

---------

1.for 2.while 3.do-while

1.for

Syntax:

for(Expr1; Expr2; Expr3)

----instructions-----

Example:

--------

class Demo

public static void main(String[] args)

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

System.out.println(i);

Status: No Compilation Error

OP: 0

---

---

9
Expr1-----> 1 time

Expr2-----> 11 times

Expr3-----> 10 times

Body -----> 10 times

Example:

---------

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:

--------

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

Example:

---------

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:

--------

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:

--------

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

22

Reason:

-------

In for loop, Expr1 is able to allow atmost 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:

--------

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:

--------

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.

Example:

--------

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 immediatly 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 completly 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++)

{}

Example:

--------

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:

---------

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

OP: 0

Hello

Hello

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:

---------

class Demo

public static void main(String[] args)

for(;;)

Status: Compilation Error

Example:

---------

class Demo

public static void main(String[] args)

for(;;);

Status: No Compilation Error

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


Example:

---------

class Demo

public static void main(String[] args)

for(;;)

{}

Status: No Compilation Error

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

---------

class Test

public static void main(String[] args)

int i=0;

while(i<10)
{

System.out.println(i);

i=i+1;

Example:

--------

class Demo

public static void main(String[] args)

int i=0;

while()

System.out.println(i);

i=i+1;

Status: Compilation Error

Reason: Conditional Expression is mandatory.

Example:

---------

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

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.

Syntaxes:

while(Condition)

---instructions-----

do

---instructions---

While(Condition):

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

Example:

---------

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

Example:

--------

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

---------

class Demo

public static void main(String[] args)

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

if(i==5)

break;

System.out.println(i);

Status: No Compilation Error

OP: 0

1234

Example:

--------

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 immediatly after break statement then that statement is

Unreachable Statement, where compiler will rise an error.

Example:

---------

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

Example:

---------

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 inorder to continue with next iteration.

Continue….

Example:

---------

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:

---------

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

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

Status: Compilation Error, Unreachable Statement.

Reason: If we provide any statement immediatly after continue statement then that statement is

unreachable statement, where compiler will rise an error.

Example:

--------

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

Example:

--------

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

if(j==5)

continue l1;

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

Status: No Compiloation Error


OP:

00

01

02

03

04

10

11

12

13

14

---

---

---

90

01

92

93

94

OO
ARRAYS

-------

*Whenver 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 achive
readability.

--> Once the array is created with some size we can not alter that during execution.

--> We can use concept called as COLLECTIONS to slove 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 memeory is allcated in heap memeory segment.

Note: When ever 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

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

---------

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

example 2:

----------

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 0 0 0
example 3:

----------

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

output:

-------

10

20

30

40

50

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

Class name for different array types:

ARRAY TYPE CLASS NAME

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

--> int[] --> [I

--> byte[] --> [B

--> short[] --> [S

--> long[] --> [J

--> float[] --> [F

--> double[] --> [D

--> char[] --> [C


example:

--------

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:

--------

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


Examples for 1D array:

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

example 1:

----------

Demo.java

----------

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

Enter the marks:

37

Enter the marks:

59

Enter the marks:

64

87 92 37 59 64

example 2:

----------

Demo1.java

----------

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

example 3:

----------

Demo1.java

----------

//WAP 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
example 4:

----------

Demo1.java

----------

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

example 5:

----------

Demo1.java

----------

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

example 6:

----------

Demo1.java

----------

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

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

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

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]

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

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

---------

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

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

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

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

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

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

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

}
}

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

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

-------

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

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

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 obejct 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 objects 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 calles
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.

offline online

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

1.customer 1.customer

2.counter 2.counter

3.money 3.money

4.ticket 4.e-tickets

5.theater 5.theater

6.seat 6.seat

7.movie 7.movie

8.snacks 8.snacks

9.[black market] 9.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

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:

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.

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

}
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


INSTANCE VARIABLE:

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

WHAT IS A 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 seperate copy of instance varibles is created.

WHERE THE INSTANCE VARIABLES ARE DECLARED ?

--> Example:

Class Demo

int x;

float y;

boolean z;

void method1()

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:

---

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 doesnot support few features operator overloading, multiple inheritence 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.

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

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;

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

LOCAL VARIABLE:

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

1. WHAT IS LOCAL VARIABLE ?

--> Local Variables are temporory variables which are used by programmers to meet temporory requierments.

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 can not access.

example: refer above example

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

-->NO,Programmer must initilize the values to the local variable.

example:1

--------

Demo.java

---------

class Demo

{
public static void main(String[] args)

int x;

System.out.println("java"); --> if local variables are not used then we wont get
compilation error

output:

-------

java

example:2

---------

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

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

ouput:

------

java

1. VALUE TYPE ASSIGNMENT

2. REFERNCE TYPE ASSIGNMENT

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

System.out.println(d1.name);

System.out.println(d1.roll_no);

output:

-------

sagar

24

sandesh

25

sandesh

25

METHODS:

--------

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

Syntax of method:

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

access_modifier returntype methodName(parameter)

method body
}

access_modifier --> optional

returnType --> compulsory

methodName --> compulsory

parameter --> optional

example:

--------

public void add(int x, int y)

int z;

z=x+y;

s.o.p(z);

TYPES OF METHODS BASED ON PARAMETER AND RETURN VALUE.

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

1. NO PARAMETER AND NO RETURN VALUE

2. PARAMETER AND NO RETURN VALUE.

3. PARAMETER AND RETURN THE VALUE.

4. NO PARAMETER AND RETURN THE VALUE.

example:1

-----------

1. NO PARAMETER AND NO RETURN VALUE

Demo.java

---------

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

class Demo

public static void main(String[] args)

Addition a1=new Addition();


a1.add();

class Addition

void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

output --> 30

example:2

-----------

2. PARAMETER AND NO RETURN VALUE

Demo.java

---------

// passing the input and no returning the output.

class Demo

public static void main(String[] args)

Addition a1=new Addition();

int x=12;

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

class Addition

void add(int a,int b)

int c;

c=a+b;

System.out.println(c);

output --> 20

example:3

-----------

3.PARAMETER AND RETURN VALUE

Demo.java

---------

// passing the input and returning the output.

class Demo

public static void main(String[] args)

Addition a1=new Addition();

int x=12;

int y=12;

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

System.out.println(res);

}
}

class Addition

int add(int a,int b)

int c;

c=a+b;

return c;

output: --> 24

example:4

-----------

4.NO PARAMETER AND RETURN VALUE

Demo.java

---------

// no passing the input and returning the output.

class Demo

public static void main(String[] args)

Addition a1=new Addition();

int res = a1.add();

System.out.println(res);

int res = a1.add();

System.out.println(res);
}

class Addition

int add()

int a,b,c;

a=14;

b=14;

c=a+b;

return c;

OUTPUT --> 28

example

--------

// WAP to return the array.

class Demo

public static void main(String[] args)

ArrayRetrun ar=new ArrayRetrun();

int[] x = ar.fun();

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

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

}
}

class ArrayRetrun

int[] fun()

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

return a;

output: --> 10 20 30 40

CONSTRUCTORS

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

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

It is a Specialized setter to initilize the object.

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

Constructor are always called during the object creation.

There are 3 ways to intilize the object.

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

1. using the refrence variable

2. using the methods

3. using the constructors

using the reference variable:

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

EXAMPLE:

--------

class Student
{

String name;

int roll_no;

class Demo2

public static void main(String[] args)

Student s1 = new Student();

s1.name ="raju";

s1.roll_no = 84;

System.out.println(s1.name);

System.out.println(s1.roll_no);

OUTPUT:

--------

raju

84

using the methods

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

EXAMPLE:

--------

class Student

String name;

int roll_no;

public void SetData(String sname, int sroll_no)

name=sname;

roll_no=sroll_no;

}
public String getName()

return name;

public int getRoll_no()

return roll_no;

class Demo2

public static void main(String[] args)

Student s1 = new Student();

s1.SetData("somu",89);

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

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

OUTPUT:

-------

somu

89

using the constructors

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

EXAMPLE:

--------

class Student

String name; //IV

int roll_no; //IV

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


{

name=sname;

roll_no=sroll_no;

System.out.println(name);

System.out.println(roll_no);

class Demo

public static void main(String[] args)

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

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

OUTPUT:

-------

bheem

28

somu

89

EXAMPLE:2

---------

// SHADOWING PROBLEM

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

class Student

String name; //IV

int age; //IV


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

name=name;

age=age;

public String getName()

return name;

public int getAge()

return age;

class StudentApp

public static void main(String[] args)

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

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

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

OUTPUT:

--------

null

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

will not happen in the proper way.

This problem is called as Shadowing problem.

Solution to the above problem is :

1. use the 'this' keyword to differeniate b/w instance and local variable.
EXAMPLE:

--------

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

class Student

private String name;

private int age;

Student(String name,int age)

this.name=name;

this.age=age;

public String getName()

return name;

public int getAge()

return age;

class StudentApp

public static void main(String[] args)

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

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

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

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

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

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

}
}

OUTPUT:

-------

ramu

21

somu

22

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

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

TYPES OF CONSTRUCTOR

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

The types of constructors are:

1. default constructor

2. user defined default constructor

3. parameterized constructor

DEFAULT CONSTRUCTOR:

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

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

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

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

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

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

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

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

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

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

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

EXAMPLE:

--------

class Student

String name;

int age;

Student()

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

age=21;

public String getName()

return name;

public int getAge()

return age;

class Demo

public static void main(String args[])

Student s1 = new Student();

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

OUTPUT:

-------

ramu

21

THE DIFFERENCE B/W CONSTRUCTOR AND METHOD

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

EXAMPLE:

--------

class A

A()

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

void A()

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

class Demo1

public static void main(String[] args)

A a1= new A();

a1.A();

a1.A();

OUTPUT:

-------
Inside the constructor

Inside the method

Inside the method

CONSTRUCTOR METHOD

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

1. Constructor should be same as class name 1. method name can be anything.

2. They dont have return type 2. return type is compulsory

3. Constructor calling is implicit 3. method calling is explicit

4. Constructor will be called only one during the object creation 4. method can be called n number times

5. access modifier permitted are : public,private,protected,default 5. we can also use static,final ...etc

6. Constructors can not be inherited 6. methods can be inherited

PARAMETERIZED CONSTRUCTOR:

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

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

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

EXAMPLE:

--------

class Student

String name;

int age;

Student(String name)

this.name=name; // PARAMETERIZED CONSTRUCTOR

public String getName()

return name;

}
}

class Demo

public static void main(String args[])

Student s1 = new Student("RAMU");

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

OUTPUT:

--------

RAMU

EXAMPLE:2

---------

class Student

String name;

int age;

Student(String name)

this.name=name; // PARAMETERIZED CONSTRUCTOR

public String getName()

return name;

class Demo

public static void main(String args[])

Student s1 = new Student();


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

OUTPUT:

-------

COMPILATION ERROR

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

CONSTRUCTOR OVERLOADING:

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

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

1. number of parameter

2. type of parameter

3. order of parameter

EXAMPLE:

--------

class Employee

private String name;

private int id;

private float salary;

public Employee(String name) //PC

this.name = name;

public Employee(String name,int id)

this.name = name;

this.id = id;
}

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

this.name = name;

this.id = id;

this.salary = salary;

public String getName()

return name;

public int getId()

return id;

public float getSalary()

return salary;

class Demo

public static void main(String[] args)

Employee e1 = new Employee("ramu");

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

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

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

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

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

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

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

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

OUTPUT:

--------

ramu

ramu

124

ramu

124

50.45

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

this() constructor call:

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

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

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

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

EXAMPLE:

--------

class A

A()

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

A(int x)
{

this();

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

class Demo

public static void main(String[] args)

A a = new A(18);

OUTPUT:

-------

inside default constructor

inside parametrized constructor

EXAMPLE:2

----------

class A

A()

this("ramu");

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

A(int x)

this();

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

A(String s)

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

class Demo1

public static void main(String[] args)

A a = new A(18);

OUTPUT:

-------

inside String parametrized constructor

inside default constructor

inside parametrized constructor

MUTATORS or SETTERS and ACCESSOR or getters

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

Based on the object state modification methods can be classified into two types:

1.MUTATORS/SETTER : These are used to set or modify the value in the object.

2.ACCESSOR/GETTERS : These are used to get the value from the object.

// example:1 MUTATORS/SETTERS and ACCESSORS/GETTERS

class Credentials

private String un;

private String pwd;

void setUn(String username)

un=username;

void setPwd(String password)

{
pwd=password;

String getUn()

return un;

String getPwd()

return pwd;

class Demo

public static void main(String[] args)

Credentials c = new Credentials();

c.setUn(" ");

c.setPwd("3443");

System.out.println(c.getUn());

System.out.println(c.getPwd());

output : -->

34343

// example:2 MUTATORS/SETTERS and ACCESSORS/GETTERS

class Student

private String name;

private int age;

private float height;


void setName(String sname)

name=sname;

void setAge(int sage)

age=sage;

void setHeight(float sheight)

height=sheight;

String getName()

return name;

int getAge()

return age;

float getHeight()

return height;

class Demo

public static void main(String[] args)

Student s = new Student();

s.setName("Subbu");
s.setAge(24);

s.setHeight(6.1f);

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

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

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

output: --> subbu

24

6.1

PASS BY VALUE

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

In java the parameter can be passed only in the value mode. Java doesnot support the any other passing techniques
other than pass by value.

In c programming language it has both pass by value and pass by reference, but java doesnot support concept of
pointer hence pass by refernece is

ruled out in java.

// PASS BY VALUE IN JAVA.

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

class Test

void swap(int x, int y)

int temp;

temp = x;

x = y;

y = temp;

class Demo

public static void main(String[] args)


{

int a=10; //LV

int b=20; //LV

Test t = new Test();

System.out.println("before swapping:");

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

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

t.swap(a,b);

System.out.println("after swapping:");

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

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

output:

-------

before swapping:

the value of a is :10

the value of b is :20

after swapping:

the value of a is :10

the value of b is :20

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

METHOD OVERLOADING IN JAVA

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

In c language we can write any number of functions but the functions name should be unique(no two functions shuold
have the same name).

example of c language:
----------------------

#include<stdio.h>

#include<conio.h>

Void main()

Int a=10, b=20, c=30;

float x=1.2, y=2.2, z=3.2;

double p=10.222, q=20.2433, r=30.3233;

printf(“%f”, add3(p,q));

printf(“%f”, add4(a,x));

printf(“%f”, add10(a,b,c));

int add1(int x, int y)

return x+y;

int add2(float x, float y)

return x+y;

int add3(double x, double y)

return x+y;

int add4(int x, float y)

return x+y;

int add5(int x, double y)

return x+y;

int add6(float x, double y)

return x+y;

}
int add7(float x, int y)

return x+y;

int add8(double x, int y)

return x+y;

int add9(double x, float y)

return x+y;

int add10(int x, int y, int z)

return x+y+z;

int add11(float x, float y, float z)

return x+y+z;

int add12(double x, double y, double z)

return x+y+z;

int add13(int x, float y, double z)

return x+y+z;

int add14(int x, float y, float z)

return x+y+z;

int add15(int x, double y, double z)

return x+y+z;
}

int add16(float x, int y, int z)

return x+y+z;

note:

-----

In the above c program even though we are properly performing addition operation but still we should remember
multiple functions name which is complex

The above problem can be overcome using the METHOD OVERLOADING concept in java.

example:

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

// METHOD OVERLOADING IN JAVA

class Demo

public static void main(String[] args)

Test t = new Test();

int a=10, b=20, c=30; // NAME OF THE


METHOD

float x=1.2f, y=2.2f, z=3.2f; // NUMBER OF


PARAMETER

double p=10.222, q=20.2433, r=30.3233; // DATATYPES


OF THE PARAMETER

// ORDER OF THE
PARAMETER

System.out.println(t.add(p,q));

System.out.println(t.add(a,x));

System.out.println(t.add(a,b,c));

System.out.println(t.add(a,p));

class Test

{
int add(int x, int y)

return x+y;

float add(float x, float y)

return x+y;

double add(double x, double y)

return x+y;

float add(int x, float y)

return x+y;

double add(int x, double y)

return x+y;

double add(float x, double y)

return x+y;

float add(float x, int y)

return x+y;

double add(double x, int y)

return x+y;

double add(double x, float y)

return x+y;

}
int add(int x, int y, int z)

return x+y+z;

float add(float x, float y, float z)

return x+y+z;

double add(double x, double y, double z)

return x+y+z;

double add(int x, float y, double z)

return x+y+z;

float add(int x, float y, float z)

return x+y+z;

double add(int x, double y, double z)

return x+y+z;

float add(float x, int y, int z)

return x+y+z;

output:

-------

30.4653

11.2
60

20.222

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

method call in following ways:

1.NAME OF THE METHOD

2.NUMBER OF PARAMETER

3.DATATYPES OF THE PARAMETER

4.ORDER OF THE PARAMETER

TYPES OF METHODS OR BLOCKS

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

The types of methods or blocks are :

1. instance methods and instance block

2. static methods and static blocks

class Demo

int a = 10;

int b = 20; // instance variables

public static void main(String[] args)

Demo d1 = new Demo();

d1.fun();

void fun() // instance methods

int c=a+b;

System.out.println(c);

}
{

System.out.println("hello world"); // instance block

NOTE: Instance blocks are anonymous(nameless) blocks which are executed during the object creation before the
constructor call

EXAMPLE:

--------

class A

A()

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

A(int x)

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

System.out.println("inside the instance block");

class Demo2

public static void main(String []args)

A a =new A();

OUTPUT:

-------

inside the instance block

inside the default constructor


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

EXAMPLE:

---------

class A

System.out.println("inside the first instance block");

System.out.println("inside the second instance block");

System.out.println("inside the third instance block");

class Demo2

public static void main(String []args)

A a =new A();

OUTPUT:

-------

inside the first instance block

inside the second instance block

inside the third instance block

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

EXAMPLE:

--------

class A
{

//int a=10;

A()

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

System.out.println("inside the instance block");

float f = 12.14f;

void fun()

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

class Demo2

public static void main(String []args)

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

A a =new A();

OUTPUT:

------

inside the main method

inside the instance block

inside the constructo

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

EXAMPLE:

---------

class A
{

int age; //IV

//IB

age=16;

System.out.println("the age is"+age);

class Demo2

public static void main(String []args)

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

A a =new A();

OUTPUT:

-------

inside the main method

the age is 16

NOTE: Instance blocks are used to provide the logic which is common for all the objects. If the logic is specific for
different

objects then we can use this code in the constructor

EXAMPLE:

--------

class Student

int register_number; //IV

//IB

System.out.println("WELCOME TO Java classes");


}

Student() //UDDC

register_number=20;

System.out.println("your registration number is :" +register_number);

Student(int x) //UDPC

register_number = x;

System.out.println("your registration number is :" +register_number);

class Demo

public static void main(String []args)

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

Student s1 =new Student();

Student s2 =new Student(21);

OUTPUT:

-------

WELCOME TO Java classes

your registration number is :20

WELCOME TO Java classes

your registration number is :21

NOTE: The memory for instance variables and methods and blocks are always given in the heap memory segment.
import java.util.*;

class Student

private String name;

private int age;

private String schoolName;

public void setData()

Scanner sc = new Scanner(System.in);

System.out.println("ENTER THE NAME : ");

name = sc.next();

System.out.println("ENTER THE AGE : ");

age = sc.nextInt();

System.out.println("ENTER THE SCHOOL NAME : ");

schoolName = sc.next();

public void display()

System.out.println("name is :"+name);

System.out.println("age is :"+age);

System.out.println("schoolname is :"+schoolName);

class Demo

public static void main(String[] args)

Student s1 = new Student();

s1.setData();
s1.display();

OUTPUT:

--------

sagar

25

jain

NOTE: Whenever the value is same for multiple objects instead of having multiple copies we can have a single copy.

In the above program schoolname is common for all the students hence we can have a single copy and it can be shared
among the objects

such common elements we should make it as static in the program to imporve memory effieceny.

EXAMPLE:2

----------

private String name;

private int age;

static private String schoolName = "jain";

NOTE: when ever java program stats executing always static members will execute first.

the order of execution is:

1. --> static variables

2. --> static blocks

3. --> static methods

STATIC METHODS:

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

Static methods are such methods present in the class where a method is prefixed with static keyword.

static methods are class methods which are shared by multiple objects.they are not associated with objetcs.

They can be accessed using the reference variable or class name


EXAMPLE:

--------

class Test

void fun1()

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

static void fun2()

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

class Demo2

public static void main(String[] args)

Test t1 =new Test();

t1.fun1();

t1.fun2();

Test.fun2();

OUTPUT:

-------

inside the instance method

inside the static method

inside the static method

refer the fig:

EXAMPLE:

---------
class Test

static int a,b,c; //SV

int x,y,z; //IV

static //SB

a=10;

b=20;

c=30;

static void fun1() //SM

System.out.println(a);

System.out.println(b);

System.out.println(c);

{ //IB

x=40;

y=50;

z=60;

a=100;

b=200;

c=300;

void fun2() //IM

System.out.println(x);

System.out.println(y);

System.out.println(z);

System.out.println(a);

System.out.println(b);

System.out.println(c);
}

class Demo

public static void main(String[] args)

Test t1 = new Test();

Test.fun1();

Test t2 = new Test();

t2.fun2();

OUTPUT:

--------

100

200

300

40

50

60

100

200

300

INSATNCE METHOD:

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

1. It is also called as non-static method.

2. If we want to call the method where obejct should be created.

3. Can be accessed using the object reference variable

4. It is always deals wuth object level

STATIC METHOD:

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

1. It is also called as class method.


2. No need of object creation for method call

3. Can be accessed using the both object ref and class name

4. it is always deals with class level

STATIC BLOCKS:

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

Static blocks are executed during the class loading.There execution is before the execution of main method.

They always initilize the static variables.

If a block is prefixed with static keyword then it is called as staic block

example:

---------

static{ static

} }

EXAMPLE:

----------

// Static blocks

class A

int x;

static int y;
{

x=10;

System.out.println("inside the instance block");

System.out.println(x);

static

y=20;

System.out.println("inside the static block");

System.out.println(y);

A()

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

class Demo1

public static void main(String[] args)

A a =new A();

INSTANCE BLOCK:

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

1. It is used to initilize the instance varibale.

2. It will always executes during object creation and before the constructor call.

3. memory will be allocated each time when a new object is created

STATIC BLOCKS:

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

1. It is used to initilize the static varibale.

2. It is executed during the class loading and bfore the execution of main method
3. Memory will be allocated only once.

CAN WE EXECUTE A JAVA PROGRAM WITHOUT A MAIN METHOD.

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

--> Till java 1.6 version a java program can be executed without a main method.

From 1.7 version owards main method is manadantory.

INHERITANCE

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

Inheritance is a process of a class aqcuring the properties(variables) and behaviour (methods) from the other class.

Inheritance can be achived using extends keywords.

Parent class is a class which gives the proerties and behaviour to another class.

child class is a class which inherit the proerties 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:1

-------

In order to relate two classes we can use extends keywords.

example:2

----------

// related classes

class visitor

String name; // parent class or super class

int ph_no;

class Hospital extends visitor

void Doctor_conslut() // child class or sub class

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

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

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

NOTE:2

------

Inheritance promotes IS- A relationship.


NOTE:3

------

Whenever the obejct 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);

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

------

Child class can call the instance method of parent class directly.

EXAMPLE:

--------
// note5

class A

void fun1() //IM

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

class B extends A

void fun2() //IM

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

class Demo

public static void main(String[] args)

B b= new B();

b.fun2();

b.fun1();

OUTPUT:

------

inside the fun2

inside the fun1

NOTE:6

------
The child class can call the inherited static methods directly.

EXAMPLE:

--------

// note4

class A

static void fun1()

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

class B extends A

void fun2()

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

class Demo

public static void main(String[] args)

B b= new B();

b.fun2();

b.fun1();

OUTPUT:

------

inside the fun2

inside the fun1


NOTE:7

------

Unlike the private members constructors are also doesnt partcipate in the inheritance.

ie, parent class consructor would not be inherited to the child class rather the control from the child class will go the
super class(parent class)

constructor and the code will get executed.

EXAMPLE:

---------

// note7

class A

int i; //IV

int j; //IV

A() //UDDC

//super();

i=1111;

j=2222;

class B extends A

B() //UDDC

super();

void display() //IM

System.out.println("i value is "+i);

System.out.println("j value is "+j);

}
class Demo

public static void main(String[] args)

B b= new B();

b.display();

OUTPUT:

------

i value is 1111

J value is 2222

// note7 example:2

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

class A

int i;

int j;

A(int x)

super();

i=1111;

j=2222;

class B extends A

B()

super();

}
void display()

System.out.println("i value is "+i);

System.out.println("j value is "+j);

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

-------

Even though the parameterized constructor of a sub-class is called yet, the default constructor in the super class is
executed first then the parameterzied

constructor of the sub-class is executed.

// note8

-----------

class A

int i,j; //IV


A() //UDDC

//super();

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

class B extends A

B() //UDDC

super();

B(int i, int j) //UDPC

super();

this.i=i;

this.j=j;

void display() //IM

System.out.println("i value is "+i);

System.out.println("j value is "+j);

class Demo

public static void main(String[] args)

B b= new B(10,20);

b.display();

OUTPUT:

-------
inside the default constructor

i value is 10

j value is 20

NOTE:9

-------

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

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

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

// EXAMPLE FOR MULTI-LEVEL INHERITANCE

class A

void fun1()

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

class B extends A

void fun2()

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

class C extends B

void fun3()

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

class Demo

public static void main(String[] args)

C c1 =new C();

c1.fun1();

c1.fun2();

c1.fun3();

}
}

OUTPUT:

-------

inside the fun1 method

inside the fun2 method

inside the fun3 method

// EXAMPLE FOR CYCLIC INHERITANCE

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

class A extends B

void fun1()

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

class B extends A

void fun2()

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

class Demo

public static void main(String[] args)

B b1 =new B();

b1.fun1();

b1.fun2();

}
OUTPUT:

--------

error: cyclic inheritance involving A

class A extends B

super keyword

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

During the inheritance if the parent class and class having the variable name and the name clash would occur and
priority is given to child class.

instance variable.

In order to access the instance variable of parent class we will use super keyword.

// EXAMPLE FOR SUPER KEYWORD

class A

int x = 10;

class B extends A

int x=20;

void fun2()

System.out.println(x); // 20

System.out.println(this.x); // 20

System.out.println(super.x); // 10

class Demo

public static void main(String[] args)

B b1 =new B();

b1.fun2();
}

this keyword : it will alwys points the currently executing object.

this() : it is used to call the constructor within the same class.

super() : it is used to call the constructor of the parent class

super keyword : it is used to access the instance variable of parent class.

this() and super()

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

NOTE: Inside the constructor the first statement should be either this() or super(). If the user is not using either super()
or this() then compiler

by default will add super() to the constructor.

EXAMPLE:

---------

class A

A()

super() --> added by the compiler

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

NOTE: super() and this() can not be placed in the same constructor.

EXAMPLE:

---------

class A

A()
{

super();

this();

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

EXECUTION OF THE INSTANCE MEMBERS IN INHERITANCE:

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

EXAMPLE:

--------

class Parent

int x = 10; //IV

//IB

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

//IB

fun1();

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

Parent()//UDDC

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

void fun1() //IM

{
System.out.println("parent class first instance method");

class Child extends Parent

int y=20; //IV

//IB

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

//IB

fun2();

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

Child() //UDDC

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

void fun2() //IM

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 fo the parent class

2. execute instance variable fallowed by instance blocks and method and finally execute parent class constrctor

3. Identify all the instance members fo the child class

4. execute instance variable fallowed by instance blocks and method and finally execute child class constrctor

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

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 fo the parent class

2. execute static variable fallowed by static blocks and method.

3. Identify all the static members fo the child class

4. execute static variable fallowed by static blocks and method.

5. then object is created during object creation constructor will be executed.

EXECUTION OF BOTH STATIC AND INSTANCE MEMBERS IN INHERITANCE:

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

EXAMPLE:

--------

class Parent

static int x = 10; // static variable

int y = 20; // instance variable

static

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

// instance block

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

// instance block
{

test1();

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

// constructor

Parent()

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

// static method

static void fun1()

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

System.out.println(x);

// instance method

void test1()

System.out.println("parent class first instance method");

System.out.println(y);

class Child extends Parent

static int a=20;

int b=40;

static

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

test2();

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

}
Child()

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

static void fun2()

System.out.println("child class first static method");

System.out.println(a);

void test2()

System.out.println("child class first instance method");

System.out.println(b);

public static void main(String[] args)

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

Child.fun1();

Child.fun2();

Child c1= new Child();

OUTPUT:

-------

parent class first static block

child class first static block

inside the main method

parent class first static method

10

child class first static method


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 construtor of parent class

7. execute the iv ib im and construtor of child class

INHERITED , OVERRIDDEN , SPECILIZED METHODS.

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

INHERITED METHOD : any method which is acquired by the child class from the parent class is called as inherited
method.

OVERRIDDEN METHOD : changes performed on inherited method is called as overridden methods

SPECIALIZED METHOD : mehods 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");

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

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 }

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

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 refernce to the child object
to achive the POLYMORPHISM.

EXAMPLE:

---------

class Vehicle

void Move()

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


method w.r.t parent class

class Bike extends Vehicle

{
void Move()

System.out.println("bike is moving medium speed");


// overriding method w.r.t child class }

class Car extends Vehicle

void Move()

System.out.println("Car is moving high speed"); //


overriding method w.r.t child class }

class Truck extends Vehicle

void Move()

System.out.println("Truck is moving low speed");


// overriding method w.r.t child class }

class Demo1

public static void main(String[] args)

Vehicle v = new Vehicle();

v = new Bike(); //[child object with parent refernce]

v.Move();

v = new Car();

v.Move();

v = new Truck();

v.Move(); // 1:3

}
OUTPUT:

-------

bike is moving medium speed

Car is moving high speed

Truck is moving low speed

RELATIONSHIPS IN JAVA

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

As a part of java application development we have to use entities as per the requirement

relationships are used to provide the optimization over memory utilization,code reusablity,execution time,ease of
shareablity.

TYPES OF RELATIONSHIPS IN JAVA:

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

1.IS-A relationship

2.HAS-A relationship

IS-A : by using this we can achive the concpet of inheritance by doing so we can perform 'code reusablity'.

HAS-A : It defines associations b/w the entites to improve the communication b/w the entites 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 referes to weak relationship whereas compostion refers to strong relationship.

arggregation will have less dependency with enclosed object where as compostion will have more dependency with
enclosed object
aggregation members can be accessed when with out enclosed object

compostion members can not be accessed without enclosed object

aggregate object is independent in nature

compostion objects are dependent in nature

EXAMPLE:

--------

class os

String name;

int size;

public os(String name, int size)

this.name=name;

this.size=size;

public String getName()

return name;

public int getSize()

return size;

class charger

String brand;

String color;

public charger(String brand, String color)

this.brand=brand;

this.color=color;

}
public String getBrand()

return brand;

public String getColor()

return color;

class mobile

os o = new os("android",125); //strong relationship

public void hasA(charger c) //weak relationship

System.out.println(c.getBrand());

System.out.println(c.getColor());

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

ABSTRACTION

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

Abstraction is one of the importent obeject oriented features in java.

It is process of hiding the internal implementation and sharing only the related functionality to the user.

ABSTRACTION: It is all about hiding the implementaion(body) of a overridden method.

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

In java abstraction can be achived in two ways:

1. Abstarct class [0-100%]

2. Interface

EXAMPLE: PROGRAM WITHOUT ABSTRACTION

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

class Vehicle

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

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

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

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

class Car extends Vehicle


{

void Start() //IM -->OM

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

class Bike extends Vehicle

void Start()

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

class Demo

public static void main(String[] args)

Vehicle V = new Vehicle();

Car C = new Car();

Bike B = new Bike();

V.Move();

V.Start();

C.Move();

C.Start();

B.Move();

B.Start();

EXAMPLE: PROGRAM WITH ABSTARCTION


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

abstract class Vehicle

void Move()

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

abstract void Start(); // abstract method

class Car extends Vehicle

void Start()

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

class Bike extends Vehicle

void Start()

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

class Demo

public static void main(String[] args)

//Vehicle V = new Vehicle();

Car C = new Car();

Bike B = new Bike();

C.Move();

C.Start();
B.Move();

B.Start();

NOTE:1

-------

1. ABSTRACT METHOD : Abstarct methods are overridden methods where it will be not have implemenation.

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

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

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

5. all the abstract methods should end with the semicolon

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

EXAMPLE:

--------

abstract class Bank

abstract void roi(); // 100% abstraction

class Sbi extends Bank

void roi()

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

}
}

class Hdfc extends Bank

void roi()

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

class Icici extends Bank

void roi()

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

class Demo1

public static void main(String[] args)

//Bank b =new Bnak();

Bank b;

b = new Sbi(); // upcasting

b.roi();

b = new Hdfc(); // upcasting

b.roi();

b = new Icici(); // upcasting

b.roi();

NOTE:2

-------

1. For abstrat class we can not create object but we can have refence
2. by parent reference we can perform upcasting and polymorphism can be achived

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

DIFFERENCE B/W NORMAL CLASS AND ABSTRACT CLASS.

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

EXAMPLE FOR NORMAL CLASS WITHOUT OBJECT OREIENTATION FEATURES:

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

class Calc

int a;

int b;

void add() // concrete method

a=10;

b=20;

int c=a+b;

System.out.println(c);

void sub() // concrete method

a=20;

b=10;

int c=a-b;

System.out.println(c);

class Demo2

public static void main(String[] args)

Calc c = new Calc();

c.add();
c.sub();

EXAMPLE FOR ABSTRACTION CLASS:

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

// normal class

abstract class Calc

int a;

int b;

abstract void add(); // abstract method

abstract void sub(); // abstract method

class Demo2

public static void main(String[] args)

//Calc c = new Calc();

//c.add();

//c.sub();

ABSTRACTION USING THE ABSTRACT CLASS

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

abstract class remote

abstract void On();

abstract void Off();

class Tv extends remote


{

void On()

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

void Off()

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

class Demo3

public static void main(String[] args)

remote r;

r = new Tv();

r.On();

r.Off();

RULES W.R.T ABSTRACTION:

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

RULE:1

-------

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

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

EXAMPLE:

--------

CASE:1
-------

abstract class Sample

abstract void fun1();

class Demo4 extends Sample

void fun1()

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

public static void main(String[] args)

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

CASE:2

-------

abstract class Sample

abstract void fun1();

class Demo4 extends Sample

public static void main(String[] args)

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

NOTE: Abstract keyword can be used with following members:

1. class

2. methods

3. Interface (methods)
4. Inner class (classes)

NOTE: Illegal combination of using abstraction

1. static

2. final

3. private

legal combinations are:

1. Strictfp

2. Synchronized

3. native

--> INTERFACE is a specification.

refer fig:2

--> Interface promotes standarization using which we can achive polymorphism.

Interface is collection of abstract methods using interface 100% abstraction can be achived becuase inside the interface
methods declaration are allowed

SYNTAX:

-------

interface interface_Name

abstract method(); --> method

Constants; --> variables(final)

ADVANTAGE OF INTERFACE:

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

1. Using the interface standarization is achived.

eg: pi value

2. It promotes polymorphism

3. 100% abstraction can be achived

4. multiple inheritance can be achived.


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

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

EXAMPLE:1

---------

interface Test

float pi = 3.14f;

void fun();

compile:

interface Test

public static final float pi = 3.14f;

public abstract void fun();

RULES OF INTERFACE:

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

RULE:1

--> When a class is implementing the inteface the methods access modifiers should be made as public beacause by
default all the abstract method in

interface are public in nature.

EXAMPLE

-------

refer diagram:

---------------
interface Calculate

/* public abstract */void add();

class Calculator implements Calculate

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

class Demo

public static void main(String[] args)

Calculator c = new Calculator();

c.add();

/*

public

protected weaker access modifiers can be given

default

private

*/
OUTPUT:

--------

30

RULE:2

-------

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

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

EXAMPLE:1

----------

interface Calculate

void add();

void mul();

class Calculator implements Calculate

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

class Demo

public static void main(String[] args)

Calculator c = new Calculator();

c.add();
}

OUTPUT:

------

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

class Calculator implements Calculate

note:

-----

The above probelm can be overcome by making class as bastract and method where class is not in a position to provide
the body then it should be made

as abstract.

EXAMPLE:2

----------

interface Calculate

void add();

void mul();

abstract class Calculator implements Calculate

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

abstract public void mul();

class Demo

public static void main(String[] args)

//Calculator c = new Calculator();


//c.add();

RULE:3

-------

An object of abstract class can not be crearted

ex: refer above program

An object of inteface cannot be created

EXAMPLE:

-------

interface Calculate

void add();

void mul();

class Demo

p s v m (---)

Calculate c = new Calculate();

OUTPUT:

-------

ERROR

--> Object can not be instantiated.

RULE:4

------

Though we cannot create the object for interface its refernce can be created.
EXAMPLE:

--------

interface Calculate

void add();

void mul();

class Demo

p s v m (---)

//Calculate c = new Calculate();

Calculate c; --> parent refernce

RULE:5

------

A class and interface cannot be realted using the extends keyword

EXAMPLE:

--------

interface Calculate

void add();

class Calculator extends Calculate

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

}
}

class Demo

public static void main(String[] args)

Calculator c = new Calculator();

c.add();

OUTPUT:

-------

ERROR

RULE:6

------

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

EXAMPLE:

--------

interface Bank

void ROI();

class SBI implements Bank

public void ROI()

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

class AXIS implements Bank

public void ROI()

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

class CANARA implements Bank

public void ROI()

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

class Calculate

public void allow(Bank ref)

ref.ROI();

class Demo1

public static void main(String[] args)

SBI s = new SBI();

AXIS a = new AXIS();

CANARA c = new CANARA();

Calculate c1= new Calculate();

c1.allow(s);

c1.allow(a);

c1.allow(c);

OUTPUT:

-------

sbi --> 7.5%

AXIS --> 9.5%


CANARA --> 8.5%

AMBIGUITY PROBLEMS WITH INTERFACE VARIABLES:

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

EXAMPLE:

-------

interface calculate1

int min = 10;

interface calculate2

int min = 20;

class Test implements calculate1,calculate2

public void disp()

System.out.println(min);

class Ambiguity

public static void main(String[] args)

Test t = new Test();

t.disp();

OUTPUT:

--------

error: reference to min is ambiguous


System.out.println(min);

both variable min in calculate1 and variable min in calculate2 match

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

EXAMPLE:

--------

interface calculate1

int min = 10;

interface calculate2

int min = 20;

class Test implements calculate1,calculate2

public void disp()

System.out.println(calculate1.min);

System.out.println(calculate2.min);

class Ambiguity

public static void main(String[] args)

Test t = new Test();

t.disp();

}
OUTPUT:

-------

10

20

RULE:14

-------

An interface can extend any number of interface.

refer dia: 7

EXAMPLE:

--------

interface calculate1

void add();

interface calculate2

void sub();

interface calculate3 extends calculate1,calculate2

void mul();

class Test implements calculate3

public void add()

int a,b,c;

a=10;

b=20;

c=a+b;

System.out.println(c);

}
public void sub()

int a,b,c;

a=20;

b=05;

c=a-b;

System.out.println(c);

public void mul()

int a,b,c;

a=20;

b=05;

c=a*b;

System.out.println(c);

class Rule14

public static void main(String[] args)

Test t = new Test();

t.add();

t.sub();

t.mul();

OUTPUT:

-------

30

15

100

DOES JAVA ALLOW MULTIPLE INHERITANCE?


--> mUltiple inheritance through classes can not be achived in java because of ambiguity probelm(diamond shape
problem).

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

EXAMPLE:

--------

interface A

int i =10;

interface B

int i = 20;

interface C extends A,B

class Test

public void disp()

System.out.println(A.i);

System.out.println(B.i);

class Demo

public static void main(String[] args)

Test t = new Test();

t.disp();

OUTPUT:

------

10
20

ADAPTER CLASS:

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

Adapter class is a normal class in java which as empty body for all the abstract methods of an interface.

EXAPLE:

---------

interface compute

void fun1();

void fun2();

void fun3();

void fun4();

void fun5();

void fun6();

class Adapter implements compute

public void fun1()

public void fun2()

public void fun3()

public void fun4()

public void fun5()

public void fun6()

{
}

class Test1 extends Adapter

public void fun1()

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

class Test2 extends Adapter

public void fun4()

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

class Demo3

public static void main(String[] args)

Test1 t1 = new Test1();

t1.fun1();

Test2 t4 = new Test2();

t4.fun4();

OUTPUT:

--------

inside fun1 method

inside fun4 method


MARKER INTERFACE:

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

Marker interface is a empty interface which doesnot contain any abstract methods or fields.

If a class implements a marker interface then it aquaries a special behavoir.

example: if a class implements clonable interface then a duplicate object with the same behaviour can be created.

examples for marker inteface are:

1. Cloneable

2. Serialization

3. Runnable

OBJECT CLONING:

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

-->The process of creating duplicate object for an existed object is called as Object Cloning.

-->If we want to perform Object Cloning in Java application then we have to use the following steps.

1.Declare an User defined Class.

2.Implement java.lang.Cloneable interface inorder to make eligible any object for cloning.

3.Override Object class clone() method in user defined class.

public Object clone() throws CloneNotSupportedException

4.In Main class,in main() method,access clone() method over the respective object

EXAMPLE:

--------

class Demo5 implements Cloneable

int a = 10;

public static void main(String[] args) throws Exception

Demo5 d = new Demo5();

System.out.println(d.a);

Demo5 d1=(Demo5)d.clone();

System.out.println(d1.a);
}

OUTPUT:

--------

10

10

Difference b/w extends and implements

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

extends:

--------

1. A class can inherit other class using the extends keyword.An interface can inherit another interface using the
extends keyword.

2. A subclass which extends super class may or may not override all the methods of superclass

3. An inertface can extends any number of interface

4. A class can extends only one super class.

implements:

----------

1. A class can be implemented other inteface uisng implements keyword.

2. class implementing interface should provide body for all methods of interface

3. An interface can never implements other interface

4. A class can implement multiple interface simultaneously.

Difference b/w interface and abstract class

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

interface:

---------

1.100% abstraction is achieved

2. interface are used when we don't know complete implementation

3.only abstract methods are allowed


4.Every methods inside interface are by default public and abstract

5.Every variables inside interface are by default public static final

6. following modifiers are not allowed for abstract methods static, private,strictfp,protected,final

7.interface cannot have static blocks

8.interface cannot have instance blocks

9.constructors are not allowed

abstract class

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

1.0-100% abstraction can be achieved

2.abstract class is used when we know parent implementation

3.both abstract and concrete methods are allowed

4.every method present in abstract class need not to be public and abstract

5.every variables present in abstract class need not to be public static final

6.no such restructions for methods

7.abstract class can have static block

8.abstract class can have instance block

9.construced are allowed

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:

--------

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

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]

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 can not access

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

System.out.println("Cargoplane is taking off");

void fly()

System.out.println("Cargoplane is flying with the low speed");

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane

void fly()

System.out.println("Passengerplane is flying with the medium speed");

void CarryPassenger()
{

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

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Airport

void allow(Plane ref)

ref.takeOff();

ref.fly();

ref.land();

class Demo

public static void main(String[] args)

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

PassengerPlane pp = new PassengerPlane();


FighterPlane fp = new FighterPlane();

Airport a = new Airport();

a.allow(cp);

a.allow(pp);

a.allow(fp);

OUTPUT:

--------

Cargoplane is taking off

Cargoplane is flying with the low speed

plane is landing

plane is taking off

Passengerplane is flying with the medium speed

plane is landing

plane is taking off

Fighterlane is flying with the high speed

plane is landing

STEPS TO ACHIEVE POLYMORPHISM:

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

1. INHERITANCE must be present.

2. classes must be related

3. METHOD OVERRIDING should be present

4. use the concept of 'PARENT REF TO CHILD OBJECT'

5. POLYMORPHISM

NOTE: To access the specialized methods we must perform 'DOWNCASTING'.


EXAMPLE:

--------

class Plane

String name;

int wheel;

void takeOff()

System.out.println("plane is taking off");

void fly()

System.out.println("plane is flying");

void land()

System.out.println("plane is landing");

class CargoPlane extends Plane

void takeOff()

System.out.println("Cargoplane is taking off");

void fly()

System.out.println("Cargoplane is flying with the low speed");

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane


{

void fly()

System.out.println("Passengerplane is flying with the medium speed");

void CarryPassenger()

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

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Demo

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 achiving the polymorphism.

DOWNCASTING: it means tempory converting the parent ref to child type to access the specialized method
WHAT IS RUNTIME POLYMORPHISM AND VIRTUAL POLYMORPHISM ?

--> METHOD OVERLOADING --> VIRTUAL POLYMORPHISM --> STATIC POLYMORPHISM --> EARLY
BINDING.

--> METHOD OVERRIDING --> RUNTIME POLYMORPHISM --> DYNAMIC POLYMORPHISM --> LATE
BINDING.

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

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

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

}
// RUNTIME POLYMORPHISM USING THE METHOD OVERRIDING.

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

class Plane

String name;

int wheel;

void takeOff()

System.out.println("plane is taking off");

void fly()

System.out.println("plane is flying");

void land()

System.out.println("plane is landing");

class CargoPlane extends Plane

void takeOff()

System.out.println("Cargoplane is taking off");

void fly()

System.out.println("Cargoplane is flying with the low speed");

void CarryCargo()

System.out.println("Cargoplane is carrying the goods");

class PassengerPlane extends Plane


{

void fly()

System.out.println("Passengerplane is flying with the medium speed");

void CarryPassenger()

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

class FighterPlane extends Plane

void fly()

System.out.println("Fighterlane is flying with the high speed");

void CarryArms()

System.out.println("Fighterplane is carrying the weapons");

class Airport

void allow(Plane ref)

ref.takeOff();

ref.fly();

ref.land();

class Demo1

public static void main(String[] args)

CargoPlane cp = new CargoPlane();


PassengerPlane pp = new PassengerPlane();

FighterPlane fp = new FighterPlane();

Airport a = new Airport();

a.allow(cp);

a.allow(pp);

a.allow(fp);

RULES OF METHOD OVERRIDING

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

RULE 1:

-------

In method overriding the method signature should be same. IE The method name and argument type should be same in
both parent and child class.

eg:

---

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

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

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

-------

METHOD OVERRIDING W.R.T STATIC METHODS:

non-static to static method overriding and static to non-static method overriding is not permited in java.

example:

-------

class A

void fun1()

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


}

class B extends A

static void fun1()

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 memebers can not be overriding.

EXCEPTION HANDLING

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

Exception is unwanted or unexpected event which occurs in the excution of program, which distrubs the normal flow
of the program.

compile time error : The mistake done by the programmer in the code which is caught by the compiler during
compilation phase.

run-time error : The faulty inputs given by the user during the execution time leads to runtime error and it is also called
as 'EXCEPTION'.

The main objective of exception handling is to achive 'graceful termination of the program'.

"Exception handling is the way writing alternative way of code to continue the normal flow of the program. "
EXAMPLE:NORMAL TERMINATION

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

import java.util.*;

class Demo

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.println("enter the value for A");

int a = sc.nextInt();

System.out.println("enter the value for B");

int b = sc.nextInt();

System.out.println("A/B is ="+(a/b));

OUTPUT:

-------

enter the value for A

10

enter the value for B

A/B is =5

NOTE: In the above example user as given valid input hence normal termination of the program can be seen.

EXAMPLE : ABRUPT TERMINATION

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

import java.util.*;

class Demo

public static void main(String[] args)

Scanner sc = new Scanner(System.in);


System.out.println("enter the value for A");

int a = sc.nextInt();

System.out.println("enter the value for B");

int b = sc.nextInt();

System.out.println("A/B is ="+(a/b));

OUTPUT:

-------

enter the value for A

10

enter the value for B

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Demo.main(Demo.java:11)

NOTE: In the above program user as not given right input at the time of execution hence it resulted in runtime error or
exception.

In this case JVM acts as DEFAULT EXCEPTION HANDLER and provides the exception details.

NOTE: Exception can be handled with the help of try and catch block.

syntax:

-------

try

risky code

catch (** e)

alternative code to handle the exception

}
EXAMPLE: GRACEFUL TERMINATION by using user difiend exception handler

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

import java.util.*;

class Demo

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.println("enter the value for A");

int a = sc.nextInt();

System.out.println("enter the value for B");

int b = sc.nextInt();

try

System.out.println("A/B is ="+(a/b));

catch (Exception e)

System.out.println("exception occuurred b value must be non-zero positive number");

// ANY RISKY CODE SHOULD PUT INSIDE THE try and catch block.

OUTPUT:

------

enter the value for A

10

enter the value for B

exception occuurred b value must be non-zero positive number


RUN-TIME STACK OR Exception object propogation

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

EXAMPLE:

---------

class Demo1

public static void wakeup()

sleep();

System.out.println("in wakeup method");

public static void sleep()

System.out.println("in sleep method");

public static void main(String[] args)

wakeup();

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

OUTPUT:

-------

in sleep method

in wakeup method

in main method

REFER FIG:

EXAMPLE:

--------
class Demo1

public static void wakeup()

System.out.println(10/0);

sleep();

public static void sleep()

System.out.println("in sleep method");

public static void main(String[] args)

wakeup();

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

OUTPUT:

-------

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Demo1.wakeup(Demo1.java:5)

at Demo1.main(Demo1.java:16)

REFER FIG:

NOTE : w.r.t above programs we have two choice :

1. use user difiend exception handler in the specific method where the exception as araised or:

2. use the UDEH in main method because anyways at the end the control will come to main method.

EXAMPLE :1
----------

class Demo1

public static void wakeup()

try

System.out.println(10/0);

sleep();

catch (Exception e)

System.out.println("exception handled in specific method");

public static void sleep()

System.out.println("in sleep method");

public static void main(String[] args)

wakeup();

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

EXAMPLE:2

-----------

class Demo1

public static void wakeup()

{
System.out.println(10/0);

sleep();

public static void sleep()

System.out.println("in sleep method");

public static void main(String[] args)

try

wakeup();

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

catch (Exception e)

System.out.println("exception handled in main");

Can we have multiple try block in a program?

--> continuous try block is no permitted in java where as continous catch block is permitted.

NOTE: for a single try block we can have multiple catch block in java.

MULTIPLE CATCH BLOCK:

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

EXAMPLE:

--------
import java.util.*;

class Demo

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

try

System.out.println("enter the value of A");

int a = sc.nextInt();

System.out.println("enter the value of B");

int b = sc.nextInt();

System.out.println(a/b);

catch(ArithmeticException e)

System.out.println("learn maths..!");

catch(InputMismatchException e)

System.out.println("plz enter valid inputs ");

catch (Exception e)

System.out.println("invalid");

OUTPUT:

-------

enter the value of A


10

enter the value of B

learn maths..!

enter the value of A

10

enter the value of B

JBSJVBSJ

plz enter valid inputs

final, finally , finalize in exception handling:

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

1. final keyword:

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

final is a keyword which can be used with classes , methods , variables

final class : class will not participate in inheritance.

final methods : that method will not permit to override.

final variables : constants, values associated with it can not be modified.

finally block:

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

finally block always associated with try and catch blocks to maintain the 'clean up code'.

EXAMPLE:

--------

import java.util.*;

class Demo

public static void main(String[] args)

{
Scanner sc = new Scanner(System.in);

try

System.out.println("enter the value of A");

int a = sc.nextInt();

System.out.println("enter the value of B");

int b = sc.nextInt();

System.out.println(a/b);

catch (Exception e)

System.out.println("invalid");

finally

System.out.println("finally executed..!");

OUTPUT:

--------

enter the value of A

10

enter the value of B

finally executed..!

enter the value of A

10

enter the value of B


0

invalid

finally executed..!

--> finally block is used to excute some set of statements which has to be executed if exception occur or it it does not
occur .

finally block is used w.r.t the codes like closing the connection with database,file,network etc..

finalize() method :

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

finalize method is invoked by 'garbage collector' just before destroying an object to perform cleap up activities.

Once finalize work is completed the G.C will destory the object.

NOTE: finally block is responisble to clean up the things w.r.t try block whereas finalize deal with exception object.

EXCEPTION OBJECT:

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

The main purpose of the catch block is to catch the exception from try block.

The exception is created as a object inside the heap memory segment.

REFER DIA

To get the information present in the exception object:

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

1. e.printStackTrace();

2. s.o.p(e);

3. s.o.p(e.getMessage());

NOTE: exception object consist of name,description, location of the exception.

EXAMPLE:
--------

import java.util.*;

class Demo1

public static void main(String[] args)

try

Scanner sc = new Scanner(System.in);

System.out.println("enter the value of A");

int a = sc.nextInt();

System.out.println("enter the value of B");

int b = sc.nextInt();

System.out.println(a/b);

catch (Exception e)

e.printStackTrace();

System.out.println();

System.out.println(e);

System.out.println();

System.out.println(e.getMessage());

OUTPUT:

-------

enter the value of A

10

enter the value of B

java.lang.ArithmeticException: / by zero

at Demo1.main(Demo1.java:15)
java.lang.ArithmeticException: / by zero

/ by zero

enter the value of A

10

enter the value of B

SDSCFSVF

java.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:864)

at java.util.Scanner.next(Scanner.java:1485)

at java.util.Scanner.nextInt(Scanner.java:2117)

at java.util.Scanner.nextInt(Scanner.java:2076)

at Demo1.main(Demo1.java:13)

java.util.InputMismatchException

null

TYPES OF EXCEPTIONS:

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

There are two types of exceptions in java:

1. PRE-DEFINED EXCEPTIONS

2. USER DIFINED EXCEPTIONS

REFER dia Exception hierarchy

1. pre - defined exceptions

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

All the exceptions present in the exception hierarchy is considered as pre defiend exceptions

There are two types of pre - defined exceptions

1. Checked Exceptions

2. Unchecked Exceptions
What is the difference b/w checked exception and unchecked exceptions?

-->Chekced exceptions is an exception recognized at compile time,but, not occurred at compilation time.

Unchecked exceptions are not recognize at compile time,these exceptions are recognized at runtime by JVM.

NOTE: In exceptions hierarchy, Runtime exceptions and its sub-class and error and its sub-classes are the example for
unchekced exceptions.

All the remaining exceptions are example for cheked exceptions.

There are two types of checked exceptions are:

1. pure checked exception

2. partially checked exceptions

what is the difference b/w pure and partially checked exceptions?

--> Pure checked exceptions is having only chekced exceptions as sub classes in it.

ex: IO exception

partially checked exception where atleast one sub class as unchecked exception present in it.

ex: Exception , throwable

Examples for unchecked exceptions:

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

note: all the sub-classes under RUNTIME EXCEPTIONS are unchecked exceptions

1. Arithmetic exception:

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

EXAMPLE:

--------

// Arithmetic exception

class Demo

public static void main(String[] args)

{
int i = 10;

int j = 0;

float f = i/j;

System.out.println(f);

OUTPUT:

--------

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Demo.main(Demo.java:8)

2. NullPointer Exception

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

EXAMPLE:

--------

// NullPointer exception

class Demo

public static void main(String[] args)

String s = null;

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

OUTPUT:

--------

Exception in thread "main" java.lang.NullPointerException

at Demo.main(Demo.java:7)
3. ArrayIndexOutOfBounds exceptions:

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

EXAMPLE:

--------

// ArrayIndexOutOfBoundsException

class Demo

public static void main(String[] args)

int a[] = {1,2,3,4,5};

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

OUTPUT:

--------

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

at Demo.main(Demo.java:7)

4.StringIndexOutOfBoundsException:

EXAMPLE:

--------

// StringIndexOutOfBoundsException:

class Demo

public static void main(String[] args)

String s = "sagar";

System.out.println(s.charAt(5));

}
}

OUTPUT:

--------

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5

at java.lang.String.charAt(String.java:658)

at Demo.main(Demo.java:7)

5. ClassCastException:

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

EXAMPLE:

---------

// ClassCastException:

class A

class B extends A

class Demo

public static void main(String[] args)

A a = new A();

B b = new B();

//B b = (B)a;

A a1 = b;

OUTPUT:

-------

Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B

at Demo.main(Demo.java:14)
NOTE: In java programs we are able to keep sub-class(child class) object reference value in the super-class(parent
class) reference variable,but

parent class object reference value can not be kept in child class variable.

If we try to do so we will get classCastException.

6.ClassNotFoundException:

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

EXAMPLE:

--------

// ClassNotFoundException:

class A

System.out.println("class loading...!");

class Demo

public static void main(String[] args)

Class c = Class.forName("XYZ");

OUTPUT:

-------

emo.java:12: error: unreported exception ClassNotFoundException; must be caught or declared to be thrown

Class c = Class.forName("XYZ");

EXAMPLES FOR ERRORS IN JAVA:

----------------------------
1. OutOfMemory Error:

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

EXAMPLE:

---------

// OutOfMemoryError:

class Demo

public static void main(String[] args)

boolean ar[] = new boolean [2147483647];

OUTPUT:

--------

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit

at Demo.main(Demo.java:6)

2. stackOverflow Error:

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

refer dia:1

EXAMPLE:

--------

// StackOverflowError:

public static void main(String[] args)

fun1();

static void fun1()

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

OUTPUT:

--------

Exception in thread "main" java.lang.StackOverflowError

EXAMPLE FOR CHECKED EXCEPTION:

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

EXAMPLE:

--------

import java.io.*;

class Demo

public static void main(String[] args)

try

FileReader r = new FileReader("abc.txt");

catch (FileNotFoundException e)

System.out.println("file not found");

OUTPUT:

-------

file not found

'throw' keyword:

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

-->'Explicitly creating exception object'.


case-1

-------

class Demo

public static void main(String[] args)

System.out.println(10/0);

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Demo.main(Demo.java:5)

note: exception handled by jvm(default)

case-2

-------

class Demo

public static void main(String[] args)

throw new ArithmeticException("/ by zero");

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Demo.main(Demo.java:5)

note: exception handled by jvm(manually)

As a programmer we can create a exception explicitly and handover to the jvm manually.To perform this activity we
need thorw keyword.
EXAMPLE:

---------

import java.util.*;

class Demo

public static void main(String[]args)

Scanner sc = new Scanner(System.in);

System.out.println("enter the value of A");

int a = sc.nextInt();

System.out.println("enter the value of B");

int b = sc.nextInt();

System.out.println(divide(a,b));

public static int divide (int a ,int b)

if (b<0)

throw new ArithmeticException ("/ by zero");

else if(b>a)

throw new ArithmeticException ("b>a");

return a/b;

OUTPUT:

-------

enter the value of A

10

enter the value of B

2
5

enter the value of A

10

enter the value of B

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Demo.divide(Demo.java:23)

at Demo.main(Demo.java:11)

enter the value of A

10

enter the value of B

20

Exception in thread "main" java.lang.ArithmeticException: b>a

at Demo.divide(Demo.java:21)

at Demo.main(Demo.java:11)

NOTE: throw keyword is best suitable for customized exception.

case-1

-------

class Demo1

static ArithmeticException e = new ArithmeticException();

public static void main(String[] args)

throw e;

OUTPUT:

-------

Exception in thread "main" java.lang.ArithmeticException

at Demo1.<clinit>(Demo1.java:3)
case-2

-------

class Demo1

static ArithmeticException e ;

public static void main(String[] args)

throw e;

OUTPUT:

--------

Exception in thread "main" java.lang.NullPointerException

at Demo1.main(Demo1.java:6)

NOTE: First we must create the exception object using new keyword and then we can throw that exception. Without
creating exception object if we

try to throw the exception we will get nullpointerexception because there is no exception object in the memory.

case-3

------

class Demo1

public static void main(String[] args)

System.out.println(10/0);

System.out.println("hello world");

OUTPUT:

-------

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Demo1.main(Demo1.java:5)
case-4

-------

class Demo1

public static void main(String[] args)

throw new ArithmeticException("/by zero");

System.out.println("hello world");

OUTPUT:

-------

Demo1.java:6: error: unreachable statement

System.out.println("hello world");

NOTE: The line below the exception is not excecuted because jvm stops the flow of execution immeaditly after finding
exception object.

In case of throw keyword the lines below throw statements are unreachable statments.

case-5

-------

class Demo1

public static void main(String[] args)

throw new Demo1();

OUTPUT:

-------

Demo1.java:5: error: incompatible types: Demo1 cannot be converted to Throwable

throw new Demo1();

^
case-6

-------

class Demo1 extends RuntimeException

public static void main(String[] args)

throw new Demo1();

OUTPUT:

-------

Exception in thread "main" Demo1

at Demo1.main(Demo1.java:5)

NOTE: All the java objects are not throwable.Only throwable objects can be thrown using throw keyword.

IMPORT STATEMENTS

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

// EXAMPLE:1

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

class Demo

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

//System.out.println("Hello World!");

class Test
{

Scanner sc = new Scanner(System.in);

OUTPUT:

-------

compilation error

NOTE: In the above program when compile, we will get compilation eror because we have not specify the location of
the Scanner class.

This problem can be overcome by 'fully qualified name'.

// EXAMPLE:2 fully qualified name

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

class Demo

public static void main(String[] args)

java.util.Scanner sc = new java.util.Scanner(System.in);

class Test

java.util.Scanner sc = new java.util.Scanner(System.in);

NOTE: Usage of fully qualified names in the program leads to readablity probelm and also the code length will
increase.

To overcome this problem we will use import statements in the java programs

// EXAMPLE:3 import statement

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

import java.util.Scanner;

class Demo
{

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

class Test

Scanner sc = new Scanner(System.in);

NOTE: Import statements are used to import the class into the program or to bring class into visibility inside the
program.

TYPES OF IMPORT STATEMENTS:

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

There are two types of import statements :

1. EXPLICIT import statements eg: import java.util.Scanner;

2 IMPLICIT import statements eg: import java.util.*;

AMBIGUITY PROBLEM IN IMPORT STATEMENTS:

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

import java.util.*; //IIS

import java.sql.*; //IIS

class Demo

public static void main(String[] args)

Date d = new Date(1);

}
output:

compilation error

Flow of execution of import statements:

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

1. Always Explicit import statements will execute first

EXAMPLE:

---------

import java.util.Date; //EIS

import java.sql.*;

class Demo

public static void main(String[] args)

Date d = new Date(1);

System.out.println(d.getClass().getName());

OUTPUT:

-------

java.util.Date

2. Implicit import statements wil be executed.

EXAMPLE:

--------

import java.util.*;

//import java.sql.*;

class Demo

public static void main(String[] args)


{

Date d = new Date(1);

System.out.println(d.getClass().getName());

OUTPUT:

----------

java.util.Date

STATIC IMPORT:

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

From the 1.5 version of java static import statemnts we can use to access the static members [methods and variables]
without using the class name.

EXAMPLE FOR NORMAL IMPORT:

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

class Demo

public static void main(String []args)

System.out.println(Math.sqrt(4));

OUTPUT:

-------

2.0

EXAMPLE FOR STATIC IMPORT :

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

import static java.lang.Math.*;

class Demo

public static void main(String []args)

System.out.println(sqrt(4));
}

output:

--------

2.0

EXAMPLE:

----------

class Demo

public static void main(String []args)

System.out.println("hi ");

System.out.println("welocme to ");

System.out.println("Java classes..! ");

EXAMPLE:

---------

import static java.lang.System.*;

class Demo

public static void main(String []args)

out.println("hi ");

out.println("welocme to ");

out.println("Java classes..! ");

DIFFERENCE B/W IMPORT STATEMENT AND STATIC IMPORT STATEMENT :


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

IMPORT STATEMENTS:

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

1. Import classes and interface present in package

2. provide more readblity

eg: System.out

Math.sqrt()

STATIC IMPORT:

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

1. Import static members without using the class name

2. less readability

PACKAGES

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

Package is the collection of related classes and interfaces as a single unit.

packages is a folder contains .class files representing related classes and interface

In java applications packages are able to provide the following advantages:

1. MODULARITY

2. ABSTRATCION

3. SECURITY

4. SHARABILITY

5. REUSABILITY

1. MODULARITY: Dividing the requirment into number of pieces and providing soloution for every individual parts
and combining all the solution

to single is called as modularity.

Module is a folder that contains .class files representing the related classes and interface

packages are used to improve the modularity in the application.


2. ABSTRACTION: If we declare classes or interface in a module/package then that classes are not visible in outside
the package by default.

hence packages can be used for ABSTRACTION.

3.SECURITY: In java apps packages are able to provide abstraction and encapsulation where both are provide security
to the app.

4.SHARABILITY: I fwe declare packages one time tehn we are able to share that packages content to any no of apps
or module at a time.

5.REUSABILITY: If we declare a packages one time then we are able to reuse any number of time within a single app
or more than one app.

TYPES OF PACKAGES:

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

There are two types of packages:

1. USER DEFINED PACKAGES

2. PREDEFIEND PACKAGES

USER DIFIEND PACKAGES:

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

Synatx for package creation:

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

package package_Name;

Synatax for execution of package:

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

import package_name.*;

EXAMPLE: case:1 --> creation of package in current working directory

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

package p1;

class B
{

public static void main(String[] args)

System.out.println("package creation");

OUTPUT:

-------

C:\Users\SAHANA RAM\Desktop\Program>javac -d . Demo.java

C:\Users\SAHANA RAM\Desktop\Program>java p1.Demo

package creation

C:\Users\SAHANA RAM\Desktop\Program>

EXAMPLE: case:2 --> creation of package in parent directory

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

package p1;

class C

public static void main(String[] args)

System.out.println("package creation 1 ");

OUTPUT:

--------

C:\Users\SAHANA RAM\Music\JAVA\Notes\New folder\1>javac -d .. Demo.java

C:\Users\SAHANA RAM\Music\JAVA\Notes\New folder\1>cd..


C:\Users\SAHANA RAM\Music\JAVA\Notes\New folder>java p2.Demo

package creation

EXAMPLE: case:3 --> creation of package in random directory

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

package p1;

class C

public static void main(String[] args)

System.out.println("package creation 1 ");

OUTPUT:

-------

D:\sep_batch\javaPrograms\DAY-42>javac -d S: C.java

D:\sep_batch\javaPrograms\DAY-42>S:

S:\>java p1.C

package creation 1

EXAMPLE: case:4 --> creation of SUB-package in current directory

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

package p2.p3;

class D

public static void main(String[] args)

System.out.println("sub-package creation ");

}
}

OUTPUT:

--------

D:\sep_batch\javaPrograms\DAY-42>java p2.p3.D

sub-package creation

EXAMPLE: case:5 --> DUPLICATE PACKAGES ARE NOT ALLOWED.

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

package p1;

class D

public static void main(String[] args)

System.out.println("sub-package creation ");

OUTPUT:

-------

D:\sep_batch\javaPrograms\DAY-42>javac -d . D.java

D:\sep_batch\javaPrograms\DAY-42>java p1.D

duplicate packages are not permitted

EXAMPLE: CASE:6 --> Multiple package creation within a same class is not
allowed

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

package p1;

package p2;

class D

public static void main(String[] args)

{
System.out.println("sub-package creation ");

OUTPUT:

-------

D.java:2: error: class, interface, or enum expected

package p2;

case:7

ADDING MULTIPLE CLASSES TO THE SAME PACKAGE:

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

EXAMPLE:

--------

package Multiple.pack1;

class A

public void fun1()

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

class B

public void fun2()

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

class Demo

public static void main(String[] args)

System.out.println("creation of multiple classes within a single package");


A a = new A();

a.fun1();

B b = new B();

b.fun2();

OUTPUT:

-------

D:\sep_batch\javaPrograms\DAY-42>java Multiple.pack1.Demo

creation of multiple classes within a single package

inside class A

inside class B

IMPORTING THE PACKAGES IN THE JAVA:

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

There are 3 ways to import the packages into the java program they are:

1. import package.*; --> implicit import statement

2. import package.className; --> explicit import statement

3. using fully qualified name --> 'fully qualified name'

EXAMPLE:

---------

Student.java

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

package pack2;

public class Student

String name;

int roll_no;

public Student(String name,int roll_no)

this.name=name;

this.roll_no=roll_no;
}

public void getData()

System.out.println("name is :"+name+" roll_no is : "+roll_no);

StudentApp.java

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

package pack1;

//import pack2.*; // implicit import statement

//import pack2.Student; // explicit import statment

class StudentApp

public static void main(String[] args)

pack2.Student s = new pack2.Student("ramu",24); // fully qualified name

s.getData();

OUTPUT:

--------

D:\sep_batch\javaPrograms\DAY-43>javac -d . Student.java

D:\sep_batch\javaPrograms\DAY-43>javac -d . StudentApp.java

D:\sep_batch\javaPrograms\DAY-43>java pack1.StudentApp

name is :ramu roll_no is : 24

PRE-DEFIEND PACKAGES :

------------------------
These packages are provided by JAVA programming language along woth java software.

examples:

----------

1. java.lang

--> This package is default package in java application, and need no to import this package to the present java file,
when we save java file with

.java extension then automatically java.lang package will be imported internally.

This package will provide funadamental classes and interfaces which is required to crearte java programs.

eg: String.class,StringBugffer,StringBuilder,System,class,Int,Float,,,,,,,

2. java.io

--> This package is able to provide predefiend classes and interface inorder to perform the INPUT AND OUTPUT
operations in java.

eg: InputStream,Serializable,FileWriter,FileOutputStream.......................................

3. java.util

--> This package is able to provide all pre-defiend classes and interface to represent the DATA STRUCTURS

eg: Collection,List,Set,Queue,Map,HashMap,LinkedList,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

OTHER IMPORTENT SUB-PACKAGES IN JAVA PACKAGE ARE:

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

java.awt

javax.swing

java.net

java.sql

java.rmi

programming format:
-------------------

The order of programming format is :

1.comment section

2.packages

3.import

4.classes / interface / Enum

TYPES OF COMMENTS IN JAVA :

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

1. Single line comment

2. multiline comment

3. Documentation comment

EXAMPLE FOR SINGLE LINE COMMENT:

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

// This program add two numbers

class Demo

public static void main(String[] args)

int a;

int b;

int c;

a=20;

b=5;

c=a+b;

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

OUTPUT:

-------

the sum is:25


EXAMPLE FOR MULTI-LINE COMMENT:

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

/* This program add two numbers

also subtarct two numbers

multiply two numbers */

class Demo

public static void main(String[] args)

int a;

int b;

int c;

a=20;

b=5;

c=a+b;

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

c=a-b;

System.out.println("the difference is:"+c);

c=a*b;

System.out.println("the product is:"+c);

OUTPUT:

-------

the sum is:25

the difference is:15

the product is:100

EXAMPLE FOR JAVA DOCUMENTATION :

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

/**

*This is documentation comment


*/

public class Demo

/**

* @param a first value

* @param a first value

* @return sum of a and b

*/

public int sum(int a, int b)

return a+b;

NOTE: JAVADOC COMMAND WILL CREATE A HTML PAGE IN WHICH THE DOCUMENTATED DETAILS
WILL BE PRESENT.

'throws' keyword

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

--> In Java program if there is a possibility of rising checked exception then compulsorly we should handle it.

case-1

-------

EXAMPLE:

---------

import java.io.*;

class Demo

public static void main(String[] args)

PrintWriter pw = new PrintWriter("abc.txt");

System.out.println("Hello World!");

OUTPUT:
-------

unreported exception FileNotFoundException; must be caught or declared to be thrown

PrintWriter pw = new PrintWriter("abc.txt");

Case-2

-------

EXAMPLE:

--------

import java.io.*;

class Demo

public static void main(String[] args)

Thread.sleep(10000);

OUTPUT:

--------

unreported exception InterruptedException; must be caught or declared to be thrown

Thread.sleep(10000);

NOTE: From the above examples we came to know that whenever checked exception arisied we must either caught is
using try catch block or we must declared

it as thrown using 'throws' keyword.

1. handling checked exception using try and catch block:

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

case-3

------

EXAMPLE:

--------

import java.io.*;

class Demo

public static void main(String[] args)


{

try

Thread.sleep(10000);

catch (InterruptedException e)

System.out.println("exception caught..!");

OUTPUT:

-------

*normal termination of the program.*

2. handling the checked exception using throws keyword

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

case-4

------

EXAMPLE:

--------

import java.io.*;

class Demo

public static void main(String[] args) throws InterruptedException

Thread.sleep(10000);

OUTPUT:

-------

*normal termination of the program.*


NOTE: throws keyword is used to duck an exception.

--> throws keyword will not handle the exception rather it will duck the exception or propagate the exception to the
caller.

--> throws keyword is used only for checked exception.using throws keyword on unchecked exception will not make
any impact.

--> it will not lead to normal termination of the program it just helps for compiling the code successfully.

case-5

-------

EXAMPLE:

--------

import java.io.*;

class Demo

public static void main(String[] args) throws ArithmeticException

System.out.println(10/0);

OUTPUT:

-------

--> throws keyword is having no impact on unchecked exception.

NOTE: throws keyword we can use to delegate responsbility of exception handling to the caller[method,main,jvm].

case-6

-------

EXAMPLE:

--------

import java.io.*;

class Demo

public static void main(String[] args) throws InterruptedException

{
method1();

public static void method1() throws InterruptedException

method2();

public static void method2() throws InterruptedException

method3();

public static void method3() throws InterruptedException

Thread.sleep(10000);

OUTPUT:

-------

*normal termination of the program.*

NOTE: throws keyword is applicable for methods constructors.

EXAMPLE:

---------

import java.io.*;

class Demo

public Demo() throws Exception

public void m1() throws Exception

public static void main(String[] args)

{
}

OUTPUT:

-------

*normal termination of the program.*

NOTE: throws keyword is not applicable for top-level class.

EXAMPLE:

--------

import java.io.*;

class Demo throws Exception

public Demo() throws Exception

public void m1() throws Exception

public static void main(String[] args)

OUTPUT:

-------

Demo.java:2: error: '{' expected

class Demo throws Exception

NOTE: throws keyword is applicable only for throwable objects[CHECKED EXCEPTION ONLY]
EXAMPLE:

--------

import java.io.*;

class Demo

public static void main(String[] args) throws Demo

OUTPUT:

-------

incompatible types: Demo cannot be converted to Throwable

public static void main(String[] args) throws Demo

EXAMPLE:

--------

import java.io.*;

class Demo extends RuntimeException

public static void main(String[] args) throws Demo

OUTPUT:

-------

*normal termination of the program.*

EXAMPLE:

--------
import java.io.*;

class Demo

public static void main(String[] args) throws Exception

throw new Exception();

OUTPUT:

-------

*normal termination of the program.*

EXAMPLE:

---------

import java.io.*;

class Demo

public static void main(String[] args) throws Error

throw new Error();

OUTPUT:

-------

*throw and throws keywords impacts only on exceptions and not on errors*

conclusion:

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

try : to maintain the risky code of the program.

catch : to maintain exception handlind code of the program


finally : to maintain the clean up code of the program

throw : to excplicitly create the exception object and hand over to jvm.

throws : to delegate the responsibility of exception handling to the caller method [where caller method may be a
method or constructor or jvm]

USER-DIFIEND EXCEPTION or CUSTOMIZED EXCEPTION

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

--> We can create our own exceptions by extending exception class

EXAMPLE:

--------

import java.util.*;

class DistinctionException extends RuntimeException

DistinctionException(String exp_msg)

super(exp_msg);

class FirstClassException extends RuntimeException

FirstClassException(String exp_msg)

super(exp_msg);

class SecondClassException extends RuntimeException

SecondClassException(String exp_msg)

super(exp_msg);

}
}

class CustException

public static void main(String[] args)

System.out.println("welcome to grade checking app..!");

System.out.println("Enter your total percentage");

Scanner sc = new Scanner(System.in);

int percentage = sc.nextInt();

if (percentage>=75)

throw new DistinctionException("Distinction ....congrats");

else if (percentage>=60)

throw new FirstClassException("FirstClass ....still you have scope to improve");

else if (percentage>=35)

throw new SecondClassException("SecondClass ....work hard to get good marks..!");

else

System.out.println("Fail ... better luck next time...!");

OUTPUT:

-------

welcome to grade checking app..!

Enter your total percentage

65

Exception in thread "main" FirstClassException: FirstClass ....still you have scope to improve

at CustException.main(CustException.java:39)
RE-THROWING THE EXCEPTION:

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

--> The process of catching an exception and throwing it to the caller method is called as re-throwing the exception.

EXAMPLE:

--------

import java.io.*;

class Demo1

public static void main(String[] args)

//String path = "C:\\Users\\SagarRam\\Desktop\\day-12pics\\8790234-6615085-image-a-


90_1548071159289.jpg";

String path = "abc.txt";

try

open(path);

catch (FileNotFoundException e)

e.printStackTrace();

public static void open(String path) throws FileNotFoundException

try

FileReader r = new FileReader(path);

catch (FileNotFoundException e)

System.out.println(e);

throw e;

}
}

OUTPUT:

-------

java.io.FileNotFoundException: abc.txt (The system cannot find the file specified)

java.io.FileNotFoundException: abc.txt (The system cannot find the file specified)

at java.io.FileInputStream.open0(Native Method)

at java.io.FileInputStream.open(FileInputStream.java:195)

at java.io.FileInputStream.<init>(FileInputStream.java:138)

at java.io.FileInputStream.<init>(FileInputStream.java:93)

at java.io.FileReader.<init>(FileReader.java:58)

at Demo1.open(Demo1.java:22)

at Demo1.main(Demo1.java:10)

VALID and INVALID BLOCKS w.r.t EXCEPTION HANDLING:

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

1. invalid

----------

try

2. invalid

----------

try

try
{

catch ()

3. valid

---------

try

try

catch ()

catch ()

4. invalid

----------

catch ()

5.invalid

---------

catch ()

finally
{

6. valid

---------

try

catch ()

finally

7. invalid

-----------

try

finally

finally

8.valid

---------

catch (ArithmeticException | InputMismatchException | NullPointerException e)


9.invalid

----------

catch (FileNotFoundException | IOException e)

10. valid

-----------

try

try

catch ()

catch ()

finally

ACCESS_MODIFIERS

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

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

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

NOTE:In java there is not concept of access_specifiers.

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

ACCESS_MODIFIERS IN JAVA:

-------------------------
1. public

2. protected

3. default

4. private

5. final

6. abstract

7. static

8. synchronized

9. native

10. strictfp

11. transient

12. volatile

ACCESS_MODIFERIS availble for user-difiend classes:

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

1. public

2. default

3. final

4. abstract

5. strictfp

ACCESS_MODIFERIS availble for inner-classes:

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

1. public

2. default

3. final

4. abstract

5. strictfp

6. private

7. protected

8. static
PUBLIC/DEFAULT access_modifers w.r.t classes:

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

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

EXAMPLE:

--------

package pack1;

public class A

public void fun1()

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

package pack2;

import pack1.A;

class B

public static void main(String[] args)

A a = new A();

a.fun1();

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

OUTPUT:

-------

inside pack1

inside pack2 of class B

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

if UDC is public in nature then members of that class can be accessed within the same package and also from differnt
packages.
EXAMPLE:

--------

class Demo

public void fun1()

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

class Demo1

public static void main(String[] args)

Demo d = new Demo();

d.fun1();

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

OUTPUT:

-------

inside class Demo

inside class Demo1

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

if UDC is default in nature then members of that class can be accessed within the same package and can not be
accessed from differnt packages.

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

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

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

(refer class notes(abstract concept))

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

1. final

2. synchronized[multithreading]

3. private

4. native

5. static

6. strictfp

strictfp [strict floating point] ACCESS_MODIFIER:

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

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

eg: 10/3 --> 3.33333

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

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

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

strictfp w.r.t methods:

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

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

independence

strictfp w.r.t classes:

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

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

Note: abstract and strictfp is a illegal combination

EXAMPLE:

--------
abstract strictfp class Demo2

abstract strictfp void fun1()

public void fun100()

abstract void method1();

abstract void method2();

OUTPUT:

-------

illegal combination

METHOD LEVEL AND VARIABLE LEVEL ACCESS MODIFIERS:

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

1. public methods and variables:

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

2. default members:

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

3. private members:

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

4. protected members:

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

EXAMPLE:

--------
package p1;

public class sample

protected void fun1()

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

package p2;

import p1.sample;

class sample2 extends sample

public static void main(String[] args)

//sample s = new sample();

//s.fun1();

//sample s = new sample2();

//s.fun1();

sample2 s2 = new sample2();

s2.fun1();

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

OUTPUT:

-------

inisde pack p1 and class sample and method fun1

inside sample2 and pack p2

[ACCESS-MODIFIES PART-2]

----------------------------
static access-modifier:

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

--> static access modfiers is applicable only on methods and variables and not applicable on top level classes.

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

legal combinations:

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

static variable

static block

static method

static nested class

native access_modifier:

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

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

native keyword is used because:

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

1. to improve the performance of the program.

2. to achive the memory level communication

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

syntax for native keyword is:

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

1. load the native libraries

2. declare a native method

3. invoke a native method

EXAMPLE:

---------

class Demo

static

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


}

public native void fun1();

// implementation is already available

class Demo1

public static void main(String[] args)

Demo d = new Demo();

d.fun1();

OUTPUT:

-------

native libraries path:

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

at Demo.fun1(Native Method)

at Demo1.main(Demo1.java:15)

illegal combinations with native:

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

native and abstract

native and strictfp

adv: performance of the program

dis_adv: program may become platform dependent.

transient access_modifier:

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

--> this access_modifier is only applicable for variables.It is used only during the process of 'serialization mechanism'.
serialization : saving the data of an object in a file.

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

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

volatile access-modifiers:

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

--> it is applicable only to variable.

int a = 25; --> p1/t1

int a = 25; --> p2/t2

int a = 25; --> p3/t3

but,

creation of seprate local copies evrytime leads to complexity of program execution.

and also memory usage will be ineffient.

the problem of 'data consistency ' can be solved.

note: it is almost deprecated modifier in java.

DAY-25
-------
STRINGS
Strings is a collection of characters or a array of characters.It is a non-primitive datatype.In java Strings are treated as
object becuase the memory
is allocated in heap segment.
Example: Sagar,StudyOnline,Java,September.......etc

Based on creation of the creation of the strings it is classified into two types:
1.IMMUTABLE STRINGS
2.MUTABLE STRINGS

IMMUTABLE STRING:
Immutable strings are such strings once it is created it can not be altered or changed.

Mulitiple ways in which immutable strings can be created.

1.String s = new String("sagar");


2.String s = "sagar";
3.char []a ={a,b,c,d};
4.byte[] a={97,98,99,100};

refer the diagram

-->Whenever we create a string using new keyword then the strings is created in heap segment[non-constant pool] and
here duplicates are not allowed.
-->Whenever we create a string without using new keyword then the strings is created in heap segment[constant pool]
and here duplicates are allowed.

COMPARING THE STRINGS USING STRING CLASS:


-----------------------------------------
1. Using the ==
2. using the equals() method
3. using the equalsIgnorecase() method
4. using the compareTo() method

EXMAPLE:1
// comparing the two strings using the == symbol.

class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagar";
if(s1 == s2)
{
System.out.println("reference are equal");
}
else
{
System.out.println("reference are not equal");
}
}
}
OUTPUT:
-------
reference are equal

NOTE: == symbol will always compare the memory address of the object.

EXAMPLE:2
---------
// comparing the two strings using the equals() method .

class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagar";
if(s1.equals(s2))
{
System.out.println("Strings are equal");
}
else
{
System.out.println("Strings are not equal");
}
}
}
OUTPUT:
-------
Strings are equal.

NOTE: equals method will compare the data present inside the two string objects

EXAMPLE:3
---------
// comparing the two strings using the == symbol .

class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 = new String("sagar");
if(s1 == s2)
{
System.out.println("reference are equal");
}
else
{
System.out.println("refrence are not equal");
}
}
}
OUTPUT:
-------
refrence are not equal

EXAMPLE:4
---------
// comparing the two strings using the equals method .

class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 = new String("sagar");
if(s1.equals(s2))
{
System.out.println("String are equal");
}
else
{
System.out.println("String are not equal");
}
}
}
OUTPUT:
-------
String are equal
EXAMPLE:5
---------
// comparing the two strings using the equalsIgnoreCase() method .

class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 = new String("SAGAR");
if(s1.equalsIgnoreCase(s2))
{
System.out.println("String are equal");
}
else
{
System.out.println("String are not equal");
}
}
}
OUTPUT:
-------
String are equal

NOTE: equalsIgnoreCase() method will compare the data present in the string object by ignoring its case.This is
method is used because java is
case sensitive.

EXAMPLE:6
---------
class Demo1
{
public static void main(String[] args)
{
String s1 = "sagar";
System.out.println(s1);
}
}

NOTE: java.lang.* package(default). Whenever we try to use the String class in the program it will be by default
imported from the jvm.
Whenever we try to print the reference (memory address) of a string, value is displayed instead of address.

EXAMPLE:7
---------

class Demo1
{
public static void main(String[] args)
{
String s1 =new String("sagar");
String s2 =new String("sagar");
String s3 ="sagar";
String s4 ="sagar";
System.out.println(s1 == s3);
System.out.println(s2 == s4);

}
}
OUTPUT:
-------
false
false
DAY-26
------
CONCATINATION OF TWO STRINGS.
Concatination of two strings can be done in two ways:
1. using the + operator
2. using the concate() method.

EXAMPLE:1
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar" + "ram";
String s2 = "sagar" + "ram";
System.out.println(s1==s2); // true
System.out.println(s1.equals(s2)); // true
}
}

EXAMPLE:2
----------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagarram";
String s3 = s1+"ram";
System.out.println(s2==s3); // false
System.out.println(s2.equals(s3)); // true
}
}

NOTE: Whenever we try to concatinatewith the use of variables of strings type then the memory will be allocated in
non-constant pool.
In the above program string value is getting concatinated with a refrence variable hence string varibale s3 is allocated
in non constant pool.

value+value --> constant pool


ref + value --> non-constant pool

EXAMPLE:3
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
s1.concat("ram");
System.out.println(s1); --> sagar
}
}

EXAMPLE:4
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagarram";
String s3 = "sagar";
s1.concat(s3);
s1= s1+"kumar";
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s1==s3);
}
}
output:
sagarkumar
sagarram
sagar
false

EXAMPLE:5
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = "sagarram";
System.out.println(s1 == s2); // false
String s3 = new String("sagar");
String s4 = new String("sagarram");
System.out.println(s3 == s4); // false
System.out.println(s2.equals(s4)); // true
String s5 = "sagarram";
String s6 = "sagar"+"ram";
String s7 = s1+"ram";
System.out.println(s6==s7); // false

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);

}
}
OUTPUT:
-------
false
false
true
false
sagar
sagarram
sagar
sagarram
sagarram
sagarram
sagarram

WHY STRINGS ARE IMMUTABLE IN JAVA?


refer diagram

NOTE: in java one object can have multiple refrence variables.In the same way any modification done on the object
will result in creation of brand
new object.
In a project if a string object is same for multiple refrences then instead of creating mutiple string object we create a
single string object which
will be shared among multiple refrence variable.

Hence it improves the performance of the program.These strings can be created without using the new keyword and
memory for such strings will be allocated
in constant pool.

The problem in this apporach is since multiple ref are pointing to same object modification made by one of the ref
variable on object will affect the
other reference variables also,
inorder to overcome this problem strings are made it as immutable.ie once the string is created it can not be altered any
modification perdformed will
result in creation of brand new object.

inbuilt methods in strings:


--------------------------
EXAMPLE:
----------
class Demo
{
public static void main(String[] args)
{
String s1 = new String("studyonline");
String s2 = new String("STUDYONLINE");

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

System.out.println(s1.toUpperCase());
System.out.println(s2.toLowerCase());

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

System.out.println(s1.startsWith("stu"));
System.out.println(s1.endsWith("ine"));

System.out.println(s1.contains("dyon"));

System.out.println(s1.indexOf("y"));

System.out.println(s1.charAt(4));
}
}
output:
-------
studyonline
STUDYONLINE
STUDYONLINE
studyonline
11
true
true
true
4
y

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

DAY-27
------
EXAMPLE:1
----------
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
s1.concat("ram");
System.out.println(s1);
}
}
OUTPUT:
-------
sagar

EXAMPLE:2
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
s1.concat("ram");
System.out.println(s1);
}
}
OUTPUT:
-------
sagar

intern() method:
----------------
It is used to create the copy of string object in the constant pool with the help of non-constant pool reference.

EXAMPLE:1
--------
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 = s1.intern();
System.out.println(s1);
System.out.println(s2);
System.out.println(s1 == s2);
}
}
OUTPUT:
-------
sagar
sagar
false

EXAMPLE:2
----------
class Demo
{
public static void main(String[] args)
{
String s1 = "sagar";
String s2 = new String("sagar");
String s3 = s2.intern();
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s1 == s3);

}
}
OUTPUT:
-------
sagar
sagar
sagar
false
false
true

trim() method.
--------------
It is used to remove the blank spaces in the begging and ending of the string.However it will not remove the spaces in
b/w the strings.

EXAMPLE:1
---------
class Demo
{
public static void main(String[] args)
{
String s1 = " Study Online ";

System.out.println(s1.trim());
}
}
OUTPUT:
-------
Study Online

charAt() method.
-----------------
The character in the string cannot be accessed directly.It can be accessed only using charAt() method.

EXAMPLE:1
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "Study Online";

System.out.println(s1[2]);
}
}
OUTPUT:
-------
COMPILATION ERROR

EXAMPLE:2
---------
class Demo
{
public static void main(String[] args)
{
String s1 = "Study Online";

System.out.println(s1.charAt(2));
}
}
OUTPUT:
-------
u

compareTo() method.
-------------------
refer diagram:

It is used to compare two strings lexio graphically ie each character in both the strings are converted in to unicode and
compared.
when this method is used result will be in fallowing way:

if the res is zero --> strings are equal


if the res is positive --> string s1 is greater than string s2
if the res is negative --> String s1 is lesser than String s2

EXAMPLE:
--------
class Demo
{
public static void main(String[] args)
{
String s1 = "abhilash";
String s2 = "asha";
int res = s1.compareTo(s2);
if(res == 0)
{
System.out.println("Strings are equal");
}
else if (res > 0)
{
System.out.println("String s1 is greater than String s2");
}
else
{
System.out.println("String s1 is lesser than String s2");
}
}
}

OUTPUT:
-------
String s1 is lesser than String s2.

constructors of String class.


-----------------------------
1. String s1 = new String(); --> for empty string

2. String s1 = new String("String value"); -->String s1 = new String("sagar");

3.String s1 = new String(StringBuffer sb);

4.char c[] = {"a","b","c","d"}; -->String s1 = new String(c);

5.byte b[] = {97,98,99,100}; --> String s1 = new String(b)


DAY-28
-------
MUTABLE STRINGS

Whenever the content of the string is frequently changing then dont create the string using String class rather create
using StringBuffer or StringBuilder
class.

If we try to create a string when content are frequently changing using the string class for every modification new
string objects will be created.
Hence it is not recommanded to create such Strings using string class.

EXAMPLE:1
--------
class Demo
{
public static void main(String[] args)
{
//String s1 = new String("sagar");
//String s2 = "sagar";

StringBuffer s1 = new StringBuffer("sagar");

System.out.println(s1);
}
}
OUTPUT:
-------
sagar

EXAMPLE:2
----------
class Demo
{
public static void main(String[] args)
{
String s1 = new String("sagar");
String s2 =s1.concat("ram");
System.out.println(s1);
System.out.println(s2);

}
}
OUTPUT:
-------
sagar
sagarram

EXAMPLE:3
----------
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
System.out.println(s1);
s1.append("ram");
System.out.println(s1);

}
}
OUTPUT:
-------
sagar
sagarram

EXPLAIN THE DIFFERENCE B/W == AND EQUALS() METHOD IN STRING CLASS AND STRINGBUFFER
CLASS.
------------------------------------------------------------------------------------------
String class --> == will compare the memory address of two string objects.
equals() method will compare the data present in the two String objects.

StringBuffer --> == will compare the memory address of two string objects.
equals() method will compare the memory address of the two String objects.

EXAMPLE:4
---------
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
StringBuffer s2 = new StringBuffer("sagar");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1 == s2);

}
}
OUTPUT:
-------
sagar
sagar
false

EXAMPLE:5
----------
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
StringBuffer s2 = new StringBuffer("sagar");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.equals(s2));

}
}

INTERNAL IMPLEMENATION OF THE MUTABLE STRING


--------------------------------------------
Do refer the diagram:

EXAMPLE:1
----------
class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer();
System.out.println(s1);
System.out.println(s1.capacity());
System.out.println(s1.length());

s1.append("students");

System.out.println(s1);
System.out.println(s1.capacity());
System.out.println(s1.length());

s1.append(" prepare for exams");

System.out.println(s1);
System.out.println(s1.capacity());
System.out.println(s1.length());

s1.append(" and get placed in a good company");

System.out.println(s1);
System.out.println(s1.capacity());
System.out.println(s1.length());

}
}
OUTPUT:
---------

16
0
students
16
8
students prepare for exams
34
26
students prepare for exams and get placed in a good company
70
59

ensureCapacity() method.
------------------------
In order to set the capacity for paticular value we can use ensureCapacity() method.

EXAMPLE:1
---------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer();
System.out.println(s1.capacity());
s1.ensureCapacity(1500);
System.out.println(s1.capacity());
}
}
OUTPUT:
-------
16
1500
EXAMPLE:2
---------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer(1500);
System.out.println(s1.capacity());

}
}
OUTPUT:
-------
1500

EXAMPLE:3
---------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
System.out.println(s1.capacity()); // 16 + number of characters
// 16 + 5 = 21

}
}
OUTPUT:
-------
21

FEW INBUILT METHODS WITH RESPECT TO STRINGBUFFER CLASS


------------------------------------------------------
1. charAt(int index) --> to get the character at specific index.
2. setCharAt(int index, char ch) --> to set the character at the given index.
3. deleteCharAt(int index) --> to delete the character at the given index.

EXAMPLE:1
----------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
System.out.println(s1);
System.out.println(s1.charAt(2));

s1.setCharAt(2,'p');
System.out.println(s1);

s1.deleteCharAt(2);
System.out.println(s1);
}
}
OUTPUT:
-------
sagar
g
sapar
saar

insert(int index, String s) method:


------------------------------------
It is used to add string or int or float etc to given index.

EXAMPLE:1
---------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("sagar");
System.out.println(s1);
s1.insert(5,"is a good boy..!");
System.out.println(s1);
s1.insert(0,6);
System.out.println(s1);
}
}
OUTPUT:
-------
sagar
sagaris a good boy..!
6sagaris a good boy..!

delete(int begin index, int end index) method:


-----------------------------------------------
It is used to delete char fromm the begging index to end-1 index

EXAMPLE:
--------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("StudyOnline");
System.out.println(s1);
s1.delete(1,5);
System.out.println(s1);

}
}
OUTPUT:
-------
StudyOnline
SOnline

reverse() method:
-----------------
It is used to reverse the given String

EXAMPLE:
--------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("StudyOnline");
System.out.println(s1);
s1.reverse();
System.out.println(s1);

}
}
OUTPUT:
-------
StudyOnline
enilnOydutS

setLength() method:
-------------------
It is used to set the length of the string.

EXAMPLE:
--------
class Demo1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("StudyOnline");
System.out.println(s1);
s1.setLength(5);
System.out.println(s1);

}
}
OUTPUT:
-------
StudyOnline
Study

DAY-29
-------
METHOD CHAINING WITH RESPECT TO STRINGS.
---------------------------------------
Calling multiple methods in the same line is called as method chaining.

EXAMPLE:
--------
StringBuffer s1 = new StringBuffer("Study");
System.out.println(s1.append("online").reverse().length());

// example for METHOD CHAINING.

class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("study");
System.out.println(s1.append("online").reverse().length());
}
}

OUTPUT:
-------
11 --> always in the method chaining the last method result will be displayed.

CONSTRUCTORS FOR STRINGBUFFER:


------------------------------
1. StringBuffer s1 = new StringBuffer();
2. StringBuffer s1 = new StringBuffer("String value"); --> StringBuffer s1 = new
StringBuffer("StudyOnline");
3. StringBuffer s1 = new StringBuffer(int capacity); --> StringBuffer s1 = new
StringBuffer(1500);
StringBuilder
-------------

StringBuilder is a inbuilt class which is used to create mutable strings.


Most of the methods present in StringBuffer class is also present in StringBuilder class.

EXAMPLE:
--------
class Demo
{
public static void main(String[] args)
{
StringBuilder s1 = new StringBuilder("studyonline");
System.out.println(s1);
s1.append(" java");
System.out.println(s1);

}
}
OUTPUT:
-------
StudyOnline
StudyOnline java

The difference b/w StringBuffer and StringBuilder is:


------------------------------------------------------
StringBuffer
StringBuilder

1. Most of the methods are synchronized 1.Non of the method


is synchronized.
2. It is thread safe. 2.Not a thread safe
3. performance is low 3.
performance is high.

few practise programs with respect to strings.


----------------------------------------------
1.READING THE STRING FROM SCANNER CLASS.

EXAMPLE:1
----------
// example for next() method and nextline() method.
----------------------------------------------------
import java.util.*;
class Demo
{
public static void main(String[] args)
{
System.out.println("enter your name:");
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println("the entered name is :" + s);
}
}
OUTPUT:
-------
enter your name:
SAGAR
the entered name is :SAGAR

EXAMPLE 1.1
-----------
// example for next() method and nextline() method.

import java.util.*;
class Demo
{
public static void main(String[] args)
{
System.out.println("enter your name:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println("the entered name is :" + s);
}
}
OUTPUT:
-------
enter your name:
study Online
the entered name is :study Online

2. REVERSE A GIVEN STRING.


--------------------------
EXAMPLE:
-------
// example for reversing the string

class Demo
{
public static void main(String[] args)
{
String s1 = "students";
String rev ="";
int len =s1.length();
for (int i=len-1;i>=0;i--)
{
rev = rev+s1.charAt(i);
}
System.out.println("Reversed string is :" + rev);
}
}
OUTPUT:
-------
students
Reversed string is stneduts

3. WAP ON STRING PALINDROME


----------------------------
madam --> is a palindrome
students --> is not a palindrome

EXAMPLE:
--------
// example for checking whether the given string is palindrome or not.

class Demo
{
public static void main(String[] args)
{
String s1 = "madam";
String rev ="";
int len =s1.length();
for (int i=len-1;i>=0;i--)
{
rev = rev+s1.charAt(i);
}
System.out.println("Reversed string is :" + rev);

if (s1.equals(rev))
{
System.out.println("the given string is a palindrome");

}
else
{
System.out.println("the given string is not a palindrome");
}

}
}
OUTPUT:
-------
Reversed string is :madam
the given string is a palindrome

4. CONVERTING CHAR ARRAY TO STRING AND VICE-VERSA.


--------------------------------------------------
example for converting char array to sring:
-------------------------------------------
// example for converting char array to string and vice-versa.

class Demo
{
public static void main(String[] args)
{
char c[] = new char[]{'s','t','u','d','y'};

// option 1
String s1 = String.valueOf(c);
System.out.println(s1);

//option 2
String s2 = new String(c);
System.out.println(s2);

}
}
OUTPUT:
-------
study
study

example for converting sring to char array :


-------------------------------------------
// example for converting char array to string and vice-versa.

class Demo
{
public static void main(String[] args)
{

String s1 = "StudyOnline";
System.out.println(s1);
char a[] = s1.toCharArray();
for (char ch :a )
{
System.out.println(ch);
}
}
}
OUTPUT:
-------
StudyOnline
S
t
u
d
y
O
n
l
i
n
e

5.LAST OCCURENCE OF THE GIVEN SUB STRING.


-----------------------------------------
EXAMPLE:
--------
// example for finding the last occurrence for the given sun-string

class Demo
{
public static void main(String[] args)
{

String s1 = "join studyonline to studyonline";


System.out.println(s1);
int a = s1.lastIndexOf("studyonline");
if (a == -1)
{
System.out.println("sub string is not found");
}
else
{
System.out.println("sub string found at the index : "+ a);
}
}
}
OUTPUT:
-------
join studyonline to studyonline
sub string found at the index : 20

ASSIGNMENTS:
------------
1. count the number of vowels and consonents from the given string string --> hello
2. reverse the words present in given string. sentence --> welcome to
studyonline

DAY-31
------
1. number of words in a given string
--------------------------------------
EXAMPLE:
--------
import java.util.*;
class Demo
{
public static void main(String[] args)
{
String str = " join studyonline to learn programming languages";
StringTokenizer s = new StringTokenizer(str);
int count = s.countTokens();
System.out.println("The number of words in the given string is: "+count);
}
}
OUTPUT:
-------
The number of words in the given string is 6

2. remove the white spaces in the given string


-----------------------------------------------
EXAMPLE:
--------

class Demo
{
public static void main(String[] args)
{
String str = " join studyonline to learn programming languages ";
System.out.println(str);
str = str.replaceAll("\\s","");
System.out.println(str);
}
}
OUTPUT:
------
join studyonline to learn programming languages
joinstudyonlinetolearnprogramminglanguages

3. Swapping Strings without using Third variable


-------------------------------------------------
EXAMPLE:
--------
class Demo
{
public static void main(String[] args)
{
String b = "hi had ur dinner? ";
String g = "hmmmm";

System.out.println("strings before swapping:"+b);


System.out.println("strings before swapping:"+g);

b = b+g;
g = b.substring(0,b.length()-g.length());
b=b.substring(g.length());

System.out.println("strings after swapping:"+b);


System.out.println("strings after swapping:"+g);
}
}
OUTPUT:
-------
strings before swapping:hi had ur dinner?
strings before swapping:hmmmm
strings after swapping:hmmmm
strings after swapping:hi had ur dinner?
4.CHECK IF THE GIVEN STRING IS ANAGRAM OR NOT.
----------------------------------------------
example for anagram
--------------------
s1 = "car";
s2 = "rac";

s1 = "from";
s2 = "form";

s1 = "silent";
s2 = "listen";

import java.util.*;
class Demo
{
public static void main(String[] args)
{
String s1 = "listen";
String s2 = "silent";

if (s1.length()!=s2.length())
{
System.out.println("Strings are not anagram");
System.exit(0);
}
char a[]=s1.toCharArray();
char b[]=s2.toCharArray();

Arrays.sort(a);
Arrays.sort(b);

if(Arrays.equals(a,b))
{
System.out.println("Strings are anagram");
}
else
{
System.out.println("Strings are not anagram");
}

}
}
OUTPUT:
-------
Strings are anagram
-----------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------

OBJECT ORIENTATION FEATURES:


----------------------------
ENCAPSULATION
-------------
It refers to wrapping the data(variable) and the code acting on the data(methods) as a single unit.

Encapsulation can be achived using:


1. By making the instance variable as private.
2. By creating Public setter and getter methods in order to access and view the data.

EXAMPLE:
--------
class Student
{
private String name;
private int age;
private int roll_no;

public void SetName(String sname)


{
name=sname;
}
public void SetAge(int sage)
{
age=sage;
}
public void SetRoll_no(int sroll_no)
{
roll_no=sroll_no;
}

public String getName()


{
return name;
}
public int getAge()
{
return age;
}
public int getRoll_no()
{
return roll_no;
}

}
class StudentApp
{
public static void main(String[] args)
{
Student s1=new Student();
s1.SetName("raju");
System.out.println(s1.getName());
s1.SetAge(21);
System.out.println(s1.getAge());
s1.SetRoll_no(84);
System.out.println(s1.getRoll_no());
}
}
OUTPUT:
-------
raju
21
84

EXAMPLE:2
---------
class Student
{
private String name;
private int age;
private int roll_no;

public void SetData(String sname, int sage, int sroll_no)


{
name=sname;
age=sage;
roll_no=sroll_no;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int getRoll_no()
{
return roll_no;
}

}
class StudentApp
{
public static void main(String[] args)
{
Student s1=new Student();
s1.SetData("raju",21,84);
System.out.println(s1.getName());
System.out.println(s1.getAge());
System.out.println(s1.getRoll_no());
}
}
OUTPUT:
-------
raju
21
84

NOTES:
------
1. DATA HIDING:
Data Hiding is hiding the data so that outside person cannot access the data directly. This can be achicved by using
the data members (variable)
as private.

2. Tightly encapsulated class


In a class if all the data members is made as private then such class is called as tightly encapsulated class.

ADAVANTAGES OF ENCAPSULATION:
------------------------------
1. SECURITY TO THE DATA.
2. ENHANCEMENT IS EASY.

-----------------------------------------------------------------------------------------------------------------------------------------------
-------
CONSTRUCTORS
------------------------------

There are 3 ways to intilize the object.


----------------------------------------
1. using the refrence variable
2. using the methods
3. using the constructors

using the reference variable:


-----------------------------
EXAMPLE:
--------
class Student
{
String name;
int roll_no;
}
class Demo2
{
public static void main(String[] args)
{
Student s1 = new Student();
s1.name ="raju";
s1.roll_no = 84;
System.out.println(s1.name);
System.out.println(s1.roll_no);

}
}
OUTPUT:
--------
raju
84

using the methods


---------------------
EXAMPLE:
--------
class Student
{
String name;
int roll_no;

public void SetData(String sname, int sroll_no)


{
name=sname;
roll_no=sroll_no;
}
public String getName()
{
return name;
}
public int getRoll_no()
{
return roll_no;
}
}

class Demo2
{
public static void main(String[] args)
{
Student s1 = new Student();
s1.SetData("somu",89);
System.out.println(s1.getName());
System.out.println(s1.getRoll_no());
}
}
OUTPUT:
-------
somu
89

using the constructors


-----------------------
EXAMPLE:
--------
class Student
{
String name;
int roll_no;

Student(String sname,int sroll_no)


{
name=sname;
roll_no=sroll_no;
System.out.println(name);
System.out.println(roll_no);
}
}

class Demo2
{
public static void main(String[] args)
{
Student s1 = new Student("bheem",28);
Student s2 = new Student("somu",89);

}
}
OUTPUT:
-------
bheem
28
somu
89

Constructor is a special block or method where name of the constructor is same as the class name.
It is a Specialized setter to initilize the object.
Constructor doesnot have any return type.The access modifier allowed for the Constructor method is
public,private,protected,default.
Constructor are always called during the object creation.

You might also like