0% found this document useful (0 votes)
15 views

Batch_37_Notes

The document provides a comprehensive overview of Java programming concepts, including how to add numbers using both direct assignment and command line arguments, the behavior of the '+' operator, and the differences between print() and println() methods. It also covers command line arguments, data type conversions, naming conventions, tokens, and the concept of packages in Java. Additionally, it discusses the implications of Java not being a pure object-oriented language due to the presence of primitive data types and introduces wrapper classes.

Uploaded by

duneshvasa
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Batch_37_Notes

The document provides a comprehensive overview of Java programming concepts, including how to add numbers using both direct assignment and command line arguments, the behavior of the '+' operator, and the differences between print() and println() methods. It also covers command line arguments, data type conversions, naming conventions, tokens, and the concept of packages in Java. Additionally, it discusses the implications of Java not being a pure object-oriented language due to the presence of primitive data types and introduces wrapper classes.

Uploaded by

duneshvasa
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 253

javaravishanker@gmail.

com
22nd August 2024

Write a Program to add two numbers :


------------------------------------
public class Addition
{
public static void main(String[] args)
{
int x = 100;
int y = 200;
int z = x + y;
System.out.println(z);
}
}

How to provide user-friendly message :


--------------------------------------
In order to provide user-friendly message we can use '+' operator.

Behavior of '+' Operator :


--------------------------
1 + 1 = 2 [Here '+' operator is working as Arithmetic Operator]

"1" + 1 = 11 [Here '+' operator is working as Concatenation Operator]

22 + "22" = 2222 [Here '+' operator is working as Concatenation Operator]

"NIT" + 22 = NIT22 [Here '+' operator is working as Concatenation Operator]

While Working with '+' operator, if any of the operand is String type then '+'
operator will behave as String concatenation operator.

//Providing User-friendly message

public class Addition


{
public static void main(String[] args)
{
int x = 100;
int y = 200;
int z = x + y;
System.out.println("The Sum is :"+z);
}
}
--------------------------------------------------------------------------
//Program to add two numbers without using 3rd variable
public class Sum
{
public static void main(String[] args)
{
int x = 100;
int y = 200;

System.out.println("The Sum is :"+x+y); //100200


System.out.println(+x+y); //300
System.out.println(""+x+y);
System.out.println("The Sum is :"+(x+y));
}
}
-------------------------------------------------------------------------
Difference between println() and print() method :
-------------------------------------------------
print() method will print the data and it will keep the cursor in the same line
where as println() method will print the data and move the cursor to the next line.

//Difference between println() and print() method :


public class Printing
{
public static void main(String[] args)
{
System.out.println("Hello "); //Hello
System.out.println("World"); //World

}
}
----------------------------------------------------------------------
Command Line Argument :
-----------------------
If we pass an argument to the main method then it is called command line Argument.

By using command line argument, We can pass some value at runtime i.e. at the time
of execution of the program.

The advantage is, Single time compilation and number of time execution with
different values.

//Program on command Line Argument


public class Command
{
public static void main(String[] args)
{
System.out.println(args[0]);

}
}

javac Command.java
java Command Virat Rohit Scott

It will print Virat


-----------------------------------------------------------------------
//Program to print complete Name of a player
public class FullName
{
public static void main(String[] x)
{
System.out.println(x[0]);

}
}

javac FullName.java
java FullName "Virat Kohli"

It will print Virat Kohli


------------------------------------------------------------------------
//Single time compilation and number of times execution
public class CommandDemo
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}

javac CommandDemo.java

java CommandDemo Scott


It Will print Scott

java CommandDemo Smith


It Will print Smith

java CommandDemo Martin


It Will print Martin
------------------------------------------------------------------------
//Accepting integer value from command line Argument
public class AcceptInteger
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}

javac AcceptInteger.java
java AcceptInteger 100 -> It will print 100
java AcceptInteger 12.90 -> It will print 12.90
java AcceptInteger A -> It will print A

Note : All Command Line Arguments are treated as String Object, even if they
represent another data type like number.
------------------------------------------------------------------------
29-08-2024
-----------
Program to add two numbers by using Command Line Argument :
----------------------------------------------------------
public class CommandAdd
{
public static void main(String[] x)
{
System.out.println(x[0] + x[1]);
}
}

javac CommandAdd.java
java CommandAdd 100 200

It will print 100200 [Here '+' operator will work as String concatenation operator]
-------------------------------------------------------------------------
How to convert a String value into integer :
---------------------------------------------
There is a predefined class called Integer, available in java.lang package. It
contains a predefined static method parseInt(String x), by using this method we can
convert a String into integer value.
Example :
---------
public class Integer
{
public static int parseInt(String x)
{
//Will accept String and convert into integer
}
}
------------------------------------------------------------------------
//Adding two numbers by converting then into integer

public class CommandAddition


{
public static void main(String[] args)
{
String x = args[0];
String y = args[1];

//Converting String into integer


int num1 = Integer.parseInt(x);
int num2 = Integer.parseInt(y);

System.out.println("Sum is :"+(num1 + num2));

}
}
=========================================================================
WAP that describes how exactly Integer.parseInt() is working internally ?
-------------------------------------------------------------------------
public class Calculate
{
public static int doSum(int x, int y)
{
return x+y;
}

public static int getSquareOfNumber(int num)


{
return num*num;
}

public static void main(String[] args)


{
int sum = Calculate.doSum(100,200);
System.out.println("Sum is :"+sum);

int square = Calculate.getSquareOfNumber(5);


System.out.println("Square is :"+square);
}
}
------------------------------------------------------------------------
How to convert a String into double ?
-------------------------------------
double d = Double.parseDouble(String x);
How to convert a String into float ?
-------------------------------------
float y = Float.parseFloat(String x);
=========================================================================
Working with Eclipse IDE :
--------------------------
IDE stands for "Integrated Dvelopment Environment".

By using Eclipse IDE, We can develop, compile and execute our java program in a
single window.

The main purpose of eclipse IDE is reduce the development time, once development
time will be reduced then automatically the cost of the project will be reduced.
------------------------------------------------------------------------
What is a package?
------------------
A package is folder in windows. In java to create a package we are using package
keyword, It must be first statement of the program.

Example :
---------
package basic;

public class Hello


{
}

How to compile : javac -d . Hello.java


[javac space -d space . space FileName.java]

Here one folder will be created called basic (package name ) and Hello.class file
will be automatically placed in the basic folder.

Types of Packages :
---------------------------
1) Predefined OR Built-in package : The packages which are created by java software
people for arranging the programs are called predefined package.

Example : java.lang, java.util, java.io, java.sql, java.net and so on

2) Userdefined Package OR Custom package : The packages which are created by user
for arranging the user-defined programs are called user-defined package.

Example :
basic;
com.ravi.basic;
com.tcs.online_shopping;
------------------------------------------------------------------------
How to execute command line argument program by using Eclipse IDE :
-------------------------------------------------------------------
package basic;

public class Command


{
public static void main(String[] args)
{
System.out.println(args[1]);
}
}

Right click on the program -> Run As -> Run configuration -> Check your main class
name -> select argument tab -> pass the appropriate value -> Run
------------------------------------------------------------------------
Write a program to find out the area of Rectangle where length and breadth of the
Rectangle must be taken from user from command line argument.

package basic;

public class AreaOfRectangle


{
public static void main(String[] args)
{
int length = Integer.parseInt(args[0]);
int breadth = Integer.parseInt(args[1]);

int areaOfRect = length * breadth;


System.out.println("Area of Rect is :"+areaOfRect);
}
}
-------------------------------------------------------------------------
30-08-2024
-----------
Naming convention in java ?
----------------------------
Naming convention provides two important characteristics :

a) Standard Code (Industry accepted code)


b) Readability of the code will enhance.

1) How to write a class in java :


----------------------------------
While writing a class in java, we should follow pascal naming convention.
Here first character of each word must be capital. In java, a class represents
noun.

Example :
---------
ThisIsExampleOfClass

System
String
Integer
DataInputStream
ArrayIndexOutOfBoundsException
Object
BufferedReader

2) How to write a method in java :


----------------------------------
While writing a method we should follow camel case naming convention, according to
this from 2nd word onwards first character of each word must be in capital. It
represents verb.

Example :
thisIsExampleOfMethod
parseInt()
readLine()
read()
print()
println()
toUpperCase()
toLowerCase()

3) How to write a field/variable in java :


-------------------------------------------
While writing a variable we should follow camel case naming convention but unlike
method variable does not have () symbol.

Example :
----------
rollNumber
customerName
customerBill
studentName
playerName

4) How to write a final and static variable :


---------------------------------------------
While writing the final and static variable we should follow snake_case naming
convention.

Example :
Integer.MIN_VALUE [MIN_VALUE is final and static variable]
Integer.MAX_VALUE [MAX_VALUE is final and static variable]

5) How to write a package :


---------------------------
A package must be written in lower case only. Generally it is reverse of company
name.

com.nit.basic
com.tcs.introduction
com.wipro.shopping

-------------------------------------------------------------------------
Tokens in java :
----------------
Token is the smallest unit of the program which is identified by the compiler.

Without token we can't complete statement or expression in java.

Token is divided into 5 types in java

1) Keyword
2) Identifier
3) Literal
4) Punctuators (Seperators)
5) Operator

Keyword
--------
A keyword is a predefined word whose meaning is already defined by the compiler.
In java all the keywords must be in lowercase only.

A keyword we can't use as a name of the variable, name of the class or name of the
method.

true, false and null look like keywords but actually they are literals.

As of now, we have 67 keywords in java.


--------------------------------------------------------------------
Identifiers :
--------------
A name in java program by default considered as identifiers.

Assigned to variable, method, classes to uniquely identify them.

We can't use keyword as an identifier.

Ex:-

class Fan
{
int coil ;

void switchOn()
{
}
}

Here Fan(Name of the class), coil (Name of the variable) and switchOn(Name of the
Method) are identifiers.
-----------------------------------------------------------------------------------
-
Rules for defining an identifier :
------------------------------------
1) Can consist of uppercase(A-Z), lowercase(a-z), digits(0-9), $ sign, and
underscore (_)
2) Begins with letter, $, and _
3) It is case sensitive
4) Cannot be a keyword
5) No limitation of length
-------------------------------------------------------------------------
Literal :
---------
The constant values which we are assigning to a variable is called literal.

In java we have 5 types of Literals :

1) Integral Literal
2) Floating Point Literal
3) Character Literal
4) Boolean Literal
5) String Literal

Note : null is also literal.


-------------------------------------------------------------------------
Integral Literal :
------------------
If any numeric literal does not contain decimal or fraction then it is called
Integral Literal.

Example : 34, 100, 45, 900

In order to represent an integral literal, we have 4 data types


byte (8 bits)
short (16 bits)
int (32 bits)
long (64 bits)

An integral literal we can represent in four different forms

a) Decimal Literal
b) Octal Literal
c) Hexadecimal Literal
d) Binary Literal (Available from JDK 1.7)

Decimal Literal :
-----------------
By default our numeric literals are decimal literal. Here base is 10 so, It accepts
10 digits i.e. from 0-9.

Example :
int x = 20;
int y = 123;
int z = 234;

Octal Literal :
---------------
If any Integer literal starts with 0 (Zero) then it will become octal literal. Here
base is 8 so it will accept 8 digits i.e 0 to 7.

Example :

int a = 018; //Invalid becuase it contains digit 8 which is out of range


int b = 0777; //Valid
int c = 0123; //Valid

Hexadecimal Literal :
---------------------
If a numeric literal starts with 0X (Zero capital X) OR 0x (zero small x) then it
will become Hexadecimal literal. Here base is 16 so it will accept 16 digits i.e 0
to 9 and A - F.

Example :

int x = 0X12; //Valid


int y = 0xadd; //Valid
int z = 0Xface; //valid
int a = 0Xage; //Inavlid because character 'g' out of range

Binary Literal :
---------------
If a numeric literal starts with 0B (Zero capital B) or 0b (Zero small b) then it
will become Binary literal. Binary literal is available from JDK 1.7v.
Here base is 2 so it will accept 2 digits i.e 0 and 1.
Note : As a developer we can represent a numeric literal into octal, hexadecimal
and binary but to get the output(result), JVM will convert into decimal format
only.
-------------------------------------------------------------------------
//Octal Literal
public class Test1
{
public static void main(String [] args)
{
int x = 015;
System.out.println(x);

}
}
------------------------------------------------------------------------
//Hexadecimal Literal
public class Test2
{
public static void main(String [] args)
{
int x = 0Xadd;
System.out.println(x);

}
}
------------------------------------------------------------------------
//Binary Literal
public class Test3
{
public static void main(String [] args)
{
int x = 0B101;
System.out.println(x);

}
}
-------------------------------------------------------------------
By default every integral literal is of type int only. byte and short are below
than int so we can assign integral literal(Which is by default int type) to byte
and short but the values must be within the range. [for Byte -128 to 127 and for
short -32768 to 32767]

Actually whenever we are assigning integral literal to byte and short data type
then compiler internally converts into corresponding type.

byte b = (byte) 12; [Compiler is converting int to byte]


short s = (short) 12; [Compiler is converting int to short]

In order to represent long value we should use either L OR l (Capital L OR Small l)


as a suffix to integral literal.

According to IT industry, we should use L bacause l looks like digit 1.


-------------------------------------------------------------------------
31-08-2024
----------

/* By default every integral literal is of type int only*/


public class Test4
{
public static void main(String[] args)
{
byte b = 128; //error int can'tbe converted to byte
System.out.println(b);

short s = 32768; //error int can'tbe converted to shot


System.out.println(s);
}
}
-----------------------------------------------------------------------
//Assigning smaller data type value to bigger data type
public class Test5
{
public static void main(String[] args)
{
byte b = 125;
short s = b; //[Implicit OR Automatic OR Widening]
System.out.println(s);
}
}
------------------------------------------------------------------------
//Converting bigger type to smaller type
public class Test6
{
public static void main(String[] args)
{
short s = 127;
byte b = (byte) s; //Explicit OR Manual OR Narrowing
System.out.println(b);
}
}

Note : User is responsible to provide Explicit type casting (In case user is trying
to assign bigger to smaller type) but here there is chance of loss of data.
-------------------------------------------------------------------------
public class Test7
{
public static void main(String[] args)
{
byte x = (byte) 127L;
System.out.println("x value = "+x);

long l = 29L;
System.out.println("l value = "+l);

int y = (int) 18L;


System.out.println("y value = "+y);

}
}
-----------------------------------------------------------------------
Is java pure Object Oriented Language ?
---------------------------------------
No, Java is not a pure object oriented langauge because it is accepting primary
data type, Actually any language which accepts primary data type is not a pure
object oriented language.

Only Objects are moving in the network but not the primary data type so java has
introduced Wrapper class concept to convert the primary data types into
corresponding wrapper object.

Primary Data type Wrapper Object


byte : Byte
short : Short
int : Integer
long : Long
float : Float
double : Double
char : Character
boolean : Boolean

Note : Apart from these 8 data types, Everything is an object in java so, if we
remove all these 8 data types then java will become pure OOP language.
-------------------------------------------------------------------------
//Wrapper claases
public class Test8
{
public static void main(String[] args)
{
Integer x = 24;
Integer y = 24;
Integer z = x + y;
System.out.println("The sum is :"+z);

Boolean b = true;
System.out.println(b);

Double d = 90.90;
System.out.println(d);

Character c = 'A';
System.out.println(c);
}
}
------------------------------------------------------------------------
How to find out the minimum, maximum value as well as size of different data
types :

The Warpper classes like Byte, Short, Integer and Long has provided predefined
static and final variables to represent minimum value, maximum value as well as
size of the respective data type.

Example :

If we want to get the minimum value, maximum value as well as size of byte data
type then Byte class (Wrapper class) has provided the following final and static
variables

Byte.MIN_VALUE : -128

Byte.MAX_VALUE : 127

Byte.SIZE : 8 (bits format)

-------------------------------------------------------------------------
//Program to find out the range and size of Integeral Data type
public class Test9
{
public static void main(String[] args)
{
System.out.println("\n Byte range:");
System.out.println(" min: " + Byte.MIN_VALUE);
System.out.println(" max: " + Byte.MAX_VALUE);
System.out.println(" size :"+Byte.SIZE);

System.out.println("\n Short range:");


System.out.println(" min: " + Short.MIN_VALUE);
System.out.println(" max: " + Short.MAX_VALUE);
System.out.println(" size :"+Short.SIZE);

System.out.println("\n Integer range:");


System.out.println(" min: " + Integer.MIN_VALUE);
System.out.println(" max: " + Integer.MAX_VALUE);
System.out.println(" size :"+Integer.SIZE);

System.out.println("\n Long range:");


System.out.println(" min: " + Long.MIN_VALUE);
System.out.println(" max: " + Long.MAX_VALUE);
System.out.println(" size :"+Long.SIZE);

}
}
------------------------------------------------------------------------
Providing _ (underscore) in integeral Literal :
------------------------------------------------
In Order to enhance the readability of large numeric literals, Java software people
has provided _ (underscore) from JDK 1.7v. While writing the big numbers to
separate the numbers we can use _

We can't start or end an integral literal with _ we will get compilation error.

//We can provide _ in integral literal


public class Test10
{
public static void main(String[] args)
{
long mobile = 98_1234_5678L;
System.out.println("Mobile Number is :"+mobile);
}
}
------------------------------------------------------------------------
public class Test11
{
public static void main(String[] args)
{
final int x = 127; //final we are using in place of const
byte b = x;
System.out.println(b);
}
}

The above program will compile as well as execute.


-------------------------------------------------------------------------
var keyword in java :
---------------------
var keyword is introduced from java 10v.
It can be used inside the method only.
It must be initialized in the same line where we are declaring the variable with
var keyword.
It is also known as local variable type inference.

public class Test12


{
public static void main(String[] args)
{
var x = 10; //Initialization is compulsory here
System.out.println(x);

}
------------------------------------------------------------------------
Converting from Decimal to another number System :
---------------------------------------------------
If we want to convert decimal to another numeber system then Integer class has
provided the following methods toBinaryString(), toOctalString(), toHexString() to
convert from decimal to binary, octal and hexadecimal repectively.

// Converting from decimal to another number system


public class Test13
{
public static void main(String[] argv)
{
//decimal to Binary
System.out.println(Integer.toBinaryString(7)); //111

//decimal to Octal
System.out.println(Integer.toOctalString(15)); //17

//decimal to Hexadecimal
System.out.println(Integer.toHexString(2781)); //add
}
}

Integer class static methods :


--------------------------------
1) public static String toBinaryString(int x)
2) public static String toOctalString(int x)
3) public static String toHexString(int x)

------------------------------------------------------------------------
02-09-2024
-----------
floating point literal :
------------------------
*If a numeric literal contains decimal or fraction then it is called Floating point
Literal.
Example : 78.90, 89.45, 12.90

*In floating point literal, we have 2 data types


float (32 bits)
double (64 bits)
*By default every floating point literal is of type double only.
double d1 = 12.90;//Valid

*But if we try to assign double literal directly to the float type then we will
get compilation error.

float f1 = 8.9; //error

*We can represent double type into float type by using the following 3 ways

float f2 = (float) 9.8; //Valid


float f3 = 7.7f; //Valid
float f4 = 8.5F; //Valid

*Even though, every floating point literal is of type double only, compiler has
provided the following two flavors to represent the double value explicitly, just
to enhance the redability of the code.

double d1 = 12D;
double d2 = 56d;

* We can represent an integral literal in four different forms, i.e. decimal,


octal, hexadecimal and binary but a floating point literal can be represented by
only form i.e DECIMAL.

* A floating point literal we can represent in exponent form.


Example : double d1 = 15e2; (15 X 10 to the power 2)
double d2 = 15e-2;

* An integral literal (byte, short, int and long) we can assign to floating point
literal but a floating point literal we can't assign to
integral literal directly.
-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
float f = 2.0; //error
System.out.println(f);
}
}
------------------------------------------------------------------------
public class Test1
{
public static void main(String[] args)
{
float b = 15.29F;
float c = 15.25f;
float d = (float) 15.30;

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

}
}
-------------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
double d = 15.15;
double e = 15d;
double f = 15.15D;

System.out.println(d+" , "+e+" , "+f);


}
}
-------------------------------------------------------------------------
public class Test3
{
public static void main(String[] args)
{
double x = 0129.89;

double y = 0167;

double z = 0178; //error [8 is out of the range]

System.out.println(x+","+y+","+z);
}
}
-------------------------------------------------------------------------
class Test4
{
public static void main(String[] args)
{
double x = 0X29;

double y = 0X9.15; //error

System.out.println(x+","+y);
}
}
-------------------------------------------------------------------------
public class Test5
{
public static void main(String[] args)
{
double d1 = 15e-3;
System.out.println("d1 value is :"+d1);

double d2 = 15e3;
System.out.println("d2 value is :"+d2);
}
}
-------------------------------------------------------------------------
public class Test6
{
public static void main(String[] args)
{
double a = 0791;

double b = 0791.0;

double c = 0777;

double d = 0Xdead;
double e = 0Xdead.0;
}
}
------------------------------------------------------------------------
public class Test7
{
public static void main(String[] args)
{
double a = 1.5e3;
float b = 1.5e3; //error
float c = 1.5e3F;
double d = 10;
int e = 10.0; //error
long f = 10D; //error
int g = 10F; //error
long l = 12.78F; //error
}
}
-------------------------------------------------------------------------
//Range and size of floating point literal
public class Test8
{
public static void main(String[] args)
{
System.out.println("\n Float range:");
System.out.println(" min: " + Float.MIN_VALUE);
System.out.println(" max: " + Float.MAX_VALUE);
System.out.println(" size :"+Float.SIZE);

System.out.println("\n Double range:");


System.out.println(" min: " + Double.MIN_VALUE);
System.out.println(" max: " + Double.MAX_VALUE);
System.out.println(" size :"+Double.SIZE);
}
}
------------------------------------------------------------------------
Character Literal :
--------------------
It is also known as char literal.

We have only one data type i.e. char data type which accepts 16 bits of memory.

char literal we can represent in the following different ways :

a) Single character enclosed with single quotes.


char ch = 'A';

b) In older languages like C and C++, which support ASCII value and range of value
is 0 - 255 that means we can assign 0 - 255 to represent
ASCII value of that particular character.
But in java we can assign 0 - 65535 to represent different characters from
different languages because Java support UNICODE chracter System.

Example :
char ch1 = 65535; //Valid
char ch2 = 65536; //Invalid
c) In order to get the UNICODE value of the character, we can assign char literal
to integral literal.

Example :
int x = 'A';

d) All the escape sequences we can represent as a char literal.

Example :
char ch = '\n';

e) We can represent char literal in 4 digit hexadecimal UNICODE format,


where the format is

'\uXXXX'

Here u stand for UNICODE [only small u]


XXXX represents exactly 4 digit.

Minimum Range = '\u0000'


Maximum Range = '\uffff'

Example : char ch = '\u0061'; //a


-------------------------------------------------------------------------
03-09-2024
----------
public class Test1
{
public static void main(String[] args)
{
char ch1 = 'a';
System.out.println("ch1 value is :"+ch1);

char ch2 = 97;


System.out.println("ch2 value is :"+ch2);

}
}
-----------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
int ch = 'A';
System.out.println("ch value is :"+ch);
}
}
-----------------------------------------------------------------------
//The UNICODE value for ? character is 63
public class Test3
{
public static void main(String[] args)
{
char ch1 = 63;
System.out.println("ch1 value is :"+ch1);

char ch2 = 64;


System.out.println("ch2 value is :"+ch2);

char ch3 = 65;


System.out.println("ch3 value is :"+ch3);
}
}
-----------------------------------------------------------------------
public class Test4
{
public static void main(String[] args)
{
char ch1 = 32000;
System.out.println("ch1 value is :"+ch1);

char ch2 = 0Xadd;


System.out.println("ch2 value is :"+ch2);
}
}

Note : We will get the output ? and ? because in the current system the
language translator is not available so itis unable to translate the given
UNICODE value into corresponding character.
-----------------------------------------------------------------------
//Addition of two character in the form of Integer
public class Test5
{
public static void main(String txt[ ])
{
int x = 'A';
int y = 'B';
System.out.println(x+y); //131
System.out.println('A' + 'A'); //130
}
}
------------------------------------------------------------------------
//Range of UNICODE Value (65535) OR '\uffff'
class Test6
{
public static void main(String[] args)
{
char ch1 = 65535;
System.out.println("ch value is :"+ch1);

char ch2 = 65536; //error


System.out.println("ch value is :"+ch2);
}
}
------------------------------------------------------------------------
//WAP in java to describe unicode representation of char in hexadecimal format
public class Test7
{
public static void main(String[] args)
{
int ch1 = '\u0000';
System.out.println(ch1);

int ch2 = '\uffff';


System.out.println(ch2);
char ch3 = '\u0041';
System.out.println(ch3); //A

char ch4 = '\u0061';


System.out.println(ch4); //a
}
}
-----------------------------------------------------------------------
class Test8
{
public static void main(String[] args)
{
char c1 = 'A';
char c2 = 65;
char c3 = '\u0041';

System.out.println("c1 = "+c1+", c2 ="+c2+", c3 ="+c3);


}
}
------------------------------------------------------------------------
class Test9
{
public static void main(String[] args)
{
int x = 'A';
int y = '\u0041';
System.out.println("x = "+x+" y ="+y);
}
}
------------------------------------------------------------------------
//Every escape sequence is char literal
class Test10
{
public static void main(String [] args)
{
char ch ='\n';
System.out.println("Hello");
System.out.println(ch);

}
}
-----------------------------------------------------------------------
public class Test11
{
public static void main(String[] args)
{
System.out.println(Character.MIN_VALUE); //white space
System.out.println(Character.MAX_VALUE); //?
System.out.println(Character.SIZE); //16 bits

}
}
------------------------------------------------------------------------
Boolean Literal :
------------------
In boolean literal we have only data type i.e boolean data type.

It accepts 1 bit of memory and also depends upon JVM implemention.


We can represent two states either true or false.

boolean isEmpty = true;


boolean isAlive = false;

Unlike C and C++, we can't assign numberic value to boolean type.

boolean b = 1; //Invalid [Valid in C and C++]

We can't assign String literal to boolean data type.


------------------------------------------------------------------------
public class Test1
{
public static void main(String[] args)
{
boolean isValid = true;
boolean isEmpty = false;

System.out.println(isValid);
System.out.println(isEmpty);
}
}
-----------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
boolean c = 0; //error
boolean d = 1; //error
System.out.println(c);
System.out.println(d);
}
}
-----------------------------------------------------------------------
public class Test3
{
public static void main(String[] args)
{
boolean x = "true"; //error
boolean y = "false"; //error
System.out.println(x);
System.out.println(y);
}
}
-----------------------------------------------------------------------
String Literal :
----------------
String is a collection of characters which will be enclosed with double quotes.

It can accept different types symols, numbers, characters because String is a


collection alpha-numeric character.

In Java we can create String by using following 3 ways :

1) By Using String Literal :


----------------------------
String str = "india";
2) By using new keyword :
-------------------------
String str1 = new String("Hyderabad");

3) By using character array [Old Approach]


------------------------------------------
char ch[] = {'R', 'A', 'J'};
-----------------------------------------------------------------------
//Three Ways to create the String Object
public class StringTest1
{
public static void main(String[] args)
{
String s1 = "Hello World"; //Literal
System.out.println(s1);

String s2 = new String("Ravi"); //Using new Keyword


System.out.println(s2);

char s3[] = {'H','E','L','L','O'}; //Character Array


System.out.println(s3);

}
}
------------------------------------------------------------------------
//String is collection of alpha-numeric character
public class StringTest2
{
public static void main(String[] args)
{
String x="B-61 Hyderabad";
System.out.println(x);

String y = "123";
System.out.println(y);

String z = "67.90";
System.out.println(z);

String p = "A";
System.out.println(p);
}
}
-----------------------------------------------------------------------
IQ
--
//IQ
public class StringTest3
{
public static void main(String []args)
{
String s = 15+29+"Ravi"+40+40;
System.out.println(s);

}
}
======================================================================
4) Punctuators :
----------------
It is also called separators.

It is used to inform the compiler how things are grouped in the code.

() {} [] ; , . @ � (var args)
-----------------------------------------------------------------
5) Operators
------------
It is a symbol which describes that how a calculation will be performed on
operands.

Types Of Operators :
------------------------
1) Arithmetic Operator (Binary Operator)

2) Unary Operators

3) Assignment Operator

4) Relational Operator

5) Logical Operators (&& || !)

6) Boolean Operators (& |)

7) Bitwise Operators (^ ~)

8) Ternary Operator

*9) Member Operator( Dot . Operator)

*10) new Operator

*11) instanceof Operator [It is also relational operator]

-----------------------------------------------------------------------
Basic Concepts of Operators :
-----------------------------
class Test
{
public static void main(String[] args)
{
int x = 15;
int y = x++;
System.out.println(x + " : "+ y);
}
}
-----------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
int x = 15;
int y = --x;;
System.out.println(x + " : "+ y);
}
}
------------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
int x = 15;
int y = ++5;
System.out.println(x + " : "+ y);
}
}
-----------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
int x = 5;
int y = ++(++x);
System.out.println(x +": "+y);
}
}
-----------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
char ch = 'A';
ch++;
System.out.println(ch);
}
}
------------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
double d1 = 12.12;
d1++;
System.out.println(d1);
}
}

Note :- Increment and Decrement Operator we can apply with any data type except
boolean.
----------------------------------------------------------------
04-09-2024
-----------
What is local variable ?
------------------------
If we declare any variable inside a method OR block OR constructor then it is
called local/ stack/ temporary/ automatic variable.

Example :
---------
public void m1()
{
int x = 100; //Local Variable
}

A local variable must be initialized by the developer before use becuase we don't
have default value for local variable.
We can't apply any kind of access modifier on local variable except final.

Without declaration and initialization we can't access local variable.

A local variable can be use from the same method, block or constructor only.[Scope
is within the same method, block or constructor]
--------------------------------------------------------------------
Example :
----------
public class Test
{
public static void main(String [] args)
{
final int x = 10;
System.out.println(x);
}
}

Why we can't access local variable outside of the method or block or


--------------------------------------------------------------------
constructor :
-------------

In java, Methods are executed in a special memory area called Stack area.

Stack is data structure which works on the basis of LIFO.

In java whenever we call a method then one stack frame is cretaed internally.

This Stack frame will automatically deleted, once the execution of the method is
completed so with that stack frame all the local variables and parameter variables
are also deleted from the memory as shown in the Program below.

public class MethodExecution


{
public static void main(String[] args)
{
System.out.println("Main Method started");
m1();
System.out.println("Main Method Ended");
}

public static void m1()


{
System.out.println("m1 Method started");
m2();
System.out.println("m1 Method Ended");
}

public static void m2()


{
int x = 100;
System.out.println("M2 method body :"+x);
}
}
Note : Here x is a local variable and scope of this x variable is within the same
method (m2 method) only, Once m2 method execution is over x variable will be
deleted from the Stack Frame.
------------------------------------------------------------------------
Limitation of Command Line Argument :
-------------------------------------
As we know by using Command Line Argument, we can pass some value
at runtime, These values are stroed in String array variable and then only the
exceution of the program will be started.

In Command line Argumenet we can't ask to enter the value from our end user as
shown in the Program.

public class CommandLimitation


{
public static void main(String[] args)
{
System.out.println("Enter your Name :");
String name = args[0];
System.out.println("Your Name is :"+name);
}
}
------------------------------------------------------------------------
public class AcceptCharacter
{
public static void main(String[] args)
{
System.out.println("Enter your Gender [M/F] :");
char gender = args[0].charAt(0);
System.out.println("Your Gender is :"+gender);
}
}
-----------------------------------------------------------------------
How to read the value from end user :
--------------------------------------
In java, we can read the data from various ways, which are as follows

1) DataInputStream class (java.io)


2) BufferedReader class (java.io)
3) Console (java.io)
4) System.in.read() (java.lang)
5) Scanner class

Scanner class :
---------------
It is a predefined class available in java.util package available from JDK 1.5v.

By using Scanner class we can read appropriate data from the end user.

System class static variables :


------------------------------
System class has provided 3 final and static variables :

System.out : Used to display normal message.

System.err : Used to display error message.

System.in : Used to take the input from the source.


How to create an Object for Scanner class :
-------------------------------------------
Scanner sc = new Scanner(System.in);

Methods of Scanner class :


---------------------------
Scanner class has provided various non static methods.

1) public String next() : Will read single word.

2) public String nextLine() : Will read multiple words OR complete line.

3) public byte nextByte() : Will read byte data.

4) public short nextShort() : Will read short data.

5) public int nextInt() : Will read int data.

6) public long nextLong() : Will read long data.

7) public float nextFloat() : Will read float data.

8) public double nextDouble() : Will read double data.

9) public boolean nextBoolean() : Will read boolean data

10) public char next().charAt(0) : Will read a char data


------------------------------------------------------------------------
Read character from user using Scanner class :
----------------------------------------------
package com.ravi.scanner_ex;

import java.util.Scanner;

public class ReadCharacter


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter your Gender :");
char gender = sc.next().charAt(0);
System.out.println("Your Gender is :"+gender);
sc.close();
}

}
-----------------------------------------------------------------------
//Reading the name from the end user
package com.ravi.scanner_ex;

import java.util.Scanner;

public class ReadName {

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter your Name :");
String name = sc.nextLine();
System.out.println("Your Name is :"+name);
sc.close();

}
-----------------------------------------------------------------------
package com.ravi.scanner_ex;

import java.util.Scanner;

public class ReadStudentData {

public static void main(String[] args)


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

System.out.print("Enter your roll number :");


int roll = sc.nextInt();

System.out.print("Enter your Name :");


String name = sc.nextLine(); //Buffer Problem
name = sc.nextLine();

System.out.println("Your roll is :"+roll);


System.out.println("Your Name is :"+name);
sc.close();

}
------------------------------------------------------------------------
05-09-2024
----------
Expression Conversion :
-----------------------
Whenever we are working with Arithmetic Operator (+,-,*,/,%) or unary minus
operator, after expression exeution the result will be converted (Promoted) to int
type, Actually to store the result minimum 32 bits format is required.

public class Test


{
public static void main(String [] args)
{
short s = 12;
short t = 14;
short u = s + t; //error
System.out.println(u);
}

After Arithmetic operator expression the result will be promoted to int type so, to
hold the result minimum 32 bit data is required.
-----------------------------------------------------------------------
Unary minus operator :
----------------------
public class Test
{
public static void main(String [] args)
{
int x = 15;
System.out.println(-x);

}
-----------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
byte b = 1;
short c = -b; //error
System.out.println(c);

In Arithmetic operator OR Unary minus operator, the result will be promated to int
type (32 bits) so to hold the result int data type is reqd.
-----------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
byte b = 1;
b += 2;
System.out.println(b);

In the above program we are using short hand operator so we will get the result in
byte format also.
------------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
int z = 5;
if(++z > 5 || ++z > 6) //Logical OR
{
z++;
}
System.out.println(z); //7

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

z = 5;
if(++z > 5 | ++z > 6) //Boolean OR
{
z++;
}
System.out.println(z); //8
}

}
-----------------------------------------------------------------------
Program on Boolean AND operator :
----------------------------------
public class Test
{
public static void main(String [] args)
{
int z = 5;
if(++z > 6 & ++z> 6)
{
System.out.println("Inside If");
z++;
}
System.out.println(z);

}
-----------------------------------------------------------------------
Working with Bitwise AND(&), Bitwise OR(|) and Bitwise X-OR (^) :
------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
System.out.println(false ^ true);

Note : If both the inputs are alternate of each other then we will get true
otherwise we will get false.[Same input output will be false]
----------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
System.out.println(5 & 6); //4
System.out.println(5 | 6); //7
System.out.println(5 ^ 6); //3

}
-----------------------------------------------------------------------
Bitwise Complement Operator (~) :
---------------------------------
It will not work with boolean type.

public class Test


{
public static void main(String [] args)
{
System.out.println(~true);//error

}
-----------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
System.out.println(~-5); // 4
System.out.println(~5); //-6

}
-----------------------------------------------------------------------
Member access operator (.) :
-----------------------------
It is called Member access operator, by using this we can access the member of the
class.
In the following program we have static method in the Welcome class, in order to
call the static method we can use Welcome class and to access the static method of
Welcome class we should use .(Dot) operator.

class Welcome
{
public static void m1() //static Method
{
System.out.println("M1 static Method");
}
}
public class Test
{
public static void main(String [] args)
{
Welcome.m1();
}

}
------------------------------------------------------------------------
class Welcome
{
public void m1() //non static Method
{
System.out.println("M1 non-static Method");
}
}
public class Test
{
public static void main(String [] args)
{
Welcome w = new Welcome();
w.m1();
}

}
Note : In order to call static method, Object is not required but to call non
static method, Object is required.
-----------------------------------------------------------------------
new Keyword :
-------------
It is also an operator.
It is used to create the object and initialize the non static member with default
value.

class Welcome
{
public void m1() //non static Method
{
System.out.println("M1 non-static Method");
}
}
public class Test
{
public static void main(String [] args)
{
Welcome w = new Welcome();
w.m1();
}

}
-----------------------------------------------------------------
Limitation of if else :
-----------------------
The major drawback with if condition is, it checks the condition again and again so
It increases the burdon over CPU so we introduced switch-case statement to reduce
the overhead of the CPU.

06-09-2024
-----------
Switch case statement in java :
-------------------------------
It is a selective statement so, we can select one statement among the available
statements.

break is optional but if we use break then the control will move from out of the
switch body.

We can write default so if any statement is not matching then default will be
executed.

In switch case we can't pass long, float and double and boolean value.

[long we can pass in switch case from java 14v]

We can pass String from JDK 1.7v and we can also pass enum from JDK 1.5v.
------------------------------------------------------------------------
import java.util.*;
public class SwitchDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter a Character :");
char colour = sc.next().toLowerCase().charAt(0);

switch(colour)
{
case 'r' : System.out.println("Red") ; break;
case 'g' : System.out.println("Green");break;
case 'b' : System.out.println("Blue"); break;
case 'w' : System.out.println("White"); break;
default : System.out.println("No colour");
}
System.out.println("Completed") ;
}
}
-----------------------------------------------------------------------
import java.util.*;
public class SwitchDemo1
{
public static void main(String args[])
{
System.out.println("\t\t**Main Menu**\n");
System.out.println("\t\t**100 Police**\n");
System.out.println("\t\t**101 Fire**\n");
System.out.println("\t\t**102 Ambulance**\n");
System.out.println("\t\t**139 Railway**\n");
System.out.println("\t\t**181 Women's Helpline**\n");

System.out.print("Enter your choice :");


Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();

switch(choice)
{
case 100:
System.out.println("Police Services");
break;
case 101:
System.out.println("Fire Services");
break;
case 102:
System.out.println("Ambulance Services");
break;
case 139:
System.out.println("Railway Enquiry");
break;
case 181:
System.out.println("Women's Helpline ");
break;
default:
System.out.println("Your choice is wrong");
}
}
}
----------------------------------------------------------------------
Passing String value in switch case :
--------------------------------------
import java.util.*;
public class SwitchDemo2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the name of the season :");
String season = sc.next().toLowerCase();

switch(season) //String allowed from 1.7


{
case "summer" :
System.out.println("It is summer Season!!");
break;

case "rainy" :
System.out.println("It is Rainy Season!!");
break;
}
}
}
-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
long l = 12L;

switch(l) //error
{
case 12L :
System.out.println("It is case 12");
break;
}
}

}
----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
float l = 12L;

switch(l)
{
case 12 :
System.out.println("It is case 12");
break;
}
}

Note : We can't pass long, float and double value.


-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
int x = 12;
int y = 12;
switch(x)
{
case y : //error
System.out.println("It is case 12");
break;
}
}

Note : In the label of switch we should take constant value.


------------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
int x = 12;
final int y = 12;

switch(x)
{
case y :
System.out.println("It is case 12");
break;
}
}

}
-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
byte b = 90;

switch(b)
{
case 128 : //error
System.out.println("It is case 127");
break;
}
}

Note : Value 128 is out of the range of byte and same applicable for short data
type
------------------------------------------------------------------------
Loops in java :
---------------
A loop is nothing but repeatation of statements based on the
specified condition.

In java we have 4 types of loops :


----------------------------------
1) do-while loop
2) while loop
3) for loop
4) for each loop
-----------------------------------------------------------------------
//Program on do while loop :
----------------------------
public class DoWhile
{
public static void main(String[] args)
{
do
{
int x = 1; //Local Variable (block Level)
System.out.println("x value is :"+x);
x++;
}
while (x<=10); //error
}
}

Note : x is a block level variable because It is declared inside do block so the


scope of this x variable will be within the do block only.
------------------------------------------------------------------------
public class DoWhile
{
public static void main(String[] args)
{
int x = 1; //Local Variable
do
{
System.out.println("x value is :"+x);
x++;
}
while (x<=10);
}
}
-----------------------------------------------------------------------
Program on while loop :
-----------------------
public class WhileDemo
{
public static void main(String[] args)
{
int x = 1;

while(x>=-10)
{
System.out.println(x);
x--;
}
}
}
-----------------------------------------------------------------------
Program on for loop :
---------------------
public class ForLoop
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
System.out.println(i);
}
}
}
------------------------------------------------------------------------
For Each loop :
----------------
It is an enhanced for loop.
It is introduced from JDK 1.5v.
It is used to retrieve OR Iterate the values one by one from the Collection like
array.

//Program on forEach loop to fetch the values from the array


public class ForEachLoop1
{
public static void main(String [] args)
{
int arr[] = {10,20,30,40,50,60,70};

for(int x : arr)
{
System.out.println(x);
}
}
}
-----------------------------------------------------------------------
How to sort Array data :
--------------------------
In java.util pacakge, there is a predefined class called Arrays which has various
static methods to sort the array in ascending or alphabetical order.

Example :
Arrays.sort(int []arr); //For sorting int array
Arrays.sort(Object []arr) //For sorting String array

-----------------------------------------------------------------------
//Sorting the integer array
package com.ravi.foreach_demo;

import java.util.Arrays;

public class ForEachLoop2 {

public static void main(String[] args)


{
int []arr = {90,67,34,12,9};

Arrays.sort(arr);

for(int x : arr)
{
System.out.println(x);
}

}
-----------------------------------------------------------------------
//Sorting the string array
package com.ravi.foreach_demo;

import java.util.Arrays;

public class ForEachLoop3 {

public static void main(String[] args)


{
String []fruits = {"Orange","Mango","Apple"};

Arrays.sort(fruits);

for(String fruit : fruits)


{
System.out.println(fruit);
}

}
------------------------------------------------------------------------
In java, Can we hold hetrogeneous types of data using array ?
-------------------------------------------------------------
Yes, by using Object array we can hold hetrogeneous type of data but we can't
peform sorting operation using Arrays.sort(), It will generate
java.lang.ClassCastException

package com.ravi.foreach_demo;

public class ForEachLoop4 {

public static void main(String[] args)


{
Object []values = {12,90.78,'A',"NIT",true};

//Arrays.sort(values); //Invalid [java.lang.ClassCastException]

for(Object value : values)


{
System.out.println(value);
}

}
-----------------------------------------------------------------------
09-09-2024
-----------
What is BLC and ELC class in java ?
------------------------------------
BLC :
------
BLC statnds for Business Logic class, In this class we are responsible to write the
logic. This class will not contain main method.
The main purpose of this BLC class to reuse this class in various packages.

Example :
----------
//BLC
public class Calculate
{
//Here We are responsible to write the logic
}

ELC :
-----
It stands for Executable Logic class, It will not contain any logic but the
execution of the program will start from this ELC class because it contains main
method.

Example :
---------
//ELC
public class Main
{
public static void main(String [] args)
{
}
}

======================================================================
How to reuse a class in java ?
-------------------------------
The slogan of java is "WORA" write once run anywhere.

A public class created in one package can be reuse from different packages also by
using import statement.

Each .java file can contain only one public class.The file name must match with the
class name.

*In a single java file, we can write only one public class and multiple non-public
classes but it is not a recommended approach because the non public class we can
use within the same package only.

So the conclusion is, we should declare every java class in a separate file to
enhance the reusability of the BLC classes.
[Note we have 10 classes -> 10 java files]

How many .class file will be created in the above approach :


------------------------------------------------------------
For a public class in a single file, Only 1 .class file will be created.

For a public class in a single file which contains n number of non public classes
then compiler will generate n number of .class file.

Example :
----------
Test.java
----------
public class Test
{

class A
{
}

class B
{
}

class C
{
}

Note : Here total 4 .class file will be generated.


----------------------------------------------------------------------
Working with static method and method return type :
---------------------------------------------------
static method :
---------------
If a method is declared with static keyword (like main method) then it is called
static method.

In order to call a static method, Object is not required, We can call static method
directly with the help of class name.
----------------------------------------------------------------------
How to call a static method available in the same class :
---------------------------------------------------------
If a static method is available in the same class (ELC class) then we can directly
call the static method from another static method, Here class name is also not
required as shown in the program.

//A static method can be directly call within the same class
package com.ravi.pack1;

public class Test1


{
public static void main (String[] args)
{
square(5);
}

public static void square(int x)


{
System.out.println("Square is :"+(x*x));
}
}
-----------------------------------------------------------------------
Calling the static method (No return value) with the help of class name :
------------------------------------------------------------------------
2 files :
----------

GetSquare.java(BLC)
-------------------
package com.ravi.pack2;

//BLC
public class GetSquare
{
public static void getSquareOfNumber(int num)
{
System.out.println("Square of "+num+" is :"+(num*num));
}
}

Test2.java(ELC)
----------------
package com.ravi.pack2;

import java.util.Scanner;

//ELC
public class Test2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the side :");
int side = sc.nextInt();
GetSquare.getSquareOfNumber(side);
sc.close();
}
}

Here getSquareOfNumber() method return type is void so there is no communication


between BLC and ELC class.
-------------------------------------------------------------------------
2 files :
----------
FindSquare.java
-----------------
//A static method returning integer value
package com.ravi.pack3;

//BLC
public class FindSquare
{
public static int getSquare(int x)
{
return (x*x);
}
}

Test3.java
-----------
package com.ravi.pack3;

import java.util.Scanner;

//ELC
public class Test3
{
public static void main (String[] arg)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of side :");
int side = sc.nextInt();

int squareOfNum = FindSquare.getSquare(side);


System.out.println("Square of "+side+" is :"+squareOfNum);

sc.close();
}
}

Here getSquare() method return type is int so there is communication is possible


between BLC and ELC class.
------------------------------------------------------------------------
Test cases with data [Validation of outer world data]:
------------------------------------------------------
2 files :
----------
Calculate.java
--------------
/*Program to find out the square and cube of
the number by following criteria
*
a) If number is 0 or Negative it should return -1
b) If number is even It should return square of the number
c) If number is odd It should return cube of the number
*/

package com.ravi.pack4;

//BLC
public class Calculate
{
public static int getSquareAndCube(int num)
{
if(num <=0)
{
return -1;
}
else if(num % 2==0)
{
return num*num;
}
else
{
return num*num*num;
}
}

Test4.java
------------
package com.ravi.pack4;

import java.util.Scanner;

public class Test4


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number :");
int num = sc.nextInt();
int result = Calculate.getSquareAndCube(num);
System.out.println("Result is :"+result);
sc.close();

}
--------------------------------------------------------------------------
2 files :
---------
Rectangle.java
--------------
package com.ravi.pack5;

//BLC
public class Rectangle
{
public static double getAreaOfRectangle(double length, double breadth)
{
return (length * breadth);
}

Test5.java
-----------
package com.ravi.pack5;

import java.util.Scanner;

public class Test5


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the length of the Rect :");
double length = sc.nextDouble();

System.out.print("Enter the breadth of the Rect :");


double breadth = sc.nextDouble();

double areaOfRectangle = Rectangle.getAreaOfRectangle(length, breadth);

System.out.println("Area of Rectangle is :"+areaOfRectangle);


sc.close();
}
}
-----------------------------------------------------------------------
10-09-2024
----------
2 files :
---------
EvenOrOdd.java
---------------
package com.ravi.pack6;

//BLC
public class EvenOrOdd
{
public static boolean isEven(int num)
{
return (num % 2 == 0);
}
}

Test6.java
----------
package com.ravi.pack6;

import java.util.Scanner;

//ELC
public class Test6
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number :");
int num = sc.nextInt();

boolean isEven = EvenOrOdd.isEven(num);


System.out.println(num+" is Even ?:"+isEven);

System.out.print("Enter another Number :");


num = sc.nextInt();

isEven = EvenOrOdd.isEven(num);
System.out.println(num+" is Even ?:"+isEven);
sc.close();
}

}
-----------------------------------------------------------------------
How to provide formatting for Decimal number :
----------------------------------------------
In java.text package, there is a predefined class called DecimalFormat through
which we can provide formatting for Decimal number.

DecimalFormat df = new DecimalFormat("00.00"); //format [String pattern]


System.out.println(df.format(double d));

Note :- format is non static method of DecimalFormat class which accpts double as a
parameter, and return type of this method is
String.

public String format(double number)


----------------------------------------------------------------------
2 files :
----------
Circle.java
------------
//Area of Circle
//If the radius is 0 or Negative then return -1.

package com.ravi.pack7;
public class Circle
{
public static String getAreaOfCircle(double radius)
{
if(radius <= 0)
{
return ""+(-1);
}
else
{
double PI = 3.14;
double areaOfCircle = PI * radius * radius;
return ""+areaOfCircle;
}
}
}

Test7.java
-----------
package com.ravi.pack7;

import java.text.DecimalFormat;
import java.util.Scanner;

public class Test7


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radius :");
double radius = sc.nextDouble();

String circle = Circle.getAreaOfCircle(radius);


//Converting String to double
double area = Double.parseDouble(circle);

DecimalFormat df = new DecimalFormat("00.00");


System.out.println("Area of Circle is :"+df.format(area));
sc.close();
}
}
------------------------------------------------------------------------
How to work with String format :
--------------------------------
2 files :
----------
Student.java
-------------
package com.ravi.pack8;

//BLC
public class Student
{
public static String getStudentDetails(int roll, String name, double fees)
{
//[Student name is : Ravi, roll is : 101, fees is :1200.90]

return "[Student name is :"+name+", roll is :"+roll+", fees is :"+fees+"]";


}
}

Test8.java
-----------
package com.ravi.pack8;

public class Test8


{
public static void main(String[] args)
{
String studentDetails = Student.getStudentDetails(111, "Smith", 12000);
System.out.println(studentDetails);
}

}
------------------------------------------------------------------------
Note : We can't invoke a method from System.out.println() statement whose return
type is void, It will generate CE.

Example :
----------
class A
{
public static void m1()
{}
}

class Main
{
public static void main(String [] args)
{
System.out.println(A.m1()); //CE
}
}
------------------------------------------------------------------------
2 files :
---------
Table.java
----------
package com.ravi.pack9;

//BLC
public class Table
{
public static void printTable(int num) //[9 X 1 = 9]
{
for(int i=1; i<=10; i++)
{
System.out.println(num+" X "+i+" = "+(num*i));
}
System.out.println("==============================");
}
}

Test9.java
-----------
package com.ravi.pack9;
//ELC
public class Test9
{
public static void main(String[] args)
{
for(int i = 1; i<=9; i++)
{
Table.printTable(i);
}
}

}
========================================================================
Types of Variable in java :
---------------------------
Based on the data type we have only 2 types of variable in java :

1) Primitive Variables
2) Reference Variables

1) Primitive Variables :
------------------------
If a variable is declared with primitive data type like byt, short, int, long and
so on then it is called Primitive Variables.

Example :
int x = 100;
boolean y = true;

2) Reference Variable :
-----------------------
If a variable is declared with class name, interface name, enum , record and so on
then it is called reference variable.

Example :
Student s; //s is reference variable
Scanner sc = new Scanner(System.in); //sc is reference variable
Integer y = null; //y is reference variable

Note : With primitive variable we can't call a method as well as we can't assign
null literal.

int x = null; //Invalid

int y = 45;
y.m1(); //Invalid

Based on declaration position Variables are divided into 4 types :

a) Class Variables OR Static Field


b) Instance Variables OR Non Static Field
c) Local /Stack/temporary/Automatic Variable
d) Parameter Variables

Program on Primitive Variables :


---------------------------------
package com.ravi.variables;
class Test
{
int x = 100; //Primitive + Instance Variable
static int y = 200; // //Primitive + Class Variable

public void acceptData(int a) //Primitive + Parameter Variable


{
int b = 400; //Primitive + Local Variable
System.out.println("Local Variable :"+b); //Stack Memory
System.out.println("Parameter Variable :"+a);//Stack Memory
System.out.println("Instance Variable :"+this.x); //HEAP MEMORY
System.out.println("Class Variable :"+Test.y); //CLASS AREA {Method
Area}
}
}

public class PrimitiveVariables


{
public static void main(String[] args)
{
Test t1 = new Test();
t1.acceptData(300);
}
}

-------------------------------------------------------------------------
Program on Reference Variables :
---------------------------------
package com.ravi.variables;

import java.util.Scanner;

class Student
{

public class ReferenceVariable


{
Student s1 = new Student(); //Reference + Non Static Variable
static Scanner sc = new Scanner(System.in); //Reference + Static Variable

public static void main(String[] args)


{
Student stud = new Student(); //Reference + Local Variable

acceptStudentObject(stud);
}
public static void acceptStudentObject(Student st) //Reference + Parameter
{
}

}
-------------------------------------------------------------------------
11-09-2024
----------
Object Oriented Programming (OOPs)
----------------------------------
What is an Object?
------------------
An object is a physical entity which exist in the real world.
Example :- Pen, Car, Laptop, Mouse, Fan and so on

An Object is having 3 characteristics :

a) Identification of the Object (Name of the Object)


b) State of the Object (Data OR Properties OR Variable of Object)
c) Behavior of the Object (Functionality of the Object)

OOP is a technique through which we can design or develop the programs using class
and object.

Writing programs on real life objects is known as Object Oriented Programming.

Here in OOP we concentrate on objects rather than function/method.

Advantages of OOP :
--------------------
1) Modularity (Dividing the bigger task into smaller task)
2) Reusability (We can reuse the component so many times)
3) Flexibility (Easy to maintain [By using interface])

Features of OOP :
-----------------
1) Class
2) Object
3) Abstraction
4) Encapsulation
5) Inheritance
6) Polymorphism

======================================================================
What is a class?
-----------------
A class is model/blueprint/template/prototype for creating the object.

A class is a logical entity which does not take any memory.

A class is a user-defined data type which contains data member and member function.

public class Employee


{
Employee Data (Properties)
+
Employee behavior (Function/Method)
}

A CLASS IS A COMPONENT WHICH IS USED TO DEFINE OBJECT PROPERTIES AND OBJECT


BEHAVIOR.
--------------------------------------------------------------

WAP in OOP to provide initial value to object properties :

2 files :
---------
Student.java
-------------
package com.ravi.oop;

//BLC
public class Student
{
String studentName; //Instance Variable
double studentHeight; //Instance Variable
int studentRollNumber; //Instance Variable

public void talk()


{
System.out.println("My name is :"+studentName);
System.out.println("My rollnumber is :"+studentRollNumber);
System.out.println("My Height is :"+studentHeight);

public void writeExam()


{
System.out.println("Every saturday "+studentName+" is writing the Exam
paper");
}

StudentDemo.java
-----------------
package com.ravi.oop;

//ELC
public class StudentDemo
{
public static void main(String[] args)
{
Student raj = new Student();
//Initialize the properties (Variables)
raj.studentRollNumber = 111;
raj.studentName = "Raj Gourav";
raj.studentHeight = 5.8;
//Calling the behavior
raj.talk();
raj.writeExam();

Student priya = new Student();


//Initializing the properties
priya.studentName = "Priya";
priya.studentRollNumber = 222;
priya.studentHeight = 5.6;
//calling the behavior
priya.talk();
priya.writeExam();

}
}
=======================================================================
Steps for creating Object Orineted Programming

Step 1 :- Create the Object based on the BLC class inside ELC
class.[main method]

Step 2 :- Define all the object properties and behavior inside


the BLC class based on your imagination.

Step 3 :- Initialize all the object properties with user friendly value by using
reference variable.

step 4 :- call the behavior (calling the methods)


-----------------------------------------------------------------------
12-09-2024
----------
How to initialize the object properties by using Object reference through Scanner
class :

2 files :
----------
Customer.java
-------------
package com.ravi.oop;

public class Customer


{
int customerId; //instance Variable
String customerName; //instance Variable
double customerBill; //instance Variable

public void buyProduct()


{
System.out.println(customerName+" has purchased one Mobile");
}

public void billPayment()


{
System.out.println(customerName+" has paid "+customerBill+" amount");
}

CustomerDemo.java
------------------
package com.ravi.oop;

import java.util.Scanner;

public class CustomerDemo


{
public static void main(String[] args)
{
Customer scott = new Customer();
//Initializing the Object Properties

Scanner sc = new Scanner(System.in);


System.out.print("Enter Customer Id :");
int id = sc.nextInt();
scott.customerId = id;

System.out.print("Enter Customer Name :");


String name = sc.nextLine();
name = sc.nextLine();
scott.customerName = name;

System.out.print("Enter Customer Bill :");


double bill = sc.nextDouble();
scott.customerBill = bill;

scott.buyProduct(); scott.billPayment();
sc.close();

}
-----------------------------------------------------------------------
Initializing the Object properties through Methods :
-----------------------------------------------------
We can also initialize the object properties through methods as shown in the
program.

2 files :
---------
Employee.java
--------------
package com.ravi.oop;

public class Employee


{
int employeeId;
String employeeName;

public void setEmployeeData()


{
employeeId = 111;
employeeName = "Smith";
}

public void getEmployeeData()


{
System.out.println("Employee Id is :"+employeeId);
System.out.println("Employee Name is :"+employeeName);

EmployeeDemo.java
------------------
package com.ravi.oop;

public class EmployeeDemo {

public static void main(String[] args)


{
Employee smith = new Employee();
smith.setEmployeeData();
smith.getEmployeeData();
}

Note : Upto here, we have learned the following two types to initialize the Object
properties
a) By using Object Reference
b) By using Methods
-----------------------------------------------------------------------
What is an instance variable ?
-------------------------------
If a non static variable is declared inside a class and outside of the
method then it is called instance variable.[class level variable]

class Test
{
int x = 100; //Instance Variable
}

An instance variable will automatically initalized with default value (even the
variable final) at the time of Object creation.

Without an object the life of the instance variable will not be started.

public class Test


{
int x = 100;

public static void main(String [] args)


{
System.out.println(x); //error [Object is not created]
}

In java, There is a special memory for object where object and its properties
(Instance Variable) are available called HEAP Memory.

The scope of instance variable is within the class as well as it depends upon the
access modifier.

=======================================================================
What is a constructor [Introduction Only]
------------------------------------------
If the name of the class and name of the method both are exactly same and It does
not contain any type of return type (Without return type)
then it is called constructor.

Example :
---------
class Student
{
public Student() //Constructor
{
}
}
-----------------------------------------------------------------------
Default constructor added by the compiler :
-------------------------------------------
In java, whenever we write a class and if we don't write any kind
of constructor in the class then automatically java compiler will add one default
constructor to the class.

Test.java
----------
public class Test
{

javac Test.java (Compilation)

Test.class
-----------
public class Test
{
public Test() //default constructor added by the compiler
{
}
}

Note :- default constructor does not take any argument.

Every java class must have at-least one constructor either explicitly
written by user OR implicitly added by compiler.

The access modifier of default constructor depnds upon class access


modifier that means if my class is public then default constrauctor added by
compiler will be public, if class is not public then default constructor added by
compiler will also not public.
----------------------------------------------------------------------
Why compiler is adding default constructor to our class :
---------------------------------------------------------
We have 2 reasons that why compiler is adding default constructor :

1) Without default constructor, Object creation is not possible in java by using


new keyword, if the class does not contain user-defined constructor.

2) As we know only class level variables are having default values so, default
constructor will initialize all the instance variables with default values with the
help of new keyword.

Data type - Default value


byte - 0
short - 0
int - 0
long - 0
float - 0.0
double - 0.0
char - (space) '\u0000'
boolean - false
String - null
Object - null (For any class i.e reference variable the default value is null)

Student.java
--------------
package com.ravi.oop;

public class Student


{
int id;
String name;

public void displayStudentData()


{
System.out.println("Id is :"+id);
System.out.println("Name is :"+name);
}

public static void main(String[] args)


{
Student raj = new Student();

Note : Even we are not initializing our instance variable but it will
be initialized by default constructor using new keyword [super () ]
-------------------------------------------------------------------
How to provide our own user-defined values for the instance variable :
----------
2 files :
----------
Manager.java
------------
package com.ravi.oop;

import java.util.Scanner;

public class Manager


{
int managerId; //Instance Variable
String managerName; //Instance Variable

public void setManagerData()


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Manager Id :");
managerId = sc.nextInt(); //id = 111
System.out.print("Enter Manager Name :");
String name = sc.nextLine(); //\n
managerName = sc.nextLine(); //smith
}

public void getManagerData()


{
System.out.println("Manager Id is :"+managerId);
System.out.println("Manager Name is :"+managerName);
}
}

ManagerDemo.java
-----------------
package com.ravi.oop;

public class ManagerDemo {

public static void main(String[] args)


{
Manager smith = new Manager();
smith.setManagerData();
smith.getManagerData();
}

}
-------------------------------------------------------------------
How to initialize the Object properties through parameter variable :
-------------------------------------------------------------------
We can initialize the instance variable by using method parameter as
shown in the program

2 files :
---------
Player.java
------------
package com.ravi.oop;

public class Player


{
int playerId; //Instance Variable
String playerName; //Instance Variable

public void setPlayerData(int pid, String pname)


{
playerId = pid;
playerName = pname;
}

public void getPlayerData()


{
System.out.println("Player Id is :"+playerId);
System.out.println("Player Name is :"+playerName);
}

PlayerDemo.java
---------------
package com.ravi.oop;

public class PlayerDemo {

public static void main(String[] args)


{
Player rohit = new Player();
rohit.setPlayerData(45, "Rohit Sharma");
rohit.getPlayerData();
System.out.println("..................");

Player virat = new Player();


virat.setPlayerData(18, "Virat Kohli");
virat.getPlayerData();

}
--------------------------------------------------------------------
How to initialize the instance variable through parameter variable as per
requirement.

2 files :
----------
Employee.java
-------------
package com.ravi.oop;

public class Employee


{
int employeeId;
String employeeName;
double employeeSalary;
char employeeGrade;

public void setEmployeeData(int id, String name, double salary)


{
employeeId = id;
employeeName = name;
employeeSalary = salary;
}

public void getEmployeeData()


{
System.out.println("Employee Id is :"+employeeId);
System.out.println("Employee Name is :"+employeeName);
System.out.println("Employee Salary is :"+employeeSalary);
System.out.println("Employee Grade is :"+employeeGrade);
}

public void calculateEmployeeGrade()


{
if(employeeSalary >= 90000)
{
employeeGrade = 'A';
}
else if(employeeSalary >= 75000)
{
employeeGrade = 'B';
}
else if(employeeSalary >= 50000)
{
employeeGrade = 'C';
}
else
{
employeeGrade = 'D';
}
}

EmployeeDemo.java
-------------------
package com.ravi.oop;

public class EmployeeDemo {

public static void main(String[] args)


{
Employee john = new Employee();
john.setEmployeeData(111, "John", 95000);
john.calculateEmployeeGrade();
john.getEmployeeData();

}
--------------------------------------------------------------------
Variable Shadow :
-----------------
Variable shadowing in Java occurs when a variable declared within a certain scope
(like a method or a block or Constructor) has the same name as a variable declared
in an outer scope (class Level).

In variable Shadow, the variable in the inner scope hides the variables in Outer
scope so known as variable shadowing.

This means that within the inner scope (Method, block Or Constructor), when we
refer to the variable directly by name, We are actually referring to the inner
variable, not the outer variable.

2 files :
---------
Student.java
-------------
package com.ravi.oop;

public class Student


{
int studentId = 111; //Instance Variable
String studentName = "Smith"; //Instance Variable

public void accept()


{
int studentId = 222; //Local Variable
String studentName = "John"; //Local Variable

System.out.println(studentId);
System.out.println(studentName);
}

}
VariableShadow.java
--------------------
package com.ravi.oop;

public class VariableShadow {

public static void main(String[] args)


{
Student s1 = new Student();
s1.accept();

}
--------------------------------------------------------------------
this keyword in java :
----------------------
Whenever instance variable name and parameter variable name both are same then at
the time of instance variable initialization our runtime environment will provide
more priority to parameter variable/local variable, parameter variables are hiding
the instance variables (Due to variable shadow)

To avoid the above said problen, Java software people introduced "this" keyword.

this keyword always refers to the current object and instance variables are the
part of the object so by using this keyword we can represent instance variable.

We cannot use this (non static member) keyword from static area (Static context).

-------------------------------------------------------------------
2 files :
----------
Customer.java
--------------
package com.ravi.oop;

public class Customer


{
int customerId;
String customerName;

public void setCustomerData(int customerId, String customerName)


{
this.customerId = customerId;
this.customerName = customerName;

public void getCustomerData()


{
System.out.println("Customer Id is :"+this.customerId);
System.out.println("Customer Name is :"+this.customerName);
}

}
ThisKeywordDemo.java
---------------------
package com.ravi.oop;

public class ThisKeywordDemo


{
public static void main(String[] args)
{
Customer raj = new Customer();
raj.setCustomerData(111, "Raj");
raj.getCustomerData();
}

}
===================================================================
How to print object properties by using toString() method :
-----------------------------------------------------------
If we want to print our object properties (Instance Variables) then we should
generate(override) toString() method in our class from Object class.

Now with the help of toString() method we need not to write any display kind of
method to print the object properties i.e instance variable.

In order to generate the toString() method we need to follow the steps


Right click on the program -> source -> generate toString()

In order to call this toString() method, we need to print the corresponding object
reference by using System.out.println() statement.

Manager m = new Manager();


System.out.println(m); //Calling toString() method of Manager class

Employee e = new Employee();


System.out.println(e); //Calling toString() method of Employee class.

2 files :
-----------
Trainer.java
------------

package com.ravi.oop;

public class Trainer {


int trainerId;
String trainerName;
String trainerSubject;

public void setTrainerData(int trainerId, String trainerName, String


trainerSubject) {
this.trainerId = trainerId;
this.trainerName = trainerName;
this.trainerSubject = trainerSubject;

@Override
public String toString()
{
return "Trainer [trainerId=" + trainerId + ", trainerName=" +
trainerName + ", trainerSubject=" + trainerSubject
+ "]";
}

ToStringDemo.java
------------------
package com.ravi.oop;

public class ToStringDemo


{
public static void main(String[] args)
{
Trainer scott = new Trainer();
scott.setTrainerData(111, "Scott", "Java");

System.out.println(scott); //toString()

}
==================================================================
16-09-2024
-----------
Role of instance variable while creating the Object :
-----------------------------------------------------
Whenever we create an objet in java, a separate copy of all the instance variables
will be created with each and every object.

Program :
---------
package com.ravi.oop;

public class Test


{
int x = 10;
public static void main(String[] args)
{
Test t1 = new Test();
Test t2 = new Test();

++t1.x; --t2.x;

System.out.println(t1.x); //11
System.out.println(t2.x); //9

}
}
------------------------------------------------------------------
What is a static field ?
------------------------
It is a class level variable.

If a variable is declared with static modifier inside a class then it is called


class variable OR static field.
A static field variable will be automatically initialized with default values and
memory will be allocated (even the variable is final) AT THE TIME OF LOADING THE
CLASS INTO JVM MEMORY.

In order to access the static member, we need not to create an object, here class
name is required.

Role of static field in Object creation :


-----------------------------------------
Whenever we create an object then a single copy of static filed is created and the
same single copy is sharable by all the objects so, if we make any changes through
one object, it will reflect to all the objects as shown in the program.

package com.ravi.oop;

public class Demo


{
static int x = 10;

public static void main(String[] args)


{
Demo d1 = new Demo();
Demo d2 = new Demo();

++d1.x; ++d2.x;

System.out.println(d1.x); //12
System.out.println(d2.x); //12
}

So, The conclusion is :

Instance Variable = Multiple Copies with each and every object


Static Field = Single Copy is sharable by all the Objects.
-----------------------------------------------------------------
When we should decalre a variable as static variable and when we should declare as
variable as a non static variable ?

Instance Variable :
-------------------
If the value of the variable is different with respect to objects then we should
declare a variable as a instance variable.

Static Variable :
------------------
If the value of the variable is common to all the objects then we should declare a
variable as a static variable.

Program :
---------
2 files :
---------
package com.nit;

public class Student


{
int rollNumber;
String studentName;
String studentAddress;
static String collegeName = "NIT";
static String courseName = "Java";

public void setStudentData(int rollNumber, String studentName, String


studentAddress)
{
this.rollNumber = rollNumber;
this.studentName = studentName;
this.studentAddress = studentAddress;
}

@Override
public String toString() {
return "Student [rollNumber=" + rollNumber + ", studentName=" +
studentName + ", studentAddress="
+ studentAddress + ", college name="
+Student.collegeName+", course name = "+ Student.courseName+" ]";

VariableDeclaration.java
-------------------------
package com.nit;

public class VariableDeclaration {

public static void main(String[] args)


{
Student raj = new Student();
raj.setStudentData(111, "Raj", "Ameerpet");
System.out.println(raj);

Student priya = new Student();


priya.setStudentData(222, "Priya", "S.R Nagar");
System.out.println(priya);

}
=================================================================
18-09-2024
----------
What is Data Hiding ?
----------------------
Data hiding is nothing but declaring our data members with private access modifier
so our data will not be accessible from outer world that means no one can access
our data directly from outside of the class.

*We should provide the accessibility of our data through methods so we can perform
VALIDATION ON DATA which are coming from outer world.

2 files :
---------
Customer.java
-------------
package com.ravi.data_hiding;

public class Customer


{
private double balance = 10000; //Data Hiding

public void deposit(double amount)


{
//Validation
if(amount <=0)
{
System.err.println("Amount can't be deposited");
}
else
{
this.balance = this.balance + amount;
System.out.println("Amount After deposit is :"+this.balance);
}
}

public void withdraw(double amount)


{
this.balance = this.balance - amount;
System.out.println("Balance After Withdraw is :"+this.balance);
}

BankApplication.java
---------------------
package com.ravi.data_hiding;

public class BankApplication {

public static void main(String[] args)


{
Customer scott = new Customer();
scott.deposit(1000);
scott.withdraw(5000);

}
-----------------------------------------------------------------
Constructor :
-------------
What is Constructor ?
---------------------
What is the advantage of writing constructor in our class ?
------------------------------------------------------------
If we don't write a constructor in our program then variable initialization and
variable re-initialization both are done in two different lines.

If we write constructor in our program then variable initialization and variable


re-initialization both are done in the same line i.e at the time of Object
creation. [08-OCT]

With Constructor approach, we need not to depend on method to re-initialize our


instance variable with user value.
----------------------------------------------------------------
Defination of Constructor :
---------------------------
It is used to construct the Object that's why it is known as Constructor.

If the name of the class and name of the method both are exactly same and it does
not contain any return type then it is called Constructor.

Example :
----------
public class Student
{
public Student() //Constructor
{
}

public void Student() //Method


{
}
}

Every java class must contain at-least one constructor, either explicitly written
by developer OR implicitly added by compiler.

*The main purpose of constructor to initialize the Object properties (Instance


Variable)

A constructor never contain any return type but internally it returns current class
object (this keyword)

package com.ravi.constructor;

public class Employee


{
public void getSalary()
{
System.out.println("Employee is getting the Salary");
}

public static void main(String[] args)


{

new Employee().getSalary();
}
}

A constructor is automatically called and executed at the time of Object creation


(No need to call explicitly like method)

Every time we create an object by using new keyword, at-least one constructor must
be invoked.
================================================================
Program that describes difference between Method and Constructor
2 files :
---------
Student.java
-------------
package com.ravi.data_hiding;

public class Student


{
public Student()
{
System.out.println("I am Constructor");
}

public void Student()


{
System.out.println("I am Method");
}
}

StudentDemo.java
-----------------
package com.ravi.data_hiding;

public class StudentDemo {

public static void main(String[] args)


{
Student s = new Student(); //Constructor will be invoked
s.Student(); //Method Will be invoked
}
}
----------------------------------------------------------------
Types of Constructor :
----------------------
In java we have 3 types of Constructors :

1) Default Constructor (Compiler added Constructor)

2) No Argument OR Parameterless OR Non Parameterized OR Zero Argument constructor


(User defined without parameter constructor)

3) Parameterized Constructor
-----------------------------------------------------------------
Default No Argument Constructor :
---------------------------------
Whenever we write a class and if we don't write any type of constructor then
automatically one default constructor is added by the compiler.

The access modifier of default constaructor would be same as class access modifier.

It does not accept any parameter.

Example.java
--------------
public class Example
{

}
javac Example.java

Example.class
------------
public class Example
{
public Example() //default constructor
{
}
}
--------------------------------------------------------------------
No Argument Constructor :
--------------------------
If a user defines a constructor inside a class without argument then it is called
no argument constructor.

No argument constructor and default constructor, both look like same the only
difference is, default constructor means added by compiler and no argument
constructor means written by user.

public class Student


{
private int rollNumber;
private String studentName;

public Student() //No Argument Constructor


{
rollNumber = 111;
studentName = "Raj";
}

No argument constructor is not recommended to initialize our object properties


because due to no argument constructor all the object properties will be
initialized with SAME VALUE as shown in the program.

2 files :
----------
Person.java
------------
package com.ravi.constructor_demo;

public class Person {


private int personId;
private String personName;

public Person() // No Argument Constructor


{
this.personId = 111;
this.personName = "Scott";
}

@Override
public String toString()
{
return "Person [personId=" + personId + ", personName=" + personName +
"]";
}
}

package com.ravi.constructor_demo;

public class NoArgumentConstructor {

public static void main(String[] args)


{
Person scott = new Person();
System.out.println(scott);

Person smith = new Person();


System.out.println(smith);

Note : In the above program we have 2 objects scott and smith but both the objects
initialized with scott data.

To avoid this we introduced Parameterized constructor.


--------------------------------------------------------------
Parameterized Constructor :
---------------------------
If we pass one or more argument to the constructor then it is called parameterized
constructor.

By using parameterized constructor all the objects will be initialized with


different values.

Example :
----------
public class Employee
{
int id;
String name;

public Employee(int id, String name)


{
this.id = id;
this.name = name;
}
}
-------------------------------------------------------------------
Initializing the Object properties through Parameterized Constructor
--------------------------------------------------------------------
2 files :
---------
Dog.java
---------
package com.ravi.constructor_demo;

public class Dog


{
private String dogName;
private double dogHeight;
private String dogColor;

public Dog(String dogName, double dogHeight, String dogColor) {


super();
this.dogName = dogName;
this.dogHeight = dogHeight;
this.dogColor = dogColor;
}

@Override
public String toString()
{
return "Dog [dogName=" + dogName + ", dogHeight=" + dogHeight + ",
dogColor=" + dogColor + "]";
}
}

ParameterizedConstructor.java
------------------------------
package com.ravi.constructor_demo;

public class ParameterizedConstructor {

public static void main(String[] args)


{
Dog tommy = new Dog("Tommy", 3.4,"Black");
System.out.println(tommy);

Dog tiger = new Dog("Tiger", 4.4,"Dark Grey");


System.out.println(tiger);

}
}
--------------------------------------------------------------------
How to write setter and getter methods :
-----------------------------------------
public class Customer
{
private double customerBill;

//Initialize the customerBill using parameterized constructor


public Customer(double customerBill)
{
this.customerBill = customerBill;
}

//Writing setter to modify the existing customerBill


public void setCustomerBill(double customerBill)
{
this.customerBill = customerBill;
}

//Writing getter to retrieve the private data value outside of BLC class
public double getCustomerBill()
{
return this.customerBill;
}
}
--------------------------------------------------------------------
FINAL CONCLUSION :
-------------------
Parameterized Constructor : To initialize the Object properties with user values.

Setter : To modify the existing object data.[Only one data at a time] OR Writing
Operation

Getter : To read/retrieve private data value outside of BLC class. [Reading


Operation]
--------------------------------------------------------------------
*** What is Encapsulation
--------------------------
[Accessing our private data with public methods like setter and getter]
--------------------------------
Binding the private data with its associated method in a single unit is called
Encapsulation.

Encapsulation ensures that our private data (Object Properties) must be accessible
via public methods like setter and getter.

It provides security because our data is private (Data Hiding) and it is only
accessible via public methods WITH PROPER DATA VALIDATION.

In java, class is the example of encapsulation.

How to achieve encapsulation in a class :


------------------------------------------
In order to achieve encapsulation we should follow the following two
techniques :

1) Declare all the data members with private access modifiers (Data Hiding OR Data
Security)

2) Write public methods to perform read(getter) and write(setter) operation on


these private data like setter and getter.

Note : If we decalre all our data with private access modifier then it is called
TIGHTLY ENCAPSULATED CLASS. On the other hand if we declare our data other then
private access modifier then it is called Loosely Encapsulated class.

Program on encapsulation :
--------------------------
2 files :
----------
Employee.java
--------------
package com.ravi.constructor_demo;

public class Employee


{
private double employeeSalary;

public Employee(double employeeSalary)


{
super();
this.employeeSalary = employeeSalary;
}
public double getEmployeeSalary() //getter
{
return employeeSalary;
}

public void setEmployeeSalary(double employeeSalary) //setter


{
if(employeeSalary <=0)
{
System.err.println("Invalid Data");
}
else
{
this.employeeSalary = employeeSalary;
}
}

@Override
public String toString()
{
return "Employee [employeeSalary=" + employeeSalary + "]";
}

SetterAndGetter.java
----------------------
package com.ravi.constructor_demo;

public class SetterAndGetter {

public static void main(String[] args)


{
Employee scott = new Employee(55000);
scott.setEmployeeSalary(scott.getEmployeeSalary()+10000);
System.out.println(scott);

//Verify whether scott is developer/designer/tester

double empSalary = scott.getEmployeeSalary();

if(empSalary >=60000)
{
System.out.println("Scott is Developer");
}
else if(empSalary >=40000)
{
System.out.println("Scott is Designer");
}
else
{
System.out.println("Scott is Tester");
}

}
--------------------------------------------------------------------
20-09-2024
-----------
Method return type as a class :
-------------------------------
While declaring a method in java, return type is compulsory.
As a method return type we have following options

1) void as a retutn type of the Method

2) Any primitive data type as a return type of the method.

3) Any class name/interface / enum / record we can take as a return type of the
method.

Example 1 :
-----------
package com.nit;

public class Demo


{
public Demo m1() //Factory Method
{
return this; //Valid
OR
return null; //Valid
OR
return new Demo(); //Valid
}
}

Example 2 :
-----------
package com.nit;

public class Demo


{
int x;

public Demo(int x)
{
this.x = x;
}

public Demo m1()


{
return new Demo(8);

}
}

Note : Here the return value depends upon the available constructor in the class.
====================================================================
What is a Factory Method :
--------------------------
If a method return type is class name menas it is returning the Object of the class
then it is called Factory Method.
--------------------------------------------------------------------
2 files :
---------
Product.java
-------------
package com.ravi.factory_method;

public class Product


{
private int productId;
private String productName;
private double productPrice;

public Product(int productId, String productName, double productPrice)


{
super();
this.productId = productId;
this.productName = productName;
this.productPrice = productPrice;
}

@Override
public String toString() {
return "Product [productId=" + productId + ", productName=" +
productName + ", productPrice=" + productPrice
+ "]";
}

public static Product getProductObject()


{
return new Product(111,"Laptop",92000);
}

ProductDemo.java
-----------------
package com.ravi.factory_method;

public class ProductDemo {

public static void main(String[] args)


{
Product obj = Product.getProductObject();
System.out.println(obj);

In the avove program getProductObject() is providing only one product object so it


is not recommended because the main purpose of any method to provide re-usability
as shown in the program below.

2 files :
----------
Employee.java
--------------
package com.ravi.factory_method;

import java.util.Scanner;

public class Employee


{
private int employeeId;
private String employeeName;
private double employeeSalary;

public Employee(int employeeId, String employeeName, double employeeSalary) {


super();
this.employeeId = employeeId;
this.employeeName = employeeName;
this.employeeSalary = employeeSalary;
}

@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" +
employeeName + ", employeeSalary="
+ employeeSalary + "]";
}

public static Employee getEmployeeObject()


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee Id :");
int id = sc.nextInt();

System.out.print("Enter Employee Name :");


String name = sc.nextLine();
name = sc.nextLine();

System.out.print("Enter Employee Salary :");


double sal = sc.nextDouble();

return new Employee(id, name, sal);


}
}

EmployeeDemo.java
------------------
package com.ravi.factory_method;

import java.util.Scanner;

public class EmployeeDemo {

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.print("How many Employee Object you want ?");
int noOfObj = sc.nextInt();

for(int i=1; i<=noOfObj; i++)


{
Employee employee = Employee.getEmployeeObject();
System.out.println(employee);
}

sc.close();

}
}
--------------------------------------------------------------------
What is Shallow and Deep copy in java :
----------------------------------------
Shallow Copy :
--------------
In Shallow copy, Only one Object will be created but the same object will be
refered by multiple reference variables.

If we modify the object properties by any of the reference variable then original
object will be modified as shown in the program.

package com.ravi.object_duplication;

public class Laptop


{
private double laptopPrice;
private String laptopBrand;

public Laptop(double laptopPrice, String laptopBrand)


{
super();
this.laptopPrice = laptopPrice;
this.laptopBrand = laptopBrand;
}

@Override
public String toString() {
return "Laptop [laptopPrice=" + laptopPrice + ", laptopBrand=" +
laptopBrand + "]";
}

public static void main(String[] args)


{
Laptop laptop1 = new Laptop(86000, "HP");
Laptop laptop2 = laptop1; [Diagram 20-SEP]

System.out.println("Before Change");
System.out.println(laptop1);
System.out.println(laptop2);

laptop2.laptopBrand = "DELL";
laptop2.laptopPrice = 95000;

System.out.println("After Change");
System.out.println(laptop1);
System.out.println(laptop2);

}
--------------------------------------------------------------------
Deep Copy :
-----------
In deep copy two different objects will be created, the 2nd object will copy the
content of first object.

If we modify the object by using reference variable then only one object will be
modified because both the objects are created in two different memory location as
shown below.

package com.ravi.object_duplication;

public class Customer


{
private int customerId;
private String customerName;

@Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" +
customerName + "]";
}

public static void main(String[] args)


{
Customer c1 = new Customer();
c1.customerId = 111;
c1.customerName = "Scott";

Customer c2 = new Customer();


c2.customerId = c1.customerId;
c2.customerName = c1.customerName;

System.out.println("Before Change");
System.out.println(c1);
System.out.println(c2);

System.out.println("..................");
System.out.println("After change in 2nd Object");
c2.customerId = 222;
c2.customerName = "Smith";
System.out.println(c1);
System.out.println(c2);
}

}
===============================================================
**Pass by Value :
-----------------
Java does not support pointers so java only works with pass by value.

Pass by value means we are sending the copy of orginal data to the method.

package com.ravi.pass_by_value;
public class PassByValueDemo1 {

public static void main(String[] args)


{
int x = 100;
changeData(x);
System.out.println(x);
}

public static void changeData(int y)


{
y = 150;
}

Here output is 100 because we are passing the copy of x to y variable


--------------------------------------------------------------------
package com.ravi.pass_by_value;

public class PassByValueDemo2 {

public static void main(String[] args)


{
int x = 100;
x = changeData(x);
System.out.println(x);
}

public static int changeData(int y)


{
y = 150;
return y;
}

Note : In both the program we are working with primitive variables.


--------------------------------------------------------------------
package com.ravi.pass_by_value;

class Customer
{
private int customerId = 111;

public void setCustomerId(int customerId)


{
this.customerId = customerId;
}

public int getCustomerId()


{
return this.customerId;
}
}

public class ReferenceDemo1


{
public static void main(String[] args)
{
Customer c1 = new Customer();
System.out.println(c1.getCustomerId()); //111

accept(c1);
System.out.println(c1.getCustomerId()); //555
}

public static void accept(Customer cust)


{
cust.setCustomerId(555);
}
}

Here we will get the Output 111 and 555, here we are working with
reference variable, the reference variable c1 is assigned to reference variable
cust hence, if we modify by using cust variable then original object will be
modified.
--------------------------------------------------------------------
package com.ravi.pass_by_value;

class Product
{
private int productId = 111;

public int getProductId()


{
return productId;
}

public void setProductId(int productId)


{
this.productId = productId;
}
}

public class ReferenceDemo2 {

public static void main(String[] args)


{
Product p1 = new Product(); //100x
System.out.println(p1.getProductId()); //111

accept(p1);
System.out.println(p1.getProductId()); //111
}

public static void accept(Product prod)


{
prod = new Product(); //200x
prod.setProductId(999);
}
}

Here on p1 reference variable we are assigning one new Product object so the old
object value will remain unchaged.
--------------------------------------------------------------------
package com.ravi.object_duplication;
public class Customer
{
private double customerBill = 4000;

public static void main(String[] args)


{
Customer c1 = new Customer();
Customer c2 = c1;

c2.customerBill = 9000;

System.out.println(c1.customerBill); //9000
System.out.println(c2.customerBill); //9000

}
-------------------------------------------------------------------
package com.ravi.object_duplication;

public class Customer


{
private double customerBill = 4000;

public static void main(String[] args)


{
Customer c1 = new Customer();

Customer c2 = new Customer();


c2.customerBill = 10000;

System.out.println(c1.customerBill); //4000
System.out.println(c2.customerBill); //10000

}
---------------------------------------------------------------
HEAP and STACK Diagram :
------------------------
What is Garbage Collector in java -----------------------------------
It is an automatic memory management technique in java.

In C++ language, A programmer is responsible to allocate as well as de-allocate the


memory otherwise we will get OutOfMemoryError.

In java language, Programmer is only responsible to allocate the memory, Memory de-
allocation is automatically done by garbage collector.

Garbage Collector is a daemon thread which is responsible to delete the objects


from the HEAP Memory. Actually It scans the heap memory and identifying which
objects are eligible for Garbage Collector.[THE OBJECTS WHICH DOES NOT CONTAIN ANY
REFERENCES ONLY THOSE OBJECTS ARE ELIGIBLE FOR GC]

It internally uses an algorithm called Mark and Sweep algorithm to delete the un-
used objects.

As a developer we can also explicitly call garbage collector by writing the


following code

System.gc();

==============================================================

How many ways we can make an object eligible for Garbage Collector :
--------------------------------------------------------------------
There are 3 ways we can make an object eligible for GC.

1) Assigning null literal to existing reference variable :


Employee e1 = new Employee(111,"Ravi");
e1 = null;

2) Creating an Object inside a method :

public void createObject()


{
Employee e2 = new Employee();
}
Here we are creating Employee object inside the method so, once the method
execution is over then e2 will be deleted from the Stack Frame and the employee
object will become eligible for GC.

3) Assigning new Object to the old existing reference variable:

Employee e3 = new Employee();


e3 = new Employee();

Earlier e3 variable was poting to Employee object after that a new Employee Object
is created which is pointing to another memory location so the first object is
eligible for GC.

===============================================================
Memory in java :
------------------
In java, whenever we create an object then Object and its content (properties and
behavior) are stroed in a special memory called HEAP Memory. Garbage collector
visits heap memory only.

All the local variables and parameters variables are executed in Stack Frame and
available in Stack Memory.
--------------------------------------------------------------
HEAP and Stack Diagram for CustomerDemo.java :
-----------------------------------------------
class Customer
{
private String name;
private int id;

public Customer(String name , int id)


{
super();
this.name=name;
this.id=id;
}
public void setId(int id) //setter
{
this.id=id;
}

public int getId() //getter


{
return this.id;
}
}

public class CustomerDemo


{
public static void main(String[] args)
{
int val = 100;

Customer c = new Customer("Ravi",2);

m1(c);

//GC [Only 1 object i.e 3000x is eligible for GC]

System.out.println(c.getId());
}

public static void m1(Customer cust)


{
cust.setId(5);

cust = new Customer("Rahul",7);

cust.setId(9);
System.out.println(cust.getId());
}
}

//Output 9 5
--------------------------------------------------------------
public class Sample
{
private Integer i1 = 900;

public static void main(String[] args)


{
Sample s1 = new Sample();

Sample s2 = new Sample();

Sample s3 = modify(s2);

s1 = null;

//GC [4 Objects 1000x,2000x,5000x and 6000x are eligible]

System.out.println(s2.i1);
}
public static Sample modify(Sample s)
{
s.i1=9;
s = new Sample();
s.i1= 20;
System.out.println(s.i1);
s=null;
return s;
}
}

//20 9
--------------------------------------------------------------
public class Test
{
Test t;
int val;

public Test(int val)


{
this.val = val;
}

public Test(int val, Test t)


{
this.val = val;
this.t = t;
}

public static void main(String[] args)


{
Test t1 = new Test(100);

Test t2 = new Test(200,t1);

Test t3 = new Test(300,t1);

Test t4 = new Test(400,t2);

t2.t = t3;
t3.t = t4;
t1.t = t2.t;
t2.t = t4.t;

System.out.println(t1.t.val);
System.out.println(t2.t.val);
System.out.println(t3.t.val);
System.out.println(t4.t.val);
}

}
--------------------------------------------------------------
public class Employee
{
int id = 100;

public static void main(String[] args)


{
int val = 200;
Employee e1 = new Employee();

e1.id = val;

update(e1);

System.out.println(e1.id);

Employee e2 = new Employee();

e2.id = 900;

switchEmployees(e2,e1); //3000x, 1000x

//GC [2 objects 2000x and 4000x]

System.out.println(e1.id);
System.out.println(e2.id);
}

public static void update(Employee e)


{
e.id = 500;
e = new Employee();
e.id = 400;
System.out.println(e.id);
}

public static void switchEmployees(Employee e1, Employee e2)


{
int temp = e1.id;
e1.id = e2.id; //500
e2 = new Employee();
e2.id = temp;
}
}
--------------------------------------------------------------
Passing an Object reference to the Constructor :(Copy Constructor)
--------------------------------------------------------------
We can pass an object reference to the constructor so we can copy the content of
one object to another object.

The following program explains how to copy the content of Employee object to
initialize Manager class properties :

3 files :
----------
Employee.java
--------------
package com.ravi.copy_constructor;

public class Employee


{
private int employeeId;
private String employeeName;

public Employee(int employeeId, String employeeName)


{
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
}

public int getEmployeeId() {


return employeeId;
}

public String getEmployeeName() {


return employeeName;
}
}

Manager.java
-------------
package com.ravi.copy_constructor;

public class Manager


{
private int managerId;
private String managerName;

public Manager(Employee emp)


{
this.managerId = emp.getEmployeeId();
this.managerName = emp.getEmployeeName();
}

@Override
public String toString() {
return "Manager [managerId=" + managerId + ", managerName=" +
managerName + "]";
}
}

CopyConstructorDemo1.java
---------------------------
package com.ravi.copy_constructor;

public class CopyConstructorDemo1 {

public static void main(String[] args)


{
Employee raj = new Employee(111, "Raj");

Manager m1 = new Manager(raj);


System.out.println(m1);

Note : In the above program we are initializing the Manager data through Employee
Data.

The following program explains how to initialize the same class data in another
object.

2 files :
---------
Player.java
-----------
package com.ravi.copy_constructor;

public class Player


{
private String name1;
private String name2;

public Player(String name1, String name2)


{
super();
this.name1 = name1;
this.name2 = name2;
}

public Player(Player p) //p = p1


{
this.name1 = p.name2;
this.name2 = p.name1;
}

@Override
public String toString() {
return "Player [name1=" + name1 + ", name2=" + name2 + "]";
}
}

CopyConstructorDemo2.java
--------------------------
package com.ravi.copy_constructor;

public class CopyConstructorDemo2 {

public static void main(String[] args)


{
Player p1 = new Player("Virat", "Rohit");
System.out.println(p1);

Player p2 = new Player(p1);


System.out.println(p2);

}
---------------------------------------------------------------
Lab Program :
-------------
Lab Program :(Method return type as a class + Passing Object ref)
----------------------------------------------------------------
A class called Customer is given to you.

The task is to find the applicable Credit card Type and create CardType object
based on the Credit Points of a customer.

Define the following for the class.


Attributes :
customerName : String,private
creditPoints: int, private

Constructor :
parameterizedConstructor: for both cusotmerName & creditPoints in that order.

Methods :
Name of the method : getCreditPoints
Return Type : int
Modifier : public
Task : This method must return creditPoints

Name of the method : toString, Override it,


Return type : String
Task : return only customerName from this.

Create another class called CardType. Define the following for the class

Attributes :
customer : Customer, private
cardType : String, private
Constructor :
parameterizedConstructor: for customer and cardType attributes in that order

Methods :
Name of the method : toString Override this.
Return type : String
Modifier : public
Task : Return the string in the following format.
The Customer 'Rajeev' Is Eligible For 'Gold' Card.

Create One more class by name CardsOnOffer and define the following for the class.

Method :
Name Of the method : getOfferedCard
Return type : CardType
Modifiers: public,static
Arguments: Customer object

Task : Create and return a CardType object after logically finding


cardType from creditPoints as per the below rules.
creditPoints cardType
100 - 500 - Silver
501 - 1000 - Gold
1000 > - Platinum
< 100 - EMI

Create an ELC class which contains Main method to test the working of the above.

4 Files :
----------
Customer.java
---------------
package com.ravi.scenario_program;

public class Customer


{
private int creditPoints;
private String customerName;

public Customer(int creditPoints, String customerName)


{
super();
this.creditPoints = creditPoints;
this.customerName = customerName;
}

public int getCreditPoints() //getter


{
return this.creditPoints;
}

@Override
public String toString()
{
return this.customerName;
}
}

CardType.java
---------------
package com.ravi.scenario_program;

public class CardType


{
private String cardType;
private Customer customer; // HAS-A Relation

public CardType(String cardType, Customer customer)


{
super();
this.cardType = cardType;
this.customer = customer;
}

@Override
public String toString()
{
//The Customer 'Rajeev' Is Eligible For 'Gold' Card.

return "The Customer '"+this.customer+"' Is Eligible For


'"+this.cardType+"' Card";
}

CardsOnOffer.java
------------------
package com.ravi.scenario_program;

public class CardsOnOffer


{
public static CardType getOfferedCard(Customer cust)
{
int crediPoint = cust.getCreditPoints();

if(crediPoint>=100 && crediPoint <=500)


{
return new CardType("Silver", cust);
}

else if(crediPoint>500 && crediPoint <=1000)


{
return new CardType("Gold", cust);
}
else if(crediPoint>1000)
{
return new CardType("Platinum", cust);
}
else
{
return new CardType("EMI", cust);
}

ELC.java
---------
package com.ravi.scenario_program;

import java.util.Scanner;

public class ELC {

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Customer Name :");
String name = sc.nextLine();

System.out.print("Enter Customer Credit Points :");


int creditPoint = sc.nextInt();

Customer c1 = new Customer(creditPoint, name);

CardType offeredCard = CardsOnOffer.getOfferedCard(c1);


System.out.println(offeredCard);

sc.close();

}
---------------------------------------------------------------
25-09-2024
----------
Modifiers on Constructor :
---------------------------
Constructor can accept all types of access modifiers which are apllicable for
accessibility level like private, default, protected and public.

package com.ravi.constructor;

public class Sample


{
private int x,y;

private Sample(int x, int y) //Private Constructor


{
this.x = x;
this.y = y;
}

@Override
public String toString() {
return "Sample [x=" + x + ", y=" + y + "]";
}

public static void main(String[] args)


{
Sample s = new Sample(12, 24);
System.out.println(s);

}
----------------------------------------------------------------
package com.ravi.constructor;

public class Demo


{
public Demo()
{
System.out.println("No Argument Constructor");
return; //Valid
}

public static void main(String[] args)


{
new Demo(); //Nameless OR Anonymous Object
}

}
----------------------------------------------------------------
Note : We can't apply static, final, abstract and synchronized modifier on
constructor.
----------------------------------------------------------------
IQ :
----
Why we should declare a constructor with private Access modifier ?

We can declare a constructor with private access modifier due to the following two
reasons :

1) If we want to declare only static variables and static methods inside a class
then we should decalre constructor with private access modifier [Object is not
required]

Example : java.util.Arrays and Math class has private constructor because It


contains only static method.

2) If we want to develop singleton class, for singleton class we should create only
one object by the class itself then we should declare the constructor with private
access modifier.

package com.ravi.constructor;

public class Foo


{
private Foo() //Private Constructor
{
System.out.println("It is a private Constructor");
}

public static void main(String [] args)


{
new Foo();
}

}
-------------------------------------------------------------------
What is an instance block OR instance initializer in java ?
------------------------------------------------------------
It is a special block in java which is automatically executed at the time of
creating the Object.

Example :

{
//Instance OR Non static block
}

If a constructor contains first line as a super() statement then only compiler will
add instance block in the 2nd line of constructor otherwise it will not be added by
the compiler.

If constructor contains super() then non static block will be executerd before the
body of the constructor.

The main purpose of instance block to initialize the instance variables (So It is
called Instance Iniatilizer) of the class OR to write a common logic which will be
applicable to all the objects.

If a class contains multiple non static blocks then it will be executed according
to the order [Top to bottom]

Instance initializer must be executed normally that menas we can't interrupt the
execution flow of any initializer hence we can't write return statement inside non
static block.

If a user defines non static block after the body of the constructor then compiler
will not placed in the 2nd line of the constructor. It will be executed as it is
because compiler will search the NSB in the class level.

-----------------------------------------------------------------
package com.ravi.instance_block;

class Test
{
{
System.out.println("Instance OR Non static Block ");
}
}

public class InstanceBlockDemo1


{
public static void main(String[] args)
{
new Test();
new Test();
new Test();
}

Everytime we will create the object, Instance block will be executed


------------------------------------------------------------------
package com.ravi.instance_block;

class Sample
{
int x;

{
x = 100;
}

public class InstanceBlockDemo2 {

public static void main(String[] args)


{
Sample s1 = new Sample();
System.out.println(s1.x);

Note : By using instance block we can initialize the instance variable.


----------------------------------------------------------------
package com.ravi.instance_block;

class Sample1
{
public Sample1()
{
System.out.println("No Arg Constr");
}

public Sample1(int x)
{
System.out.println("Parameterized Constructor");
}

{
System.out.println("Non Static Block");
}

public class InstanceBlockDemo3 {

public static void main(String[] args)


{
new Sample1();
new Sample1(15);

Note : Non static block will be added to all the constructors which contains
super().
-------------------------------------------------------------------
package com.ravi.instance_block;

class NIT
{
public NIT()
{
super();
//NSB
System.out.println("No Arg constr");
}

public NIT(String batch)


{
this();
System.out.println("Parameterized Constr "+batch);
}

{
System.out.println("Instance Block OR Non static Block");
}
}

public class InstanceBlockDemo4 {

public static void main(String[] args)


{
new NIT("Batch 37");

Note : Non static block will not be added to the constructor which contains this()
------------------------------------------------------------------
package com.ravi.instance_block;

class Demo1
{
int x;

{
x = 100;
System.out.println(x);
}

{
x = 200;
System.out.println(x);
}

{
x = 300;
System.out.println(x);
}

public Demo1()
{
x = 400;
System.out.println(x);
}
}

public class InstanceBlockDemo5 {

public static void main(String[] args)


{
new Demo1();
}

Note : NSB will be executed according to the order.


-------------------------------------------------------------------
package com.ravi.instance_block;

public class InstanceDemo6


{
{
System.out.println("Instance block");
return;
}

public static void main(String[] args)

{
// TODO Auto-generated method stub

}
Note : no return keyword inside non static block
-----------------------------------------------------------------
package com.ravi.instance_block;

class General
{
public General()
{
System.out.println("Constructor Body");

{
System.out.println("Non Static Block");
}
}
}

public class InsatanceBlockDemo7


{
public static void main(String[] args)
{
new General();
}

Note : Here non static block will be executed after the body of constructor.
----------------------------------------------------------------
Order of instance variable initialization in the program life cycle :

All the instance variables are initialized in the following order during the life
cycle :

1) It will initialized with default value at the time of Object


creation. [new Demo(); Demo class instance variable will be initialized with
default value, init method is working internally]

2) Now control will verify whether, we have initailized at the time of variable
declaration or not.

3) Now control will verify whether, we have initailized


inside non static block or not. [If present]

4) Now control will verify whether, we have initailized in the


body of the constructor or not.

5) Now control will verify whether, we have initailized in the method body or not
but it is not recommended because Object is already created, we need to call the
method explicitly, It is not the part of the object.

Default value [new keyword] => At the time of declaration => in the body of non
static block => in the body of constructor => Inside method body [Not Recommended]

package com.ravi.instance_initialization;

class Demo
{
int x = 100; //Initialization Order1
Demo()
{
this.x = 300; //Initialization Order3
}

{
x = 200; //Initialization Order2
}
}

public class InstanceInitializationOrder


{
public static void main(String[] args)
{
Demo d1 = new Demo();
System.out.println(d1.x);

}
----------------------------------------------------------------
What is blank final field in java ?
------------------------------------
If a final instance variable is not initialized at the time of declaration then it
is called blank final field.

final int A ; //Blank final field

A final variable must have user-defined value.

A blank final field can't be initialized by default constrcutor as shown in the


program.

class Test
{
final int A; //Blank final field

public static void main(String[] args)


{
Test t1 = new Test();
System.out.println(t1.A);
}
}

A blank final field must be explicitly initialized by the user till the execution
of constructor body.[Till Object creation]. It can be iniatialized in the following
two places :

a) Inside a non static block [If available]


b) Inside the constructor body

class Test
{
final int A ; //Blank final field

{
A = 100;
}

public static void main(String[] args)


{
Test t1 = new Test();
System.out.println(t1.A);
}
}

* A blank final field can't be initialized by method.[Object creation is already


completed]

* A blank final field can also have default values as shown the in the program.

class Test
{
final int A ; //Blank final field

{
printDefaultValue();
A = 100;
}

public void printDefaultValue()


{
System.out.println(A);
}

public static void main(String[] args)


{
Test t1 = new Test();
System.out.println(t1.A);
}
}

A blank final must be iniatilized explicitly by user in all the constructors


available in the class.

package com.ravi.basic;

class Sample
{
private final int x;

public Sample()
{
x = 100;
}

public Sample(int y)
{
x = y;
}

public int getX()


{
return x;
}

public class BlankFinalField {

public static void main(String[] args)


{
Sample s1 = new Sample();
System.out.println(s1.getX());

Sample s2 = new Sample(200);


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

}
=================================================================
Relationship between the classes :
----------------------------------
In java we have 2 types of relation in between the classes :

a) IS-A Relation
b) HAS-A Relation

IS-A Relation :
---------------
class Car
{
}
class Ford extends Car //[Ford IS-A car ]
{
}

HAS-A Relation :
-----------------
class Engine
{
}

class Car
{
private Engine engine; //Car HAS-A Engine.
}

IS-A relation we can achieve by using Inheritance Concept.


HAS-A relation we can achieve by using Association Concept.

27-09-2024
------------
Inheritance (IS-A Relation) :
--------------------------------
Deriving a new class (child class) from existing class (parent class) in such a way
that the new class will acquire all the properties and features (except private)
from the existing class is called inheritance.

It is one of the most imporatnt feature of OOPs which provides "CODE REUSABILITY".

Using inheritance mechanism the relationship between the classes is parent and
child. According to Java the parent class is called super class and the child class
is called sub class.

In java we provide inheritance using 'extends' keyword.

*By using inheritance all the feature of super class is by default available to the
sub class so the sub class need not to start the process from begning onwards.

Inheritance provides IS-A relation between the classes. IS-A relation is tightly
coupled relation (Blood Relation) so if we modify the super class content then
automatically sub class content will also modify.

Inheritance provides us hierarchical classification of classes, In this hierarchy


if we move towards upward direction more generalized properties will occur, on the
other hand if we move towards downwand more specialized properties will occur.
------------------------------------------------------------------
Types of Inheritance in java :
------------------------------
Java supports 5 types of inheritance :

1) Single level Inheritance


2) Multi level Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance (Not supported using class)
5) Hybrid Inheritance (Combination of two)
---------------------------------------------------------------
Program on Single Level Inheritance :
-------------------------------------
package com.ravi.inheritance;

class Father
{
public void house()
{
System.out.println("3 BHK House");
}
}
class Son extends Father
{
public void car()
{
System.out.println("Audi Car");
}
}

public class SingleLevelDemo1


{
public static void main(String[] args)
{
Son s1 = new Son();
s1.house();
s1.car();
}

Note : In inheritance we should always create the object for more


specialized class(son class);
------------------------------------------------------------------
package com.ravi.inheritance;

class Super
{
private int x,y;

public int getX()


{
return x;
}

public void setX(int x)


{
this.x = x;
}

public int getY()


{
return y;
}

public void setY(int y)


{
this.y = y;
}
}

class Sub extends Super


{
public void dispalyData()
{
System.out.println("x value is :"+getX());
System.out.println("y value is :"+getY());
}
}

public class SingleLevelDemo2 {

public static void main(String[] args)


{
Sub s1 = new Sub();
s1.setX(100);
s1.setY(200);
s1.dispalyData();

}
---------------------------------------------------------------
28-09-2024
-----------
How to initialize the super class properties :
----------------------------------------------
In order to initialize the super class properties we should use super keyword in
the sub class as a first line of constructor.

super keyword always referes to its immediate super class.

Just like this keyword, super keyword (non static member) also we can't use inside
static context.

super keyword we can use 3 ways in java :


------------------------------------------
1) To access super class variable
2) To access super class method
3) To access super class constructor.

1) To access the super class variable (Variable Hiding) :


---------------------------------------------------------
Whenever super class variable name and sub class variable name both are same then
it is called variable Hiding, Here sub class variable hides super class variable.

In order to access super class variable i.e super class memory, we should use super
keyword as shown in the program.

VariableHiding.java
-------------------
package com.ravi.super_keyword;

class Father
{
protected double balance = 50000;
}
class Son extends Father
{
protected double balance = 9000; //Variable Hiding

public void getBalance()


{
System.out.println("Son balance is :"+this.balance);
System.out.println("Father balance is :"+super.balance);
}
}

public class VariableHiding


{
public static void main(String[] args)
{
Son s = new Son();
s.getBalance();

}
---------------------------------------------------------------
2) To call super class method :
-------------------------------
If the super class non static method name and sub class non static method name both
are same (Method Overriding) and if we create an object for sub class then sub
class method will be
executed (bottom to top), if we want to call super class method from sub class
method body then we we should use super keyword as shown in the program.

class Super
{
public void show()
{

System.out.println("Super class show method");


}
}
class Sub extends Super
{
public void show()
{
super.show();
System.out.println("Sub class show method");
}
}
public class CallingSuperClassMethod
{
public static void main(String[] args)
{
Sub sub = new Sub();
sub.show();
}

}
--------------------------------------------------------------
3) To access the super class constructor (Constructor Chaining) :
----------------------------------------------------------------
Whenever we write a class in java and we don't write any kind of constructor to the
class then the java compiler will automatically add one default no argument
constructor to the class.

THE FIRST LINE OF ANY CONSTRUCTOR IS RESERVERD EITHER FOR super() or this() keyword
that means first line of any constructor is used to call another constructor of
either same class OR super class.

In the first line of any constructor if we don't specify either super() or this()
then the compiler will automatically add super() to the first line of constructor.

Now the purpose of this super() [added by java compiler], to call the default
constructor or No-Argument constructor of the super class.

In order to call the constructor of super class as well as same class, we have
total 4 cases.
---------------------------------------------------------------
Case 1:
-------
super() : Automatically added by java compiler to maintain the
hierarchy in the first line of the Constructor. It
is used to call default OR no argument constructor
of super class.

package com.ravi.constructor_demo;

class Alpha
{
public Alpha()
{
super();
System.out.println("Alpha class");
}
}
class Beta extends Alpha
{
public Beta()
{
super();
System.out.println("Beta class");
}
}

public class CallingSuperClassConstructor


{
public static void main(String[] args)
{
Beta b = new Beta();

}
---------------------------------------------------------------
Case 2 :
---------
super("Java") : Must be explicitly written by user in the
first line of constructor [not inside a method]. It is used to call
the parameterized constructor of super class.

package com.ravi.constructor_demo;

class Super
{
protected String name;

public Super(String name)


{
this.name = name;
}

}
class Sub extends Super
{
public Sub()
{
super("Java"); //Calling Parameterized constr
}

public String getSubjectName()


{
return this.name;
}
}

public class CallingParameterizedConstructor


{
public static void main(String[] args)
{
Sub s1 = new Sub();
System.out.println(s1.getSubjectName());

}
--------------------------------------------------------------
Program that describes default constructor and super() will be added by the
compiler.

ConstructorDemo.java
---------------------
package com.ravi.super_demo;

class Alpha
{
public Alpha()
{
System.out.println("Alpha class Constructor!!!");
}
}
class Beta extends Alpha
{}

class Gamma extends Beta


{
public Gamma()
{
System.out.println("Gamma class Constructor!!!");
}
}

public class ConstructorDemo {

public static void main(String[] args)


{
new Gamma();
}

30-09-2024
----------
Case 3 :
--------
this() : Must be explicitly written by user in the
first line of constructor. It is used to call
no argument constructor of current class.

package com.ravi.super_demo;

class Super
{
public Super()
{
System.out.println("Super class no argument constructor");
}
public Super(String msg)
{
this();
System.out.println("Super class Parameterized constructor :"+msg);
}
}
class Sub extends Super
{
public Sub()
{
super("Java");
System.out.println("Sub class no argument constructor");
}
}

public class CallingSameClassNoArg


{
public static void main(String[] args)
{
new Sub();

}
----------------------------------------------------------------
Case 4 :
---------
this(15) : Must be explicitly written by user in the
first line of constructor. It is used to call
parameterized constructor of current class.

package com.ravi.super_demo;

class Base
{

public Base()
{
this(15);
System.out.println("No Argument Constructor of Base class");
}

public Base(int x)
{
System.out.println("Parameterized Constructor of Base class :"+x);
}
}

class Derived extends Base


{
public Derived()
{
System.out.println("No Argument Constructor of Derived class");
}
}

public class ParameterizedConstructorOfCurrent


{
public static void main(String[] args)
{
Derived d = new Derived();
}

}
----------------------------------------------------------------
Program on super keyword :
--------------------------
package com.ravi.super_demo;

class Shape
{
protected int x;

public Shape(int x)
{
super();
this.x = x;
System.out.println("x value is :"+x);
}
}
class Square extends Shape
{

public Square(int side)


{
super(side);
}

public void getAraeOfSquare()


{
double area = x * x;
System.out.println("Area of Square is :"+area);
}
}

public class SuperDemo1 {

public static void main(String[] args)


{
Square ss = new Square(5);
ss.getAraeOfSquare();

}
----------------------------------------------------------------
Another Program on super keyword :
----------------------------------
package com.ravi.super_demo;

class Shape
{
protected int x;

public Shape(int x)
{
super();
this.x = x;
System.out.println("x value is :"+x);
}
}

class Rectangle extends Shape


{
protected int breadth;

public Rectangle(int length, int breadth) //10 20


{
super(length);
this.breadth = breadth;
}

public void getAreaOfRectangle()


{
double area = super.x * this.breadth;
System.out.println("Area of Rectangle :"+area);
}

class Circle extends Shape


{
protected final double PI = 3.14;

public Circle(int radius)


{
super(radius);
}

public void getAreaOfCircle()


{
double area = PI * x * x;
System.out.println("Area of Circle is :"+area);
}
}

public class SuperDemo1 {

public static void main(String[] args)


{
Rectangle rr = new Rectangle(10, 20);
rr.getAreaOfRectangle();

Circle cc = new Circle(3);


cc.getAreaOfCircle();

}
================================================================
HOW MANY WAYS WE CAN INITIALIZE THE OBJECT PROPERTIES ?
-------------------------------------------------------
The following are the ways to initialize the object properties :
----------------------------------------------------------------
public class Test
{
int x,y;
}

1) At the time of declaration :

Example :

public class Test


{
int x = 10;
int y = 20;
}

Test t1 = new Test(); [x = 10 y = 20]


Test t2 = new Test(); [x = 10 y = 20]

Here the drawback is all objects will be initialized with same value.
-----------------------------------------------------------------------

2) By using Object Reference :

public class Test


{
int x,y;
}

Test t1 = new Test(); t1.x=10; t1.y=20;


Test t2 = new Test(); t2.x=30; t2.y=40;

Here we are getting different values with respect to object but here the program
becomes more complex.
---------------------------------------------------------------
3) By using methods :

A) First Approach (Method without Parameter)


----------------------------------------------
public class Test
{
int x,y;

public void setData()


{
x = 100; y = 200;
}
}

Test t1 = new Test(); t1.setData(); [x = 100 y = 200]


Test t2 = new Test(); t2.setData(); [x = 100 y = 200]

Here also, all the objects will be iniatilized with same


value.

B) Second Approach (Method with Parameter)


-------------------------------------------
public class Test
{
int x,y;
public void setData(int x, int y)
{
this.x = x;
this.y = y;
}
}

Test t1 = new Test(); t1.setData(12,78); [x = 12 y = 78]


Test t2 = new Test(); t2.setData(15,29); [x = 15 y = 29]

Here the Drawback is initialization and re-initialization both are done in two
different lines so Constructor introduced.
----------------------------------------------------------------------
4) By using Constructor

A) First Approach (No Argument Constructor)


--------------------------------------------
public class Test
{
int x,y;

public Test() //All the objects will be initialized with


{ same value
x = 0; y = 0;
}

Test t1 = new Test(); [x = 0 y = 0]


Test t2 = new Test(); [x = 0 y = 0]

B) Second Approach (Parameterized Constructor)


-----------------------------------------------
public class Test
{
int x,y;

public Test(int x, int y)


{
this.x = x;
this.y = y;
}
}

Test t1 = new Test(12,78); [x = 12 y = 78]


Test t2 = new Test(15,29); [x = 15 y = 29]

This is the best way to initialize our instance variable because variable
initialization and variable re-initialization both will be done in the same line as
well as all the objects will be initialized with different values.

C) Third Approach (Copy Constructor)


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

public class Manager


{
private int managerId;
private String managerName;
public Manager(Employee emp)
{
this.managerId = emp.getEmployeeId();
this.managerName = emp.getEmployeeName();
}
}

Here with the help of Object reference (Employee class) we are


initializing the properties of Manager class. (Copy Constructor)

d) By using instance block (Instance Initializer)


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

public class Test


{
int x,y;

public Test()
{
System.out.println(x); //100
System.out.println(y); //200
}

//Instance block
{
x = 100;
y = 200;
}

------------------------------------------------------------------
5) By using super keyword :

class Super
{
int x,y;

public Super(int x , int y)


{
this.x = x;
this.y = y;
}
}
class Sub extends Super
{
Sub()
{
super(100,200); //Initializing the properties of super class
}
}

new Sub();
================================================================
WAP in java for Single Level Inheritance :
-------------------------------------------
package com.ravi.super_demo;

class TemporaryEmployee
{
protected int employeeNumber;
protected String employeeName;
protected String employeeAddress;

public TemporaryEmployee(int employeeNumber, String employeeName, String


employeeAddress)
{
super();
this.employeeNumber = employeeNumber;
this.employeeName = employeeName;
this.employeeAddress = employeeAddress;
}
}
class PermanentEmployee extends TemporaryEmployee
{
protected String department;
protected String designation;

public PermanentEmployee(int employeeNumber, String employeeName, String


employeeAddress, String department, String designation) {
super(employeeNumber, employeeName, employeeAddress);
this.department = department;
this.designation = designation;
}

@Override
public String toString()
{
return "PermanentEmployee [employeeNumber=" + employeeNumber + ",
employeeName=" + employeeName
+ ", employeeAddress=" + employeeAddress + ", department="
+ department + ", designation=" + designation
+ "]";
}
}

public class SingleLevelDemo1


{

public static void main(String[] args)


{
PermanentEmployee p = new PermanentEmployee(1, "Scott", "Ameerpet",
"IT", "Java Developer");
System.out.println(p);
}
}
----------------------------------------------------------------
01-10-2024
-----------
Program on Hierarchical Inheritance :
--------------------------------------
package com.ravi.inheritance;

import java.util.Scanner;

class Employee
{
protected double employeeSalary;
public Employee(double employeeSalary)
{
super();
this.employeeSalary = employeeSalary;
}
}
class Developer extends Employee
{
public Developer(double developerSalary)
{
super(developerSalary);
}

@Override
public String toString()
{
return "Developer [employeeSalary=" + employeeSalary + "]";
}

}
class Designer extends Employee
{
public Designer(double designerSalary)
{
super(designerSalary);
}

@Override
public String toString()
{
return "Designer [employeeSalary=" + employeeSalary + "]";
}
}

public class HierachicalInheritance


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Developer Salary :");
double devSalary = sc.nextDouble();
Developer developer = new Developer(devSalary);
System.out.println(developer);

System.out.print("Enter Designer Salary :");


double desSalary = sc.nextDouble();
Designer designer = new Designer(desSalary);
System.out.println(designer);
sc.close();
}

}
----------------------------------------------------------------
Program on Multilevel inheritance :
-----------------------------------
package com.ravi.inheritance;

class Student
{
protected int studentId;
protected String studentName;
protected String studentAddress;

public Student(int studentId, String studentName, String studentAddress)


{
super();
this.studentId = studentId;
this.studentName = studentName;
this.studentAddress = studentAddress;
}

@Override
public String toString()
{
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentAddress=" + studentAddress
+ "]";
}
}

class Science extends Student


{
protected int phyMarks;
protected int cheMarks;
public Science(int studentId, String studentName, String studentAddress, int
phyMarks, int cheMarks) {
super(studentId, studentName, studentAddress);
this.phyMarks = phyMarks;
this.cheMarks = cheMarks;
}
@Override
public String toString()
{
return super.toString()+"Science [phyMarks=" + phyMarks + ", cheMarks="
+ cheMarks + "]";
}

}
class PCM extends Science
{
protected int maths;

public PCM(int studentId, String studentName, String studentAddress, int


phyMarks, int cheMarks, int maths) {
super(studentId, studentName, studentAddress, phyMarks, cheMarks);
this.maths = maths;
}

@Override
public String toString()
{
return super.toString()+"PCM [maths=" + maths + "]";
}

public void totalMarks()


{
int total = phyMarks + cheMarks + maths;
System.out.println("Total Marks is :"+total);
}

public class MultiLevelInheritance {

public static void main(String[] args)


{
PCM p = new PCM(1, "Smith", "S R Nagar", 60, 70, 90);
p.totalMarks();
System.out.println(p);

}
----------------------------------------------------------------
**Why java does not support multiple Inheritance ?
--------------------------------------------------
Multiple Inheritance is a situation where a sub class wants to inherit the
properties two or more than two super classes.

In every constructor we have super() or this(). When compiler will add super() to
the first line of the constructor then we have an ambiguity issue that super() will
call which super class constructor as shown in the diagram [01-OCT-24]

It is also known as Diamond Problem in java so the final conclusion is we can't


achieve multiple inheritance using classes but same we can achieve by using
interface [interface does not contain any constructor]

================================================================
Access modifiers in java :
---------------------------
In order to define the accessibility level of the class as well as member of the
class we have 4 access modifiers :

1) private (Within the same class)


2) default (Within the same package)
3) protected (Within the same package Or even from another
package by using Inheritance)
4) public (No Restriction)

private :
---------
It is the most restrictive access modifier because the member declared as private
can't be accessible from outside of the class.
In Java we can't declare an outer class as a private or protected. Generally we
should declare the data member(variables) as private.

In java outer class can be declared as public, abstract, final, sealed and non-
sealed only.

default :-
----------
It is an access modifier which is less restrictive than private. It is such kind of
access modifier whose physical existance is not avaialble that means when we don't
specify any kind of access modifier before the class name, variable name or method
name then by default it would be default.
As far as its accessibility is concerned, default members are accessible within the
same folder(package) only. It is also known as private-package modifier.

protected :
------------
It is an access modifier which is less restrictive than default because the member
declared as protected can be accessible from the outside of the package (folder)
too but by using inheritance concept.

2 files :
----------
Test.java [It is in com.nit.m1 package]
---------------------------------------
package com.nit.m1;

public class Test


{
protected int x = 500;

ELC.java[It is in com.nit.m2 package]


--------------------------------------
package com.nit.m2;

import com.nit.m1.Test;

public class ELC extends Test


{
public static void main(String[] args)
{
ELC e1 = new ELC();
System.out.println(e1.x);
}

Note : From the above programs it is clear that protected members are accessible
from outside of the pacakge but by using Inheritance.

public :
-------
It is an access modifier which does not contain any kind of restriction that is the
reason the member declared as public can be accessible from everywhere without any
restriction.

According to Object Oriented rule we should declare the classes and methods as
public where as variables must be declared as private or protected according to the
requirement.

Note : If a method is used for internal purpose only (like validation)


then we can declare that method as private method.It is called
Helper method.
----------------------------------------------------------------
02-10-2024
-------------
JVM Architecture with class loader sub system :
-----------------------------------------------
The entire JVM Architecture is divided into 3 sections :

1) Class Loader sub system


2) Runtime Data areas (Memory Areas)
3) Execution Engine

Class Loader Sub System :


-------------------------
The main purpose of Class Loader sub system to load the required .class file into
JVM Memory from different memory loactions.

In order to load the .class file into JVM Memory, It uses an algorithm called
"Delegation Hierarchy Algoroithm".

Internally, Class Loader sub system performs the following Task

1) LOADING
2) LINKING
3) INITIALIZATION

LOADING :
---------
In order to load the required .class file, JVM makes a request to class loader sub
system. The class loader sub system follows delegation hierarchy algorithm to load
the required .class files from different areas.

To load the required .class file we have 3 different kinds of class loaders.

1) Bootstrap/Primordial class loader

2) Extension/Platform class loader

3) Application/System class loader

Bootstrap/Primordial class Loader :-


------------------------------------
It is responsible for loading all the predefined .class files that means all API
level predefined classes are loaded by Bootstrap class loader.

It has the highest priority becuase Bootstrap class loader is the super class for
Platform class loader.

It loads the classes from the following path


C -> Program files -> Java -> JDK -> lib -> jrt-fs.jar

Platform/Extension class loader :


----------------------------------
It is responsible to load the required .class file which is given by some 3rd party
in the form of jar file.

It is the sub class of Bootstrap class loader and super class of Application class
loader so it has more priority than Application class loader.

It loads the required .class file from the following path.


C -> Program files -> Java -> JDK -> lib -> ext -> ThirdParty.jar

command to create the jar file :


jar cf FileName.jar FileName.class [*.class]
[If we want to compile more than one java file at a time then the command is :
javac *.java]

Application/System class loader :


---------------------------------------
It is responsible to load all userdefined .class file into JVM memory.

It has the lowest priority because it is the sub class Platform class loader.

It loads the .class file from class path level or environment


variable.
----------------------------------------------------------------
How Delegation Hierarchy algorithm works :-
---------------------------------------------------
Whenever JVM makes a request to class loader sub system to load the required .class
file into JVM memory, first of all, class loader sub system makes a request to
Application class loader, Application class loader will delegate(by pass) the
request to the Extension class loader, Extension class loader will also delegate
the request to Bootstrap class loader.

Bootstrap class loader will load the .class file from lib folder(jrt.jar) and then
by pass the request back to extension class loader, Extension class loader will
load the .class file from ext folder(*.jar) and by pass the request back to
Application class loader, It will load the .class file from environment variable
into JVM memory.

Note :-
------
If all the class loaders are failed to load the .class file into JVM memory then we
will get a Runtime exception i.e java.lang.ClassNotFoundException.

Note : java.lang.Object is the first class to be loaded into JVM Memory.


---------------------------------------------------------------
03-10-2024
-----------
What is Method Chaning in java ?
--------------------------------
It is a technique through we call multiple methods in a single
statement.

In this method chaining, always for calling next method we depend upon last method
return type.

The final return type of the method depends upon last method call as shown in the
program.

MethodChainingDemo1.java
-------------------------
package com.ravi.method_chaining;

public class MethodChainingDemo1 {

public static void main(String[] args)


{
String s1 = "india";
char ch = s1.toUpperCase().concat(" is great").charAt(1);
System.out.println(ch);
}

MethodChainingDemo2.java
-------------------------
package com.ravi.method_chaining;

public class MethodChainingDemo2 {

public static void main(String[] args)


{
String str = "hyderabad";
int length = str.concat(" is an IT city").toUpperCase().length();
System.out.println("Length is :"+length);
}

}
---------------------------------------------------------------
Role of java.lang.Class class in class loading :
----------------------------------------------------
There is a predefined class called Class available in java.lang pacakge.

In JVM memory whenever we load a class then it is loaded in special memory called
Method Area and retutn type is java.lang.Class.

java.lang.Class cls = AnyClass.class

java.lang.Class class contains a predefined non static method


called getName() through which we can get the fully qualified
name [Package Name + class Name]

public String getName() : Provide fully qualified name of the class.


---------------------------------------------------------------
WAP that describes java.lang.Class will hold any class .class file into JVM Memory.

ClassLoadingReturnType.java
---------------------------
package com.ravi.class_loading;

class Customer{}

class Employee{}

class Player{}

public class ClassLoadingReturnType {

public static void main(String[] args)


{
java.lang.Class cls = Customer.class;
System.out.println("class name is :"+cls.getName());

cls = Player.class;
System.out.println("class name is :"+cls.getName());

cls = Employee.class;
System.out.println("class name is :"+cls.getName());
}

}
----------------------------------------------------------------
WAP that describes Application class loader is responsible to
load the user defined .class file

java.lang.Class class has provided a predefined non static method called


getClassLoader(), the return type of this method
is ClassLoader class.[Factory Method]

This method will provide the class loader name which is responsible to load
the .class file into JVM Memory.

public ClassLoader getClassLoader()

Test.java
-----------
package com.ravi.class_loading;

public class Test


{
public static void main(String[] args)
{
System.out.println("Test.class file is loaded
by :"+Test.class.getClassLoader());

}
---------------------------------------------------------------
WAP that describes Platform class Loader is the super class for
Application class loader

getClassLoader() method return type is ClassLoader so further we can call any


method of ClassLoader class, ClassLoader class
has provided a method called getParent() whose return type is again ClassLoader
only

public ClassLoader getParent();

package com.ravi.class_loading;

public class Demo {

public static void main(String[] args)


{
ClassLoader parent = Demo.class.getClassLoader().getParent();
System.out.println(parent);

}
----------------------------------------------------------------
package com.ravi.class_loading;

public class Demo {

public static void main(String[] args)


{
ClassLoader parent =
Demo.class.getClassLoader().getParent().getParent();
System.out.println(parent); //null

Note :- Here we will get the output as null because it is built in class loader
for JVM which is used for internal purpose (loading only predefined .class file) so
implementation is not provided hence we are getting null.
----------------------------------------------------------------
verify :-
-------
It ensures the correctness of the .class files, If any suspicious activity is there
in the .class file then It will stop the execution immediately by throwing a
runtime error i.e java.lang.VerifyError.

There is something called ByteCodeVerifier(Component of JVM), responsible to verify


the loaded .class file i.e byte code. Due to this verify module JAVA is highly
secure language.

java.lang.VerifyError is the sub class of java.lang.linkageError

----------------------------------------------------------------
prepare :
---------
[Static variable memory allocation + static variable initialization with default
value]

It will allocate the memory for all the static data members, here all the static
data member will get the default values so if we have static int x = 100; then for
variable x memory will be allocated (4 bytes) and now it will initialize with
default value i.e 0, even the variable is final.

static Test t = new Test();

Here, t is a static reference variable so for t variable (reference variable)


memory will be allocated as per JVM implementation i.e for 32 bit JVM (4 bytes of
Memory) and for 64 bit (8 bytes of memory) and initialized with null.
----------------------------------------------------------------
Resolve :
---------
All the symbolic references will be converted into direct references OR actual
reference.
---------------------------------------------------------------
javap -verbose FileName.class

Note :- By using above command we can read the internal details of .class file.
-----------------------------------------------------------------
04-10-2024
-----------
Initialization :
-----------------
Here class initialization will take place. All the static data member will get
their actual value and we can also use static block for static data member
initialization.
Here, In this class initialization phase static variable and static block is having
same priority so it will executed according to the order.(Top to bottom)

--------------------------------------------------------------
Static Block in java :
-----------------------
It is a special block in java which is automatically executed at the time of
loading the .class file.

Example :

static
{

Static blocks are executed only once because in java we can load the .class files
only once.

If we have more than one static block in a class then it will be executed according
to the order [Top to bottom]

The main purpose of static block to initialize the static data member of the class
so it is also known as static initializer.

In java, a class is not loaded automatically, it is loaded based on the user


request so static block will not be executed everytime, It depends upon whether
class is loaded or not.

static blocks are executed before the main or any static method.

A static blank final field must be initialized inside the static block only.

static final int A; //static blank final field

static
{
A = 100;
}

A static blank final field also have default value.

We can't write any kind of return statement inside static block.

If we don't declare static variable before static block body execution then we can
perform write operation(Initialization is possible due to prepare phase) but read
operation is not possible directly otherwise we will get an error Illegal forward
reference, It is possible with class name bacause now compiler knows that it is
coming from class area OR Method area.
--------------------------------------------------------------
//static block
class Foo
{
Foo()
{
System.out.println("No Argument constructor..");
}
{
System.out.println("Instance block..");
}

static
{
System.out.println("Static block...");
}

}
public class StaticBlockDemo
{
public static void main(String [] args)
{
System.out.println("Main Method Executed ");
}

Here Foo.class file is not loaded into JVM Memory so static block of Foo class will
not be executed.
--------------------------------------------------------------
class Test
{
static int x;

static
{
x = 100;
System.out.println("x value is :"+x);
}

static
{
x = 200;
System.out.println("x value is :"+x);
}

static
{
x = 300;
System.out.println("x value is :"+x);
}

}
public class StaticBlockDemo1
{
public static void main(String[] args)
{
System.out.println("Main Method");
System.out.println(Test.x);
}
}

Note : If a class contains more than 1 static block then it will be executed from
top to bottom.
--------------------------------------------------------------
class Foo
{
static int x;

static
{
System.out.println("x value is :"+x);
}
}

public class StaticBlockDemo2


{
public static void main(String[] args)
{
new Foo();
}
}

Note : static variables are also having default value.


--------------------------------------------------------------
class Demo
{

final static int a ; //Blank static final field

static
{
a = 100;
System.out.println(a);
}
}
public class StaticBlockDemo3
{
public static void main(String[] args)
{
System.out.println("a value is :"+Demo.a);
}
}

Note : A blank static final field must be initialized through static block only.
--------------------------------------------------------------
class A
{
static
{
System.out.println("A");
}

{
System.out.println("B");
}

A()
{
System.out.println("C");
}
}
class B extends A
{
static
{
System.out.println("D");
}

{
System.out.println("E");
}

B()
{
System.out.println("F");
}

}
public class StaticBlockDemo4
{
public static void main(String[] args)
{
new B();
}
}

Note : Always Parant class will be loaded first then only Child class will be
loaded.
--------------------------------------------------------------
//illegal forward reference

class Demo
{
static
{
i = 100;
}

static int i;
}

public class StaticBlockDemo5


{
public static void main(String[] args)
{
System.out.println(Demo.i);
}
}

Note : For static variable i, already memory is allocated in the prepare phase so
we can initialize (can perform write operation)
in the static block without pre-declaration.
--------------------------------------------------------------
class Demo
{
static
{
i = 100;
//System.out.println(i); //Invalid
System.out.println(Demo.i);
}
static int i;
}

public class StaticBlockDemo6


{

public static void main(String[] args)


{
System.out.println(Demo.i);
}
}

Note : Without declaring the static variable if we try to access(read Operation)


static variable value in the static block directly then we will get compilation
error, we can access with the help of class name (Class Area)
--------------------------------------------------------------
class StaticBlockDemo7
{
static
{
System.out.println("Static Block");
return;
}

public static void main(String[] args)


{
System.out.println("Main Method");
}
}

Note : We can't write return statement in static and non static block
----------------------------------------------------------
public class StaticBlockDemo8
{
final static int x; //Blank static final field

static
{
m1();
x = 15;
}

public static void m1()


{
System.out.println("Default value of x is :"+x);
}

public static void main(String[] args)


{
System.out.println("After initialization :"+StaticBlockDemo8.x);
}
}

A blank static final field also has default value.


--------------------------------------------------------------
class Test
{
public static final Test t1 = new Test(); //t1 = null

static
{
System.out.println("static block");
}

{
System.out.println("Non static block");
}

Test()
{
super();
System.out.println("No Argument Constructor");
}
}

public class StaticBlockDemo9


{
public static void main(String[] args)
{
new Test();
}
}

Note : First non static block, constructor then only static block will be executed.
--------------------------------------------------------------
Variable Memory Allocation and Initialization :
-------------------------------------------------
1) static field OR Class variable :
-----------------------------------
Memory allocation done at prepare phase of class loading and initialized with
default value even variable is final.

It will be initialized with Original value (If provided by user at the time of
declaration) at class initialization phase.

When JVM will shutdown then during the shutdown phase class will be un-loaded from
JVM memory so static data members are destroyed. They have long life.

2) Non static field OR Instance variable


-----------------------------------------
Memory allocation done at the time of object creation using new keyword
(Instantiation) and initialized as a part of Constructor with default values even
the variable is final. [Object class-> at the time of declaration -> instance block
-> constructor]

When object is eligible for GC then object is destroyed and all the non static data
memebers are also destroyed with corresponding object. It has less life in
comparison to static data members becuase they belongs to object.

3) Local Variable
------------------
Memory allocation done at stack area (Stack Frame) and developer is responsible to
initialize the variable before use. Once metod execution is over, It will be
deleted from stack Frame henec it has shortest life.

4) Parameter variable
----------------------
Memory allocation done at stack area (Stack Frame) and end user is responsible to
pass the value at runtime. Once metod execution is over, It will be deleted from
stack Frame henec it has shortest life.

Note : We can done validation only one parameter variables.


--------------------------------------------------------------
05-10-2024
-----------
Can we write a Java Program without main method ?
--------------------------------------------------
class WithoutMain
{
static
{
System.out.println("Hello User!!");
System.exit(0);
}
}

It was possible to write a java program without main method till JDK 1.6V. From JDK
1.7v onwards, at the time of loading the .class file JVM will verify the presence
of main method in the .class file. If main method is not available then it will
generate a runtime error that "main method not found in so so class".
--------------------------------------------------------------
How many ways we can load the .class file into JVM memory :
-----------------------------------------------------------
There are so many ways to load the .class file into JVM memory but the following
are the common examples :

1) By using java command

public class Test


{
}

javac Test.java
java Test

Here we are making a request to class loader sub system to load Test.class file
into JVM memory

2) By using Constructor (new keyword at the time of creating object).

3) By accessing static data member of the class.

4) By using inheritance

5) By using Reflection API


==============================================================
//Program that describes we can load a .class file by using new keyword (Object
creation) OR by accessing static data member of the class.

class Demo
{
static int x = 10;
static
{
System.out.println("Static Block of Demo class Executed!!! :"+x);
}
}
public class ClassLoading
{
public static void main(String[] args)
{
System.out.println("Main Method");
//new Demo();
System.out.println(Demo.x);
}
}
-------------------------------------------------------------
//Program that describes whenever we try to load sub class, first of all super
class will be loaded. [before parent, child can't exist]

class Alpha
{
static
{
System.out.println("Static Block of super class Alpha!!");
}
}
class Beta extends Alpha
{
static
{
System.out.println("Static Block of Sub class Beta!!");
}
}
class InheritanceLoading
{
public static void main(String[] args)
{
new Beta();
}
}
--------------------------------------------------------------
Loading the .class file by using Reflection API :
-------------------------------------------------
java.lang.Class class has provided a predefined static and factory method called
forName(String className), It is mainly used to load the given .class file at
runtime, The return type of this method is java.lang.Class

public static java.lang.Class forName(String className)

Note : This method throws a checked execption i.e ClassNotFoundException

Program :
---------
package com.nit.iq; //FQN com.nit.iq.Sample

class Sample
{
static
{
System.out.println("Static Block");
}
}
public class DynamicLoading
{
public static void main(String[] args) throws Exception
{
Class.forName("com.nit.iq.Sample"); //FQN
}
}

NOte : From the above program it is clear that Class.forName(String className) is


used to load the given .class file dynamically at runtime.
--------------------------------------------------------------
** What is the difference between java.lang.ClassNotFoundException and
java.lang.NoClassDefFoundError

java.lang.ClassNotFoundException :-
-----------------------------------------
It occurs when we try to load the required .class file at RUNTIME by using
Class.forName(String className) statement or loadClass() static of ClassLoader
class and if the required .class file is not available at runtime then we will get
an exception i.e java.lang.ClassNotFoundException

Note :- It does not have any concern at compilation time, at run time, JVM will
simply verify whether the required .class file is available or not available.

class Test
{
static
{
System.out.println("Static Block");
}
}
public class DynamicLoading
{
public static void main(String[] args) throws Exception
{
Class.forName("Employee");
}
}

Note : Here we will get java.lang.ClassNotFoundException because at runtime class


loader is unable to find Employee.class.
--------------------------------------------------------------
java.lang.NoClassDefFoundError :
--------------------------------
It occurs when the class was present at the time of COMPILATION but at runtime the
required .class file is not available(manualy deleted by user ) Or it is not
available in the current directory (Misplaced) then we will get a runtime error i.e
java.lang.NoClassDefFoundError.

class Sample
{
public void greet()
{
System.out.println("Hello Everyone");
}
}
public class NoClassDefFoundErrorDemo
{
public static void main(String[] args)
{
Sample s1 = new Sample();
s1.greet();
}
}

After compilation either delete Sample.class or put this .class file in another
folder[remove from the current folder]
--------------------------------------------------------------
** A static method does not act on instance variable directly why?

All the static members (static variable, static block, static method, static
nested inner class) are loaded/executed at the time of loading the .class file into
JVM Memory.

At class loading phase object is not created because object is created in the 2nd
phase i.e Runtime data area so at the TIME OF EXECUTION OF STATIC METHOD AT CLASS
LOADING PAHSE, NON STATIC VARIABLE WILL NOT BE AVAILABLE henec we can't access non
static variable from static context[static block, static method and static nested
inner class]

class Sample
{
private int x;
public Sample(int x)
{
this.x = x;
}

public static void access()


{
System.out.println("x value is :"+x);
}

}
public class StaticDemo
{
public static void main(String[] args)
{
Sample s1 = new Sample(10);
Sample.access();
}
}

--------------------------------------------------------------
07-10-2024
-----------
Runtime Data Areas :
---------------------
It is also known as Memory Area.

Once a class is loaded then based on variable type method type it is divided into
different memory areas which are as follows :

1) Method Area
2) HEAP Area
3) Stack Area
4) PC Register
5) Native Method Stack

Method Area :
-------------
Whenever a class is loaded then the class is dumpped inside method area and returns
java.lang.Class class.

It provides all the information regarding the class like name of the class, name of
the package, static and non static fields available in the class, methods available
in the class and so on.

We have only one method area per JVM that means for a single JVM we have only one
Method area.

This Method Area OR Class Area is sharable by all the objects.


--------------------------------------------------------------
Program to Show From Method Area we can get complete information of the class.
(Reflection API)

2 files :
---------
Test.java
----------
package com.ravi.method_area;

import java.util.Scanner;

public class Test


{
Scanner sc = new Scanner(System.in);
int x = 100;
int z = 900;
static int y = 200;
static Scanner scanner = new Scanner(System.in);

public static void show() {}


public static void m1() {}
public void accept() {}
public void display() {}

ClassDescription.java
-----------------------
package com.ravi.method_area;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ClassDescription {

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


{
Class cls = Class.forName(args[0]);

System.out.println("Class Name is :"+cls.getName());


System.out.println("Package Name is :"+cls.getPackageName());

System.out.println("Available Methods are :");


int count = 0;
Method[] methods = cls.getDeclaredMethods();

for(Method method : methods)


{
System.out.println(method.getName());
count++;
}
System.out.println("Total number of methods are :"+count);

System.out.println("Available Fileds are :");

Field[] fields = cls.getDeclaredFields();


count = 0;
for(Field field : fields)
{
System.out.println(field.getName());
count++;
}
System.out.println("Total number of fields are :"+count);

Note :- getDeclaredMethods() is a predefined non static method available in


java.lang.Class class , the return type of this method is Method array where Method
is a predefined class available in java.lang.reflect sub package.

getDeclaredFields() is a predefined non static method available in java.lang.Class


class , the return type of this method is Field array where Field is a predefined
class available in java.lang.reflect sub package.

Field and Method both the classes are providing getName() method to get the name of
the field and Method.
--------------------------------------------------------------
HEAP AREA :
-----------
Whenever we create an object in java then the properties and behavior of the object
are strored in a special memory area called HEAP AREA.

We have only one HEAP AREA per JVM.


--------------------------------------------------------------
STACK Area :
------------
All the methods are executed as a part of Stack Area.

Whenever we call a method in java then internally one stack Frame will be created
to hold method related information.

Every Stack frame contains 3 parts :


1) Local Variable arrays
2) Frame Data
3) Operand Stack.
We have multiple stack area for a single JVM.

JVM creates a separate thread for every runtime Stack.[MT]


-------------------------------------------------------------
HEAP and STACK Diagram for Static data member and array variables.

class Alpha
{
int val;

static int sval = 200;


static Beta b = new Beta();

public Alpha(int val)


{
this.val = val;
}
}

public class Beta


{
public static void main(String[] args)
{
Alpha am1 = new Alpha(9);
Alpha am2 = new Alpha(2);

Alpha []ar = fill(am1, am2);

ar[0] = am1;
System.out.println(ar[0].val);
System.out.println(ar[1].val);
}

public static Alpha[] fill(Alpha a1, Alpha a2)


{
a1.val = 15;

Alpha fa[] = new Alpha[]{a2, a1};

return fa;
}
}
--------------------------------------------------------------
08-10-2024
-----------
PC Register :
-------------
It stands for Program counter Register.

In order to hold the current executing instruction of running thread we have


separate PC register for each and every thread.
----------------------------------------------------------------
Native Method Stack :
----------------------
Native method means, the java methods which are written by using native languages
like C and C++. In order to write native method we need native method library
support.

Native method stack will hold the native method information in a separate stack.
---------------------------------------------------------------------
Execution Engine : [Interpreter + JIT Compiler]

Interpreter
------------
In java, JVM contains an interpreter which executes the program line by line.
Interpreter is slow in nature because at the time of execution if we make a mistake
at line number 9 then it will throw the execption at line number 9 and after
solving the execption again it will start the execution from line number 1 so it is
slow in execution that is the reason to boost up the execution java software people
has provided JIT compiler.

JIT Compiler :
--------------
It stands for just in time compiler. The main purpose of JIT compiler to boost up
the execution so the execution of the program will be completed as soon as
possible.

JIT compiler holds the repeated instruction like method signature, variables,
native method code and make it available to JVM at the time of execution so the
overall execution becomes very fast.
--------------------------------------------------------------
HAS-A Relation :
----------------
If we use any class as a property to another class then it is called HAS-A
relation.

class Engine
{
}

class Car
{
private Engine engine; //HAS-A relation
}

Association :
---------------
Association is a connection between two separate classes that can be built up
through their Objects.

The association builds a relationship between the classes and describes how much a
class knows about another class.

This relationship can be unidirectional or bi-directional. In Java, the association


can have one-to-one, one-to-many, many-to-one and many-to-many relationships.

Example:-
One to One: A person can have only one PAN card
One to many: A Bank can have many Employees
Many to one: Many employees can work in single department
Many to Many: A Bank can have multiple customers and a customer can have multiple
bank accounts.

3 files :
----------
Student.java
-------------
package com.ravi.association;

public class Student


{
private int studentId;
private String studentName;
private int studentMarks;

public Student(int studentId, String studentName, int studentMarks)


{
super();
this.studentId = studentId;
this.studentName = studentName;
this.studentMarks = studentMarks;
}

@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentMarks=" + studentMarks
+ "]";
}

public int getStudentId() {


return studentId;
}

public String getStudentName() {


return studentName;
}

public int getStudentMarks() {


return studentMarks;
}
}

Trainer.java
-------------
package com.ravi.association;

import java.util.Scanner;

public class Trainer


{
public static void viewStudentProfile(Student obj)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Student id :");
int id = sc.nextInt();

if(id==obj.getStudentId())
{
System.out.println(obj);
}
else
{
System.err.println("Id is not matching");
}
}
}

AssociationDemo.java
----------------------
package com.ravi.association;

public class AssociationDemo {

public static void main(String[] args)


{
Student raj = new Student(1, "Raj",70);
Trainer.viewStudentProfile(raj);
}

}
--------------------------------------------------------------
Composition (Strong reference) :
--------------------------------
Composition in Java is a way to design classes such that one class contains an
object of another class. It is a way of establishing a "HAS-A" relationship between
classes.

Composition represents a strong relationship between the containing class and the
contained class.If the containing object (Car object) is destroyed, all the
contained objects (Engine object) are also destroyed.

A car has an engine. Composition makes strong relationship between the objects. It
means that if we destroy the owner object, its members will be also destroyed with
it. For example, if the Car is destroyed the engine will also be destroyed as well.

Program Guidelines :
--------------------
One object can't exist without another object
We will not create two separate objects

3 files :
----------
Engine.java
------------
package com.ravi.composition;

public class Engine


{
private String engineType;
private int horsePower;

public Engine(String engineType, int horsePower) {


super();
this.engineType = engineType;
this.horsePower = horsePower;
}

public String getEngineType() {


return engineType;
}

public void setEngineType(String engineType) {


this.engineType = engineType;
}

public int getHorsePower() {


return horsePower;
}

public void setHorsePower(int horsePower) {


this.horsePower = horsePower;
}

@Override
public String toString() {
return "Engine [engineType=" + engineType + ", horsePower=" +
horsePower + "]";
}
}

Car.java
---------
package com.ravi.composition;

public class Car


{
private String carName;
private int carModel;
private final Engine engine; // HAS-A relation [Blank final filed]

public Car(String carName, int carModel)


{
super();
this.carName = carName;
this.carModel = carModel;
this.engine = new Engine("Battery", 1200); //Composition
}

@Override
public String toString() {
return "Car [carName=" + carName + ", carModel=" + carModel + ",
engine=" + engine + "]";
}

CompositionDemo.java
---------------------
package com.ravi.composition;

public class CompositionDemo {

public static void main(String[] args)


{
Car car = new Car("Seltos", 2024);
System.out.println(car);
}

}
Assignemnts :
--------------
Develop one program based on composition
MotherBoard and Laptop
Department and University.
--------------------------------------------------------------
Aggregation (Weak Referance) :
------------------------------
Aggregation in Java is another form of association between classes that represents
a "HAS-A" relationship, but with a weaker bond compared to composition.

In aggregation, one class contains an object of another class, but the contained
object can exist independently of the container. If the container object is
destroyed, the contained object can still exist.

3 files :
----------
College.java
-------------
package com.ravi.aggregation;

public class College


{
private String collegeName;
private String collegeLocation;

public College(String collegeName, String collegeLocation) {


super();
this.collegeName = collegeName;
this.collegeLocation = collegeLocation;
}

@Override
public String toString() {
return "College [collegeName=" + collegeName + ", collegeLocation=" +
collegeLocation + "]";
}
}

Student.java
-------------
package com.ravi.aggregation;

public class Student


{
private int studentId;
private String studentName;
private String studentAddress;
private College college;

public Student(int studentId, String studentName, String studentAddress,


College college) {
super();
this.studentId = studentId;
this.studentName = studentName;
this.studentAddress = studentAddress;
this.college = college;
}
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentAddress=" + studentAddress
+ ", college=" + college + "]";
}
}

AggregationDemo.java
---------------------
package com.ravi.aggregation;

public class AggregationDemo {

public static void main(String[] args)


{
College clg = new College("VIT", "Vellore");

Student s1 = new Student(1, "A", "Ameerpet", clg);


System.out.println(s1);

Student s2 = new Student(2, "B", "S.R Nagar", clg);


System.out.println(s2);

Note :- IS-A relation is tightly coupled relation so if we modify the content of


super class, sub class content will also modify but in HAS-A realtion we are
accessing the properties of another class so we are not allowed to modify the
content, we can access the content or Properties.
-------------------------------------------------------------
Assignemnts :
-------------
Order and Customer
Person abd Address
Account and Customer
--------------------------------------------------------------
Description of System.out.println() :
-------------------------------------
public class System
{
public final static java.io.PrintStream out = null; //HAS-A Relation
}

System.out.println();

Internally System.out.println() creates HAS-A relation because System class


contains a predefined class called java.io.PrintStream as shown in the above
example.

The following program describes that how System.out.println() works internally :

package com.nit.m1;
class Hello
{
public static String out = "Hyderabad"; //HAS-A Relation
}

public class HasADemo {

public static void main(String[] args)


{
System.out.println(Hello.out.length());
}

}
--------------------------------------------------------------
***Polymorphism :
-----------------
Poly means "many" and morphism means "forms".

It is a Greek word whose meaning is "same object having different behavior".

In our real life a person or a human being can perform so many task, in the same
way in our programming languages a method or a constructor can perform so many
task.

Eg:-

void add(int a, int b)

void add(int a, int b, int c)

void add(float a, float b)

void add(int a, float b)

--------------------------------------------------------------
09-10-2024
-----------
Types of Polymorphism :
-----------------------
Polymorphism can be divided into two types :

1) Static polymorphism OR Compile time polymorphism OR Early binding

2) Dynamic Polymorphism OR Runtime polymorphism OR Late binding


----------------------------------------------------------------
1) Static Polymorphism :
------------------------
The polymorphism which exist at the time of compilation is called Static OR compile
time polymorphism.

In static polymorphism, compiler has very good idea that which method is invoked
depending upon METHOD PARAMETER.

Here the binding of the method is done at compilation time so, it is known as early
binding.

We can achieve static polymorphism by using Method Overloading concept.


Example of static polymorphism : Method Overloading.

2) Dynamic Polymorphism
-----------------------
The polymorphism which exist at runtime is called Dynamic polymorphim Or Runtime
Polymorphism.

*Here compiler does not have any idea about method calling, at runtime JVM will
decide which method will be invoked depending upon CLASS TYPE OBJECT.

Here method binding is done at runtime so, it is also called Late Binding.

We can achieve dynamic polymorphism by using Method Overriding.

Example of Dynamic Polymorphism : Method Overriding

-----------------------------------------------------------------
Method Overloading :
--------------------
Writing two or more methods in the same class or even in the super and sub class in
such a way that the method name must be same but the argument must be different.

While Overloading a method we can change the return type of the method.

If parameters are same but only method return type is different then it is not an
overloaded method.

Method overloading is possible in the same class as well as super and sub class.

While overloading the method the argument must be different otherwise there will be
ambiguity problem.

Method Overloading allows two methods with same name to differ


in:
1. Number of parameters
2. Data type of parameters
3. Sequence of data type of parameters(int -long and long int)

IQ :
----
Can we overload the main method/static method ?

Yes, we can overload the main method OR static method but the execution of the
program will start from main method which accept String [] array as a parameter.

Note :- The advantage of method overloading is same method name we can reuse for
different functionality for refinement of the method.

Note :- In System.out.println() or System.out.print(), print()


and println() methods are best example for Method Overloading.

Example :
----------
public void makePayment(Cash c)
{
}
public void makePayment(UPI c)
{
}
public void makePayment(CreditCard c)
{
}
-----------------------------------------------------------------
2 files :
----------
Addition.java
-------------
//Program on Constructor Overloading
package com.ravi.constructor_overloading;

public class Addition


{

public Addition(int x, int y)


{
this(10,20,30);
System.out.println("Sum of two integer is :"+(x+y));
}

public Addition(int x, int y, int z)


{
this(2.3F, 8.9f);
System.out.println("Sum of three integer is :"+(x+y+z));
}

public Addition(float x, float y)


{
System.out.println("Sum of two float is :"+(x+y));
}

Main.java
---------
package com.ravi.constructor_overloading;

public class Main {

public static void main(String [] args)


{
new Addition(12,90);
}

}
-----------------------------------------------------------------
Program on Method Overloading :
-------------------------------
2 Files :
---------

Sum.java
---------
package com.ravi.method_overload;

public class Sum


{
public int add(int x, int y)
{
return x + y;
}

public String add(String x, String y)


{
return x + y;
}

public double add(double x, double y)


{
return x + y;
}

Main.java
----------
package com.ravi.method_overload;

public class Main


{
public static void main(String[] args)
{
Sum s = new Sum();
double add1 = s.add(2.6, 7.8);
System.out.println("Addition of two double is :"+add1);

String add2 = s.add("Data", "base");


System.out.println("Concatenation of two String :"+add2);

int add3 = s.add(12, 24);


System.out.println("Addition of two integer :"+add3);
}
}
---------------------------------------------------------------
14-10-2024
-----------
Var-Args :
------------
It was introduced from JDK 1.5 onwards.

It stands for variable argument. It is an array variable which can hold 0 to n


number of parameters of same type or different type by using Object class.

It is represented by exactly 3 dots (...) so it can accept any number of argument


(0 to nth) that means now we need not to define method body again and again, if
there is change in method parameter value.

var-args must be only one and last argument.

We can use var-args as a method parameter only.


---------------------------------------------------------------
The program says var args can accept 0 to n number of parameters.

2 files :
----------
Test.java
----------
package com.ravi.var_args;

public class Test


{
public void accept(int ...x)
{
System.out.println("Var Args executed");
}
}

Main.java
----------
package com.ravi.var_args;

public class Main


{
public static void main(String... args)
{
Test t1 = new Test();
t1.accept();
t1.accept(12);
t1.accept(12,89);
t1.accept(12,78,56);
}

}
---------------------------------------------------------------
//Program to add sum of parameters passes inside a method using var args

2 files :
---------
Test.java
---------
package com.ravi.var_args1;

public class Test


{
public void sumOfParameters(int... values)
{
int sum = 0;

for(int value : values)


{
sum = sum + value;
}
System.out.println("Sum of parameter is :"+sum);

}
}

Main.java
---------
package com.ravi.var_args1;

public class Main


{
public static void main(String[] args)
{
Test t1 = new Test();
t1.sumOfParameters(12,24,24);
t1.sumOfParameters(100,200,300);

}
---------------------------------------------------------------
Program that describes Var args must be only one and last argument .

2 files :
---------
Test.java
---------
package com.ravi.var_args2;

public class Test


{
// All commented codes are invalid

/*
* public void accept(float ...x, int ...y) { }
*
* public void accept(int ...x, int y) { }
*
* public void accept(int...x, int ...y) {}
*/

public void accept(int x, int... y) //


{
System.out.println("x value is :" + x);

for (int z : y)
{
System.out.println(z);
}
}
}

Main.java
---------
package com.ravi.var_args2;

public class Main {

public static void main(String[] args)


{
new Test().accept(12, 10,20,30,40);

}
}
---------------------------------------------------------------
//Program to show that var args can hold hetrogeneous elements
Test.java
----------
package com.ravi.var_args3;

public class Test


{
public void acceptHetro(Object ...obj)
{
for(Object o : obj)
{
System.out.println(o);
}
}
}

Main.java
---------
package com.ravi.var_args3;

public class Main {

public static void main(String[] args)


{
new Test().acceptHetro(true,45.90,12,'A', new String("Ravi"));

}
---------------------------------------------------------------
Wrapper classes in java :
-------------------------
We have 8 primitive data types in java i.e byte, short, int, long and so on.

Except these 8 primitive data types, everything in java is an object.

If we remove these 8 primitive data types then only java can become pure object
oriented language.

On these primitive data types, we can't assign null or we can't invoke a method.

These primitive data types are unable to move in the network, only objects are
moving in the network.

We can't perform serialization and object cloning on primitive data types.

To avoid the above said problems, From JDK 1.5v, java software people has provided
the following two concepts :

a) Autoboxing
b) Unboxing

Autoboxing
--------------
When we convert the primitive data types into corresponding wrapper object then it
is called Autoboxing as shown below.

Primitive type Wrapper Object


---------------- ------------------
byte - Byte
short - Short
int - Integer
long - Long
float - Float
double - Double
char - Chracter
boolean - Boolean

Note : ALL THE WRAPPER CLASSES ARE IMMUTABLE(UN-CHANGED) AS WELL AS equals(Object


obj) and hashCode() method is overridden
in all the Wrapper classes.
---------------------------------------------------------------
//Integer.valueOf(int);
public class AutoBoxing1
{
public static void main(String[] args)
{
int a = 12;
Integer x = Integer.valueOf(a); //Upto 1.4 version
System.out.println(x);

int y = 15;
Integer i = y; //From 1.5 onwards compiler takes care
System.out.println(i);
}
}
--------------------------------------------------------------
public class AutoBoxing2
{
public static void main(String args[])
{
byte b = 12;
Byte b1 = Byte.valueOf(b);
System.out.println("Byte Object :"+b1);

short s = 17;
Short s1 = Short.valueOf(s);
System.out.println("Short Object :"+s1);

int i = 90;
Integer i1 = Integer.valueOf(i);
System.out.println("Integer Object :"+i1);

long g = 12;
Long h = Long.valueOf(g);
System.out.println("Long Object :"+h);

float f1 = 2.4f;
Float f2 = Float.valueOf(f1);
System.out.println("Float Object :"+f2);

double k = 90.90;
Double l = Double.valueOf(k);
System.out.println("Double Object :"+l);

char ch = 'A';
Character ch1 = Character.valueOf(ch);
System.out.println("Character Object :"+ch1);
boolean x = true;
Boolean x1 = Boolean.valueOf(x);
System.out.println("Boolean Object :"+x1);

}
}
In the above program we have used 1.4 approach so we are converting primitive to
wrapper object manually.
--------------------------------------------------------------
Overloaded valueOf() method :
-----------------------------
1) public static Integer valueOf(int x) : It will convert the given int value into
Integer Object.

2) public static Integer valueOf(String str) : It will convert


the given String into Integer Object.
[valueOf() method will convert the String into Wrapper object where as
parseInt() method will convet the String into primitive type]

3) public static Integer valueOf(String str, int radix/base) :


It will convert the given String number into Integer object
by using the radix or base.

Note :- We can pass base OR radix upto 36


i.e A to Z (26) + 0 to 9 (10) -> [26 + 10 = 36], It can be
calculated by using Character.MAX_RADIX.
Output will be generated on the basis of radix

//Integer.valueOf(String str)
//Integer.valueOf(String str, int radix/base)
public class AutoBoxing3
{
public static void main(String[] args)
{
Integer a = Integer.valueOf(15);

Integer b = Integer.valueOf("25");

Integer c = Integer.valueOf("111",36); //Here Base we can take upto 36

System.out.println(a);
System.out.println(b);
System.out.println(c);

}
}
---------------------------------------------------------------
public class AutoBoxing4
{
public static void main(String[] args)
{
Integer i1 = new Integer(100);
Integer i2 = new Integer(100);
System.out.println(i1==i2);

Integer a1 = Integer.valueOf(15);
Integer a2 = Integer.valueOf(15);
System.out.println(a1==a2);
}
}

--------------------------------------------------------------
Converting primtive to String type :
------------------------------------
Integer class has provided a static method toString() which will convert the int
value into String type.

//Converting integer value to String


public class AutoBoxing5
{
public static void main(String[] args)
{
int x = 12;
String str = Integer.toString(x);
System.out.println(str+2);
}
}
---------------------------------------------------------------
15-10-2024
-----------
Unboxing :
----------------
Converting wrapper object to corresponding primitive type is called Unboxing.

Wrapper Primitive
Object type
---------- ----------
Byte - byte

Short - short

Integer - int

Long - long

Float - float

Double - double

Chracter - char

Boolean - boolean
-----------------------------------------------------------------
We have total 8 Wrapper classes.

Among all these 8, 6 Wrapper classes are the sub class of Number class which
represent numbers (either decimal OR non decimal)
so all the following six wrapper classes (Which are sub class of Number class) are
providing the following common methods.

1) public byte byteValue()

2) public short shortValue()

3) public int intValue()


4) public long longValue()

5) public float floatValue()

6) public double doubleValue()


--------------------------------------------------------------
//Converting Wrapper object into primitive
public class AutoUnboxing1
{
public static void main(String args[])
{
Integer obj = 15; //Upto 1.4
int x = obj.intValue();
System.out.println(x);
}
}
--------------------------------------------------------------
public class AutoUnboxing2
{
public static void main(String[] args)
{
Integer x = 25;
int y = x; //JDK 1.5 onwards
System.out.println(y);
}
}
---------------------------------------------------------------
public class AutoUnboxing3
{
public static void main(String[] args)
{
Integer i = 15;
System.out.println(i.byteValue());
System.out.println(i.shortValue());
System.out.println(i.intValue());
System.out.println(i.longValue());
System.out.println(i.floatValue());
System.out.println(i.doubleValue());
}
}
---------------------------------------------------------------
public class AutoUnboxing4
{
public static void main(String[] args)
{
Character c1 = 'A';
char ch = c1.charValue();
System.out.println(ch);
}
}
---------------------------------------------------------------
public class AutoUnboxing5
{
public static void main(String[] args)
{
Boolean b1 = true;
boolean b = b1.booleanValue();
System.out.println(b);
}
}
--------------------------------------------------------------
Unlike primitive types we can't convert one wrapper type object to another wrapper
object.

Example :

Long l = 12; //Invalid

Float f = 90; //Invalid

Double d = 123; //Invalid

package com.ravi.basic;

public class Conversion


{
public static void main(String[] args)
{
long l = 12; //Implicit OR Widening
byte b = (byte) 12L; //Explicit OR Narrowing

Long a = 12L;
Double d = 90D;
Double d1 = 90.78;
Float f = 12F;
}

}
---------------------------------------------------------------
Ambiguity issue while overloading a method :
---------------------------------------------
When we overload a method then compiler is selecting appropriate method among the
available methods based on the following types.

1. Different number of parameters


2. Different data type of parameters
3. Different sequence(order) of data type of parameters

In order to solve the ambiguity issue while overloading a method compiler has
provided the following rules :

1) Most Specific Type :


-----------------------
Compiler alwyas provide more priority to most specific data type or class type.

double > float [Here float is the most specific type]


float > long
long > int
int > char
int > short
short > byte

2) WAV [Widening -> Autoboxing -> Var Args]

Compiler gives the priority to select appropriate method by using


the following sequence :
Widening ---> Autoboxing ----> Var args

3) Nearest Data type or Nearest class (sub class)

While selecting the appropriate method in ambiguity issue compiler provides


priority to nearest data type or nearest class i.e sub class
---------------------------------------------------------------
class Test
{
public void accept(double d)
{
System.out.println("double");
}
public void accept(float d)
{
System.out.println("float");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(6);

}
}

Here float will be executed because float is the nearest type.


--------------------------------------------------------------
class Test
{
public void accept(int d)
{
System.out.println("int");
}
public void accept(char d)
{
System.out.println("char");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(6);

}
}

Here int will be executed because int is the nearest type.


--------------------------------------------------------------
class Test
{
public void accept(int ...d)
{
System.out.println("int");
}
public void accept(char ...d)
{
System.out.println("char");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept();
}
}

Here char will be executed because char is the most specific type
--------------------------------------------------------------
class Test
{
public void accept(short ...d)
{
System.out.println("short");
}
public void accept(char ...d)
{
System.out.println("char");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept();
}
}
Here we will get compilation error because there is no relation between char and
short based on the specific type rule.
--------------------------------------------------------------
class Test
{
public void accept(short ...d)
{
System.out.println("short");
}
public void accept(byte ...d)
{
System.out.println("byte");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept();
}
}
Here byte will be executed because byte is the specific type.
--------------------------------------------------------------
class Test
{
public void accept(double ...d)
{
System.out.println("double");
}
public void accept(long ...d)
{
System.out.println("long");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept();
}
}
Here long will be executed because long is the most specific type.
--------------------------------------------------------------
class Test
{
public void accept(byte d)
{
System.out.println("byte");
}
public void accept(short s)
{
System.out.println("short");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t1 = new Test();
t1.accept(15);
t1.accept(byte(15));
}
}
Here value 15 is of type int so, we can't assign directly to byte and short, If we
want, explicit type casting is reqd.
---------------------------------------------------------------
class Test
{
public void accept(int d)
{
System.out.println("int");
}
public void accept(long s)
{
System.out.println("long");
}
}
public class AmbiguityIssue {
public static void main(String[] args)
{
Test t = new Test();
t.accept(9);

}
}
Note : Here int will be executed because int is the nearest type
--------------------------------------------------------------
class Test
{
public void accept(int d, long l)
{
System.out.println("int-long");
}
public void accept(long s, int i)
{
System.out.println("long-int");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(9,9);
}
}
Here We will get ambiguity issue.
--------------------------------------------------------------
class Test
{
public void accept(Object s)
{
System.out.println("Object");
}
public void accept(String s)
{
System.out.println("String");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(9);

}
}
Here Object will be executed
--------------------------------------------------------------
class Test
{
public void accept(Object s)
{
System.out.println("Object");
}
public void accept(String s)
{
System.out.println("String");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept("NIT");
}
}
Here String will be executed
--------------------------------------------------------------
class Test
{
public void accept(Object s)
{
System.out.println("Object");
}
public void accept(String s)
{
System.out.println("String");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(null);

}
}
String will executed because String is the nearest type.
--------------------------------------------------------------
class Test
{
public void accept(Object s)
{
System.out.println("Object");
}
public void accept(String s)
{
System.out.println("String");
}
public void accept(Integer i)
{
System.out.println("Integer");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(null);
}
}
Here We will get compilation error
---------------------------------------------------------------
class Alpha
{
}
class Beta extends Alpha
{
}
class Test
{
public void accept(Alpha s)
{
System.out.println("Alpha");
}
public void accept(Beta i)
{
System.out.println("Beta");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(null);

}
}
Here Beta will be executed.
--------------------------------------------------------------
class Test
{
public void accept(Number s)
{
System.out.println("Number");
}
public void accept(Integer i)
{
System.out.println("Integer");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(12);

}
}

Here Integer will be executed.


--------------------------------------------------------------
class Test
{
public void accept(long s)
{
System.out.println("Widening");
}
public void accept(Integer i)
{
System.out.println("Autoboxing");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(12);
}
}
Here widening is having more priority
--------------------------------------------------------------
class Test
{
public void accept(int ...s)
{
System.out.println("Var args");
}
public void accept(Integer i)
{
System.out.println("Autoboxing");
}
}
public class AmbiguityIssue {

public static void main(String[] args)


{
Test t = new Test();
t.accept(12);

}
}
Here Autoboxing will be executed.
--------------------------------------------------------------
16-10-2024
-----------
***Method Overriding :
----------------------
Writing two or more non static methods in super and sub class in such a way that
method name along with method parameter (Method Signature) must be same is called
Method Overriding.

Method Overriding is not possible without inheritance.

Generally we can't change the return type of the method while overriding a method
but from JDK 1.5v there is a concept called Co-variant (In same direction) through
which we can change the
return type of the method.

Example :
---------
class Super
{
public void m1()
{
}
}
class Sub extends Super
{
public void m1() //Overridden Method
{

}
}

Method overriding is mainly used to replacing the implementation


of super class method by sub class method body.

Advantage of Method Overriding :


---------------------------------
The advantage of Method Overriding is, each sub class is specifying its own
specific behavior.
---------------------------------------------------------------
**What is upcasting and downcasting ?
--------------------------------------
Upcasting :-
------------
It is possble to assign sub class object to super class reference variable (up)
using dynamic polymorphism. It is known as Upcasting.

Example:- Animal a = new Lion(); //valid [upcasting]

Downcasting :
-------------
By default we can't assign super class object to sub class reference variable.

Lion l = new Animal(); //Invalid

Even if we type cast Animal to Lion type then compiler will allow but at runtime
JVM will not convert Animal object (Generic type) into Lion object (Specific type)
and it will throw an exception java.lang.ClassCastException

Lion l = (Lion) new Animal(); //At runtime we will get


java.lang.ClassCastException

Note : To avoid this ClassCastException we should use instanceof opertor.


-----------------------------------------------------------------
AnimalDemo.java
----------------
package com.ravi.mo;

class Animal
{
public void eat()
{
System.out.println("Generic Animal is eating");
}
}
class Lion extends Animal
{
public void eat()
{
System.out.println("Lion Animal is eating");
}
}
class Horse extends Animal
{
public void eat()
{
System.out.println("Horse Animal is eating");
}
}

public class AnimalDemo {

public static void main(String[] args)


{
Animal a1 = null;

a1 = new Lion(); a1. eat(); //Dynamic Method Dispatch

a1 = new Horse(); a1. eat(); //Dynamic Method Dispatch

}
-----------------------------------------------------------------
@Override Annotation :
--------------------------
In Java we have a concept called Annotation, introduced from JDK 1.5 onwards. All
the annotations must be start with @ symbol.

@Override annotation is metadata (Giving information that method is overridden) and


it is optional but it is always a good practice to write @Override annotation
before the Overridden method so compiler as well as user will get the confirmation
that the method is overridden method and it is available in the super class.

If we use @Override annotation before the name of the overridden method in the sub
class and if the method is not available in the super class then it will generate a
compilation error so it is different from comments because comment will not
generate any kind of compilation error if method is not an overridden method, so
this is how it is different from comment.

package com.ravi.mo;

class Bird
{
public void fly()
{
System.out.println("Genric Bird is flying");
}
}
class Parrot extends Bird
{
@Override
public void fly()
{
System.out.println("Parrot Bird is flying");
}
}
class Peacock extends Bird
{
@Override
public void fly()
{
System.out.println("Paecock Bird is flying");
}
}

public class MethodOverridingDemo1 {

public static void main(String[] args)


{
Bird b = null;
b = new Parrot(); b.fly();
b = new Peacock(); b.fly();
}

}
----------------------------------------------------------------
Method Overloading is also possible in super and sub class as shown below

package com.ravi.mo;

class Bird
{
public void fly()
{
System.out.println("Genric Bird is flying");
}

public void roam()


{
System.out.println("Generic Bird is roamig");
}

}
class Parrot extends Bird
{
//Method Overloading
public int fly(double height)
{
System.out.println("Parrot is flying with :"+height);
return 0;
}

@Override
public void roam()
{
System.out.println("Parrot Bird is roamig");

}
}
public class MethodOverridingDemo1 {

public static void main(String[] args)


{
Parrot p = new Parrot();
p.fly(15.6);
p.roam();
}

}
----------------------------------------------------------------
18-10-2024
-----------
Variable Hiding concept in upcasting :
---------------------------------------
class Super
{
int x = 100;

}
class Sub exetnds Super
{
int x = 200; //Variable Hiding
}

Only non static methods are overridden in java but not the variables[variables are
not overridden in java] because behavior will change but not the
property(variable).

Note : In upcasting variable will be always executed besed on the current reference
class variable.

package com.ravi.method_overriding;

class Vehicle
{
protected String name = "Generic Vehicle";

public String run()


{
return "Generic Vehicle is running";
}
}
class Car extends Vehicle
{
protected String name = "Car Vehicle"; //Variable Hiding

@Override
public String run()
{
return "Car Vehicle is running";
}
}
public class VariableHiding
{
public static void main(String[] args)
{
Vehicle v = new Car();
System.out.println(v.name+" : "+v.run());

System.out.println(".................");
Car c1 = new Car();
Vehicle v1 = c1;
System.out.println(c1.name +" : "+v1.name);
}
}
-----------------------------------------------------------------
Can we override private method ?
--------------------------------
No, We can't override private method because private methods are not visible (not
available) to the sub class hence we can't override.

We can't use @Override annotation on private method of sub class because it is not
overridden method, actually it is re-declared by sub class developer.

package com.ravi.method_overriding;

class Super
{
private void m1()
{
System.out.println("Private method of super class");
}
}
class Sub extends Super
{
//It is not an overridden method
private void m1() //Re-declare m1 method is sub class
{
System.out.println("Private method of Sub class");
}
}

public class PrivateMethodOverriding {

public static void main(String[] args)


{

Note :- private method of super class is not available or not inherited in the sub
class so if the sub class declare the method with same signature then it is not
overridden method, actually it is re-declared in the sub class.
-----------------------------------------------------------------
Role of access modifier while overriding a method :
---------------------------------------------------
While overriding the method from super class, the access modifier of sub class
method must be greater or equal in comparison to access modifier of super class
method otherwise we will get compilation error.

In terms of accessibility, public is greater than protected, protected is greater


than default (public > protected > default)
[default < protected < public]

**So the conclusion is we can't reduce the visibility of the method while
overriding a method.

Note :- private method is not availble (visible) in sub class so it is not the part
of method overriding.

package com.ravi.method_overriding;

class RBI
{
public void loan()
{
System.out.println("Instruction to provide loan");
}
}
class SBI extends RBI
{
@Override
protected void loan() //error due to protected
{
System.out.println("SBI provides loan @ 9.2%");
}
}
public class AccessibilityLevel {

public static void main(String[] args) {


RBI r = new SBI();
r.loan();
}
}

Note : We can't reduce the visibility.


----------------------------------------------------------------
Co-variant in java :
--------------------
In general we cann't change the return type of method while overriding a method. if
we try to change it will generate compilation error because in method overriding,
return type of both the methods must be compaitable as shown in the program below.

class Animal
{
public void sleep()
{
}
}

class Dog extends Animal


{
@Override
public int sleep() //error
{
return 0;
}
}

public class MethodOverriding


{
public static void main(String[] args)
{

}
}
Note : error, return type int is not compaitable with void.
----------------------------------------------------------------
But from JDK 1.5 onwards we can change the return type of the method in only one
case that the return type of both the METHODS(SUPER AND SUB CLASS METHODS) MUST BE
IN INHERITANCE RELATIONSHIP (IS-A relationship so it is compatible) called Co-
Variant as shown in the program below.

Note :- Co-variant will not work with primitive data type, it will work only with
classes.

class Alpha
{
}
class Beta extends Alpha
{
}

class Animal
{

public Alpha sleep()


{
System.out.println("Sleep method of super class");
return new Beta();
}
}

class Dog extends Animal


{
@Override
public Beta sleep()
{
System.out.println("Sleep method of Sub class");
return null;
}
}

public class CoVariantDemo1


{
public static void main(String[] args)
{
Animal a1 = new Dog();
a1.sleep();
}
}
-----------------------------------------------------------------
package com.ravi.method_return_type;

import java.io.IOException;

class Alpha
{
public Object m1()
{
System.out.println("Super class m1 method");
return new String();
}
}
class Beta extends Alpha
{
public Double m1()
{
System.out.println("Sub class m1 method");
return null;
}
}

public class CoVariant2


{
public static void main(String[] args) throws IOException
{
Alpha a = new Beta();
a.m1();
}

}
----------------------------------------------------------------
21-10-2024
-----------
package com.ravi.co_variant;

class Vehicle
{
public Vehicle run()
{
System.out.println("Generic Vehicle is Running");
return this;
}
}
class Car extends Vehicle
{
@Override
public Car run()
{
System.out.println("Car Vehicle is Running");
return this;
}
}

public class CoVariantDemo3


{
public static void main(String[] args)
{
Vehicle vehicle = new Car();
vehicle.run();

}
----------------------------------------------------------------
While working with co-variant (In the same direction), sub class method return type
object, if we can assign to super class method return then only it is compatible
and it is co-variant as shown in the program.

package com.ravi.co_variant;
class Bird
{
public Object fly()
{
System.out.println("Generic Bird is flying");
return null;
}
}
class Sparrow extends Bird
{
@Override
public String fly()
{
System.out.println("Sparrow Bird is flying");
return "NIT";
}
}

public class CoVariantDemo4 {

public static void main(String[] args)


{
Bird b = new Sparrow();
Object str = b.fly();
System.out.println(str);

Note : According to Liskov substitution principle (LSP), super class object can be
replace by sub class object but to support co-variant (In the same direction) sub
class object we can assign super class object i.e super class methdo return type
i.e in one direction.
----------------------------------------------------------------
**What is Method Hiding in java ?
OR
Can we override static method ?
OR
Can we override main method ?

While working with method hiding we have all different cases :

Case 1 :
--------
A public static method of super class by default available to sub class so, from
sub class we can call super class static method with the help of Class name as well
as object reference as shown in the below program

class Super
{
public static void m1()
{
System.out.println("Static Method of Super class..");
}
}
class Sub extends Super
{
}

public class StaticMethodDemo1


{
public static void main(String[] args)
{
Sub.m1();
System.out.println("..........");
Sub s1 = new Sub();
s1.m1();

}
}
----------------------------------------------------------------
Case 2 :
-------
We can't override a static method with non static method because static method
belongs to class and non static method belongs to object, If we try to override
static method with non static method then it will generate an error i.e overridden
method is static as shown below.

class Super
{
public static void m1()
{
System.out.println("Static Method of Super class..");
}
}
class Sub extends Super
{
public void m1() //error
{
System.out.println("Non Static Method of Sub class..");
}

public class StaticMethodDemo2


{
public static void main(String[] args)
{

}
}
----------------------------------------------------------------
Case 3 :
--------
We can't override any non static method with static method, If we try then it will
generate an error, Overriding method is static.

class Super
{
public void m1()
{
System.out.println("Non Static Method of Super class..");
}
}
class Sub extends Super
{
public static void m1() //error
{
System.out.println("Static Method of Sub class..");
}
}

public class StaticMethodDemo1


{
public static void main(String[] args)
{

}
}

So, the conclusion is we cannot overide static with non static method as well as
non-static with static method because static method belongs to class and non-static
method belongs to object.
----------------------------------------------------------------
Case 4 :
-------
Program that describes method hiding as well as sub class method can't hide super
class method because return type is not compaitable

class Super
{
public static void m1()
{
System.out.println("Non Static Method of Super class..");
}
}
class Sub extends Super
{
public static int m1()
{
System.out.println("Static Method of Sub class..");
return 0;
}
}

public class StaticMethodDemo1


{
public static void main(String[] args)
{

}
}

Note : sub class method can't hide super class method


================================================================
We can't override static method because It belong to class but not object, If we
write static method in the sub class with same signature and compaitable return
type then It is Method Hiding but not Method Overriding here compiler will search
the method of super class and JVM will also execute the method of super class
because method is not overridden.[Single copy and belongs to class area]
Note :- 1) We can't apply @Override annotation on static methods.

2) Static methods can't be overridden so behavior is


same for all the Objects hence it is Static Polymorphism.

class Animal
{
public static void m1()
{
System.out.println("Animal");
}
}
class Dog extends Animal
{
//Method Hiding
public static void m1()
{
System.out.println("Dog");
}
}

class Horse extends Animal


{
//Method Hiding
public static void m1()
{
System.out.println("Horse");
}
}
public class StaticMethodDemo1
{
public static void main(String[] args)
{
Animal a = new Horse();
a.m1();
}
}

Note : Here we assign Dog object or Horse Object, Output will be same i.e Animal.

Note : static variable, instance variable and static method of super class are not
overridden so we will get super class output.
----------------------------------------------------------------
Progrm that describes Polymorphic behaviour of sub classes :
-----------------------------------------------------------
package com.ravi.polymorphic_behavior;

class Animal
{
public void sleep()
{
System.out.println("Generic Animal is sleeping");
}
}
class Lion extends Animal
{
@Override
public void sleep()
{
System.out.println("Lion is sleeping");
}
}
class Dog extends Animal
{
@Override
public void sleep()
{
System.out.println("Dog is sleeping");
}
}
public class AnimalDemo
{
public static void main(String[] args)
{
Animal lion = new Lion();
Animal dog = new Dog();

callSleepingAnimal(lion);
callSleepingAnimal(dog);

public static void callSleepingAnimal(Animal a1)


{
a1.sleep();
}

Note : From above program it is clear that based on the runtime object appropriate
method is invoked.
---------------------------------------------------------------
package com.ravi.polymorphic_behavior;

class Animal
{
public void sleep()
{
System.out.println("Generic Animal is sleeping");
}
}
class Lion extends Animal
{
@Override
public void sleep()
{
System.out.println("Lion is sleeping");
}

public void roar()


{
System.out.println("Lion is Roaring");
}

}
class Dog extends Animal
{
@Override
public void sleep()
{
System.out.println("Dog is sleeping");
}

public void bark()


{
System.out.println("Dog is Barking");
}

class Tiger extends Animal


{
@Override
public void sleep()
{
System.out.println("Tiger is sleeping");
}

public void roar()


{
System.out.println("Tiger is Roaring");
}

}
public class AnimalDemo
{
public static void main(String[] args)
{
Animal lion = new Lion();
Animal dog = new Dog();

callSleepingAnimal(lion);
callSleepingAnimal(dog);

public static void callSleepingAnimal(Animal a1)


{
Lion lion = (Lion)a1;
lion.sleep(); lion.roar();
}

Note : Here we will get java.lang.ClassCastException because Dog object can't be


converted into lion type.
----------------------------------------------------------------
22-10-2024
-----------
package com.ravi.dynamic_method_dispatch;

class Person
{
public int getAge()
{
return 32;
}

public void printInfo()


{
System.out.println(this.getAge());
}
}
class Student extends Person
{
@Override
public int getAge()
{
return 22;
}
}
public class DynamicMethodDispatch
{
public static void main(String[] args)
{
new Student().printInfo();
}

}
----------------------------------------------------------------
package com.ravi.dynamic_method_dispatch;

class Person
{
public int getAge()
{
return 32;
}

public void printInfo()


{
System.out.println(this.getAge());
}
}
class Student extends Person
{
@Override
public int getAge()
{
return 22;
}

public void printInfo()


{
System.out.println(super.getAge());
}

}
public class DynamicMethodDispatch
{
public static void main(String[] args)
{
new Student().printInfo();
}
}
---------------------------------------------------------------
package com.ravi.dynamic_method_dispatch;

class Bird
{
protected int weathers = 2;

public static void fly()


{
System.out.println("Bird is flying");
}
}
class Parrot extends Bird
{
protected int weathers = 4;

public static void fly()


{
System.out.println("Parrot is flying");
}
}

public class IQ {

public static void main(String[] args)


{
Parrot p = new Parrot();
Bird b = p;
System.out.println(p.weathers); //4
p.fly();
System.out.println(b.weathers); //2
b.fly();

}
----------------------------------------------------------------
instanceof operator :
---------------------
It is a relational operator so it returns boolean value.
It is also a keyword.
It is used to describe whether a reference variable is holding an object of
particular type or not.
There must be an IS-A relation between reference variable and partcular class OR
interface type.
It is used to avoid java.lang.ClassCastException.

Programs :
-----------
package com.ravi.instance_of;

class Bird
{
}

class Fish
{
}

public class InstanceOfDemo {

public static void main(String[] args)


{
Fish f = new Fish();

if(f instanceof Fish)


{
System.out.println("f is pointing to Fish Object");
}

else if(f instanceof Bird) //error


{

}
----------------------------------------------------------------
package com.ravi.instance_of;

class Test
{

public class InstanceOfDemo1


{
public static void main(String[] args)
{
Test t1 = new Test();

if(t1 instanceof Test)


{
System.out.println("t1 is the instance of Test");
}

else if(t1 instanceof Object)


{
System.out.println("t1 is the instance of Object");
}

}
---------------------------------------------------------------
package com.ravi.instance_of;

public class InstanceDemo2 {

public static void main(String[] args)


{
Integer i = 45;
if(i instanceof Integer)
{
System.out.println("i is pointing Integer Object");
}

else if(i instanceof Number)


{
System.out.println("i is pointing to Number Object");
}

}
----------------------------------------------------------------
package com.ravi.instance_of;

class A{}

class B extends A{}

class C extends B{}

class D extends C{}

public class InstanceOfDemo3


{
public static void main(String[] args)
{
D d1 = new D();

if(d1 instanceof D) //Here instead of D we can take A,B,C Object


{

}
================================================================
package com.ravi.polymorphic_behavior;

class Animal
{
public void sleep()
{
System.out.println("Generic Animal is sleeping");
}
}
class Lion extends Animal
{
@Override
public void sleep()
{
System.out.println("Lion is sleeping");
}

public void roar()


{
System.out.println("Lion is Roaring");
}

}
class Dog extends Animal
{
@Override
public void sleep()
{
System.out.println("Dog is sleeping");
}

public void bark()


{
System.out.println("Dog is Barking");
}

class Tiger extends Animal


{
@Override
public void sleep()
{
System.out.println("Tiger is sleeping");
}

public void roar()


{
System.out.println("Tiger is Roaring");
}

class Cat extends Animal


{
public void sleep()
{
System.out.println("Cat is sleeping");

public void meow()


{
System.out.println("Meow Meow");
}
}

public class AnimalDemo


{
public static void main(String[] args)
{
Animal lion = new Lion();
Animal dog = new Dog();
Animal tiger = new Tiger();
Animal cat = new Cat();
callSleepingAnimal(lion);
callSleepingAnimal(dog);
callSleepingAnimal(tiger);
callSleepingAnimal(cat);

public static void callSleepingAnimal(Animal a1)


{
if(a1 instanceof Lion)
{
Lion lion = (Lion)a1;
lion.sleep();
lion.roar();
}
else if(a1 instanceof Dog)
{
Dog d1 = (Dog) a1;
d1.sleep(); d1.bark();
}
else if(a1 instanceof Tiger)
{
Tiger t1 = (Tiger) a1;
t1.sleep(); t1.roar();
}
else if(a1 instanceof Cat)
{
Cat c1 = (Cat) a1;
c1.sleep(); c1.meow();
}

}
================================================================
*What is the limitation of 'new' keyword ?
OR
What is the difference between new keyword and newInstance() method?
OR
How to create the Object for the classes which are coming dynamically from the
database or from some file at runtime.

The limitation with new keyword is, It demands the class name at the begning or at
the time of compilation so new keyword is not suitable to create the object for the
classes which are coming from database or files at runtime dynamically.

In order to create the object for the classes which are coming at runtime from
database or files, we should use newInstance() method available in java.lang.Class
class.

Methods :
----------
public Object newInstance() : Predefined non static method of
java.lang.Class. It is used to
create the object for dynmacilly
loaded classes.
public native java.lang.Class getClass() :Predefined non static method of Object
class.
----------------------------------------------------------------
class Student
{
}
class Employee
{
}
public class ObjectAtRuntime
{
public static void main(String[] args) throws Exception
{
Object obj = Class.forName(args[0]).newInstance();
System.out.println("Object created for :"+obj.getClass().getName());
}
}

Methods :
---------

Note : We can pass any class at runtime, newInstance() method will create the
Object.
----------------------------------------------------------------
class Ravi
{
public void hi()
{
System.out.println("Hello Hyderabad");
}
}

class Sample
{
public void greet()
{
System.out.println("Hello India");
}
}
public class ObjectAtRuntime1
{
public static void main(String[] args) throws Exception
{
Object obj = Class.forName(args[0]).newInstance();

if(obj instanceof Sample)


{
Sample s = (Sample)obj;
s.greet();
}

else if(obj instanceof Ravi)


{
Ravi r = (Ravi) obj;
r.hi();
}

}
}
===============================================================
final keyword in java :
-----------------------
It is used to provide some kind of restriction in our program.
We can use final keyword in ways 3 ways in java.

1) To declare a class as a final. (Inheritance is not possible)


2) To declare a method as a final (Overriding is not possible)
3) To declare a variable (Field) as a final (Re-assignment is not possible)

1) To declare a class as a final :


-----------------------------------
Whenever we declare a class as a final class then we cann't extend or inherit that
class otherwise we will get a compilation error.

We should declare a class as a final if the composition of the class (logic of the
class) is very important and we don't want to share the feature of the class to
some other developer to modify the original behavior of the existing class, In that
situation we should declare a class as a final.

Declaring a class as a final does not mean that the variables and methods declared
inside the class will also become as a final, only the class behavior is final that
means we can modify the variables value as well as we can create the object for the
final classes.

Note :- In java String and All wrapper classes are declared as final class.

--------------------------------------------------------------
final class A
{
private int x = 100;

public void setData()


{
x = 120;
System.out.println(x);
}
}
class B extends A
{
}
public class FinalClassEx
{
public static void main(String[] args)
{
B b1 = new B();
b1.setData();
}
}
Here A class is final so, we can't inherit class A hence we will get compilation
error.
-------------------------------------------------------------
final class Test
{
private int data = 100;

public Test(int data)


{
this.data = data;
System.out.println("Data value is :"+data);
}
}
public class FinalClassEx1
{
public static void main(String[] args)
{
Test t1 = new Test(200);

}
}

Note : If a class contains private constructor then we should declare that class
with final access modifier.
---------------------------------------------------------------
Sealed class in Java :
-----------------------
It is a new feature introduced from java 15v (preview version) and become the
integral part of java from 17v.

It is an improvement over final keyword.

By using sealed keyword we can declare classes and interfaces as sealed.

It is one kind of restriction that describes which classes and interfaces can
extend or implement from Sealed class Or interface.

It is similar to final keyword with less restriction because here we can permit the
classes to extend from the original Sealed class.

The class which is inheriting from the sealed class must be final, sealed or non-
sealed.

The sealed class must have atleast one sub class.

We can also create object for Sealed class.

It provides the following modifiers :

1) sealed : Can be extended only through permitted class.

2) non-sealed : Can be extended by any sub class, if a user wants to give


permission to its sub classes.

3) permits : We can provide permission to the sub classes, which are inheriting
through Sealed class.

4) final : we can declare permitted sub class as final so, it cannot be extended
further.

---------------------------------------------------------------
Programs :
-----------
SealedDemo1.java
------------------
package com.ravi.m1;

sealed class Bird permits Parrot,Sparrow


{
public void fly()
{
System.out.println("Generic Bird is flying");
}
}
non-sealed class Parrot extends Bird
{
@Override
public void fly()
{
System.out.println("Parrot Bird is flying");
}
}
final class Sparrow extends Bird
{
@Override
public void fly()
{
System.out.println("Sparrow Bird is flying");
}
}

public class SealedDemo1


{
public static void main(String[] args)
{
Bird b = null;
b = new Parrot(); b.fly();
b = new Sparrow(); b.fly();

}
--------------------------------------------------------------
SealedDemo2.java
-----------------
package com.ravi.m1;

sealed class OnlineClass permits Mobile,Laptop


{
public void attendOnlineJavaClass()
{
System.out.println("Online java class!!!");
}
}
final class Mobile extends OnlineClass
{
@Override
public void attendOnlineJavaClass()
{
System.out.println("Attending Java class through mobile.");
}
}
final class Laptop extends OnlineClass
{
@Override
public void attendOnlineJavaClass()
{
System.out.println("Attending Java class through Laptop.");
}
}
public class SealedDemo2
{
public static void main(String[] args)
{
OnlineClass c = null;
c = new Mobile(); c.attendOnlineJavaClass();
c = new Laptop(); c.attendOnlineJavaClass();
}

}
---------------------------------------------------------------
2) To declare a method as a final (Overriding is not possible)
---------------------------------------------------------------
Whenever we declare a method as a final then we can't override that method in the
sub class otherwise there will be a compilation error.

We should declare a method as a final if the body of the method i.e the
implementation of the method is very important and we don't want to override or
change the super class method body by sub class method body then we should declare
the super class method as final method.

class A
{
protected int a = 10;
protected int b = 20;

public final void calculate()


{
int sum = a+b;
System.out.println("Sum is :"+sum);
}
}
class B extends A
{
@Override
public void calculate()
{
int mul = a*b;
System.out.println("Mul is :"+mul);
}
}
public class FinalMethodEx
{
public static void main(String [] args)
{
A a1 = new B();
a1.calculate();
}
}

Note : We can't oevrride final method in the sub class.


--------------------------------------------------------------
class Alpha
{
private final void accept()
{
System.out.println("Alpha class accept method");
}
}
class Beta extends Alpha
{
protected void accept()
{
System.out.println("Beta class accept method");
}
}
public class FinalMethodEx1
{
public static void main(String [] args)
{
new Beta().accept();
}
}

Note : Here Program will compile and execute because private method of super class
is not available to sub class.
--------------------------------------------------------------
3) To declare a variable/Field as a final :
--------------------------------------------
In older langugaes like C and C++ we use "const" keyword to declare a constant
variable but in java, const is a reserved word for future use so instead of const
we should use "final" keyword.

If we declare a variable as a final then we can't perform re-assignment (i.e


nothing but re-initialization) of that variable.

In java It is always a better practise to declare a final variable by uppercase


letter according to the naming convention.

class A
{
final int A = 10;
public void setData()
{
A = 10; //error
System.out.println("A value is :"+A);
}
}
class FinalVarEx
{
public static void main(String[] args)
{
A a1 = new A();
a1.setData();
}
}
--------------------------------------------------------------
class Student
{
private int rollNumber;
private String studentName;

public Student(int rollNumber, String studentName)


{
this. rollNumber = rollNumber;
this.studentName = studentName;
}

}
class FinalVarEx1
{
public static void main(String[] args)
{
final Student s1 = new Student(111,"Scott");
s1 = new Student(222,"Smith"); //error
}
}
--------------------------------------------------------------
24-10-2024
----------
Nested classes in java :
-------------------------
In java it is possible to define a class (inner class) inside another class (outer
class) called nested class.

In the same way, It is also possible to define a class/interface/enum/


annotation/record inside another class/interface/enum/annotation and record as
shown below.

Programs that describes all different possible combinations :


-------------------------------------------------------------
package com.ravi.inner_class_concept;

public class Demo1


{
public class Test
{
//class
}

interface Drawable
{
//interface
}

enum Direction
{

record Student()
{

@interface Hello
{

}
-------------------------------------------------------------
package com.ravi.inner_class_concept;
public interface Demo2
{
public class Test
{
}

enum Direction
{
}

record Student()
{

@interface Hello
{

}
--------------------------------------------------------------
package com.ravi.inner_class_concept;

public enum Demo3


{
A,B; //Enum constants
class Test
{
}

interface Printable
{

record Student()
{

@interface Hello
{

}
--------------------------------------------------------------
package com.ravi.inner_class_concept;

public record Demo4()


{
class Test
{

}
interface Drawable
{

enum Season
{

@interface Hello
{

}
--------------------------------------------------------------
package com.ravi.inner_class_concept;

public @interface Demo5


{
class Test
{

interface Moveable
{

enum Color
{

record Employee()
{

}
--------------------------------------------------------------
Inner classes in Java create a strong encapsulation and HAS-A relationship
between the inner class and its outer class.

An inner class, .class file will be represented by $ symbol.

Advantages of inner class :


--------------------------------
1) It is a way of logically grouping classes that are only used in one place.

2) It is used to achieve strong encapsulation.

3) It enhance the readability and maintainability of the code.

Types of Inner classes in java :


--------------------------------
There are 4 types of inner classes in java :

1) Non Static Nested class OR Regular class


2) Static Nested class
3) Method / Method local class
4) Anonymous inner class

Non static Nested class :


-------------------------
If a non static class declared inside the Outer class but outside of the method
then it is called non static nested class.

We can apply private, default, protected, public, abstract and final modifiers on
non static nested class.

With the help of outer class we can load inner class also, If inner class contains
non static member then object is required for Outer class as well as inner class.

Inner class we can't represent directly, we need to take the support of Outer class
because inner class is a non static member of Outer class.

It is also known as Regular OR Mebmer class.


--------------------------------------------------------------
class Outer
{
private int a = 15;

class Inner
{
public void displayValue()
{
System.out.println("Value of a is " + a);
}
}
}
public class Test1
{
public static void main(String... args)
{
Outer out = new Outer();

Outer.Inner in = out.new Inner();

in.displayValue();

}
}

Note : An inner class can directly access the private data of Outer class.
--------------------------------------------------------------
class MyOuter
{
private int x = 7;
public void makeInner()
{
MyInner in = new MyInner();
System.out.println("Inner y is "+in.y);
in.seeOuter();
}
class MyInner
{
private int y = 15;
public void seeOuter()
{
System.out.println("Outer x is "+x);
}
}
}
public class Test2
{
public static void main(String args[])
{
MyOuter m = new MyOuter();
m.makeInner();
}
}
-------------------------------------------------------------
Variable Shadow in Nested class :
----------------------------------
If outer class and inner class variable names are same then inner class variable
will be access with inner class object (Variable Shadow bacause in the same scope),
If we want to access Outer class variable from inner class then we need
ClassName.this.variableName.

package com.ravi.inner_class;

class Outer1
{
private int x = 100;

public class Inner1


{
private int x = 200; //Variable Shadow

public void show()


{
System.out.println(Outer1.this.x);
System.out.println(this.x);
}

}
}
public class InnerClassDemo2
{
public static void main(String[] args)
{
Outer1.Inner1 in = new Outer1().new Inner1();
in.show();
}
}
--------------------------------------------------------------
class MyOuter
{
private int x = 15;
class MyInner
{
public void seeOuter()
{
System.out.println("Outer x is "+x);
}
}
}
public class Test3
{
public static void main(String args[])
{
//Creating inner class object in a single line
MyOuter.MyInner m = new MyOuter().new MyInner();
m.seeOuter();
}
}
--------------------------------------------------------------
class MyOuter
{
static int x = 7;
class MyInner
{
public static void seeOuter() //MyInner.seeOuter();
{
System.out.println("Outer x is "+x);
}
}
}

public class Test4


{
public static void main(String args[])
{
MyOuter.MyInner.seeOuter();
}
}
-------------------------------------------------------------
class Car
{
private String make;
private String model;
private Engine engine;

public Car(String make, String model, int horsePower)


{
this.make = make;
this.model = model;
this.engine = new Engine(horsePower);
}

//Inner class
private class Engine
{
private int horsePower;

public Engine(int horsePower)


{
this.horsePower = horsePower;
}

public void start()


{
System.out.println("Engine started! Horsepower: " + horsePower);
}

public void stop()


{
System.out.println("Engine stopped.");
}
}

public void startCar()


{
System.out.println("Starting " + make + " " + model);
this.engine.start();
}

public void stopCar()


{
System.out.println("Stopping " + make + " " + model);
this.engine.stop();
}
}
public class Test5
{

public static void main(String[] args) {

Car myCar = new Car("Swift", "Desire", 1200);

myCar.startCar();

myCar.stopCar();
}
}
-----------------------------------------------------------------
25-10-2024
-----------
class Laptop
{
private String brand;
private String model;
private Motherboard motherboard;

public Laptop(String brand, String model, String motherboardModel, String


chipset)
{
this.brand = brand;
this.model = model;
this.motherboard = new Motherboard(motherboardModel, chipset);
}

public void switchOn()


{
System.out.println("Turning on " + brand + " " + model);
this.motherboard.boot();
}

//Motherboard inner class


public class Motherboard
{
private String model;
private String chipset;

public Motherboard(String model, String chipset)


{
this.model = model;
this.chipset = chipset;
}

public void boot()


{
System.out.println("Booting " + brand + " " + model + " with " +
chipset + " chipset");
}
}
}
public class Test6
{
public static void main(String[] args)
{

Laptop laptop = new Laptop("HP", "ENVY", "IRIS", "Intel");

laptop.switchOn();
}
}
--------------------------------------------------------------
class Person
{
private String name;
private int age;
private Heart heart;

public Person(String name, int age)


{
this.name = name;
this.age = age;
this.heart = new Heart();
}

public void describe()


{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Heart beats per minute: " +
this.heart.getBeatsPerMinute());
}

// Inner class representing the Heart


private class Heart
{
private int beatsPerMinute;

public Heart()
{
this.beatsPerMinute = 72;
}

public int getBeatsPerMinute()


{
return this.beatsPerMinute;
}

public void setBeatsPerMinute(int beatsPerMinute)


{
this.beatsPerMinute = beatsPerMinute;
}
}
}
public class Test7
{
public static void main(String[] args)
{
Person person = new Person("Virat", 30);
person.describe();
}
}
-------------------------------------------------------------
class University
{
private String name;

public University(String name)


{
this.name = name;
}

public void displayUniversityName()


{
System.out.println("University Name: " + name);
}

public class Department


{
private String name;
private String headOfDepartment;

public Department(String name, String headOfDepartment)


{
this.name = name;
this.headOfDepartment = headOfDepartment;
}

// Method to display department details


public void displayDepartmentDetails()
{
displayUniversityName();
System.out.println("Department Name: " + name);
System.out.println("Head of Department: " + headOfDepartment);

}
}
}
public class Test8
{
public static void main(String[] args)
{

University university = new University("JNTU");

University.Department cs = university.new Department("Computer Science",


"Dr. John");

University.Department ee = university.new Department("Electrical


Engineering", "Dr. Scott");

cs.displayDepartmentDetails();
ee.displayDepartmentDetails();
}
}
---------------------------------------------------------------
class OuterClass
{
private int x = 200;

class InnerClass
{
public void display() //Inner class display method
{
System.out.println("Inner class display method");
}

public void getValue()


{
display();
System.out.println("Can access outer private var :"+x);
}
}

public void display() //Outer class display method


{
System.out.println("Outer class display");
}
}
public class Test9
{
public static void main(String [] args)
{
OuterClass.InnerClass inobj = new OuterClass().new InnerClass();
inobj.getValue();

new OuterClass().display();

}
}

Note : From inner class object, we can access inner class display() method, If we
want to call Outer class display method
then Outer class Object is reqd.
---------------------------------------------------------------
class OuterClass
{
int x;
abstract class InnerClass
{
int x;
}
}
public class Test10
{
}

Note : In a non static nested inner class we can apply private, default, protected,
public, abstract and final modifiers.
---------------------------------------------------------------
static nested inner class :
----------------------------
It is class level nested class.

If we decalre a static class inside another class then it is called Static nested
inner class.

For static nested inner class, Outer class object is not required.

If static nested inner class contains only static memebr then inner class object is
also not required.

If static nested inner class contains non static member then inner class object is
required.

We cann't access non static member of Outer class from static nested inner class
[Static context].
---------------------------------------------------------------
//static nested inner class
class BigOuter
{
static class Nest //static nested inner class
{
void go() //Instance method of static inner class
{
System.out.println("Hello welcome to static nested class");
}
}
}
class Test11
{
public static void main(String args[])
{
BigOuter.Nest n = new BigOuter.Nest();
n.go();

}
}
---------------------------------------------------------------
class Outer
{
static int x = 15;

static class Inner


{
void msg()
{
System.out.println("x value is "+x);
}
}
}
class Test12
{
public static void main(String args[])
{
Outer.Inner obj=new Outer.Inner();
obj.msg();
}
}
---------------------------------------------------------------
class Outer
{
static int x = 25;

static class Inner


{
static void msg()
{
System.out.println("x value is "+x);

}
}
}
class Test13
{
public static void main(String args[])
{
Outer.Inner.msg();
}
}
---------------------------------------------------------------
class Outer
{
int x=15; //error (not possible because try to access instance variable)
static class Inner
{
void msg()
{
System.out.println("x value is "+x);
}
}
}
class Test14
{
public static void main(String args[])
{
Outer.Inner obj=new Outer.Inner();
obj.msg();
}
}
---------------------------------------------------------------
package com.ravi.m1;

class Outer
{
static int x = 200;
static
{
System.out.println("Outer class static block");
}

static class Inner


{
static
{
System.out.println("Inner class static block");
}

public static void m1()


{
System.out.println("Inner class Static Method :"+x);
}
}
}

public class StaticNestedDemo


{
public static void main(String[] args)
{
Outer.Inner.m1();
}

Here We are accessing inner class static method from main method so, first of all
inner class static block will be executed and from inner class static method, we
are accessing Outer class static variable so Outer class will be loaded and static
block will be executed.
===============================================================
Method level inner class :
--------------------------
Local OR Method Local Inner class :
------------------------------------
If we define a class with class name inside the method body then it is called Local
OR Method local inner class.

public void m1()


{
class Inner
{
}
}

The Scope of this method local inner class within the same stack frame only so we
can't use local inner class outside of the method.

It is used to perform some opertion within the method only.

We can't apply any kind of access modifier on method local inner class except final
and abstract.
---------------------------------------------------------------
//program on method local inner class
class MyOuter3
{
private String x = "Outer class private data";

public void doSttuff()


{
String z = "local variable";

class MyInner //Only final and abstract applicable


{
public void seeOuter()
{
System.out.println("Outer x is "+x);
System.out.println("Local variable z is : "+z);
}
}
MyInner mi = new MyInner();
mi.seeOuter();

}
public class Test15
{
public static void main(String args[])
{
MyOuter3 m = new MyOuter3();
m.doSttuff();
}
}
---------------------------------------------------------------
//local inner class we can't access outside of the method
class MyOuter3
{
private String z = "Outer class Data";

public void doSttuff()


{
String x = "local variable";

class MyInner
{
String z = "CLASS instance variable";
public void seeOuter()
{
System.out.println("Outer x is "+MyOuter3.this.z);
System.out.println("Class variable z is : "+this.z);
System.out.println("Local variable is : "+x);
}
}

}
MyInner mi = new MyInner();
mi.seeOuter();

}
public class Test16
{
public static void main(String args[])
{
MyOuter3 m = new MyOuter3();
m.doSttuff();
}
}

Note : Method local inner class we can't access outside of the method.
--------------------------------------------------------------
26-10-2024
----------
Anonymous inner class
----------------------
If we decalre a class inside a method without any name then it
is called Anonymous inner class.

The main purpose of anonymous inner class to extend a class or implement an


interface.

The anonymous inner class declaration (without name) and object creation both will
be done in the same line.

We can create only object for anonymous inner class so it is a singleton class.

*A normal class can extend a class as well as implement many number of interfaces
but an anonymous inner can either extend
a class or implement an interface.

Inside an anoymous inner class we can write static and non static variable, static
and non static block. We can't define constructor as well as we can't declare
abstract method.
--------------------------------------------------------------
package com.ravi.anonymous_demo;

class Vehicle
{
public void run()
{
System.out.println("Generic Vehicle is Running");
}
}

public class AnonymousInnerDemo1


{
public static void main(String[] args)
{
//Anonymous inner class (Hidden class)
Vehicle car = new Vehicle()
{
@Override
public void run()
{
System.out.println("Car is running");
}
};
car.run();

//Anonymous inner class (Hidden class)


Vehicle bike = new Vehicle()
{
@Override
public void run()
{
System.out.println("Bike is running");
}
};
bike.run();

}
---------------------------------------------------------------
package com.ravi.anonymous_demo;

class Card
{
public void payment()
{
System.out.println("Payment through Generic card");
}

public class AnonymousInnerDemo2 {

public static void main(String[] args)


{
Card creditCard = new Card()
{
@Override
public void payment()
{
System.out.println("Payment through Credit card");
}
};

creditCard.payment();

}
=============================================================
Abstraction : [Hiding the complexcity]
---------------------------------------
Showing the essential details without showing the background details is called
abstraction.

In order to achieve abstraction we use the following two


concepts :

1) Abstract class (we can achieve 0 - 100% abstraction)


2) Interface (we can achieve 100 % abstraction)

=============================================================

Abstract class and abstract methods :


-------------------------------------------
A class that does not provide complete implementation (partial implementation) is
defined as an abstract class.
An abstract method is a common method which is used to provide easiness to the
programmer because the programmer faces complexcity to remember the method name.

An abstract method observation is very simple because every abstract method


contains abstract keyword, abstract method does not contain any method body and at
the end there must be a terminator i.e ; (semicolon)

In java whenever action is common but implementations are different then we should
use abstract method, Generally we declare abstract method in the super class and
its implementation must be provided in the sub classes.

if a class contains at least one method as an abstract method then we should


compulsory declare that class as an abstract class.

Once a class is declared as an abstract class we can't create an object for that
class.

*All the abstract methods declared in the super class must be overridden in the sub
classes otherwise the sub class will become as an abstract class hence object can't
be created for the sub class as well.

In an abstract class we can write all abstract method or all concrete method or
combination of both the method.

It is used to acheive partial abstraction that means by using abstract classes we


can acheive partial abstraction(0-100%).

*An abstract class may or may not have abstract method but an abstract method must
have abstract class.

Note :- We can't declare an abstract method as final, private and static (illegal
combination of modifiers)

We can't declare an abstract class as a final.

--------------------------------------------------------------
AbstractDemo1.java
-------------------
abstract class Bird
{
public abstract void fly();

}
class Parrot extends Bird
{
@Override
public void fly()
{
System.out.println("Parrot Bird is flying");
}
}
class Sparrow extends Bird
{
@Override
public void fly()
{
System.out.println("Sparrow Bird is flying");
}
}

public class AbstractDemo1


{
public static void main(String[] args)
{
Bird b ;
b = new Parrot(); b.fly();
b = new Sparrow(); b.fly();
}
}
---------------------------------------------------------------
package com.ravi.abstract_demo;

abstract class Bike


{
protected int speed = 90;

public Bike()
{
System.out.println("Bike class Constructor");
}

public void getBikeDetails()


{
System.out.println("It has two wheels");
}

public abstract void run();

class Unicorn extends Bike


{
@Override
public void run()
{
System.out.println("Bike is running");
}
}
public class IQ
{
public static void main(String[] args)
{
Bike b = new Unicorn();
System.out.println(b.speed);
b.getBikeDetails();
b.run();

}
-------------------------------------------------------------
28-10-2024
------------
How to initialize the abstract class properties :
--------------------------------------------------
package com.ravi.abstract_demo;
abstract class Shape
{
protected String shapeType;

public Shape(String shapeType)


{
super();
this.shapeType = shapeType;
}

public abstract void draw();


}

class Rectangle extends Shape


{
public Rectangle(String shapeType)
{
super(shapeType);
}

@Override
public void draw()
{
System.out.println("Drawing "+shapeType);
}
}

class Square extends Shape


{
public Square(String shapeType)
{
super(shapeType);
}

@Override
public void draw()
{
System.out.println("Drawing "+shapeType);
}
}

public class AbstractDemo1 {

public static void main(String[] args)


{
Rectangle rr = new Rectangle("Rectangle");
rr.draw();

Square ss = new Square("Square");


ss.draw();

}
-------------------------------------------------------------
IQ :
----
What is the advantage of taking instance variable OR writing constructor inside
abstract class ?
As we know we can't create an object for abstract class but still we can take
object properties (Instance variable) and
constructor, To call the abstract class constructor for initialization of instance
variable we should use sub class object (Using super keyword)
-------------------------------------------------------------
Anonymous inner class using abstract method :
----------------------------------------------
package com.ravi.abstract_demo;

abstract class Vehicle


{
public abstract void run();
}

public class AbstractDemo2


{
public static void main(String[] args)
{
Vehicle car = new Vehicle()
{
@Override
public void run()
{
System.out.println("Car is running");
}
};
car.run();

Vehicle bike = new Vehicle()


{
@Override
public void run()
{
System.out.println("Bike is running");
}
};
bike.run();

}
------------------------------------------------------------
package com.ravi.abstract_demo;

abstract class Alpha


{
public abstract void show();
public abstract void demo();
}

abstract class Beta extends Alpha


{
@Override
public void show() //demo();
{
System.out.println("Show method overridden");
}
}
class Gamma extends Beta
{
@Override
public void demo()
{
System.out.println("Demo method overridden");

}
}

public class AnonymousDemo3 {

public static void main(String[] args)


{
Gamma g = new Gamma();
g.show();
g.demo();

Note : From the above program it is clear that all the abstract methods must be
overridden in the sub classes otherwise sub class will become as an abstract class
so, object will not be created.
-------------------------------------------------------------
Polymorphism with Array :
--------------------------
package com.ravi.abstract_demo;

abstract class Animal


{
public abstract void checkup();
}
class Dog extends Animal
{
@Override
public void checkup()
{
System.out.println("Dog Animal Checkup");
}
}
class Lion extends Animal
{
@Override
public void checkup()
{
System.out.println("Lion Animal Checkup");
}
}
class Horse extends Animal
{
@Override
public void checkup()
{
System.out.println("Horse Animal Checkup");
}
}
public class AnimalChecking
{
public static void main(String[] args)
{
Dog dogs[] = {new Dog(), new Dog(), new Dog()};

Lion lions[] = {new Lion(), new Lion()};

Horse horses[] = {new Horse(), new Horse(), new Horse()};

animalCheck(dogs);
System.out.println("..........");
animalCheck(lions);
System.out.println("..........");
animalCheck(horses);

public static void animalCheck(Animal ...animals)


{
for(Animal animal : animals)
{
animal.checkup();
}
}
}
-----------------------------------------------------------
30-10-2024
-----------
interface :
------------
interface upto java 1.7
------------------------
An interface is a keyword in java which is similar to a class which defines working
functionality of a class.

Upto JDK 1.7 an interface contains only abstract method that means there is a
guarantee that inside an interfcae we don't have concrete or general or instance
methods.

From java 8 onwards we have a facility to write default and static methods.

By using interface we can achieve 100% abstraction concept because it contains only
abstract methods.

In order to implement the member of an interface, java software people has provided
implements keyword.

All the methods declared inside an interface is by default public and abstract so
at the time of overriding we should apply public access modifier to sub class
method.

All the variables declared inside an interface is by default public, static and
final.

We should override all the abstract methods of interface to the sub classes
otherwise the sub class will become as an abstract class hence object can't be
created.
We can't create an object for interface, but reference can be created.

By using interface we can acheive multiple inheritance in java.

We can achieve loose coupling using inetrface.

Note :- inside an interface we can't declare any blocks (instance, static),


instance variables (No properties) as well as we can't write constructor inside an
interface.

-----------------------------------------------------------
package com.ravi.interface_demo;

interface Moveable
{
int SPEED = 120; //public + static + final

void move(); //public + abstract


}

class Car implements Moveable


{
@Override
public void move()
{
//SPEED = 120; Invalid
System.out.println("Car Speed is :"+SPEED);
}
}

public class InterfaceDemo1


{
public static void main(String[] args)
{
Moveable m = new Car();
m.move();
System.out.println("Speed of Car is :"+Moveable.SPEED);

}
-----------------------------------------------------------
BankApplication.java
---------------------
package com.ravi.interface_demo;

interface Bank
{
void deposit(double amount);
void withdraw(double amount);
}
class Customer implements Bank
{
private double balance;

public Customer(double balance)


{
super();
this.balance = balance;
}

@Override
public void deposit(double amount)
{
if(amount <=0)
{
System.err.println("Amount can't be deposited!!");
}
else
{
this.balance = this.balance + amount;
System.out.println("Amount after deposit is :"+this.balance);
}
}

@Override
public void withdraw(double amount)
{
if(amount > this.balance)
{
System.err.println("Insufficient Balance!!");
}
else
{
this.balance = this.balance - amount;
System.out.println("Amount after Withdraw is :"+this.balance);
}

}
}
public class BankApplication
{
public static void main(String[] args)
{
Bank b = new Customer(1000);
b.deposit(10000);
b.withdraw(5000);

}
-----------------------------------------------------------
Program on loose coupling :
----------------------------
Loose Coupling :- If the degree of dependency from one class object to another
class is very low then it is called loose coupling. [interface]

Tightly coupled :- If the degree of dependency of one class to another class is


very high then it is called Tightly coupled.

According to IT industry standard we should always prefer loose coupling so the


maintenance of the project will become easy.

High Cohesion [Encapsulation]:


------------------------------
Our private data must be accessible via public methods (setter and getters) so, in
between data and method we must have high cohesion.
(tight coupling) so, validation of outer data is possible.

6 files :
-----------
HotDrink.java
---------------
package com.ravi.loose_coupling;

public class Restaurant


{
public static void acceptObject(HotDrink hd)
{
hd.prepare();
}
}

Tea.java
---------
package com.ravi.loose_coupling;

public class Tea implements HotDrink


{
@Override
public void prepare()
{
System.out.println("Preparing Tea");
}

Coffee.java
------------
package com.ravi.loose_coupling;

public class Tea implements HotDrink


{
@Override
public void prepare()
{
System.out.println("Preparing Tea");
}

Restaurant.java
---------------
package com.ravi.loose_coupling;

public class Restaurant


{
public static void acceptObject(HotDrink hd)
{
hd.prepare();
}
}

Horlicks.java
---------------
package com.ravi.loose_coupling;
public class Horlicks implements HotDrink
{
@Override
public void prepare()
{
System.out.println("Preparing Horlicks");

LooseCoupling.java
-------------------
package com.ravi.loose_coupling;

public class LooseCoupling {

public static void main(String[] args)


{
Restaurant.acceptObject(new Tea());
Restaurant.acceptObject(new Coffee());
Restaurant.acceptObject(new Horlicks());

}
-----------------------------------------------------------
It is always better to take method return type as interface so we can return any
implementer class object as shown in the example below

public HotDrink accept()


{
return new Tea() OR new Coffee() OR new Horlicks() OR any future
implementer class object...........................
}
-----------------------------------------------------------
Multiple Inheritance by using interface :
-----------------------------------------
In a class we have a constructor so, it is providing ambiguity issue but inside an
interface we don't have constructor so multiple inheritance is possible using
interface.

The sub class constructor super keyword will move to Object class constructor.(29-
OCT)

package com.ravi.mi;

interface A
{
void m1();
}
interface B
{
void m1();
}

class C implements A,B


{
@Override
public void m1()
{
System.out.println("Multiple Inheritance");
}
}

public class MultipleInheritance


{
public static void main(String[] args)
{
C c1 = new C();
c1.m1();

}
-----------------------------------------------------------
Extending interface :
---------------------
One interface can extends another interface, it cannot implement because interface
cannot provide implementation for the abstract method.

package com.ravi.interface_demo;

interface Alpha
{
void m1();
}
interface Beta extends Alpha
{
void m2();
}

class Implementer implements Beta


{
@Override
public void m1()
{
System.out.println("M1 method Implemented!!");
}

@Override
public void m2()
{
System.out.println("M2 method Implemented!!");
}
}

public class InterfaceDemo


{
public static void main(String[] args)
{
Implementer i = new Implementer();
i.m1(); i.m2();

}
-----------------------------------------------------------
interface from JDK 1.8 onwards :
--------------------------------
Limitation of abstract method :
OR
Maintenance problem with interface in an Industry upto JDK 1.7

The major maintenance problem with interface is, if we add any new abstract method
at the later stage of development inside an existing interface then all the
implementer classes have to override that abstract method otherwise the
implementer class will become as an abstract class so it is one kind of boundation.

We need to provide implementation for all the abstract methods available inside an
interface whether it is required or not?

To avoid this maintenance problem java software people introduced default method
inside an interface.
--------------------------------------------------------------
What is default Method inside an interface?
------------------------------------------------
default method is just like concrete method which contains method body and we can
write inside an interface from java 8 onwards.

default method is used to provide specific implementation for the implementer


classes which are implmenting from interface because we can override default method
inside the sub classes to provide our own specific implementation.

*By using default method there is no boundation to override the default method in
the sub class, if we really required it then we can override to provide my own
implementation.

by default, default method access modifier is public so at the time of overriding


we should use public access modifier.

default method we can write inside an interface only but not inside a class.
-------------------------------------------------------------
4 files :
----------
Vehicle.java(I)
----------------
package java8;

public interface Vehicle


{
void run();
void horn();

default void digitalMeter() //JDK 1.8


{
System.out.println("Digital Meter Facility");
}
}

Car.java(C)
-----------
package java8;

public class Car implements Vehicle {


@Override
public void run()
{
System.out.println("Car is running");
}

@Override
public void horn()
{
System.out.println("Car has horn");
}

@Override
public void digitalMeter()
{
System.out.println("Car has Digital Meter Facility");
}
}

Bike.java(C)
-------------
package java8;

public class Bike implements Vehicle


{
@Override
public void run()
{
System.out.println("Bike is running");
}

@Override
public void horn()
{
System.out.println("Bike has horn");
}

Main.java
----------
package java8;

public class Main {

public static void main(String[] args)


{
Vehicle v = null;
v = new Car(); v.run(); v.horn(); v.digitalMeter();
v = new Bike(); v.run(); v.horn();

}
}

Note :- abstract method is a common method which is used to provide easiness to the
programmer so, by looking the abstract method we will get confirmation that this is
common behavior for all the sub classes and it must be implemnted in all the sub
classes.

Common method [Behavior] -> abstract method


Uncommon method [Behavior] -> default method
--------------------------------------------------------------
Priority of deafult and concrete method :
-----------------------------------------
While working with class and interface, default method is having low
priority than concrete method, In the same way class is more powerfult than
interface.

class C extends B implements A {} //Valid

class C implements A extends B {} //Invalid

MethodPriority.java
-------------------
package java8;

interface A
{
default void m1()
{
System.out.println("Default Method of interface A");
}
}
class B
{
public void m1()
{
System.out.println("Concrete Method of class B");
}
}

class C extends B implements A


{

}
public class MethodPriority
{
public static void main(String[] args)
{
C c1 = new C();
c1.m1();

Output : Concrete Method of class B


==============================================================
Can we achieve multiple inheritance using default method :
----------------------------------------------------------
Multiple inheritance is possible in java by using default method inside an
interface, here we need to use super keyword to differenciate the super interface
methods.
Before java 1.8, we have abstract method inside an interface but now we can write
method body(default method) so to execute the default method inside an interface we
need to take super keyword with interface name(Alpha.super.m1()).

package java8;

interface Alpha
{
public default void m1()
{
System.out.println("Default method of Alpha interface");
}
}

interface Beta
{
public default void m1()
{
System.out.println("Default method of Beta interface");
}
}

class C implements Alpha,Beta


{
@Override
public void m1()
{
Alpha.super.m1();
Beta.super.m1();
System.out.println("Multiple Inheritance is Possible!!");
}
}

public class MultipleInheritance


{
public static void main(String[] args)
{
C c1 = new C();
c1.m1();

}
--------------------------------------------------------------
What is static method inside an interface?
------------------------------------------
We can define static method inside an interface from java 1.8 onwards.

static method is only available inside the interface, It is not available to the
implementer classes.

It is used to provide common functionality which we can apply/invoke from any


BLC/ELC class.

By default static method of an inetrafce contains public access modifier.


--------------------------------------------------------------
2 files :
----------
Calculate.java
-----------------
package com.ravi.java8;

public interface Calculate


{
static double getSquare(double num)
{
return num*num;
}

static double getCube(double num)


{
return num*num*num;
}
}

Main.java
----------
package com.ravi.java8;

public class Main {

public static void main(String[] args)


{
System.out.println(Calculate.getSquare(4));
System.out.println(Calculate.getCube(5));

}
-------------------------------------------------------------
Program that describe that static method of an interface is only available to
interface only that means we can access the static method of an interface by using
only one way i.e interface name.

interface Hello
{
public static void m1()
{
System.out.println("m1 static method");
}
}

public class Test implements Hello


{
public static void main(String [] args)
{
Test t1 = new Test();
t1.m1(); //error [Only possible way to call static
method using interafce name]
}
}
--------------------------------------------------------------
02-11-2024
------------
Can we write main method inside an interface ?
----------------------------------------------
interface is implicitly an abstract class, From java 8v onwards we can write static
method so we can also write main method, Since it is a class so main method will be
executed from interface body also.
package com.ravi.interface_demo;

public abstract interface Printable


{
public static void main(String[] args)
{
System.out.println("interface main method");
}
}
--------------------------------------------------------------
Interface Static Method:
------------------------
a) Accessible using the interface name.
b) Cannot be overridden by implementing classes.(Not Available)
c) Can be called using the interface name only.

Class Static Method:


--------------------
a) Accessible using the class name.
b) Can be hidden (not overridden) in subclasses by redeclaring a static method
with the same signature.
c) Can be called using the super class, sub class name as well as sub class
object also as shown in the program below.

package com.ravi.interface_demo;

class A
{
public static void m1()
{
System.out.println("Static method A");
}
}
class B extends A
{

}
public class Demo
{
public static void main(String [] args)
{
A.m1();
B.m1(); //valid
new B().m1(); //valid
}
}
--------------------------------------------------------------
Interface from java 9v version
-------------------------------
Yes, From java 9 onwards we can also write private static and private non-static
methods inside an interface.

The folowing are the advantages of writing private methods :


a) Code Reusability
b) Hiding the implementation details by writing the logic
inside private method (We can achieve 100% abstraction)

These private methods will improve code re-usability inside interfaces.


For example, if two default methods needed to share common and confidential code, a
private method would allow them to do so, but without exposing that private method
to it�s implementing classes.

Using private methods in interfaces have four rules :

1) private interface method cannot be abstract.


2) private method can be used only inside interface.
3) private static method can be used inside other static and non-static interface
methods.
4) private non-static methods cannot be used inside private static methods.

package com.ravi.interface_demo;

interface Acceptable
{
void m1(); //[Abstract Method, JDK 1.0]

default void m2() //[default Method, JDK 1.8]


{
System.out.println("Default Method of an interface");
m4();
m5();
}

static void m3() //[static Method, JDK 1.8]


{
System.out.println("Static Method of an interface");
m5();
}

private void m4() //[Private non static method, JDK 9]


{
System.out.println("Private non Static Method of an interface");
}

private static void m5() //[Private static method, JDK 9]


{
System.out.println("Private Static Method of an interface");
}

/*default void m6()


{
System.out.println("Another Default method");
m4(); //Re-Using our private methods
m5();
}*/

}
class Implementer implements Acceptable
{
@Override
public void m1()
{
System.out.println("Abstract method Implemented");
}
}
public class InterfaceMember
{
public static void main(String[] args)
{
Acceptable a1 = new Implementer();
a1.m1();
a1.m2();
Acceptable.m3();
//a1.m6();

Note : We can achieve 100% abstraction by using private method inside interface.
--------------------------------------------------------------
Can an interface extend a class [Oracle Documentation 9.2]:
------------------------------------------------------------
An interface can't extend a class, It can extend only interface.

Every public method of Object class is implicitly re-declare inside every interface
as an abstract method to support upcasting.

We can't override any public method of object class as a


default method inide interface.

package com.ravi.interface_class;

interface Acceptable
{

public class InterfaceMethods {

public static void main(String[] args)


{
Acceptable a = null;
a.hashCode();
a.toString();
a.equals(null);

}
--------------------------------------------------------------
package com.ravi.interface_class;

interface Hello
{
public default String toString() //error
{
return null;
}
}
public class InterfaceMethods1 {
public static void main(String[] args) {
// TODO Auto-generated method stub

We can't override public non final method of Object class


as a default method inside interface.
-------------------------------------------------------------
package com.ravi.interface_class;

interface Hello
{
@Override
public String toString();

@Override
public boolean equals(Object obj);

@Override
public int hashCode();

}
public class InterfaceMethods1 {

public static void main(String[] args) {


// TODO Auto-generated method stub

The above program is valid but now compiler will not add these 3 public methods of
Object class.
--------------------------------------------------------------
Anonymous inner class with interface:
--------------------------------------
package com.ravi.anonymous_inner_class;

@FunctionalInterface
interface Student
{
void writeExam();
}

public class AnonymousInnerDemo


{
public static void main(String[] args)
{
Student science = new Student()
{
@Override
public void writeExam()
{
System.out.println("Science Students are Writing exam");

}
};
science.writeExam();

Student arts = new Student()


{
@Override
public void writeExam()
{
System.out.println("Arts Students are Writing exam");

};
arts.writeExam();
}

}
---------------------------------------------------------------
Introduction to Functional Programming :
----------------------------------------
What is Lambda Expression in java ?
------------------------------------
It is a new feature introduced in java from JDK 1.8 onwards.
It is an anonymous function i.e function without any name.
In java it is used to enable functional programming.
It is used to concise our code as well as we can remove boilerplate code.
It can be used with functional interface only.
If the body of the Lambda Expression contains only one statement then curly braces
are optional.
We can also remove the variables type while defining the Lambda Expression
parameter.
If the lambda expression method contains only one parameter then we can remove ()
symbol also.

In lambda expression return keyword is optional but if we use return keyword then
{} are compulsory.

Independently Lamda Expression is not a statement.

It requires a target variable i.e functional interface reference only.

Lamda target can't be class or abstract class, it will work with functional
interface only.
-------------------------------------------------------------
Program on Lambda Expression :
------------------------------
package com.ravi.lambda_expression;

@FunctionalInterface
interface Printable
{
void print();
}
public class LambdaDemo1
{
public static void main(String[] args)
{
Printable p = ()-> System.out.println("Printing");
p.print();
}

}
----------------------------------------------------------------------
package com.ravi.lambda_expression;

interface Vehicle
{
void run();
}
public class LambdaDemo2 {

public static void main(String[] args)


{
Vehicle car = ()-> System.out.println("Car is Running");
Vehicle bike = ()-> System.out.println("Bike is Running");
Vehicle bus = ()-> System.out.println("Bus is Running");

car.run(); bike.run(); bus.run();


}

}
-----------------------------------------------------------------------
package com.ravi.lambda_expression;

@FunctionalInterface
interface Calculate
{
void doSum(int x, int y);
}

public class LambdaDemo3


{
public static void main(String[] args)
{
Calculate calc = (c,d) -> System.out.println(c+d);
calc.doSum(12, 24);
}

}
-----------------------------------------------------------------------
package com.ravi.lambda_expression;

@FunctionalInterface
interface Length
{
int getStringLength(String str);
}
public class LambdaDemo4 {

public static void main(String[] args)


{
Length l = str -> str.length();
System.out.println("Length is :"+l.getStringLength("India"));
}

}
-----------------------------------------------------------------------
package com.ravi.lambda_expression;

import java.util.Scanner;

/* If the input number is 0 or negative return -1


* If the input number is even return square of the number
* If the input number is even return cube of the number
* */

@FunctionalInterface
interface Calculator
{
double getSquareAndCube(int num);
}

public class LambdaDemo5 {

public static void main(String[] args)


{
Calculator calc = num ->
{
if(num<=0)
{
return -1;
}
else if(num % 2== 0)
{
return (num*num);
}
else
{
return (num*num*num);
}
};

Scanner sc = new Scanner(System.in);


System.out.print("Enter a number :");
int no = sc.nextInt();

System.out.println(calc.getSquareAndCube(no));

}
-----------------------------------------------------------------------
What is type parameter<T> in java ?
------------------------------------
It is a technique through which we can make our application indepenedent of data
type. It is represented by <T>

In java we can pass Wrapper classes as well as User-defined classes to this type
parameter.

We cannot pass any primitive type to this type parameter.

package com.ravi.lambda_expression;
class Accept<T>
{
private T x;

public Accept(T x)
{
super();
this.x = x;
}

public T getX()
{
return x;
}
}

public class TypeParameterDemo


{
public static void main(String[] args)
{
Accept<Integer> intType = new Accept<Integer>(12);
System.out.println("Integer type :"+intType.getX());

Accept<String> strType = new Accept<String>("NIT");


System.out.println("String type :"+strType.getX());

Accept<Student> stdType = new Accept<Student>(new Student(111));


System.out.println(stdType.getX());
}

record Student(Integer studentId)


{

}
-----------------------------------------------------------------------
30-07-2024
-----------

Working with predefined functional interfaces :


------------------------------------------------------
In order to help the java programmer to write concise java code in day to day
programming java software people has provided the following predefined functional
interfaces

1) Predicate<T> boolean test(T x);


2) Consumer<T> void accept(T x);
3) Function<T,R> R apply(T x);
4) Supplier<T> T get();
5) BiPredicate<T,U> boolean test(T x, U y);
6) BiConsumer<T, U> void accept(T x, U y);
7) BiFunction<T,U,R> R apply(T x, U y);
8) UnaryOperator<T> T apply(T x)
9) BinaryOperator<T> T apply(T x, T y)

Note :-
-------
All these predefined functional interfaces are provided as a part of
java.util.function sub package.

Predicate<T> functional interface :


-------------------------------------------
It is a predefined functional interface available in java.util.function sub
package.

It contains an abstract method test() which takes type parameter <T> and returns
boolean value. The main purpose of this interface to test one argument boolean
expression.

@FunctionalInterface
public interface Predicate<T>
{
boolean test(T x);
}

Note :- Here T is a "type parameter" and it can accept any type of User defined
class as well as Wrapper class like Integer, Float, Double and so on.

We can't pass primitive type.


----------------------------------------------------------------
Programs on Predicate<T> functional interface :
------------------------------------------------
package com.ravi.functional_interface_demo;

import java.util.Scanner;
import java.util.function.Predicate;

public class PredicateDemo1


{
public static void main(String[] args)
{
//Verify whether a number is even or add
Predicate<Integer> p1 = num -> num%2==0;

Scanner sc = new Scanner(System.in);


System.out.print("Enter a number to verify even/odd :");
int no = sc.nextInt();

System.out.println("Is "+no+" even number ?"+p1.test(no));


sc.close();

}
----------------------------------------------------------------------
package com.ravi.functional_interface_demo;

import java.util.Scanner;
import java.util.function.Predicate;

public class PredicateDemo2 {

public static void main(String[] args)


{
// Verify my name starts with 'A' or not ?
Predicate<String> p2 = name -> name.startsWith("A");

Scanner sc = new Scanner(System.in);


System.out.print("Enter your Name :");
String name = sc.nextLine();

System.out.println(name+ " starts with character A :"+p2.test(name));


sc.close();

}
-----------------------------------------------------------------------
package com.ravi.functional_interface_demo;

import java.util.Scanner;
import java.util.function.Predicate;

public class PredicateDemo3 {

public static void main(String[] args)


{
//Verify my name is Ravi or not
Predicate<String> p3 = str -> str.equals("Ravi");

Scanner sc = new Scanner(System.in);


System.out.print("Enter your Name :");
String name = sc.nextLine();

System.out.println("Are you Ravi ?"+p3.test(name));


}

}
-----------------------------------------------------------------------
Assignments :
-------------
1) Using Predicate verify whether a person is eligible for vote or not?

2) Using Predicate verify a year a leap year or not?


-----------------------------------------------------------------------
Consumer<T> functional interface :
-----------------------------------------
It is a predefined functional interface available in java.util.function sub
package.

It contains an abstract method accept() and returns nothing. It is used to accept


the parameter value or consume the value.

@FunctionalInterface
public interface Consumer<T>
{
void accept(T x);
}
-----------------------------------------------------------------------
package com.ravi.functional_interface_demo;

import java.util.function.Consumer;
record Employee(Integer employeeId, String employeeName)
{

public class ConsumerDemo1 {

public static void main(String[] args)


{
Consumer<Integer> c1 = num -> System.out.println(num);
c1.accept(12);

Consumer<String> c2 = str -> System.out.println(str);


c2.accept("NIT");

Consumer<Double> c3 = num -> System.out.println(num);


c3.accept(12.89);

Consumer<Employee> c4 = emp -> System.out.println(emp);


c4.accept(new Employee(111, "Scott"));

Consumer<String> c5 = str -> System.out.println(str.toUpperCase());


c5.accept("India");
}

}
-----------------------------------------------------------------------
Function<T,R> functional interface :
-----------------------------------------
Type Parameters:
T - the type of the input to the function.
R - the type of the result of the function.

It is a predefined functional interface available in java.util.function sub


package.

It provides an abstract method apply that accepts one argument(T) and produces a
result(R).

Note :- The type of T(input) and the type of R(Result) both will be decided by the
user.

@FunctionalInterface
public interface Function<T,R>
{
public abstract R apply(T x);
}
----------------------------------------------------------------------
package com.ravi.functional_interface_demo;

import java.util.Scanner;
import java.util.function.Function;

public class FunctionaDemo1 {

public static void main(String[] args)


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

//Finding the square of the number


Function<Integer, Integer> fn1 = num -> num*num;
System.out.print("Enter a number to find the square :");
int no = sc.nextInt();
System.out.println("Square of "+no+" is :"+fn1.apply(no));

//Finding the length of my city name


Function<String,Integer> fn2 = str -> str.length();
System.out.print("Enter your city name :");
String cityName = sc.nextLine();
cityName = sc.nextLine();
System.out.println("Length of "+cityName+" is :"+fn2.apply(cityName));

//getting String value


Function<String,String> fn3 = str -> 50 + 50 + str + 40 + 40;
System.out.println(fn3.apply("India"));

sc.close();

}
}
-----------------------------------------------------------------------
Supplier<T> Functional Interface :
----------------------------------
Supplier<T> prdefined functional interface :
--------------------------------------------
It is a predefined functional interface available in java.util.function sub
package.

It provides an abstract method get() which does not take any argument but
produces/supply a value of type T.

@FunctionalInterface
public interface Supplier<T>
{
T get();
}
-----------------------------------------------------------------------
package com.ravi.functional_interface_demo;

import java.util.Scanner;
import java.util.function.Supplier;

record Product(Integer productId, String productName, Double productPrice)


{

public class SupplierDemo1


{
public static void main(String[] args)
{
Supplier<Product> s1 = ()->
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Product Id :");
int id = sc.nextInt();

System.out.print("Enter Product Name :");


String name = sc.nextLine();
name = sc.nextLine();

System.out.print("Enter Product Price :");


double price = sc.nextDouble();

return new Product(id, name, price);


};

Product product = s1.get();


System.out.println(product);

}
-----------------------------------------------------------------------
package com.ravi.functional_interface_demo;

import java.util.function.Supplier;

public class SupplierDemo2 {

public static void main(String[] args)


{
Supplier<String> s1 = ()-> 50 + 50 + "NIT" + 40 + 40;
System.out.println(s1.get());

}
-----------------------------------------------------------------------
31-07-2024
-----------
How to create our own functional interfaces with Type parameter :
-----------------------------------------------------------------
package com.ravi.functional_interface_ex;

@FunctionalInterface
interface TriFunction<T,U,V,R>
{
R apply(T t, U u, V v);
}

public class UserDefinedFunctionalInterface


{
public static void main(String[] args)
{
TriFunction<Integer,String,Integer,String> fn = (a,b,c)-> a + b + c;
System.out.println(fn.apply(12, " NIT ", 18));
}

}
-----------------------------------------------------------------------
BiPredicate<T,U> functional interface :
-----------------------------------
It is a predefined functional interface available in java.util.function sub
package.

It is a functional interface in Java that represents a predicate (a boolean-valued


function) OF TWO ARGUMENTS.

The BiPredicate interface has method named test, which takes two parameters and
returns a boolean value, basically this BiPredicate is same with the Predicate,
instead, it takes 2 arguments for the metod test.

@FunctionalInterface
public interface BiPredicate<T, U>
{
boolean test(T t, U u);
}

Type Parameters:

T - the type of the first argument to the predicate


U - the type of the second argument the predicate
Note : return type is boolean.
-----------------------------------------------------------------------
import java.util.function.*;
public class Lambda11
{
public static void main(String[] args)
{
BiPredicate<String, Integer> filter = (x, y) ->
{
return x.length() == y;
};

boolean result = filter.test("Ravi", 4);


System.out.println(result);

result = filter.test("Hyderabad", 10);


System.out.println(result);
}
}
-----------------------------------------------------------------------
import java.util.function.BiPredicate;

public class Lambda12


{
public static void main(String[] args)
{
// BiPredicate to check if the sum of two integers is even
BiPredicate<Integer, Integer> isSumEven = (a, b) -> (a + b) % 2 == 0;

System.out.println(isSumEven.test(2, 3));
System.out.println(isSumEven.test(5, 7));
}
}
-----------------------------------------------------------------------
BiConsumer<T, U> functional interface :
---------------------------------------
It is a predefined functional interface available in java.util.function sub
package.

It is a functional interface in Java that represents an operation that accepts two


input arguments and returns no result.

It takes a method named accept, which takes two parameters and performs an action
without returning any result.

@FunctionalInterface
public interface BiConsumer<T, U>
{
void accept(T t, U u);
}
-----------------------------------------------------------------------
import java.util.function.BiConsumer;

public class Lambda13


{
public static void main(String[] args)
{
BiConsumer<Integer, String> updateVariables = (num, str) ->
{
num = num * 2;
str = str.toUpperCase();
System.out.println("Updated values: " + num + ", " + str);
};

int number = 15;


String text = "nit";

updateVariables.accept(number, text);

// Values after the update (note that the original values are unchanged)
System.out.println("Original values: " + number + ", " + text);
}
}
-----------------------------------------------------------------------
BiFunction<T, U, R> Functional interface :
---------------------------------
It is a predefined functional interface available in java.util.function sub
package.

It is a functional interface in Java that represents a function that accepts two


arguments and produces a result R.

The BiFunction interface has a method named apply that takes two arguments and
returns a result.

@FunctionalInterface
public interface BiFunction<T, U, R>
{
R apply(T t, U u);
}
-----------------------------------------------------------------------
import java.util.function.BiFunction;

public class Lambda14


{
public static void main(String[] args)
{
// BiFunction to concatenate two strings
BiFunction<String, String, String> concatenateStrings = (str1, str2) -> str1 +
str2;

String result = concatenateStrings.apply("Hello", " Java");


System.out.println(result);

// BiFunction to find the length two strings


BiFunction<String, String, Integer> concatenateLength = (str1, str2) ->
str1.length() + str2.length();

Integer result1 = concatenateLength.apply("Hello", "Java");


System.out.println(result1);

}
}
----------------------------------------------------------------------
UnaryOperator<T> :
------------------
It is a predefined functional interface available in java.util.function sub
package.

It is a functional interface in Java that represents an operation on a single


operand that produces a result of the same type as its operand. This is a
specialization of Function for the case where the operand and result are of the
same type.

It has a single type parameter, T, which represents both the operand type and the
result type.

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T,R>
{
public abstract T apply(T x);
}
-----------------------------------------------------------------------
import java.util.function.*;
public class Lambda15
{
public static void main(String[] args)
{
UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(5));

UnaryOperator<String> concat = str -> str.concat("base");


System.out.println(concat.apply("Data"));
}
}
--------------------------------------------------------------------
BinaryOperator<T>
-----------------
It is a predefined functional interface available in java.util.function sub
package.
It is a functional interface in Java that represents an operation upon two operands
of the same type, producing a result of the same type as the operands.

This is a specialization of BiFunction for the case where the operands and the
result are all of the same type.

It has two parameters of same type, T, which represents both the operand types and
the result type.

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,U,R>
{
public abstract T apply(T x, T y);
}
----------------------------------------------------------------------
import java.util.function.*;
public class Lambda16
{
public static void main(String[] args)
{
BinaryOperator<Integer> add = (a, b) -> a + b;
System.out.println(add.apply(3, 5));
}
}
--------------------------------------------------------------
*What is marker interface in java ?
-----------------------------------
A marker interface is an interface which does not contain any field or method,
basically a marker interface is an empty interface or tag interface.

public interface Drawable //Marker interface


{

The main purpose of Marker interface to provide additional information to the JVM
regarding the object like object is Serilizable, Clonable OR
randomly accessible or not.

In java we have 3 predefined marker interfaces : java.io.Serilizable,


java.lang.Cloneable, java.util.RandomAccess.

Note : We can create our own marker interface by using instanceof operator.
--------------------------------------------------------------
****What is difference between abstract class and interface ?
----------------------------------------------------------------
The following are the differences between abstract class and interface.

1) An abstract class can contain instance variables but interface variables are by
default public , static and final.

2) An abstract class can have state (properties) of an object but interface can't
have state of an object.

3) An abstract class can contain constructor but inside an interface we can't


define constructor.

4) An abstract class can contain instance and static blocks but inside an interface
we can't define any blocks.
5) Abstract class can't refer Lambda expression but using Functional interface we
can refer Lambda Expression.

6) By using abstract class multiple inheritance is not possible but by using


interface we can achieve multiple inheritance.

------------------OOPs Completed..............................

Exception Handling :
--------------------
What is an execption ?
----------------------
An execption is a runtime error.

An execption is an abnormal situation or un-expected situation in a noraml


execution flow.

An exception encounter due to dependency, if one part of the program is dependent


to another part then there might be a chance of getting Exception.

AN EXCEPTION ALSO ENCOUNTER DUE TO WRONG INPUT GIVEN BY THE USER.


---------------------------------------------------------------
Different Crieteria of Exception :
----------------------------------
The following are the different criteria for exception :

1) java.lang.ArithmeticException

Whenever we divide a number by 0 (an int value) then we will get


java.lang.ArithmeticException

int x = 10;
int y = 0;
int z = x/y;
System.out.println(z);

2) java.lang.ArrayIndexOutOfBoundsException
If we try to access the index of the array where element is not available then
we will get java.lang.ArrayIndexOutOfBoundsException

int []arr = {10,20,30};


System.out.println(arr[3]); //No value available for 3rd index

3) java.lang.NagativeArraySizeException
Whenever we create an array and if we pass some negative value as
a size of an array then we will will get java.lang.NagativeArraySizeException

int []arr = new int[-10];

4) java.lang.NullPointerException
Whenever we want to call any non static method on the reference
variable which is pointing to null then we will get
java.lang.NullPointerException

String str = null;


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

5) java.lang.NumberFormatException
If we try to convert any String into numeric format but the String
value is not in a proper format then we will get
java.lang.NumberFormatException

String str = "NIT";


int no = Integer.parseInt(str);
System.out.println(no);

6) java.util.InputMismatchException
At the time of taking the input from the Scanner class if input is
not valid from user then we will get java.util.InputMismatchException

Scanner sc = new Scanner(System.in);


System.out.println("Enter your Roll :");
int roll = sc.nextInt(); //Eleven
---------------------------------------------------------------
13-11-2024
-----------
Exception Hierarchy :
--------------------
This Exception hierarchy is available in the diagram (Exception_Hierarchy.png)

Note :- As a developer we are responsibe to handle the Exception. System admin is


responsibe to handle the error because we cannot recover from error.

-------------------------------------------------------------------
Exception format :
------------------
The java software people has provided the format of exception so whenever we print
exception object then the format is

Fully Qualified Name : errorMesage

Package Name + Class Name : errorMessage


-------------------------------------------------------------------
WAP to show that java.lang.Exception is the super class for all the exceptions
(Checked + Unchecked)

package com.ravi.basic;

import java.io.IOException;

public class ExceptionSuper


{
public static void main(String[] args)
{
Exception e = new IOException("Input/Output Exception");
System.out.println(e);

Exception e1 = new ArithmeticException("Divide by zero problem");


System.out.println(e1);
}
}
--------------------------------------------------------------------
WAP that describes that whenever an exception is encounter in the program then
program will be terminated in the middle.

package com.ravi.basic;
import java.util.Scanner;

public class AbnormalTermination


{
public static void main(String[] args)
{
System.out.println("Main method Started!!!");

Scanner sc = new Scanner(System.in);

System.out.print("Enter the value of x :");


int x = sc.nextInt();

System.out.print("Enter the value of y :");


int y = sc.nextInt();

int result = x/y;


System.out.println("Result is :"+result);

System.out.println("Main method Completed!!!");


sc.close();
}
}

In the above program, If we put the value of y as 0 then program will be terminated
in the middle, IT IS CALLED ABNORMAL TERMINATION.
Actually JVM has a default exception handler which is responsible to handle the
execption and terminate the program in the middle abnormaly.
--------------------------------------------------------------------
In order to work with exception, java software people has provided the following
keywords :

1) try block
2) catch block
3) finally block [Java 7 try with resourses]
4) throw
5) throws
====================================================================
Key points to remember :
--------------------------------
-> With try block we can write either catch block or finally block or both.
-> In between try and catch we can't write any kind of statement.
-> try block will trace our program line by line.
-> If we have any exception inside the try block,With the help of JVM, try block
will automatically create the appropriate Exception object and then throw the
Exception Object to the nearest catch block.
-> In the try block whenever we get an exception the control will directly jump to
the nearest catch block so the remaining code of try block will not be executed.
-> catch block is responsible to handle the exception.
-> catch block will only execute if there is an exception inside try block.
--------------------------------------------------------------
try block :
-----------
Whenever our statement is error suspecting statement OR Risky statement then we
should write that statement inside the try block.

try block must be followed either by catch block or finally block or both.
*try block is responsible to trace our code line by line, if any execption
encounter then with the help of JVM, TRY BLOCK WILL CREATE APPROPRIATE EXECPTION
OBJECT, AND THROW THIS EXCEPTION OBJECT to the nearest catch block.

After the execption in the try block, the remaining code of try block will not be
executed because control will directly transfer to the catch block.

In between try and catch block we cannot write any kind of statement.

catch block :
--------------
The main purpose of catch block to handle the exception which is thrown by try
block.

catch block will only executed if there is an exception in the try block.

-------------------------------------------------------------------
package com.ravi.basic;

import java.util.Scanner;

public class TryDemo


{
public static void main(String[] args)
{
System.out.println("Main method started....");
Scanner sc = new Scanner(System.in);

try
{
System.out.print("Enter the value of x :");
int x = sc.nextInt();

System.out.print("Enter the value of y :");


int y = sc.nextInt();

int result = x/y;


System.out.println("Result is :"+result);
System.out.println("End of try block");

}
catch(Exception e)
{
System.out.println("Inside Catch Block");
System.err.println(e);
}
System.out.println("Main method ended....");
sc.close();
}
}

In the above program if we put the value of y as 0 but still program will be
executed normally because we have used try-catch so it is a
normal termination even we have an exception in the program.
--------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
try
{
// System.out.println(10/0);
// OR
throw new ArithmeticException("Ravi is dividing be zero");
}
catch (Exception e)
{
System.out.println("Inside Catch Block");
System.err.println(e);
}
}
}

From the above program it is clear that try block implicitly creating the exception
object with the help of JVM and throwing the execption object to the nearest catch
block.
--------------------------------------------------------------------
he main purpose of Exception handling to provide user-friendly message to our end
user as shown in the program.

package com.ravi.basic;

import java.util.Scanner;

public class CustomerDemo


{
public static void main(String[] args)
{
System.out.println("Hello Client, Welcome to my application");

Scanner sc = new Scanner(System.in);


try
{
System.out.print("Enter the value of a :");
int a = sc.nextInt();

System.out.print("Enter the value of b :");


int b = sc.nextInt();

int result = a/b;


System.out.println("Result is :"+result);

}
catch(Exception e)
{
System.err.println("Sir, don't put zero");
}
sc.close();
System.out.println("Thank you for Visiting my application..");
}
}

Exception handlinag = No Abnormal Termination + User-friendly message on wrong


input given by the client.
====================================================================
14-11-2024
----------
Throwable class Method to print Exception :
--------------------------------------------
Throwable class has provided the following three methods :

1) public String getMessage() :- It will provide only error message.

2) public void printStackTrace() :- It will provide the complete details regarding


exception like exception class name, exception error message, exception class
location, exception method name and exception line number.

3) public String toString() :- It will convert the exception into String


representation.

package com.ravi.basic;

public class PrintStackTrace


{
public static void main(String[] args)
{
System.out.println("Main method started...");
try
{
String x = "NIT";
int y = Integer.parseInt(x);
System.out.println(y);
}
catch(Exception e)
{
e.printStackTrace(); //For complete Exception details
System.out.println("---------------------------");
System.out.println("............................");
System.err.println(e.getMessage()); //only for Exception message
System.out.println("..............");
System.err.println(e.toString());
}
System.out.println("Main method ended...");

}
--------------------------------------------------------------------
Working with Specific Exception :
---------------------------------
While working with exception, in the corresponding catch block we can take
Exception (super class) which can handle any type of Exception.

On the other hand we can also take specific type of exception (ArithmetiException,
InputMismatchException and so on) which will handle only one type i.e specific type
of exception.

public class Test


{
public static void main(String [] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException e) //Specific Exception
{
System.err.println("Divide by zero Problem");
}
System.out.println("Completed");
}
}

--------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
try
{
throw new OutOfMemoryError();
}
catch (Error e) //Specific
{
System.err.println("Some User message");
}
System.out.println("Completed");
}
}

Note : From the try block we are throwing the OutOfmemoryError so , Error OR
Throwable is required in the catch block for handling purpose, If we pass Exception
then catch block will not be executed.
--------------------------------------------------------------------
Working with Infinity and Not a number(NaN) :
---------------------------------------------
10/0 -> Infinity (Java.lang.ArithmeticException)
10/0.0 -> Infinity (POSITIVE_INFINITY)

0/0 -> Undefined (Java.lang.ArithmeticException)


0/0.0 -> Undefined (NaN)

While dividing a number with Integral literal in both the cases i.e Infinity (10/0)
and Undefined (0/0) we will get java.lang.ArithmeticException because java software
people has not provided any final, static variable support to deal with Infinity
and Undefined.

On the other hand while dividing a number with with floating point literal in the
both cases i.e Infinity (10/0.0) and Undefined (0/0.0) we have final, static
variable support so the program will not be terminated in the middle which are as
follows

10/0.0 = POSITIVE_INFINITY
-10/0.0 = NEGATIVE_INFINITY
0/0.0 = NaN

package com.ravi.basic;

public class InfinityFloatingPoint


{
public static void main(String[] args)
{
System.out.println("Main Started");
System.out.println(10/0.0);
System.out.println(-10/0.0);
System.out.println(0/0.0);
System.out.println(10/0);
System.out.println("Main Ended");
}

}
-------------------------------------------------------------------
Working with multiple try catch :
---------------------------------
According to our application requirement we can provide multiple try-catch in my
application to work with multiple execptions.

package com.ravi.basic;
public class MultipleTryCatch
{
public static void main(String[] args)
{
System.out.println("Main method started!!!!");

try
{
int arr[] = {10,20,30};
System.out.println(arr[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Array index is out of limit!!!");
}

try
{
String str = null;
System.out.println(str.length());
}
catch(NullPointerException e)
{
System.err.println("ref variable is pointing to null");
}

System.out.println("Main method ended!!!!");


}
}
--------------------------------------------------------------------
* Single try with multiple catch block :
-----------------------------------------
According to industry standard we should write try with multiple catch blocks so we
can provide proper information for each and every exception to the end user.

While working with multiple catch block always the super class catch block must be
last catch block.

From java 1.7v this multiple exceptions we can write in a single catch block by
using | symbol.

If try block is having more than one exception then always try block will entertain
only first exception because control will transfer to the nearest catch block.

package com.ravi.basic;
public class MultyCatch
{
public static void main(String[] args)
{
System.out.println("Main Started...");
try
{
int c = 10/0;
System.out.println("c value is :"+c);

int []x = {12,78,56};


System.out.println(x[4]);
}

catch(ArrayIndexOutOfBoundsException e1)
{
System.err.println("Array is out of limit...");
}
catch(ArithmeticException e1)
{
System.err.println("Divide By zero problem...");
}
catch(Exception e1)
{
System.out.println("General");
}

System.out.println("Main Ended...");
}
}
--------------------------------------------------------------------
package com.ravi.basic;

public class MultyCatch1


{
public static void main(String[] args)
{
System.out.println("Main method started!!!");
try
{
String str1 = "null";
System.out.println(str1.toUpperCase());

String str2 = "Ravi";


int x = Integer.parseInt(str2);
System.out.println("Number is :"+x);
}
catch(NumberFormatException | NullPointerException e)
{
e.printStackTrace();
}

System.out.println("Main method ended!!");


}

}
-------------------------------------------------------------------
finally block [100% Guaranteed for Exceution]
---------------------------------------------
finally is a block which is meant for Resource handling purposes.

According to Software Engineering, the resources are memory creation, buffer


creation, opening of a database, working with files, working with network resourses
and so on.

Whenever the control will enter inside the try block always the finally block would
be executed.

We should write all the closing statements inside the finally block because
irrespective of exception finally block will be executed every time.

If we use the combination of try and finally then only the resources will be
handled but not the execption, on the other hand if we use try-catch and finally
then execption and resourses both will be handled.

package com.ravi.basic;

public class FinallyBlock


{
public static void main(String[] args)
{
System.out.println("Main method started");

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

}
finally
{
System.out.println("Finally Block");
}

System.out.println("Main method ended");


}

Note :- In the above program finally block will be executed, even we have an
exception in the try block but here only the resourses will be handled but not the
exception.
---------------------------------------------------------------

package com.ravi.basic;

public class FinallyWithCatch


{
public static void main(String[] args)
{
try
{
int []x = new int[-2];
x[0] = 12;
x[1] = 15;
System.out.println(x[0]+" : "+x[1]);
}
catch(NegativeArraySizeException e)
{
System.err.println("Array Size is in negative value...");

}
finally
{
System.out.println("Resources will be handled here!!");
}
System.out.println("Main method ended!!!");
}
}

In the above program exception and resourses both are handled because we have a
combination of try-catch and finally.

Note :- In the try block if we write System.exit(0) and if this line is executed
then finally block will not be executed.
--------------------------------------------------------------------
Limitation of finally Block :
------------------------------
The following are the limitation of finally block :

1) In order to close the resourses, user is responsible to write finally block


manualy.

2) Due to finally block the length of the program will be increased.

3) In order to close the resourses inside the finally block, we need


to declare the resourses outside of try block.

package com.ravi.basic;

import java.util.InputMismatchException;
import java.util.Scanner;

public class FinallyLimitation


{
public static void main(String[] args)
{
Scanner sc = null;
try
{
sc = new Scanner(System.in);
System.out.print("Enter your Age :");
int age = sc.nextInt();
System.out.println("Your Age is :"+age);
}
catch(InputMismatchException e)
{
System.err.println("Please provide numberic value only ");
}
finally
{
System.out.println("Inside finally block");
sc.close();
}
}
}
--------------------------------------------------------------------
try with resources :
--------------------
To avoid all the limitation of finally block, Java software people introduced a
separate concept i.e try with resources from java 1.7 onwards.

Case 1:
-------
try(resource1 ; resource2) //Only the resources will be handled
{
}

Case 2 :
----------
//Resources and Exception both will be handled
try(resource1 ; resource2)
{
}
catch(Exception e)
{
}

Case 3 :
----------
try with resourses enhancement from java 9v

Resourse r1 = new Resourse();


Resourse r2 = new Resourse();

try(r1; r2)
{
}
catch(Exception e)
{
}

There is a predefined interface available in java.lang package called AutoCloseable


which contains predefined abstract method i.e close() which throws Exception.

There is another predefined interface available in java.io package called


Closeable, this Closeable interface is the sub interface for AutoCloseable
interface.

public interface java.lang.AutoCloseable


{
public abstract void close() throws Exception;
}
public interface java.io.Closeable extends java.lang.AutoCloseable
{
void close() throws IOException;
}

Whenever we pass any resourse class as part of try with resources as a parameter
then that class must implements either Closeable or AutoCloseable interface so, try
with resourses will automatically call the respective class
close() method even an exception is encountered in the try block.

ResourceClass rc = new ResourceClass()


try(rc)
{
}
catch(Exception e)
{

This ResourceClass must implements either Closeable or AutoCloseable interface so,


try block will automatically call the close() method as well as try block will get
the guarantee of close() method support in the respective class.

The following program explains how try block is invoking the close() method
available in DatabaseResource class and FileResourse class.

3 files :
----------
DatabaseResourse.java
-----------------------
package com.ravi.try_with_resourse;

public class DatabaseResourse implements AutoCloseable


{
@Override
public void close() throws Exception
{
System.out.println("Database Resourse Closed...");
}

FileResourse.java
------------------
package com.ravi.try_with_resourse;

import java.io.Closeable;
import java.io.IOException;

public class FileResourse implements Closeable


{
@Override
public void close() throws IOException
{
System.out.println("File Resourse Closed..");

Main.java
-----------
package com.ravi.try_with_resourse;

public class Main {


public static void main(String[] args) throws Exception
{
var dr = new DatabaseResourse();
var fr = new FileResourse();
try(dr;fr)
{
System.out.println(10/0);
}

}
--------------------------------------------------------------------
//Program to close Scanner class automatically using try with resourses

package com.ravi.try_with_resourse;

import java.util.InputMismatchException;
import java.util.Scanner;

public class TryWithResourse1 {

public static void main(String[] args)


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

try(sc)
{
System.out.print("Enter your Roll :");
int roll = sc.nextInt();
System.out.println("Your Roll is :"+roll);
}
catch(InputMismatchException e)
{
System.err.println("Please provide numeric value");
}
System.out.println("Execution Completed");

Note :- Scanner class internally implementing Closeable interface so it is


providing auto closing facility from java 1.7, as a user we need to pass the
reference of Scanner class inside try with resources try()

Whenver we write try with resourses then automatically compiler will generate
finally block internally to close the resourses automatically.
====================================================================
16-11-2024
-----------
Nested try block :
------------------
If we write a try block inside another try block then it is called Nested try
block.

try //Outer try


{
statement1;
try //Inner try
{
statement2;
}
catch(Exception e) //Inner catch
{
}
}
catch(Exception e) //Outer Catch
{
}

The execution of inner try block depends upon outer try block that means if we have
an exception in the Outer try block then inner try block will not be executed.
--------------------------------------------------------------------
package com.ravi.basic;

public class NestedTryBlock


{
public static void main(String[] args)
{
try //outer try
{
String x = null;
System.out.println("It's length is :"+x.length());

try //inner try


{
String y = "NIT";
int z = Integer.parseInt(y);
System.out.println("z value is :"+z);

}
catch(NumberFormatException e)
{
System.err.println("Number is not in a proper format");
}
}
catch(NullPointerException e)
{
System.err.println("Null pointer Problem");
}
}
}
------------------------------------------------------------------
Writing try-catch inside catch block :
---------------------------------------
We can write try-catch inside catch block but this try-catch block will be exceuted
if the catch block will executed that means if we have an exception in the try
block.

package com.ravi.basic;

import java.util.InputMismatchException;
import java.util.Scanner;

public class TryWithCatchInsideCatch


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

try(sc )
{
System.out.print("Enter your Roll number :");
int roll = sc.nextInt();
System.out.println("Your Roll is :"+roll);

}
catch(InputMismatchException e)
{
System.err.println("Provide Valid input!!");

try
{
System.out.println(10/0);
}
catch(ArithmeticException e1)
{
System.err.println("Divide by zero problem");
}

}
finally
{
try
{
throw new ArrayIndexOutOfBoundsException("Array is out of
bounds");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Array is out of Bounds");
}
}
}

Note : inside finally block we can write try catch block.


--------------------------------------------------------------------
try-catch with return statement
-------------------------------
If we write try-catch block inside a method and that method is returning some value
then we should write return statement in both the places i.e inside the try block
as well as inside the catch block.

We can also write return statement inside the finally block only, if the finally
block is present. After this return statement we cannot write any kind of
statement. (Unrechable)

Always finally block return statement having more priority then try-catch return
statement.

-------------------------------------------------------------------
package com.ravi.advanced;
public class ReturnExample
{
public static void main(String[] args)
{
System.out.println(methodReturningValue());
}

public static int methodReturningValue()


{
try
{
System.out.println("Try block");
return 10/0;
}
catch (Exception e)
{
System.out.println("catch block");
return 20; //return statement is compulsory
}

}
}
--------------------------------------------------------------------
package com.ravi.advanced;

public class ReturnExample1 {

public static void main(String[] args)


{
System.out.println(m1());
}

@SuppressWarnings("finally")
public static int m1()
{
try
{
System.out.println("Inside try");
return 100;
}
catch(Exception e)
{
System.out.println("Inside Catch");
return 200;
}
finally
{
System.out.println("Inside finally");
return 300;
}

// System.out.println("...."); Unreachable line


}
}
--------------------------------------------------------------------
Initialization of a variable in try and catch :
-----------------------------------------------
A local variable must be initialized inside try block as well as catch block OR at
the time of declaration.

If we initialize inside the try block only then from catch block we cannot access
local variable value, Here initialization is compulsory inside catch block.
--------------------------------------------------------------------
package com.ravi.basic;

public class VariableInitialization


{
public static void main(String[] args)
{
int x;
try
{
x = 100;
System.out.println(x);
}
catch(Exception e)
{
x = 200;
System.out.println(x);
}
System.out.println("Main completed!!!");
}

}
--------------------------------------------------------------------
**Difference between Checked Exception and Unchecked Exception :
----------------------------------------------------------------
Checked Exception :
----------------------
A checked exception is a common exception that must be declared or handled by the
application code where it is thrown, Here compiler takes very much care and wanted
the clarity regarding the exception by saying that, by using this code you may face
some problem at runtime and you did not report me how would you handle this
situation at runtime are called Checked exception, so provide either try-catch or
declare the method as throws.

All the checked exceptions are directly sub class of java.lang.Exception OR


Throwable.

Eg:
---
FileNotFoundException, IOException, InterruptedException,ClassNotFoundException,
SQLException, CloneNotSupportedException, EOFException and so on

Unchecked Exception :-
--------------------------
An unchecked exception is rare and any exception that does not need to be declared
or handled by the application code where it is thrown, here compiler does not take
any care are called unchecked exception.

Unchecked exceptions are directly entertain by JVM because they are rarely occurred
in java.

All the un-checked exceptions are sub class of RuntimeException

RuntimeException is also Unchecked Exception.


Eg:
---
ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
NumberFormatException, ClassCastException, ArrayStoreException and so on.
-----------------------------------------------------------------
Some Bullet points regarding Checked and Unchecked :
-----------------------------------------------------
Checked Exception :
------------------
1) Common Exception
2) Compiler takes care (Will not compile the code)
3) Handling is compulsory (try-catch OR throws)
4) Directly the sub class of java.lang.Exception OR Throwable

Unchecked Exception :
----------------------
1) Rare Exception
2) Comiler will not take any care
3) Handling is not Compulsory
4) Sub class of RuntimeException

When to provide try-catch or declare the method as throws :-


-----------------------------------------------------------
try-catch
----------
We should provide try-catch if we want to handle the exception by own as well as if
we want to provide user-defined messages to the client.

throws :
--------
throws keyword describes that the method might throw an Exception, It also might
not. It is used only at the end of a
method declaration to indicate what exceptions it supports OR what type of
Exception it might throw which will be handled by JVM.

Note :- It is always better to use try catch so we can provide appropriate user
defined messages to our client.

--------------------------------------------------------------------
*Why compiler takes very much care regarding the checked Exception ?
---------------------------------------------------------------
As we know Checked Exceptions are very common exception so in case of checked
exception "handling is compulsory" because checked Exception depends upon other
resources as shown below.

IOException (we are depending upon System Keyboard OR Files )


FileNotFoundException(We are depending upon the file)
InterruptedException (Thread related problem)
ClassNotFoundException (class related problem)
SQLException (SQL related or database related problem)
CloneNotSupportedException (Object is the resourse)
EOFException(We are depending upon the file)
--------------------------------------------------------------------
* What is the difference between throw and throws :
----------------------------------------------------

You might also like