0% found this document useful (0 votes)
7 views413 pages

Understanding Java Language Basics

The document provides an overview of programming languages, focusing on syntax, semantics, and the differences between statically and dynamically typed languages. It also covers Java's history, its compiler and JVM roles, and the importance of functions and methods in Java programming. Additionally, it discusses command line arguments, naming conventions, and the concept of tokens in Java.

Uploaded by

Vaibhav Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views413 pages

Understanding Java Language Basics

The document provides an overview of programming languages, focusing on syntax, semantics, and the differences between statically and dynamically typed languages. It also covers Java's history, its compiler and JVM roles, and the importance of functions and methods in Java programming. Additionally, it discusses command line arguments, naming conventions, and the concept of tokens in Java.

Uploaded by

Vaibhav Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

29-August-23

-------------
A language is a communication media.

Any language contains two important things

1) Syntax (Rules)
2) Semantics (Structure OR Meaning)

English langugae translation :


--------------------------------
Subject + verb + Object (Syntax)

He is a boy. (Valid)

He is a box. (Invalid)

Example of Progamming Language :


----------------------------------------
int a = 10;
int b = 0;
int c = a/b;

Note :-
Syntax of the programming language is taken care by compiler.
compiler generates errors if a user does not follow the syntax of the programming
language.

Semantics is taken care by our runtime Environment. It generates Exception if a


user does not follow the semantics.
----------------------------------------------------------------
30-Aug-23
---------
What is the difference between statically typed(Strongly typed)
and Dynamically typed (loosly typed) language?

Statically(Strongly) typed language :-


---------------------------------------
The languages where data type is compulsory before initialization of a variable are
called statically typed language.
In these languages we can hold same kind of value during the execution of the
program.

Ex:- C,C++,Core Java, C#

Dynamically(Loosly) typed language :-


-------------------------------------------
The languages where data type is not compulsory and it is optional before
initialization of a variable then it is called dynamically typed language.

In these languages we can hold different kind of value during the execution of the
program.
Ex:- Visual Basic, Javascript, Python
----------------------------------------------------------------
Flavors Of JAVA language :
------------------------------
1) JSE (Java Standard Edition) ->J2SE -> Core Java
2) JEE (Java Enterprise Edition) -> J2EE -> Advanced Java

3) JME (Java Micro Edition) -> J2ME -> Android Application

-------------------------------------------------------------------
What is the difference between stand-alone programs and web-related
programs?

Standalone Application
--------------------------
If the creation(development), compilation and execution of the program, everthing
is done in a single system then it is called stand-alone program.
Eg:- C, C++, Java, C# and so on.

Stand alone programs are also known as Software OR Desktop application.

As a developer we should always suggest stand alone application to our client, if


the client data is private or if we want to upload the data in the website then we
need to provide a separate username and password to each and every client.

Web - related Application :-


--------------------------------
If creation of the program, compilation of the program and execution of the
program, Everything is done on different places then it is called web related
program.
Eg:- Advanced Java, PHP, [Link], Python

Web related programs are also known as websites or web application.

As a developer we should suggest website to our client if the client information is


public.
-------------------------------------------------------------------
What is a function :-
-----------------------
A function is a self defined block for any general purpose, calculation or printing
some data.

The major benefits with function are :-


-------------------------------------------
1) Modularity :- Dividing the bigger modules into number of smaller modules where
each module will perform its independent task.

2) Easy understanding :- Once we divide the bigger task into number of smaller
tasks then it is easy to understand the entire code.

3) Reusability :- We can reuse a particular module so many number of times so It


enhances the reusability nature.

Note :- In java we always reuse our classes.

4) Easy Debugging :- Debugging means finding the errors, With function It is easy
to find out the errors because each module is independent with another module.
------------------------------------------------------------------
31-Aug-23
---------

Why we pass parameter to a function :-


--------------------------------------------
We pass parameter to a function for providing more information regrading the
function.

Eg:-

userdefined function predefined function


public void start(int a) start(3);//The fan is running in mode 3
{
//start the fan
}

-----------------------------------------------------------------------------------
---
Why functions are called method in java?
----------------------------------------------
In C++ there is a facility to write a function inside the class as well as outside
of the class by using :: (Scope resolution Operator), But in java all the functions
must be declared inside the class only.

That is the reason member functions are called method in java.

Variable --> Field


function ---> Method
-------------------------------------------------------------------
History of java :
----------------
First Name of Java : OAK (In the year 1991 which is a tree name)

Project Name :- Green Project

Inventor of Java : - James Gosling and his friends

Official Symbol :- Coffee CUP

Java :- Island (Indonesia)


-----------------------------------------------------------------
01-Sep-23
---------
Role of Java Compiler :
-----------------------
1) It will check the syntax.
2) It also checks compatibility issues(LHS = RHS
3) It converts the source code into machine code.
Why java become so popular in the IT Industry ?
-----------------------------------------------------
C and C++ programs are platform dependent programs that means the .exe file created
on one machine will not be executed on the another machine if the system
configuration is different.

That is the reason C and C++ programs are not suitable for website development.

Where as on the other hand java is a platform independent language. Whenever we


write a java program, the extension of java program must be .java. Now this .java
file we submit to java compiler (javac) for compilation process. After successful
compilation the compiler will generate a very special machine code file i.e .class
file (also known as bytecode). Now this .class file we submit to JVM for execution
purpose.
The role of JVM is to load and execute the .class file. Here JVM plays a major role
because It converts the .class file into appropriate machine code instruction
(Operating System format) so java becomes platform independent language and it is
highly suitable for website development.

Note :- We have different JVM for different Operating System that means JVM is
platform dependent technology where as Java is platform Independent technology.
-------------------------------------------------------------------
What is the difference between bit code and bytecode?
-----------------------------------------------------
Bit code is directly understood by Operating System but on the other hand byte code
is understood by JVM, JVM is going to convert this byte code into machine
understandable format.
-------------------------------------------------------------------
Comments in JAVA :-
------------------------
Comments are used to increase the readability of the program. It is ignored by the
compiler.
In java we have 3 types of comments

1) Single line Comment (//)

2) Multiline Comment (/* ------------------------------- */)

3) Documentation Comment (/** -------------------------- */)

/**
Name of the Project : Online Shopping
Date created :- 12-12-2021
Last Modified - 16-01-2022
Author :- Ravishankar
Modules : - 10 Modules
*/
------------------------------------------------------------------
Note :-
1) In java whenever we write a program we need at least a main method which takes
String array as an argument.

2) In java the execution of the program always starts and ends with main method.

Write a program in Java to display Welcome message


--------------------------------------------------
public class Welcome
{
public static void main(String[] args)
{
[Link]("Welcome to Java language !!!");
}
}
-----------------------------------------------------------------
Description of main() method :
-----------------------------------

public :-
--------
public is an access modifier in java. The main method must be declared as public
otherwise JVM cannot execute our main method or in other words JVM can't enter
inside the main method for execution of the program.
If main method is not declared as public then program will compile but it will not
be executed by JVM.

Note :- From java compiler point of view there is no rule to declare our methods as
public.
-----------------------------------------------------------------
static :-
--------
In java our main method is static so JVM need not to create an object to call the
main method.

If a method is declared as a static then we need not to create an object to call


that method.

We can directly call the static methods, if it is defined in the same class on the
other hand if is defined in another class then we can call with the help of class
name.

If we don't declare the main method as static method then our program will compile
but it will not be executed by JVM.
-----------------------------------------------------------------
void :-
-------
It is a keyword. It means no return type. Whenever we define any method in java and
if we don't want to return any kind of value from that particular method then we
should write void before the name of the method.
Eg:

public void input() public int accept()


{ {
} return 15;
}

Note :- In the main method if we don't write void or any other kind of return type
then it will generate a compilation error.

In java whenever we define a method then compulsory we should define return type of
method.(Syntax rule)
-----------------------------------------------------------------
main() :-
----------
It is a user defined function/method because a user is responsible to define some
logic inside the main method.

main() method is very important method because every program execution will start
from main() method only, as well as the execution of the program ends with main()
method only.

Internally JVM is calling this main method with the help of class name.
-----------------------------------------------------------------
Command Line Argument (Introduction):-
-------------------------------------
Whenever we pass an argument/parameter to the main method then it is called Command
Line Argument.

The argument inside the main method is String because String is a alpha-numeric
collection of character so, It can accept numbers,decimals, characters, combination
of number and character.
That is the reason java software people has provided String as a parameter inside
the main method.(More Wider scope to accept the value)
-----------------------------------------------------------------
04-Sep-23
---------
String [] args :-
------------------
Here String is a predefined class available in [Link] package(Header files in C
and C++) and args is an array variable of type String.

Note :- args is an array variable, we can take square bracket before the variable
as well as after the variable.
--------------------------------------------------------------------
[Link]() :-
-------------------------
It is an output statement in java, By using [Link]() statement we can
print anything on the console.

In [Link](), System is a predefined class available in [Link]


package, out is a reference variable of PrintStream class available in [Link]
package and println() is a predfined method available in PrintStream class.

In [Link], .(dot) is a member access operator. It is called as period. It is


used to access the member of the class.
-------------------------------------------------------------------
//Write a program in java to add two number
public class Add
{
public static void main(String[] args)
{
int x = 12;
int y = 24;
int z = x + y;
[Link](z);
}
}

Note :- We are getting the output as 36 but it is not user-friendly


message
--------------------------------------------------------------------
How to provide user-friendly message :
---------------------------------------
//Write a program in java to add two number
public class Add
{
public static void main(String[] args)
{
int x = 12;
int y = 89;
int z = x + y;
[Link]("Sum is :"+z);
}
}
--------------------------------------------------------------------
//Add two numbers without 3rd variable
public class Addition
{
public static void main(String[] args)
{
int x = 12;
int y = 12;
[Link]("Sum is :"+x+y);
[Link](+x+y);
[Link](""+x+y);
[Link]("Sum is :"+(x+y));
}
}
-------------------------------------------------------------------
How to write our first program Eclipse IDE :
--------------------------------------------------
-> It stands for Integrated Development Environment.

-> By using Eclipse IDE , In a single window we can develop, compile and execute
our programs

-> Eclipse IDE provides an environment to execute our program with very less time.
Once the time will be reduced then automatically the cost of the project will be
reduced.

What is a package :
------------------
-> A package is nothing but folder in widows.

-> The main purpose of package to arrange our programs so fast searching will
become easy.

The following command will create a folder having same name with package :

Program :
---------

package [Link];

public class Hello


{
public void m1()
{
}
}

javac -d .[Link] (Compilation style of the programs which


contains package statement in cmd)
----------------------------------------------------------------------
Command Line Argument :
------------------------------
Whenever we pass any argument to the main method then it is called Command Line
Argument.

By using Command Line Argument we can pass some value at runtime.

The advantage of command line argument is "Single time compilation and number of
times execution".
------------------------------------------------------------------
//Write a program to pass some value at runtime using Command Line Argument

public class Command


{
public static void main(String[] x)
{
[Link](x[0]);
}
}

Note :- javac [Link] [Compilation]


java Command "Virat Kohli" [Executing and passing Virat kohli at runtime]
Here It will print Virat Kohli
--------------------------------------------------------------------
05-Sep-23
---------
//WAP in java to add two numbers by using command Line Argument
public class CommandAdd
{
public static void main(String x[])
{
[Link](x[0] + x[1]);
}
}

Note :- In the above program both the values are appended to each other and here
'+' operator behaves like String concatenation operator
----------------------------------------------------------------------
How to convert a String value into integer :
--------------------------------------------
If we want to convert any String value into integer then java software people has
provided a predefined class called Integer available in [Link] package, this
class contains a predefined static method parseInt(String x) through which we can
convert any String value into integer.
This parseInt(String str) method throws an exception
[Link]

//This Integer class is a prdefined class given by java software


public class Integer
{
public static int parseInt(String x)
{
//Logic to convert String into integer and returns integer

return integer value;


}
}
---------------------------------------------------------------------
package [Link];

public class CommandAdd


{
public static void main(String x[])
{
//Converting String to integer
int i = [Link](x[0]);
int j = [Link](x[1]);

[Link]("Sum is :"+(i+j));
}
}

How to execute Command line program in Eclipse IDE :


-------------------------------------------------------------
Right click on the Program -> Run as -> Run configuration -> Arguments -> Program
Argument (Pass some value accroding to your use ) -> Click on Run
----------------------------------------------------------------------
06-Sep-23
---------
Naming convention in java language :
--------------------------------------------
1) How to write a class in java
----------------------------------
While writing a class in java we should follow pascal naming conventation.

ThisIsExampleOfClass (Each word first letter is capital)


Example :
-----------
String
System
Integer
BufferedReader
DataInputStream
ClassNotFoundException
ArithmeticException

2) How to write a method in java :


---------------------------------------
In order to write methods in java we need to follow camel case naming conventation.

thisIsExampleOfMethod()

Example:
----------
read()
readLine()
toUpperCase()
charAt()

3) How to write variable(Fields) in java


--------------------------------------------
In order to write variables in java we need to follow camel case naming convention.

rollNumber;
employeeName;
customerNumber;
customerBill;

4) How to final variabl(Field)


-------------------------------
final double PI = 3.14;
final int A = 90;

5) How to write final and static variable

MAX_VALUE;
MIN_VALUE;
Each character must be capital and in between every word _ symbol should be there.
-----------------------------------------------------------------------
Token :
--------
A token is the smallest unit of the program that is identified by the compiler.
Every Java statements and expressions are created using tokens.

A token can be divided into 5 types

1) Keywords
2) Identifiers
3) Literals
4) Punctuators
5) Operators

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.

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 start()
{
}
}

Here Fan(Name of the class), coil (Name of the variable) and start(Name of the
function) 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
-----------------------------------------------------------------------------------
-
Literals :-
-----------
Assigning some constant value to variable is called Literal.
Java supports 5 types of Literals :

1) Integral Literal Ex:- int x = 15;

2) Floating Point Literal Ex:- float x = 3.5f;

3) Character Literal Ex:- char ch = 'A';

4) Boolean Literal Ex:- boolean b = true;

5) String Literal Ex:- String x = "Naresh i Technology";

Note :- null is also a literal.


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

Ex:- 15, 45, 890

In integral Literal we have 4 data types


a) byte (8 bits )
b) short (16 bits)
c) int (32 bits)
d) long (64 bits)

An integral literal we can specify or represent in different ways

a) Decimal literal (Base 10)


b) Octal literal (Base 8)
c) Hexadecimal literal (Base 16)
d) Binary Literal (Base 2) (Available from JDK 1.7 onwards)

Note :- As a developer we can represent an integral literal in different


forms(decimal, octal, hexadecimal and binary) but JVM always produces the output in
decimal form only

Decimal Literal :-
-------------------
The base of decimal literal is 10. we can accept any digit from 0-9

Octal Literal :-
----------------
The base is 8. Here we can accept digits from 0-7 only. In java if any integral
literal prefeix with '0' (Zero) then it becomes octal lietral.

Example:-

int x = 015; //Valid


int y = 018;//Invalid

Hexadecimal Literal :-
-------------------------
The base is 16. Here we can accept digits from 0-15 (0-9 and A-F). In java if any
integral literal prefix with 0X or 0x (zero with capital X OR zero with small x)
then it becomes hexadecimal literal.
Example :-

int x = 0X15; //Valid


int y = 0x14;//Valid
int z = 0Xadd; //Valid
int a = 0Xage; //Invalid ['g' is out of range]

Binary Literal :-
-----------------
It is introduced from jdk 1.7 onwards. The base or radix is 2. Here we can accept
digits 0 and 1 only. In java if any integral Literal prefix with 0B or 0b (zero
capital B or 0 small b) then it becomes binary literal.

Example :-

int x = 0B111; //Valid


int y = 0b101010; //Valid
int z = 0B12; //Invalid [digit 2 is out of range]

Note :-
------
Being a user we can represent integral literal in decimal, octal, hexadecimal and
binary form but JVM always produces the result in decimal only.
-----------------------------------------------------------------------
07-Sep-23
----------
//Octal literal
public class Test1
{
public static void main(String[] args)
{
int one=01;
int six=06;
int seven=07;
int eight=010;
int nine=011;
[Link]("Octal 01 = "+one);
[Link]("Octal 06 = "+six);
[Link]("Octal 07 = "+seven);
[Link]("Octal 010 = "+eight);
[Link]("Octal 011 = "+nine);
}
}
----------------------------------------------------------------------
//Hexadecimal
public class Test2
{
public static void main(String[] args)
{
int i = 0x10; //16
int j = 0Xadd; //2781
[Link](i);
[Link](j);
}
}
----------------------------------------------------------------------
//Binary Literal
public class Test3
{
public static void main(String[] args)
{
int i = 0b101;
int j = 0B111;
[Link](i); //5
[Link](j); //7
}
}
---------------------------------------------------------------------
By default every integral literal is of type int only but we can specify explicitly
as long type by suffixing with l (small l) OR L (Capital L).

According to industry standard L is more preferable because l (small l) looks like


1(digit 1).

There is no direct way to specify byte and short literals explicitly. If we assign
any integral literal to byte variable and if the value is within the range (-128 to
127) then it is automatically treated as byte literals.

If we assign integral literals to short and if the value is within the range (-
32768 to 32767) then automatically it is treated as short literals.
-----------------------------------------------------------------------
/* By default every integral literal is of type int only*/
public class Test4
{
public static void main(String[] args)
{
byte b = 128; //error becoz 128 is int value
[Link](b);

short s = 32768; //error becoz 32768 is int value


[Link](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;
[Link](s);
}
}
-----------------------------------------------------------------------
//Converting bigger type to smaller type
public class Test6
{
public static void main(String[] args)
{
short s = 136;
byte b = (byte) s;
[Link](b);
}
}
---------------------------------------------------------------------
public class Test7
{
public static void main(String[] args)
{
byte x = (byte) 127L;
[Link]("x value = "+x);

long l = 29L;
[Link]("l value = "+l);

int y = (int) 18L;


[Link]("y value = "+y);

}
}
---------------------------------------------------------------------
08-Sep-23
---------
Java is pure object oriented language or not ?
----------------------------------------------

No, Java is not a pure Object-Oriented language. In fact any language which accepts
the primary data type like int, float, char is not a pure object oriented language
hence java is also not a pure object oriented language.

If we remove all 8 primitive data types from java then Java will become pure object
oriented language.

In java we have a concept called Wrapper classes through which we can convert the
primary data types into corrosponding Wrapper Object.

Primary data types Corrosponding Wrapper Object


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

All these wrapper classes are available in [Link] package.


---------------------------------------------------------------------
//Autoboxing
public class Test8
{
public static void main(String[] args)
{
Integer x = 24;
Integer y = 24;
Integer z = x + y;
[Link]("The sum is :"+z);

Boolean b = true;
[Link](b);

Double d = 90.90;
[Link](d);
}
}
---------------------------------------------------------------------
How to know the minimum and maximum value as well as size of integral literal data
types:
-----------------------------------------------------------------------------------
-
Thses classes (Wrapper classes) are providing the static and final variables
through which we can find out the minimum, maximum value as well as size of the
data types

Example:- I want to find out the range and size of Byte class

Byte.MIN_VALUE = -128

Byte.MAX_VALUE = 127

[Link] = 8 (in bits format)

Here MIN_VALUE, MAX_VALUE and SIZE these are static and final variables available
in these classes(Byte, Short, Integer and Long).
---------------------------------------------------------------------
//Program to find out the range and size of Integeral Data type
public class Test9
{
public static void main(String[] args)
{
[Link]("\n Byte range:");
[Link](" min: " + Byte.MIN_VALUE);
[Link](" max: " + Byte.MAX_VALUE);
[Link](" size :"+[Link]);

[Link]("\n Short range:");


[Link](" min: " + Short.MIN_VALUE);
[Link](" max: " + Short.MAX_VALUE);
[Link](" size :"+[Link]);

[Link]("\n Integer range:");


[Link](" min: " + Integer.MIN_VALUE);
[Link](" max: " + Integer.MAX_VALUE);
[Link](" size :"+[Link]);

[Link]("\n Long range:");


[Link](" min: " + Long.MIN_VALUE);
[Link](" max: " + Long.MAX_VALUE);
[Link](" size :"+[Link]);

}
}
---------------------------------------------------------------------
Underscore Facility in integeral literal :
--------------------------------------------
From java 7v onwards, now we can provide _ symbol while writing the
integral literal just to enhance the readability of the number.

//We can provide _ in integral literal


public class Test10
{
public static void main(String[] args)
{
long mobile = 98_1234_5678L;
[Link]("Mobile Number is :"+mobile);
}
}
--------------------------------------------------------------------
public class Test11
{
public static void main(String[] args)
{
final int x = 12;
byte b = x;
[Link](b);
}
}
-------------------------------------------------------------------
// Converting from decimal to another number system
public class Test12
{
public static void main(String[] argv)
{
//decimal to Binary
[Link]([Link](7));

//decimal to Octal
[Link]([Link](15));

//decimal to Hexadecimal
[Link]([Link](2781));
}
}
---------------------------------------------------------------------
// Converting from decimal to another number system
public class Test12
{
public static void main(String[] argv)
{
//decimal to Binary
[Link]([Link](47));

//decimal to Octal
[Link]([Link](15));

//decimal to Hexadecimal
[Link]([Link](2781));
}
}
-------------------------------------------------------------------
//var keyword from java 10v
public class Test13
{
public static void main(String[] args)
{
var x = 12; //From java 10v
x = 15;
[Link]("x value is :"+x);
}
}
---------------------------------------------------------------------
Floating point Literals :
---------------------------
1) The literals which contains decimal point or fraction are called Floating Point
Literal.

Ex:- 23.89; //Floating Point Literal

2) In floating point literals we have 2 data types


a) float(32 bits)
b) double (64 bits)

3) By default every floating point literal is of type double so the following


expression will generate a compilation error.

float f = 23.90; //error

So now we can have 3 solutions

float f1 = 23.90f;

float f2 = 23.90F;

float f3 = (float) 23.90;

4) As we know by default every floating point literal is of type double but still
we have two flavors given by the java compiler to represent double value explicitly
just to enhance the readability of the code.

a) double d1 = 1.1d;
b) double d2 = 1.1D;

5) *While working with Integral literal we had four flavors i.e decimal, octal,
hexadecimal and binary.
But while working with floating point literal only decimal form is allowed.

6) *Any integral literal we can assign on floating point literal but floating point
literal we can't assign on integral literal.

7) We can represent floating point literal in exponent form.

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


---------------------------------------------------------------------
09-Sep-23
---------
public class Test
{
public static void main(String[] args)
{
float f = 2.0; //error
[Link](f);
}
}
-----------------------------------------------------------------------
public class Test1
{
public static void main(String[] args)
{
//float a = 1.0;
float b = 15.29F;
float c = 15.25f;
float d = (float) 15.25;
[Link](b +" : "+c+" : " +d);

}
}
---------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
double d = 15.15;
double e = 15.15d;
double f = 15.15D;
[Link](d+" : "+e+" : "+f);
}
}
----------------------------------------------------------------------
public class Test3
{
public static void main(String[] args)
{
double x = 0129.89;

double y = 0167;

double z = 0187; //error

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

double y = 0X9.15;

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

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

double b = 0791.0;

double c = 0777;

double d = 0Xdead;

double e = 0Xdead.0; //error


}
}
---------------------------------------------------------------------
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)
{
[Link]("\n Float range:");
[Link](" min: " + Float.MIN_VALUE);
[Link](" max: " + Float.MAX_VALUE);
[Link](" size :"+[Link]);

[Link]("\n Double range:");


[Link](" min: " + Double.MIN_VALUE);
[Link](" max: " + Double.MAX_VALUE);
[Link](" size :"+[Link]);
}
}
----------------------------------------------------------------------
Character Literal :
-------------------
1) It is also known as char literal.

2) In char literal we have one data type i.e char data type which accepts 2 bytes
(16 bits) of memory.

3) There are multiple ways to represent char literal as shown below

a) Single character enclosed with single quotes.

Ex:- char c = 'a';


b) We can assign integral literal to char data type to represent UNICODE
values.
The older languages like C and C++ support ASCII Value whose range is 0-255
only;
The Java language supports UNICODE values where the range is 0- 65535.

c) Char literals we can also assign to integral data types to get the UNICODE
value of that particular character.

d) Char literals we can also represent in UNICODE format where it must contain
4 digit hexadecimal number.

The format is '\uXXXX' [\u0000 to \uffff]

Note :- XXXX is hexadecimal number in digits

e) A charcter starts with \ (Back slash) is called as escape sequence. Every


Escape sequence is also char literal. Java supports the following escape sequences.
In java we have 8 escape sequences
a) \n -> Inserting a new line
b) \t -> For providing tab space
c) \r -> carriage return(move the cursor to the first line)
d) \b -> Inserting a Backspace
e) \f ->(Form feed) Inserts a form feed (For moving to next page)
f) \' -> single quotes
g) \" -> Double quotes
h) \\ -> Back slace
---------------------------------------------------------------------
public class Test1
{
public static void main(String[] args)
{
char ch1 = 'a';
[Link]("ch1 value is :"+ch1);

char ch2 = 97;


[Link]("ch2 value is :"+ch2);

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

char ch2 = 64;


[Link]("ch2 value is :"+ch2);

char ch3 = 1;
[Link]("ch3 value is :"+ch3);
}
}
---------------------------------------------------------------------
public class Test4
{
public static void main(String[] args)
{
char ch1 = 65535;
[Link]("ch1 value is :"+ch1);

char ch2 = 0Xadd;


[Link]("ch2 value is :"+ch2);
}
}

Note :- Here we will get the output as ? because the equivalent language translator
for these particular characters are not available in my system.
----------------------------------------------------------------------
//Addition of two character in the form of Integer
public class Test5
{
public static void main(String txt[ ])
{
int x = 'A';
int y = 'B';
[Link](x+y);
[Link]('A' + 'A');
}
}
--------------------------------------------------------------------
//Range of UNICODE Value (65535)
class Test6
{
public static void main(String[] args)
{
char ch1 = 65535;
[Link]("ch value is :"+ch1);

char ch2 = 65536; //error


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

char ch2 = '\uffff';


[Link](ch2);

char ch3 = '\u0041';


[Link](ch3);

char ch4 = '\u0061';


[Link](ch4);
}
}
----------------------------------------------------------------------
class Test8
{
public static void main(String[] args)
{
char c1 = 'A';
char c2 = 65;
char c3 = '\u0041';

[Link]("c1 = "+c1+", c2 ="+c2+", c3 ="+c3);


}
}
--------------------------------------------------------------------
class Test9
{
public static void main(String[] args)
{
int x = 'A';
int y = '\u0041';
[Link]("x = "+x+" y ="+y);
}
}
----------------------------------------------------------------------
//Every escape sequence is char literal
class Test10
{
public static void main(String [] args)
{
char ch ='\n';
[Link](ch);
}
}
----------------------------------------------------------------------
public class Test11
{
public static void main(String[] args)
{
[Link](Character.MIN_VALUE); //white space
[Link](Character.MAX_VALUE); //?
[Link]([Link]); //16 bits
}
}
----------------------------------------------------------------------
//Java Unicodes
public class Test12
{
public static void main(String[] args)
{
[Link](" Java Unicodes\n");
for (int i = 31; i < 126; i++)
{
char ch = (char)i; // Convert unicode to character
String str = i + " "+ ch;
[Link](str + "\t\t");
if ((i % 5) == 0) // Set 5 numbers per row
[Link]( );
}
}
}
---------------------------------------------------------------------
11-Sep-23
---------
Boolean literal :
-----------------
1) boolean literal contains only one data type i.e boolean data type which accepts
1 bit of memory and it has two states i.e true and false.

2) It takes one bit of memory i.e true or false.

Example:-
boolean isValid = true;
boolean isEmpty = false;

3) Unlike c and c++, In java it is not possible to assign integreal literal to


boolean data type.

boolean b = 0; (Invalid in java but valid in c and c++)


boolean c = 1; (Invalid in java but valid in c and c++)

4) We can't assign String value to boolean data type.

boolean d = "true"; //here true is String literal not boolean, not possible
boolean e = "false";//here false is String literal not boolean, not possible

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

[Link](isValid);
[Link](isEmpty);
}
}
--------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
boolean c = 0; //error
boolean d = 1; //error
[Link](c);
[Link](d);
}
}
---------------------------------------------------------------------
public class Test3
{
public static void main(String[] args)
{
boolean x = "true"; //error
boolean y = "false"; //error
[Link](x);
[Link](y);
}
}
---------------------------------------------------------------------
String Literal :-
----------------
A string literal in Java is basically a sequence of characters. These characters
can be anything like alphabets, numbers or symbols which are enclosed with double
quotes. So we can say String is alpha-numeric collection of character.

How we can create String in Java :-


-----------------------------------
In java String can be created by using 3 ways :-

1) By using String Literal

String x = "Ravi";

2) By using new keyword

String y = new String("Hyderabad");

3) By using character array

char z[] = {'H','E','L','L','O'};

---------------------------------------------------------------------
//Three Ways to create the String Object
public class StringTest1
{
public static void main(String[] args)
{
String s1 = "Hello World"; //Literal
[Link](s1);

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


[Link](s2);

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


[Link](s3);

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

String z = "67.90";
[Link](z);

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

}
}
----------------------------------------------------------------------
Punctuators :
---------------
It is also called separators.

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

() {} [] ; , . @
-----------------------------------------------------------------------------------
-
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

10) new Operator

11) instanceof Operator


---------------------------------------------------------------
Arithmetic Operator OR Binary Operator :
-----------------------------------------------
It is known as Arithmetic Operator OR Binary Operator because it works with minimum
two operands.

Ex:- +, - , *, / and % (Modula Or Modulus Operator)


----------------------------------------------------------------------
//Arithmetic Operator
// Addition operator to join two Strings working as String concatenation optr
public class Test1
{
public static void main(String[] args)
{
String s1 = "Welcome to";
String s2 = " Java ";
String s3 = s1 + s2;
[Link]("String after concatenation :"+s3);

}
}
----------------------------------------------------------------------
How to read the value from the user/keyboard (Accepting the data from client)
-----------------------------------------------------------------------------------
--------
In order to read the data from the client or keyboard, java software people has
provided a predefined class called Scanner available in [Link] package.

It is available from java 5v.

static variables of System class :


------------------------------------
System is a predefined class which contains 3 static variables.

[Link] :- It is used to print normal message on the screen.

[Link] :- It is used to print error message on the screen.

[Link] :- It is used to take input from the user.(Attaching the keyboard with
System resource)

How to create the Object for Scanner class :


--------------------------------------------------
Scanner sc = new Scanner([Link]); //Taking the input from the user

Scanner class provides various methods :


-----------------------------------------------
String next() :- Used to read a single word.

String nextLine() :- Used to read complete line or multiple Words.

byte nextByte() :- Used to read byte value

short nextShort() :- Used to read short value

int nextInt() :- Used to read integer value


float nextFloat() :- Used to read float value

double nextDouble() :- Used to read double value

boolean nextBoolean() :- Used to read boolean value.

char next().charAt(0) :- Used to read a character


--------------------------------------------------------------
//WAP to read your name from the keyboard
import [Link].*;
public class Test2
{
public static void main(String [] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter your Name :");
String name = [Link]();
[Link]("Your Name is :"+name);

}
}
----------------------------------------------------------------------
//BUFFER PROBLEM
import [Link].*;
public class ReadName
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);

[Link]("Enter your roll number :");


int roll = [Link]();

[Link]("Enter your Name :");


String name = [Link](); //Buffer Problem
name = [Link]();

[Link]("Your roll number is :"+roll);


[Link]("Your name is :"+name);

}
}
---------------------------------------------------------------------
//Arithmetic Operator (+, -, *, / , %)
//Reverse of a 3 digit number
import [Link].*;
class Test3
{
public static void main(String[] args)
{
[Link]("Enter a three digit number :");
Scanner sc = new Scanner([Link]);

int num = [Link](); //num = 567

int rem = num % 10; //rem = 7


[Link]("The Reverse is :"+rem); //The reverse is :765

num = num /10; //num = 56


rem = num % 10; //rem = 6
[Link](rem);

num = num/10; //num = 5


[Link](num);
}
}

--------------------------------------------------------------
12-Sep-23
----------
Unary Operator :
--------------------
The operator which works upon single operand is called Unary Operator. Here in java
we have 3 types of unary opertor.

1) Unary minus operator (-)

2) Increment Operator (++)

3) Decrement Operator (--)


---------------------------------------------------------------
//*Unary Operators (Acts on only one operand)
//Unary minus Operator
class Test4
{
public static void main(String[] args)
{
int x = 15;
[Link](-x);
[Link](-(-x));
}
}
---------------------------------------------------------------
//Unary Operators
//Unary Pre increment Operator
class Test5
{
public static void main(String[] args)
{
int x = 15;
int y = ++x; //First increment then assignment
[Link](x+":"+y);
}
}
--------------------------------------------------------------
//Unary Operators
//Unary Post increment Operator
class Test6
{
public static void main(String[] args)
{
int x = 15;
int y = x++; //First assignment then increment
[Link](x+":"+y);
}
}
-------------------------------------------------------------
//Unary Operators
//Unary Pre increment Operator
class Test7
{
public static void main(String[] args)
{
int x = 15;
int y = ++15; //error
[Link](y);
}
}
--------------------------------------------------------------
//Unary Operators
//Unary Pre increment Operator
class Test8
{
public static void main(String[] args)
{
int x = 15;
int y = ++(++x); //error
[Link](y);
}
}
--------------------------------------------------------------

//Unary Operators
//Unary post increment Operator
class Test9
{
public static void main(String[] args)
{
int x = 15;
[Link](++x + x++);
[Link](x);
[Link]("..................");

int y = 15;
[Link](++y + ++y);
[Link](y);
}
}

--------------------------------------------------------------
Note :- Increment and decrement operator we can apply with any data type except
boolean.
---------------------------------------------------------------
//Unary Operators
//Unary post increment Operator
class Test10
{
public static void main(String[] args)
{
char ch ='A';
ch++;
[Link](ch);
}
}
---------------------------------------------------------------
//Unary Operators
//Unary post increment Operator
class Test11
{
public static void main(String[] args)
{
double d = 15.15;
d++;
[Link](d);
}

---------------------------------------------------------------
//Unary Operators
//Unary Pre decrement Operator
class Test12
{
public static void main(String[] args)
{
int x = 15;
int y = --x; //First decrement then assignment
[Link](x+":"+y);
}
}
--------------------------------------------------------------
//Unary Operators
//Unary Post decrement Operator
class Test13
{
public static void main(String[] args)
{
int x = 15;
int y = x--;
[Link](x+":"+y);
}
}
---------------------------------------------------------------
Interview Question
----------------------
Whenever we work with Arithmetic Operator or Unary minus operator, the minimum data
type required is int, So after calculation of expression it is promoted to int
type.

//IQ
class Test14
{
public static void main(String args[])
{
byte i = 1;
byte j = 1;
byte k = i + j; //error
[Link](k);
}
}
-------------------------------------------------------------
class Test15
{
public static void main(String args[])
{
/*byte b = 6;
b = b + 7; //error
[Link](b); */

byte b = 6;
b += 7;//short hand operator b += 7 is equal to (b = b + 7)
[Link](b);

}
}

Note :- In the above program it generates error while working with Arithmetic
Operator but when we change the operator from
Arithmetic to short hand operator then the expression result we can assign on byte
data type.
--------------------------------------------------------------
class Test16
{
public static void main(String args[])
{
byte b = 1;
byte b1 = -b; //error
[Link](b1);
}
}
---------------------------------------------------------------
What is a local variable :
----------------------------
If a variable is declared inside a method body(not as a method parameter) then it
is called Local / Stack/ Temporary / Automatic variable.

Ex:-

public void input()


{
int y = 12;
}

Here in the above example y is local variable.

Local variable we can't use outside of the function or method.

A local variable must be initialized before use otherwise we wiil get compilation
error.

We can't use any access modifier on local variable except final.

Program
---------
public class Test17
{
public static void main(String [] args)
{
int x ; //must be initialized before use
[Link](x);

public int y = 100;//only final is acceptable


[Link](y);
}
}
Note :- In the above program we will get compilation error
-----------------------------------------------------------------------
//Program that shows local variable we cannot use outside of the method
(Diagram 12-SEP)
class StackMemory
{
public static void main(String[] args)
{
[Link]("Main method started..");
m1();
[Link]("Main method ended..");
}
public static void m1()
{
[Link]("m1 method started..");
m2();
[Link]("m1 method ended.."+x);//error
}
public static void m2()
{
int x = 100;
[Link]("I am m2 method!!!"+x);
}
}
Note :- In the above program we have declared x variable inside m2 method and we
want to use x variable inside m1 method which is not
possible becoz x is a local variable.
--------------------------------------------------------------
//*Program on Assignment Operator
class Test18
{
public static void main(String args[])
{
int x = 5, y = 3;
[Link]("x = " + x);
[Link]("y = " + y);

x %= y; //short hand operator x = x % y


[Link]("x = " + x);
}
}
-----------------------------------------------------------------------
Description of [Link]() with program
-------------------------------------------------
//BLC
class Welcome //System
{
static String msg = "Hyderabad";

//static PrintStream out;


}

//ELC
class IQ
{
public static void main(String[] args)
{
[Link]([Link]()); //[Link]()
}

}
-----------------------------------------------------------------------
What is BLC class in java ?
---------------------------
BLC stands for Business Logic class. The class which does not contain main method
and it is only meant for writing logic is called BLC class.

What is ELC class in java ?


---------------------------
ELC stands for Executable Logic class. The class which contains main method and it
is meant executing of our program logic is known as ELC class.

--------------------------------------------------------------------
13-Sep-23
----------
Relational Operator :-
------------------------
These operators are used to compare the values. The return type is boolean. We have
total 6 Ralational Operators.

1) > (Greater than)

2) < (Less than)

3) >= (Greater than or equal to)

4) <= (Less than or equal to)

5) == (double equal to)

6) != (Not equal to )

//*Program on relational operator(6 Operators)


class Test19
{
public static void main(String args[])
{
int a = 10;
int b = 20;
[Link]("a == b : " + (a == b) ); //false
[Link]("a != b : " + (a != b) ); //true
[Link]("a > b : " + (a > b) ); //false
[Link]("a < b : " + (a < b) ); //true
[Link]("b >= a : " + (b >= a) ); //true
[Link]("b <= a : " + (b <= a) ); //false
}
}
--------------------------------------------------------------
If condition :
---------------
It is decision making statement. It is used to test a boolean expression. The
expression must return boolean type.

//Program to check a number is 0 or +ve or -ve


import [Link];
class Test20
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Please enter a Number :");

int num = [Link]();


if(num == 0)
[Link]("It is zero");

else if(num>0)
[Link](num+" is positive");
else
[Link](num+" is negative");

[Link](); //To close Scanner resource


}
}
--------------------------------------------------------------
/*program to calculate telephone bill
For 100 free call rental = 360
For 101 - 250, 1 Rs per call
For 251 - unlimited , 1.2 Rs per call
*/
import [Link].*;
class Test21
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter current Reading :");
int curr_read = [Link]();

[Link]("Enter Previous Reading :");


int prev_read = [Link]();

int nc = curr_read - prev_read;


[Link]("Your Number of call for this month is :"+nc);

double bill = 0.0;


if (nc <=100)
{
bill = 360;
}
else if(nc<=250)
{
bill = 360 + (nc-100)*1.0;
}
else if(nc >250)
{
bill = 360 + 150 + (nc-250)*1.2;
}
[Link]("The bill is :"+bill);
}
}
--------------------------------------------------------------
Nested if:
---------
If an 'if condition' is placed inside another if condition then it is called Nested
if.
In nested if condition, we have one outer if and one inner if condition, the inner
if condition will only execute when outer if condition returns true.

if(condition) //Outer if condition


{
if(condition) //inner if condition
{
}
else //inner else
{
}
}
else //outer else
{
}
--------------------------------------------------------------
//Nested if
//big among three number
class Test22
{
public static void main(String args[])
{
int a =15;
int b =12;
int c =18;

int big=0;

if(a>b) //(Outer if condition)


{
if(a>c) //Nested If Block (inner if)
big=a;
else
big=c;
}
else //already confirmed b is greater than a
{
if(b>c)
big=b;
else
big=c;
}
[Link]("The big number is :"+big);
}
}

Note :- In the above program to find out the biggest number among three number we
need to take the help of nested if condition but the code becomes complex, to
reduce the length of the code Logical Operator came into the picture.
--------------------------------------------------------------

Logical Operator :-
--------------------
It is used to combine or join the multiple conditions into a single statement.

It is also known as short-Circuit logical operator.


In Java we have 3 logical Operators

1) && (AND Logical Operator)

2) || (OR Logical Operator)

3) ! (NOT Logical Operator)

&& :- All the conditions must be true. if the first expression is false it will
not check right side expressions.

|| :- Among multiple conditions, at least one condition must be true. if the


first expression is true it will not check right side expressions.

! :- It is an inverter, it makes true as a false and false as a true.

Note :- The && and || operator only works with boolean operand so the following
code will not compile.

if(5 && 6)
{

}
---------------------------------------------------------------
//*Program on Logical Operator (AND, OR, Not Operator)
//Biggest number among 3 numbers

class Test23
{
public static void main(String args[])
{
[Link] sc = new [Link]([Link]);
[Link]("Enter the value of a :");
int a = [Link]();
[Link]("Enter the value of b :");
int b = [Link]();
[Link]("Enter the value of c :");
int c = [Link]();

int big =0;

if(a>b && a>c)


big = a;
else if(b>a && b>c)
big = b;
else
big = c;
[Link]("The big number is :"+big);
}
}
---------------------------------------------------------------
//OR Operator (At least one condition must be true)
class Test24
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
[Link](a>b || a<c); //true
[Link](b>c || a>c); //false
}
}
-------------------------------------------------------------
// !Operator (not Operator works like an Inverter)
class Test25
{
public static void main(String args[])
{
[Link](!true);
}
}
--------------------------------------------------------------
Boolean Operators :
-----------------------
Boolean Operators work with boolean values that is true and false. It is used to
perform boolean logic upon two boolean expressions.

It is also known as non short circuit. There are two non short circuit logical
operators.

& boolean AND operator (All condions must be true but if first expression is
false still it will check all right side expressions)

| boolean OR operator (At least one condition must be true but if the first
condition is true still it will check all right side expression )
--------------------------------------------------------------
//* Boolean Operators
/*
& boolean AND operator
| boolean OR operator

*/
//Works with boolean values

class Test26
{
public static void main(String[] args)
{
int z = 5;
if(++z > 5 || ++z > 6) //Logical OR
{
z++;
}
[Link](z); //7

[Link]("................");

z = 5;
if(++z > 5 | ++z > 6) //Boolean OR
{
z++;
}
[Link](z); //8
}
}
--------------------------------------------------------------
class Test27
{
public static void main(String[] args)
{
int z = 5;
if(++z > 6 & ++z> 6)
{
z++;
}
[Link](z);
}
}

---------------------------------------------------------------
Bitwise Operator :-
---------------------
In order to work with binary bits java software people has provided Bitwise
operator. It also contains 3 operators

& (Bitwise AND) :- Returns true if both the inputs are true.

| (Bitwise OR) :- Returns false if both the inputs are false

^ (Bitwise X-OR) :- Returns true if both the arguments are opposite to each other.

//Bitwise Operator
class Test28
{
public static void main(String[] args)
{
[Link](true & true); //true
[Link](false | true); //true
[Link](true ^ true); //true

[Link](6 & 7); //6


[Link](6 | 7); //7
[Link](6 ^ 7); //1
}
}
---------------------------------------------------------------
//Bitwise Complement Operator
public class Test29
{
public static void main(String args[])
{
//[Link](~ true);
[Link](~ -8);

}
}
---------------------------------------------------------------
14-Sep-23
---------
Ternary Operator OR Conditional Operator :
--------------------------------------------------
The ternary operator (? :) consists of three operands. It is used to evaluate
boolean expressions. The operator decides which value will be assigned to the
[Link] is used to reduced the size of if-else condition.
//Ternary Operator OR Conditional Operator
public class Test30
{
public static void main(String args[])
{
int a = 60;
int b = 59;
int max = 0;

max=(a>b)?a:b; //Type casting


[Link]("Max number is :"+max);

}
}
--------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
char a = 'A';
int i = 65 ;
[Link](false ? i : a); //Type casting
[Link](true ? a : 65);
}
}

---------------------------------------------------------------
Member access Operator Or Dot Operator :
--------------------------------------------------
It is used to access the member of the class so whenever we want to invoke the
member of the class (fields + methods) then we should use dot(.) operator.

We can directly call any static method and static variable from the main method
with the help of class name , here object is not required as shown in the program
below.

If static variable or static method is present in the same class where main method
is available then we can directly call but if the static variable and static method
is available in another class then to call those static members of the class, class
name is required.

class Welcome
{
static int x = 100;

public static void access()


{
[Link](x);
}
}
public class Test
{

public static void main(String[] args)


{
//Outside of the class(In Welcome class)
[Link]();
Welcome.x = 10;
[Link](Welcome.x);
//Inside the class (Test class)
show();
[Link](y);
}

public static void show()


{
[Link](y);
}

static int y = 200;


}
--------------------------------------------------------------
//* new Operator

This Operator is used to create Object. If the member of the class (field + method)
is static, object is not required. we can directly call with the help of class
name.

On the other hand if the member of the class (variables + method) is not declared
as static then it is called non-static member Or instance member , to call the non-
static member object is required.

class Welcome
{
int x = 100; //non-static variable

public void access() //non-static method


{
[Link](x);
}
}
public class Test
{
public static void main(String[] args)
{
Welcome w = new Welcome();
[Link](w.x);
[Link]();
}

}
-------------------------------------------------------------
instanceof operator :-

1)This Operator will return true/false

2) It is used to check a reference variable is holding the particular/corrosponding


type of Object or not.

3) It is also a keyword.

4) In between the object reference and class name , we must have some kind of
relation (assignment relation) otherwise we will get compilation error.

//* instanceof operator


public class Test
{
public static void main(String[] args)
{
String str = "india";

if(str instanceof String)


{
[Link]("Holding the String object");
}
else
{
[Link]("Not holding the String object");
}

Integer i = 45;
if(i instanceof Number)
{
[Link]("Holding the Integer object");
}
else
{
[Link]("Not holding the Integer object");
}

}
}
--------------------------------------------------------------
Types of variables in java
---------------------------
-> Based on the data type we can define the variable into two
categories

a) Primitive type variables


b) Non-primitive type(Reference type) variable

-> Example of primitive type variables


int x = 15;

-> Example of Reference type variable


Customer c = new Customer();

Here 'c' is reference variable

Note :- Any variable if we declare with the help of class then it is called
reference variable.

-> Based on the declaration position we can define a varible


into 4 categories

a) Instance variable OR Non-Static field


b) Class variable OR Static field
c) Parameter variable
d) Local variable [1 more flavour = block level variable]

Example :
---------
//Primitive Example
public class Test
{
int a = 100; //Instance variable
static int b = 200; //class variable

public static void main(String[] args)


{
Test t = new Test();
[Link](t.a);
[Link](b);
access(300);
}

public static void access(int c) //here c is parameter variable


{
int d = 400; // d is a local variable
[Link](c);
[Link](d);
}
}

//Here a,b,c and d all are primitive variables.

---------------------------------------------------------------------
Reference variable Example :
----------------------------
import [Link].*;
class Student
{
public void show()
{
[Link]("Batch 24 student");
}
}

public class Test


{
Student st = new Student(); //Instance + Reference Variable

//static + Reference Variable


static Scanner sc = new Scanner([Link]);

public static void main(String[] args)


{
Student s1 = new Student(); //s1 is local variable
getObjectData(s1);
}

//here we are assigning s1 variable to st variable


public static void getObjectData(Student st) //st is parameter var
{
[Link]();
}
}
----------------------------------------------------------------
What is Method Signature ?

-> Method Name along with method parameter is called Method


Signature.
---------------------------------------------------------------------
15-Sep-23
----------
Control Statements in java :
------------------------------
What is drawback of if condition :-
---------------------------------------
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.

switch case :-
----------------
In switch case dpending upon the parameter the appropriate case would be executed
otherwise default would be executed.

In this approch we need not to check each and every case, if the appropriate case
is available then directly it would be executed.

break keyword is optional here but we can use as per requirement. It will move the
control outside of the body of the switch.
----------------------------------------------------------------
import [Link].*;
public class SwitchDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Please Enter a Character :");
//Method Chaining

char colour = [Link]().toLowerCase().charAt(0);


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

[Link]("Enter your choice :");


Scanner sc = new Scanner([Link]);
int choice = [Link]();

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

switch(season)
{
case "summer" :
[Link]("It is summer Season!!");
break;

case "rainy" :
[Link]("It is Rainy Season!!");
break;
}
}
}
-----------------------------------------------------------------------

public class Test2


{
public static void main(String[] args)
{
float val = 1;
switch(val) //Error, can't pass long, float and double
{
case 1:
[Link]("Hello");
break;
}
}
}
-----------------------------------------------------------------------
Note :- In the switch statement we can't pass long, float and double value. Strings
are allowed from JDK 1.7 version. enums are allowed from java 5 version.
----------------------------------------------------------------------
Loop in java :
---------------
A loop is nothing but repeatation of statement that means by using loop we can
repeat a statement so many number of times based on specified condition.

In java we have 4 kinds of loop

1) do-while loop
2) while loop
3) for loop
4) for-each loop

do-while loop :-
------------------
It will repeat the statment but in this loop first of all statement will be printed
and then only the condition will verify so it is also called exit control loop.

do
{
statement;
}
while();
----------------------------------------------------------------------
//program on do-while loop
public class Test3
{
public static void main(String [] args)
{
do
{
int x = 1; //error x is block level variable
[Link](x+"\t");
x++;
}
while (x<=10);
}
}
----------------------------------------------------------------------
//Program on do-while loop to print 1-10
public class Test4
{
public static void main(String[] args)
{
int x = 1; //Local variable
do
{

[Link](x+"\n");
x++;
}
while (x<=10);
}
}
-----------------------------------------------------------------------
here basic drawback with do-while loop is, first of all it will print the value and
then only it will check the condition.

To avoid this problem we introduced while loop

while loop :-
-------------
In while loop first of all we will verify the condition, if the condition is true
then only the control will enter inside the body of the loop hence it is known as
entry control loop.

while(condition)
{
statement;
}
----------------------------------------------------------------------
//program on while loop
public class Test5
{
public static void main(String[] args)
{
int x = -1;

while(x>=-10)
{
[Link](x);
x--;
}
}
}
-----------------------------------------------------------------------
//Program on for loop
public class Test6
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
[Link]("i value is :"+i);
}

}
}
-----------------------------------------------------------------------
//Program to accept user input to initialize our loop
import [Link];
public class Test7
{
public static void main(String [] args)
{
[Link]("Please enter a number from where you want to start
the loop : ");
Scanner sc = new Scanner([Link]);
int i = [Link]();
do
{
[Link](i+"\t"); // \t for tab space
i = i + 1;
}
while (i<=100);
}
}
----------------------------------------------------------------------
//WAP in java to print all even number from 1 -100

public class Test8


{
public static void main(String [] args )
{
for(int i=2; i<=100; i=i+2)
{
[Link](i+"\t");
}

}
}
----------------------------------------------------------------------
//WAP to print sum of first 100 natural number (1+2+3+4+.......100)
public class Test9
{
public static void main(String[] args)
{
int sum = 0;

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


{
sum = sum + i;
}

[Link]("The sum is :"+ sum);


}
}
----------------------------------------------------------------------
for-each loop :
----------------
It is introduced from JDK 1.5 onwards.

It is also known as enhanced for loop.

It is used to retrieve the values from the collection.


-----------------------------------------------------------------
import [Link];
public class Test10
{
public static void main(String [] args)
{
int x[] = {89,56,34,12,9};

[Link](x);

for(int y : x)
[Link](y);
}

}
Note :
-------
1) In the above program each value of x is assigning to y variable.

2) x is an array variable but y is an ordinary variable

3) in [Link] package there is a predefined class called Arrays which contains a


static method sort(), by using this static method we can sort an array in ascending
order. sort() method takes Object array as a parameter.
---------------------------------------------------------------
-----------------------------------------------------------------------
public class StringDemo
{
public static void main(String[] args)
{
String []words = {"Java","is","programming","language"};

for(String word : words)


{
[Link](word);
}
}
}
----------------------------------------------------------------------
//Nested loop
public class Test11
{
public static void main(String[] args)
{
int weeks = 4;
int days = 7;

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


{
[Link]("Week: " + i);
for (int j = 1; j <= days; ++j)
{
[Link](" Day: " + j);
}
}
}
}

//break
class Test12
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
if(i==5)
break;
[Link]("i value is :"+i);

}
}
}
----------------------------------------------------------------
//continue (Will skip the current execution sequence)
class Test13
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
if(i==5)
continue;
[Link]("i value is :"+i);
}
}
}
----------------------------------------------------------------------
Working with static Method and return type :
----------------------------------------

/*
* Finding the area of circle
* if radius is 0 or negative then
* return -1 otherwise return area of circle
*
*/

This program contains 2 files :


-----------------------------
[Link](BLC)
----------------
package [Link].method_return;

//BLC
public class Circle
{
public static String getAreaOfCircle(int radius)
{
if(radius <=0)
return "-1";
else
{
final double PI = 3.14;
double area = PI * radius * radius;
return ""+area;
}
}
}

[Link](ELC)
----------------------

package [Link].method_return;

import [Link];
import [Link];

public class AreaOfCircle


{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the radius of the Circle :");
int rad = [Link]();

String areaOfCircle = [Link](rad);

//converting String value to double


double circleArea = [Link](areaOfCircle);

DecimalFormat df = new DecimalFormat("000.000");


[Link]("Area of circle is :"+[Link](circleArea));

}
}

Note :- [Link] package has provided a predefined class called


DecimalFormat, by using this class we can provide the format for decimal
values ("00.00")

This class provides a predefined method format() which accepts double as a


parameter as shown in the above program.
---------------------------------------------------------------------
16-Sep-23
---------
WAP in java to get the student details in String format.

2 files

[Link]
------------
package [Link].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 +"]";

}
}

[Link]
---------
package [Link].pack8;

public class Test


{
public static void main(String[] args)
{
String details = [Link](101, "Ravi", 14000.90);
[Link]("Student Details are :"+details);
}

}
--------------------------------------------------------------------
Program to print the table
---------------------------
2 files
-------
[Link]
-----------
package [Link].pack9;

//BLC
public class Table
{
public static void printTable(int num) //5
{
for(int i=1; i<=10; i++)
{
[Link](num + " X "+i+" = "+(num*i));
}
}
}

[Link]
---------

package [Link].pack9;

import [Link];

//ELC
public class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the number whose table you want to print : ");

[Link]([Link]());
[Link]();
}

}
---------------------------------------------------------------------
16-Sep-23
----------
Object Oriented Programming(OOPs) :
-----------------------------------
An Object is a physical entity which is existing in the real world.

Writing Java program on those Real World Object is known as Object Oriented
Programming.

OOPs is a methdology to develop the programs using class and object.

In object oriented programming we concentrate on Objects.

Every Object contains properties(Data members or Variables) and behavior (Member


function or Method).
Advantages of OOPs
----------------------
We have 3 advantages

1) Modularity (Dividing the bigger modules into smaller one)

2) Reusability (One module we can reuse so many times)

3) Flexibility (Easily add some new Features)

Features of OOPs
--------------------
We have 6 features

1) Class
2) Object
3) Abstraction
4) Encapsulation
5) Inheritance
6) Polymorphism
----------------------------------------------------------------
What is a class ?
------------------
A class is a model/blueprint/template/prototype for creating an object.

A class is userdefined data type which contains data members and member function.

Example :
---------
public classs Student
{
Student Data (Student Variables or Student properties)
+
Student behavior (Function / Method of the student)
}

A class is a logical representation of object.

*A class is a component which is used to define object properties and object


behavior.

Object :
---------
An object is a physical entity.

Anything which is existing in the real world is called as object.

Example :
-----------
Mouse, Laptop, key, pen and so on.

An object has 3 characteristics :


-----------------------------------
1) Identification (Name of the Object)

2) Properties (Variables OR data members)

3) Behavior (Function Or Method.)


----------------------------------------------------------------------
First Object Oriented Program on Laptop
---------------------------------------
package [Link];

public class Laptop


{
//Instance variable (Properties)
String brand;
double price;
double screenSize;

public void usedToWriteProgram()


{
[Link]("We are writing Java program using "+brand+" laptop");
}

public String getLaptopInformation()


{
return "[Laptop : Brand is :"+brand+", Laptop price is :"+price+", Laptop
screen size is :"+screenSize+"]";
}

public static void main(String[] args)


{
Laptop hp = new Laptop();
//Initializing the properties
[Link] = "HP Pavilion";
[Link] = 79000.78;
[Link] = 14.2;

//calling the behavior


[Link]();
String information = [Link]();
[Link](information);

[Link](".....................");

Laptop lanavo = new Laptop();


//Initializing the properties
[Link] = "Lanavo Idea Pad";
[Link] = 60000.90;
[Link] = 15.4;

//calling the behavior


[Link]();
String lanavoInformation = [Link]();
[Link](lanavoInformation);

}
----------------------------------------------------------------------
Default constructor added by the compiler
--------------------------------------------------
In java whenever we write a class and If user does not write any type of
constructor then automatically compiler will add default constructor to the class.
class Test
{
//Here in this class we don't have constructor
}

javac [Link] (At the time of compilation automatically compiler will add
default constructor)

class Test
{
Test() //default constructor added by the compiler
{
}
}
-------------------------------------------------------------------------
----------------------------------------------------------------
Why compiler adds default constructor to our class :
---------------------------------------------------
If the compiler does not add default constructor to our class then object creation
is not possible in java. At the time of object creation by using new keyword we
depend upon the constructor.

Every Java class contains at least one constructor, implicitly added by compiler OR
explicitly written by user.

The main purpose of defualt constructor(added by the compiler) to initialize the


instance variables of the class with some default values.
The default values are:
byte - 0
short - 0
int - 0
long - 0
float - 0.0
double - 0.0
char - (Space)
boolean - false
String - null
Object - null
------------------------------------------------------------------------
//WAP in java to show that default constructor is used to initialize the instance
variable.

public class Student


{
int sno;
String sname;

public void talk()


{
[Link](sno);
[Link](sname);
}
public static void main(String [] args)
{
Student ram = new Student();
[Link]();
}
}
----------------------------------------------------------------------
How to provide our userdefined values for the instance variable :
-----------------------------------------------------------------
The default values provided by compiler are not useful for the user, hence user
will take a separate method (acceptData()) to re-initialize the instance variable
value so the user will get its own userdefined values.

The following program explains how to re-initialize our object property (instance
variable) with method support.

[Link]
-------------
package [Link];

public class Product


{
int prodId;
String prodName;

public void acceptData()


{
prodId = 111;
prodName = "Nikon";
}

public void displayProductData()


{
[Link]("Product Id is :"+prodId);
[Link]("Product Name is :"+prodName);
}

public static void main(String[] args)


{
Product camera = new Product();
[Link]();
[Link]();
[Link]();
}
}
---------------------------------------------------------------------
How to write BLC(Business Logic class ) and ELC (Executable Logic class)
---------------------------------------------------------------
In OOP if we write everything in a single class then it is not an object oriented
approach even we are creating object, It enhances tight coupling (dependency is
very high).

if we separate our classes with BLC and ELC approach then reusability of our BLC
classes would be possible from same package and even from different package.

This package contains 3 files [All these classes are in the same package]
---------------------------------------------------------------------
[Link]
------------
package [Link].blc_elc;

//BLC
public class Player
{
int playerId;
String playerName;
double playerPrice;

public void acceptPlayerData(int id, String name, double price)


{
playerId = id;
playerName = name;
playerPrice = price;
}

public void playerInformation()


{
[Link]("Player Id is :"+playerId);
[Link]("Player Name is :"+playerName);
[Link]("Player Price is :"+playerPrice);
}

[Link]
----------
package [Link].blc_elc;

//ELC
public class Main
{
public static void main(String[] args)
{
Player rohit = new Player();
[Link](45, "Rohit Sharma", 12000.00);
[Link]();

[Link]
----------
package [Link].blc_elc;

public class Virat {

public static void main(String[] args)


{
Player virat = new Player();
[Link](18, "Virat Kohli", 12500.00);
[Link]();
}

In order to re-use this Player class (BLC) class, we have another class called
Dhoni available in another package

[Link]
-----------
package [Link].re_use;
import [Link].blc_elc.Player;

public class Dhoni {

public static void main(String[] args)


{
Player dhoni = new Player();
[Link](7, "MSD", 15890.90);
[Link]();
}

----------------------------------------------------------------------
instance variable :
--------------------
A non-static variable which is declared inside the class but outside of a method is
called instance variable.

The life of an instance variable starts at the time of object creation.

[Instance variable is having strong association with object , we can't think about
instance variable without object]

instance variables are always the part of the object.

As far as as its accessibility is concerned, instance variable we can use anywhere


with object reference.

Parameter variable :
-----------------------
If a variable is declared inside the method parameter (not inside the method body)
then the variables are called as parameter variables.

As far as its scope is concerned, parameters variables we can access within the
same method body but not outside of the method.

----------------------------------------------------------------------
21-Sep-23
----------
this keyword (Diagram):
-----------------------
Whenever our instance variable name and parameter variable name both are same then
at the time of variable initialization our runtime environment gets
confused that which one is an instance variable which one is parameter variable.

To avoid this problem we should use this keyword.

this keyword always refers to the current object and we know that instance
variables are the part of object but not the parameter variable.

this keyword we can't use from a static context because it is a non- static member.

It is also known as variable shadowing.

2 files :
---------
[Link]
-------------
package [Link].this_keyword;
//BLC
public class Customer
{
int custId;
String custName;

//
public void setCustomerData(int custId, String custName)
{
[Link] = custId;
[Link] = custName;

//[Link]();
}

public void getCustomerData()


{
[Link]("Customer Id is :"+custId);
[Link]("Customer Name is :"+custName);
}

[Link]
-----------------

package [Link].this_keyword;
//ELC
public class CustomerDemo {

public static void main(String[] args)


{
new Customer().setCustomerData(111, "Raj");

}
-----------------------------------------------------------------------
Role of instance variable while creating the Object :
-----------------------------------------------------
Whenever we create an object in java, a separate copy of all the instance variables
will be created with each and every object as shown in the program below.

package [Link].this_keyword;

public class Test


{
int x = 10;

public static void main(String[] args)


{
Test t1 = new Test();
Test t2 = new Test();

++t1.x; --t2.x;
[Link](t1.x);
[Link](t2.x);
}

}
-----------------------------------------------------------------------
Working with static variable :
----------------------------------
In static variable only one copy will be created and this single copy will be
sharable by all the objects as shown in the program below.

package [Link].this_keyword;

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;

[Link](d1.x);
[Link](d2.x);
}

Note :

instance variable = MULTIPLE COPIES WITH MULTIPLE OBJECTS

static variable = SINGLE COPY FOR ALL THE OBJECTS


----------------------------------------------------------------------
22-Sep-23
---------
When we should declare a variable as an instance variable and when we should go
with static variable?

Whenever the value of the variable is different with respect to objects then we
should declare the variable as instance variable.

On the other hand if the value of the variable is common for all the objects then
we should declare the variable as a static variable, if we declare static variable
as an instance variable then multiple copies will be created for holding same
value, so there is a westage of memory.

Note :- static variable will save the memory so the overall execution of the
program will become faster.

2 files :-
---------
[Link]
------------
package [Link].instance_static;
//BLC
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)
{
[Link]= rollNumber;
[Link] = studentName;
[Link] = studentAddress;
}

public String getStudentData()


{
return "Student [Roll is :"+[Link]+", Name is :"+this.
studentName+", Address is :"+[Link]+", College Name
is :"
+[Link]+", Course Name is :"+[Link]+"]";

[Link]
-----------------
package [Link].instance_static;

import [Link];

//ELC
public class StudentDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Student Roll Number :");
int roll = [Link]();

[Link]("Enter Student Name :");


String name = [Link]();
name = [Link]();

[Link]("Enter Student Address :");


String addr = [Link]();

Student raj = new Student();


[Link](roll, name, addr);
[Link]([Link]());
[Link]();
}
}
------------------------------------------------------------------------
How to print object properties value (instance variable value) :
----------------------------------------------------------------------
If we want to print object properties value then we need to override a method
called toString() available in [Link] class.

Whenever we override this toString() method in our class then we need not to write
any kind of display() method to display our data(instance variable).

In order to call toString() method we need to print the object reference(name of


the object) using [Link]()

2 files :-

[Link]
------------
package [Link].to_string;
//BLC
public class Manager
{
double managerSalary;
String managerName;

public void setManagerData(double sal, String name)


{
[Link] = sal;
[Link] = name;
}
//Generate toString Automatically to print object properties

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

[Link]
----------------
package [Link].to_string;

//ELC
public class ManagerDemo
{
public static void main(String[] args)
{
Manager m1 = new Manager();
[Link](40000.00, "VK");
[Link](m1); //passing object reference inside the s.o.p
//statement which will automatically call
//toString() method
}

}
-----------------------------------------------------------------------
How to generate toString() method :
-----------------------------------
Right click on the program -> source -> generate toString()
-> select all -> generate
-----------------------------------------------------------------------
Lab Program :
-------------
2 files
--------
[Link]
-------------
package [Link].lab_prog;

public class Manager


{
int managerId;
String managerName;
double managerSalary;
char managerGrade;

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


{
managerId = id;
managerName = name;
managerSalary = salary;
}

public void calculateManagerGrade()


{
if([Link] >=100000)
managerGrade ='A';

else if([Link] >=90000)


managerGrade ='B';

else if ([Link] >=70000)


managerGrade ='C';

else
managerGrade = 'D';
}

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

[Link]
----------------
package [Link].lab_prog;

public class ManagerDemo {

public static void main(String[] args)


{
Manager m1 = new Manager();
[Link](1, "Raj", 95000);
[Link]();
[Link](m1);

}
}
------------------------------------------------------------------------23-Sep-23
---------
Data hiding :
---------------
Data hiding means our data (variables) must be hidden from outer world that means
no one can access our data directly from outside of the class.

To achieve data hiding concept we should declare our class properties or data
members or variables with private access modifier.

We should not provide access of data directly but we can access our data via
methods. Once we are accessing our data through methods then we can PERFORM
VALIDATION ON DATA WHICH ARE COMING FROM OUTER WORLD.

Note :- Data members must be declared as private where as member functions (Method)
must be declared as public.

2 Files :
---------
[Link]
--------------
package [Link].data_hiding;

public class Customer


{
private double balance = 1000; //data hiding

public void deposit(int amount)


{
//Validate the amount
if(amount<=0)
{
[Link]("Amount can't be deposited!!!");
}
else
{
balance = balance + amount;
[Link]("Balance after deposit is :"+balance);
}
}

public void withdraw(int amount)


{
balance = balance - amount;
[Link]("Balance after withdraw is :"+balance);
}
}

[Link]
------------------------
package [Link].data_hiding;

public class BankingApplication


{
public static void main(String[] args)
{
Customer raj = new Customer();
[Link](3000);
[Link](1000);
}
}
-----------------------------------------------------------------------
Abstraction (Hiding the complxcity):
------------------------------------
Abstraction :
--------------
Showing the essential details without showing the background details (non-
essential) is called Abstraction.

In real world a user always interacts with the functionality of the product but not
the data or internal details so for a user method/function is essential details
where as data is non-essential details.

So being a developer we should always hide the data from the user(by declaring them
private) where as on the other hand we should always decalre member function/Method
as public so a user can easily interact with the product.

Example :
-----------
class Fan
{
private int coil;
private int wings;

public void switchOn()


{
}

public void switchOff()


{
}
}

Note :- Here User will interact with the functionality of the fan i.e switchOn and
switchOff but will not interact with data(coil, wings) directly.

Note :- In java we can achieve abstarction by using abstract class and interface
concept.

abstract class provide partial abstraction(0-100%) where as interface provides 100%


abstraction.
-----------------------------------------------------------------------
Encapsulation :-
----------------
Binding the data member with its associated function/method in a single unit is
called encapsulation.

In other words we can say "Grouping the related things together is called
Encapsulation".

In encapsulation data must be tightly coupled with associated function.

It provides us security because we can't access the data directly, data must be
accessible via methods.
We can achieve encapsulation in our program by using following

a) Declare all the data members as private (Tightly encapsulated class)


b) Define getters and setters for each instance variable to perform read and write
operation.

Note :
-----
If we declare all the instance variables with private access modifier then it is
called tightly encapsulated class

On the other hand if some variables are declared with private access modifier and
other variables are not declared with private access modifier then it is called
loosly encapsulated class

2 Files :
---------
[Link]
-------------
package [Link];

public class Student


{
private int rollNumber;

public int getRollNumber() //getter


{
return rollNumber;
}

public void setRollNumber(int rollNumber) //setter


{
[Link] = rollNumber;
}

[Link]
----------------

package [Link];

public class StudentDemo {

public static void main(String[] args)


{
Student s1 = new Student();
[Link](111);
[Link]("My roll Number is :"+[Link]());

}
------------------------------------------------------------------------
25-Sep-23
---------
Constructor :
--------------
Why we write a constructor in a program
OR
what is the benefit of writing constructor in our program :-
-----------------------------------------------------------
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.

(As shown in the diagram 25-09-23)


----------------------------------------------------------------
26-Sep-23
---------
Defination of constructor :
-----------------------------
It is used to construct the object that is why it is called Constructor.

If the name of the class and name of the method both are same then it is called
constructor or in other words constructor is a special method whose name is same as
class name.

*The main purpose of constructor is to initialize the instance variable of the


object.

Every java class has a constructor either explicitly written by the user or
implicitly added by the compiler.

A constructor never containing any return type including void also, if we try to
put the return type then it will become normal method.

A constructor is automatically called and executed at the time of creating object.

A constructor is called and executed once per object that means if we create an
object then automatically the constructor will be called and executed,
again if we create another object for second time then again the constructor will
be called and executed.

In java we have 3 types of constructors :


----------------------------------------------
1) Default constructor

2) No Argument constructor OR Parameterless constructor

3) Parameterized Constructor

----------------------------------------------------------------------
2) No argument constructor :-
----------------------------------
The constructor written by the user in the class without any parameter then it
is called No argument constructor or parameter less constructor or zero argument
constructor.

By using no argument constructor all the objects will be initialized with same
values so it is not recommended approach because we will not be able to customized
each individual object with different value, to avoid this parameterized
constructor came into picture.
[Diagram is available 26-SEp-23]

Ex:-
public class Test
{
int x, y;

public Test() //No argument constructor, written by the user


{
x = 100;
y = 200;
}
}
-----------------------------------------------------------------------
2 files :
---------

[Link]
------------

package [Link].no_arg_cons;

public class Person


{
private Integer personId;
private String personName;
private Double personBill;

public Person() //No-Argument Constructor


{
personId = 111;
personName = "Raj";
personBill = 12890.67;
}

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

[Link]
--------------------------
package [Link].no_arg_cons;

public class NoArgumentConstructor


{
public static void main(String[] args)
{
Person raj = new Person();
[Link](raj);

[Link]("............");

Person ram = new Person();


[Link](ram);

Note :- In the above program we are creating two different objects but
they are containing same data.
----------------------------------------------------------------------
3) Parameterized Constructor :
------------------------------

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

3) Parameterized Constructor :
------------------------------
If one or more argument is passed to the constructor then it is called
parameterized constructor.

If we want to initialize our objects with different values(unlike no argument


constructor) then we should choose parameterized constructor.

public class Test


{
private int x,y;

public Test(int x, int y) //parameterized constructor.


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

Test t1 = new Test(10,20);


Test t2 = new Test(100,200);
----------------------------------------------------------------------

2 files :
---------
[Link]
--------
package [Link].parameterized_constructor;

public class Dog


{
private String dogName;
private int dogAge;
private double dogHeight;

public Dog(String dogName, int dogAge, double dogHeight)


{
super();
[Link] = dogName;
[Link] = dogAge;
[Link] = dogHeight;
}
//Modifying the Dog name
public void setDogName(String dogName) {
[Link] = dogName;
}

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

[Link]
------------------------------
package [Link].parameterized_constructor;

public class ParameterizedConstructor {

public static void main(String[] args)


{
Dog d1 = new Dog("Tiger", 4, 3.2);
[Link]("Lion");
[Link](d1);

[Link]("................");

Dog d2 = new Dog("Tommy",6,3.0);


[Link](d2);

}
-----------------------------------------------------------------------
How many ways to initialize our object properties
--------------------------------------------------------
There are 5 ways to initialize our object properties (instance variables)

1) AT THE TIME OF DECLARTION

class Exapmle
{
int x = 10;
int y = 20;
}

Exapmle e1 = new Exapmle();


Exapmle e2 = new Exapmle();
Exapmle e3 = new Exapmle();

It is not a recommended approach because if we create multiple objects then all


the objects will contain same value.

2) BY USING OBJECT REFERENCE


class Example
{
int x;
int y;

Example e1 = new Example(); e1.x=10; e1.y=20;


Example e2 = new Example(); e2.x=30; e2.y=40;
Example e3 = new Example(); e3.x=50; e3.y=60;
}

It is also not a recommended approach because here the length of the code
will increase as well as the understanability of the code will decrease.

3) BY USING METHODS

class Example
{
int x;
int y;
public void input()
{
x = 100;
y = 200;
}
}

Note :- All the objects will initialize with same value

class Example
{
int x;
int y;
public void input(int x, int y)
{
this.x = x;
this.y = y;
}
}

All the objects will initialize with different values

It this approach variable initialization and variable re-initialization


both will be done in different places so to avoid this constructors are introduced.

4) BY USING CONSTRUCTORS(PARAMETERIZED CONSTRUCTOR)

This is the best approach to initialize our instance variable of the


object in this approach variable initialization and variable re-initialization both
will be done in a single line.

5) BY USING SETTER METHOD

If we want to modify our instance variable then setter is best approach.

SO CONCLUSIUON IS
a) Constructors are used to initialize the object properties
b)
Setters are used to modify the object properties
c)
Methods are used for calculation or printing the data
d)
To print object properties we have toString() method
e)
If Properties are private then to read properties value in
another class we should use getter.
---------------------------------------------------------------------
27-Sep-23
---------
HAS-A Relation :
----------------
Whenever we are using class variable (ref. variable) as a property to another class
then it is called HAS-A relation.

Program on HAS-A relation :


---------------------------
3 Files :
---------
[Link](BLC)
-----------------
package [Link].has_a_reln;

public class College


{
private String collegeName;
private String collegeAddress;

public College(String collegeName, String collegeAddress)


{
super();
[Link] = collegeName;
[Link] = collegeAddress;
}

@Override
public String toString()
{
return "College [collegeName=" + collegeName + ", collegeAddress=" +
collegeAddress + "]";
}

[Link](BLC)
------------------
package [Link].has_a_reln;

public class Student


{
private int studentId;
private String studentName;
private String studentAddress;

private College clg; //HAS-A Relation

public Student(int studentId, String studentName, String studentAddress,


College clg) //clg = c1
{
super();
[Link] = studentId;
[Link] = studentName;
[Link] = studentAddress;
[Link] = clg;
}

@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentAddress=" + studentAddress
+ ", clg=" + clg + "]";
}

[Link]
-------------------------
package [Link].has_a_reln;

public class HasARelationProgram {

public static void main(String[] args)


{
College c1 = new College("NIT", "Hyderabad");

Student s1 = new Student(1, "A", "AMPT", c1);


Student s2 = new Student(2, "B", "SR NAGAR", c1);
[Link](s1);
[Link](s2);

---------------------------------------------------------------------
Another program on HAS-A Relation :
------------------------------------
Program on HAS-A relation :
---------------------------
3 Files :
---------
[Link](BLC)
-----------------
package [Link].has_a_reln;

public class Order


{
private int OrderId;
private String itemName;
private double itemPrice;
private int itemQuantity;

public Order(int orderId, String itemName, double itemPrice, int


itemQuantity) {
super();
OrderId = orderId;
[Link] = itemName;
[Link] = itemPrice;
[Link] = itemQuantity;
}

@Override
public String toString() {
return "Order [OrderId=" + OrderId + ", itemName=" + itemName + ",
itemPrice=" + itemPrice + ", itemQuantity="
+ itemQuantity + "]";
}

[Link](BLC)
-----------------
package [Link].has_a_reln;

public class Customer


{
private int custId;
private String customerName;
private String shippingAddress;
private double totalBill;
private long mobileNumber;
private Order order; //HAS - A Relation

public Customer(int custId, String customerName, String shippingAddress,


double totalBill, long mobileNumber,
Order order) //order = o1
{
super();
[Link] = custId;
[Link] = customerName;
[Link] = shippingAddress;
[Link] = totalBill;
[Link] = mobileNumber;
[Link] = order;
}

@Override
public String toString() {
return "Customer [custId=" + custId + ", customerName=" + customerName
+ ", shippingAddress=" + shippingAddress
+ ", totalBill=" + totalBill + ", mobileNumber=" +
mobileNumber + ", order=" + order + "]";
}

[Link](ELC)
----------------
package [Link].has_a_reln;

public class Zomato {

public static void main(String[] args)


{
//[Link](new Customer(1, "ABC", "b-61, AMPT, HYD", 280.0,
9812345678L, new Order(123,"Butter Chicken",280.00,1)));
Order o1 = new Order(123,"Butter Chicken", 560.00, 2);
Customer c1 = new Customer(1, "ABC", "Ameerpet", 560.00, 9812345678L, o1);
[Link](c1);
}
}
--------------------------------------------------------------------
Passing an object reference to the constructor (Copy Constructor) :
-------------------------------------------------------------------
How to pass an object reference to the constructor :
----------------------------------------------------
The main purpose of passing an object reference to the constructor is to copy the
content of one object to another
object.

3 files :
---------
[Link](BLC)
------------------
package [Link].passing_object_ref;

public class Employee


{
private int employeeNumber;
private String employeeName;

public Employee(int employeeNumber, String employeeName)


{
super();
[Link] = employeeNumber;
[Link] = employeeName;
}

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

public int getEmployeeNumber() {


return employeeNumber;
}

public String getEmployeeName() {


return employeeName;
}

[Link](BLC)
-----------------
package [Link].passing_object_ref;

public class Manager


{
private int managerId;
private String managerName;

public Manager(Employee emp) //emp = e1


{
managerId = [Link]();
managerName = [Link]();
}

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

[Link](ELC)
---------------------------------------
package [Link].passing_object_ref;

public class PassingObjectRefToConstructor


{
public static void main(String[] args)
{
Employee e1 = new Employee(111, "Raj");

Manager m1 = new Manager(e1);


[Link](m1);

}
}
---------------------------------------------------------------------
28-Sep-23
---------
Program on Passing Object Reference to the Constructor :
--------------------------------------------------------
package [Link].passing_object_ref_to_cons;

public class Player


{
private String name1, 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 + "]";
}
}

package [Link].passing_object_ref_to_cons;

public class ObjetReferenceToConstructor


{
public static void main(String[] args)
{
Player p1 = new Player("Rohit", "Virat");
[Link](p1);

[Link]("..............");
Player p2 = new Player(p1);
[Link](p2);
}
}
---------------------------------------------------------------------
Copy Constructor Program :
--------------------------
[Link](BLC)
--------------
package [Link].copy_constr;

public class Milk


{
private double milkPrice;

public double getMilkPrice()


{
return milkPrice;
}

public void setMilkPrice(double milkPrice)


{
[Link] = milkPrice;
}

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

[Link](BLC)
---------------
package [Link].copy_constr;

public class Baby


{
private String babyName;
private int babyAge;
private Milk milk;
private String milkType;

public Baby(String babyName, int babyAge, Milk milk) //milk = m


{
super();
[Link] = babyName;
[Link] = babyAge;
[Link] = milk;

if([Link]() > 60)


{
milkType = "Full Cream";
}
else
{
milkType = "Tonned Milk";
}
}

@Override
public String toString() {
return "Baby [babyName=" + babyName + ", babyAge=" + babyAge + ",
milk=" + milk + ", milkType=" + milkType
+ "]";
}

[Link](ELC)
-------------------------
package [Link].copy_constr;

public class CopyConstructor {

public static void main(String[] args)


{
Milk m = new Milk();
[Link](55);

Baby baby = new Baby("Aardhya", 2, m);


[Link](baby);

}
--------------------------------------------------------------------
Method return type as a class :
--------------------------------
We can take return type of the method as a class. As a return type of method we can
take all primitive data type (byte, Short, int and so on) class name, interface
name;
public class Test
{
public Test m1()
{

return 5;
}
}
---------------------------------------------------------------------
The following program explains how to tale return type of a method as class

2 files :
---------
[Link]
--------------
package [Link].class_as_a_return_type;

import [Link];
import [Link];

public class Employee


{
private int employeeId;
private String employeeName;
private double employeeSalary;
private Date hireDate; //HAS-A Relation

public Employee(int employeeId, String employeeName, double employeeSalary, Date


hireDate) {
super();
[Link] = employeeId;
[Link] = employeeName;
[Link] = employeeSalary;
[Link] = hireDate;
}

public static Employee getEmployeeObject()


{
Scanner sc = new Scanner([Link]);
[Link]("Enter Employee Id :");
int id = [Link]();

[Link]("Enter Employee Name :");


String name = [Link]();
name = [Link]();

[Link]("Enter Employee Salary :");


double salary = [Link]();

Date d = new Date();

Employee e1 = new Employee(id, name, salary, d);

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

[Link]
--------------------------
package [Link].class_as_a_return_type;

import [Link];

public class ClassAsAReturnValue {

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
[Link]("How many objects you want ? ");
int numberOfObjects = [Link]();

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


{
Employee emp = [Link]();
[Link](emp);
}

}
}
------------------------------------------------------------------------
29-Sep-23
---------
LAB Program :
---------------
A BLC 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 CreditCard which contains Main method to test the working of
the above.

Program :
---------
4 files are there :
--------------------
[Link](BLC)
------------------
package [Link].lab_credit_card_program;

public class Customer


{
private String customerName;
private int creditPoints;

public Customer(String customerName, int creditPoints)


{
super();
[Link] = customerName;
[Link] = creditPoints;
}

public int getCreditPoints()


{
return [Link];
}

@Override
public String toString()
{
return ""+[Link];
}

[Link](BLC)
-------------------
package [Link].lab_credit_card_program;

public class CardType


{
private Customer customer;
private String cardType;

public CardType(Customer customer, String cardType)


{
super();
[Link] = customer;
[Link] = cardType;
}

@Override
public String toString()
{
return "The Customer '"+[Link]+"' Is Eligible For
'"+[Link]+"' Card";
}

[Link](BLC)
-----------------------
package [Link].lab_credit_card_program;

public class CardsOnOffer


{
public static CardType getOfferedCard(Customer obj)
{
int creditPoint = [Link]();

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


{
return new CardType(obj, "Silver");
}
else if(creditPoint > 500 && creditPoint <=1000)
{
return new CardType(obj, "Gold");
}
else if(creditPoint > 1000)
{
return new CardType(obj, "Platinum");
}
else
{
return new CardType(obj, "EMI");
}
}
}

[Link](ELC)
---------------------
package [Link].lab_credit_card_program;

import [Link];

public class CreditCard {

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);

[Link]("Enter Customer Name :");


String name = [Link]();

[Link]("Enter Credit Point of Customer :");


int creditPoint = [Link]();

Customer c1 = new Customer(name, creditPoint);

CardType offeredCard = [Link](c1);

[Link](offeredCard);

}
}
-------------------------------------------------------------------------
Lab Program :
-------------
The payroll system of an organization involves calculating the gross salary of each
type of employee and the tax applicable to each.
Create the following entity classes as described below.

Class Employee
Fields: id: int, name : String, basicSalary : double, HRAPer : double, DAPer :
double

Public Method: calculateGrossSalary() - returns a double


Calculate the gross salary as : basicSalary +HRAPer +DAPer

Class Manager
Fields: id: int, name : String, basicSalary : double, HRAPer : double,DAPer :
double, projectAllowance: double
Public Method: calculateGrossSalary() - returns a double
Calculate the gross salary as : basicSalary +HRAPer +DAPer + projectAllowance

Class Trainer
Fields: id: int, name : String, basicSalary : double, HRAPer : double,DAPer :
double, batchCount: int, perkPerBatch: double
Public Method: calculateGrossSalary() - returns a double
Calculate the gross salary as : basicSalary +HRAPer +DAPer +(batchCount *
perkPerBatch)

Class Sourcing
Fields: id: int, name : String, basicSalary : double, HRAPer : double,DAPer :
double, enrollmentTarget: int, enrollmentReached: int, perkPerEnrollment: double
Public Method: calculateGrossSalary() - returns a double

Calculate the gross salary as : basicSalary +HRAPer +DAPer


+((enrollmentReached/enrollmentTarget)*100)*perkPerEnrollment)

Class TaxUtil
Fields: None
Public Methods:
calculateTax(Employee) - returns a double
calculateTax(Manager) - returns a double
calculateTax(Trainer) - returns a double
calculateTax(Sourcing) - returns a double

Tax Calculation Logic: If gross salary is greater than 30000 tax is 20% else, tax
is 5%

Note : Attributes/Fields must be non-Private for the above classes.

A ClassObject class is given to you with the main Method. Use this class to test
your solution.
---------------------------------------------------------------
This Lab program contains 6 files :
------------------------------------
[Link]
-------------
package [Link].lab_prog_tax_util;

public class Employee


{
int id;
String name;
double basicSalary;
double HRAPer;
double DAPer;

public Employee(int id, String name, double basicSalary, double hRAPer, double
dAPer) {
super();
[Link] = id;
[Link] = name;
[Link] = basicSalary;
HRAPer = hRAPer;
DAPer = dAPer;
}

public double calculateGrossSalary()


{
double grossSalary = [Link] + [Link] + [Link];
return grossSalary;
}
}

[Link]
-------------
package [Link].lab_prog_tax_util;

public class Manager


{
int id;
String name;
double basicSalary;
double HRAPer;
double DAPer;
double projectAllowance;

public Manager(int id, String name, double basicSalary, double hRAPer, double
dAPer, double projectAllowance) {
super();
[Link] = id;
[Link] = name;
[Link] = basicSalary;
HRAPer = hRAPer;
DAPer = dAPer;
[Link] = projectAllowance;
}

public double calculateGrossSalary()


{
double grossSalary = [Link] + [Link] +
[Link]+[Link];
return grossSalary;
}
}

[Link]
-------------
package [Link].lab_prog_tax_util;

public class Trainer


{
int id;
String name;
double basicSalary;
double HRAPer;
double DAPer;
int batchCount;
double perkPerBatch;
public Trainer(int id, String name, double basicSalary, double hRAPer, double
dAPer, int batchCount,
double perkPerBatch) {
super();
[Link] = id;
[Link] = name;
[Link] = basicSalary;
HRAPer = hRAPer;
DAPer = dAPer;
[Link] = batchCount;
[Link] = perkPerBatch;
}

public double calculateGrossSalary()


{
double grossSalary = basicSalary +HRAPer +DAPer +(batchCount *
perkPerBatch);

return grossSalary;
}
}

[Link]
--------------
package [Link].lab_prog_tax_util;

public class Sourcing


{
int id;
String name;
double basicSalary;
double HRAPer;
double DAPer;
int enrollmentTarget;
int enrollmentReached;
double perkPerEnrollment;

public Sourcing(int id, String name, double basicSalary, double hRAPer,


double dAPer, int enrollmentTarget,
int enrollmentReached, double perkPerEnrollment) {
super();
[Link] = id;
[Link] = name;
[Link] = basicSalary;
HRAPer = hRAPer;
DAPer = dAPer;
[Link] = enrollmentTarget;
[Link] = enrollmentReached;
[Link] = perkPerEnrollment;
}
public double calculateGrossSalary()
{
double grossSalary = basicSalary +HRAPer +DAPer +
((enrollmentReached/enrollmentTarget)*100)*perkPerEnrollment;
return grossSalary;
}
}

[Link]
-------------
package [Link].lab_prog_tax_util;

public class TaxUtil


{
public double calculateTax(Employee emp)
{

if([Link]() > 30000)


{
return [Link]()*0.20;
}
else
{
return [Link]()*0.05;
}
}
public double calculateTax(Manager man)
{
if([Link]() > 30000)
{
return [Link]()*0.20;
}
else
{
return [Link]()*0.05;
}
}
public double calculateTax(Trainer tnr)
{
if([Link]() > 30000)
{
return [Link]()*0.20;
}
else
{
return [Link]()*0.05;
}
}
public double calculateTax(Sourcing src)
{
if([Link]() > 30000)
{
return [Link]()*0.20;
}
else
{
return [Link]()*0.05;
}
}

[Link]
----------------

package [Link].lab_prog_tax_util;

public class ClassObject {

public static void main(String[] args)


{
Employee e1 = new Employee(101, "Virat", 25000, 3000, 2500);

TaxUtil tu = new TaxUtil();


double tax = [Link](e1);
[Link]("Total tax for Virat in this year is : "+tax);

-------------------------------------------------------------------------
instance block in java
------------------------
It is a new feature introduced in java. The main purpose of instance block to
initialize the instance variable of the class before the constructor, that is the
reason it is also known as instance initializer.

An instance block we can write inside the class even inside the method or
constructor.

An instance block will be automatically placed in the second line of constructor at


the time of compilation.

An instance block will be executed automatically at the time of creating the object
BEFORE THE CONSTRUCTOR BODY EXECUTION.

Instance block will execute once per object that means whenever we create an
object, instance block will be executed.

If we have multiple instance blocks in a class then they would be executed in the
same order as they were written in the class(order wise)

Example :-

//Instance Block

}
------------------------------------------------------------------------
//WAP which displays instance block is executed before the Constructor
body
2 files :
--------
package [Link].instance_block;

public class Instance


{
public Instance()
{
[Link]("No argument Constructor");
}

//instance block
{
[Link]("Instance Block");
}

[Link]
-------------------
package [Link].instance_block;

public class InstanceBlock1 {

public static void main(String[] args)


{
new Instance(); //Nameless Object OR Anonymous object
[Link]("..........");
new Instance();

}
}

Note :- From the above program it is clear that instance block will be executed as
per object.
------------------------------------------------------------------------
WAP in Java that describes instance blocks are executed from top to bottom.

2 files :-
-----------
[Link]
----------
package [Link].instance_block;

public class Test


{
int x;

public Test()
{
[Link](x);
}

{
x = 100;
[Link](x);
}
{
x = 200;
[Link](x);
}

{
x = 300;
[Link](x);
}

[Link]
-------------------
package [Link].instance_block;

public class InstanceBlock2 {

public static void main(String[] args)


{
new Test();
}
}
------------------------------------------------------------------------
Some important points regarding constructor :-

1) We can declare a constructor as private. We should declare constructor


as private due to following two reasons

a) If our class contains only static methods.


b) We want to develop singleton class, singleton class means only one
object is possible by owner of the class.

2) We cannot declare a constructor as a static and final


-------------------------------------------------------------------------
HEAP AND STACK DIAGRAM :
------------------------
What is HEAP Memory ?
---------------------
In java, whenever we create the objects, all the objects are created in a special
memory called HEAP MEMORY.

What is STACK Memory?


---------------------
In java, All the methods are executed as a part of Stack Memory. Whenever we call a
method then stack frame will be created.

What is Garbage Collector ?


---------------------------
Garbage Collector :-
----------------------
In older language like C++, It is the responsibility of the programmer to allocate
the memory as well as to de-allocate the memory otherwise there may be chance of
getting OutOfMemoryError

But in Java a user is not responsible to de-allocate the memory that means memory
allocation is the responsibility of user but memory de-allocation is automatically
done by Garbage Collector.
Garbage collection is the process of looking at heap memory, identifying which
objects are in use and which are not, and deleting the unused objects (The object
which does not contain any references).

It is an automatic memory management in java. JVM internally contains a thread


called Garbage collector, It is responsible to delete the unused objects or the
objects which are not containing any references in the heap memory.

Note :- GC uses an algorithm mark and sweep to make an un-used objects eligible for
Garbage Collection.[Diagram 30-SEP-23]

-----------------------------------------------------------------------
How many ways we can make an object eligible for garbage Collector :
--------------------------------------------------------------------
There are 3 ways to make an Object eligible for Garbage Collector :
----------------------------------------------------------------
1) Assigning a null literal to reference variable

Employee e1 = new Employee();


e1 = null;

2) Creating an object inside the method

public void createObject()


{
Employee e2 = new Employee();
}
Note :- Once the method execution is over automatically Object is eligible for
Garbage Collector

3) Assigning new object to the Existing reference variable

Employee e3 = new Employee();

e3 = new Employee();
----------------------------------------------------------------------
HEAP and STACK diagram for [Link]
-----------------------------------------
[Link] (Single file)
---------------------------
class Customer
{
private String name;
private int id;

public Customer(String name , int id) //constructor


{
[Link]=name;
[Link]=id;
}

public void setId(int id) //setter


{
[Link]=id;
}

public int getId() //getter


{
return id;
}
}

public class CustomerDemo


{
public static void main(String[] args)
{
int val=100;
Customer c = new Customer("Ravi",2);

m1(c);

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

[Link]([Link]());
}

public static void m1(Customer cust)


{
[Link](5);

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

[Link](9);
[Link]([Link]());
}
}

// 9 5
----------------------------------------------------------------------------
HEAP and STACK diagram for [Link]
-----------------------------------------
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 are eligible for GC 1000x,2000x,5000x and 6000x]

[Link](s2.i1);
}
public static Sample modify(Sample s)
{
s.i1=9;
s = new Sample();
s.i1= 20;
[Link](s.i1);
s=null;
return s;
}
}

//20 9
----------------------------------------------------------------------------
HEAP and STACK diagram for [Link]
-----------------------------------------
public class Test
{
Test t;
int val;

public Test(int val)


{
[Link] = val;
}

public Test(int val, Test t)


{
[Link] = 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; //3000x


t3.t = t4; //4000x
t1.t = t2.t; //3000
t2.t = t4.t; //2000x

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}

}
//300 200 400 200
----------------------------------------------------------------------
03-Oct-23
---------
HEAP and STACK diagram for [Link]
--------------------------------------
public class Employee
{
int id=100;
public static void main(String[] args)
{
int val=200;

Employee e1 = new Employee();


[Link]=val;

update(e1);

[Link]([Link]);

Employee e2 = new Employee();

[Link]=500;

switchEmployees(e2,e1);

//GC [2 objects 2000x and 4000x are eligible for Garbage Collector]

[Link]([Link]);
[Link]([Link]);
}

public static void update(Employee e)


{
[Link]=500;
e=new Employee();
[Link]=400;
}

public static void switchEmployees(Employee e1,Employee e2)


{
int temp=[Link];
[Link]=[Link];
e2= new Employee();
[Link]=temp;
}
}

//500 500 500


---------------------------------------------------------------------
Relationship between the classes :
----------------------------------
In java, we have two types of relation between the classes.

a) IS-A Relation (We can achieve by using Inheritance concept)


b) HAS-A Relation(We can achieve by using Association concept)

class Vehicle
{
private Engine engine; \\HAS-A relation

}
class Car extends Vechile
{
//Car IS-A Vehicle so it is creating IS-A relation
}

--------------------------------------------------------------------
04-Oct-23
---------

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 C++ the parent class is called Base class and the child class
is called Derived class, 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 downward more specialized properties will occur.

Types of Inheritance :
----------------------
There are 5 types of Inheritance in java :-

1) Single level Inheritance


2) Multi level Inheritance
3) Hierarchical Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance [Not supported by Java using classes]

WAP in java to implement Single Level Inheritance (Only Basic)


---------------------------------------------------------------
3 files :
---------
[Link]
-----------
package [Link];

public class Super


{
protected int x;
protected int y;

public void setSuperData(int x, int y)


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

[Link]
---------
package [Link];

public class Sub extends Super


{
public void showData()
{
[Link]("x value is :"+x);
[Link]("y value is :"+y);
}
}

[Link]
---------
package [Link];

public class Main


{
public static void main(String[] args)
{
Sub s = new Sub();
[Link](100, 200);
[Link]();

}
------------------------------------------------------------------------
WAP in java to implement Single level inheritance :
----------------------------------------------------
Writing multiple classes in a single file (Not recommended)

1 file :
---------
[Link]
---------------------------
package [Link].single_lev;

class Emp
{
protected int employeeNumber;
protected String employeeName;
protected double employeeSalary;

public void setEmp(int employeeNumber, String employeeName, double


employeeSalary)
{
[Link] = employeeNumber;
[Link] = employeeName;
[Link] = employeeSalary;
}

}
class Pemp extends Emp
{
protected String department;
protected String designation;
public void setPemp(String department, String designation)
{
[Link] = department;
[Link] = designation;
}

@Override
public String toString()
{
return "Pemp [department=" + department + ", designation=" +
designation + ", employeeNumber=" + employeeNumber
+ ", employeeName=" + employeeName + ", employeeSalary=" +
employeeSalary + "]";
}
}

public class SingleLevelInheritance


{
public static void main(String[] args)
{
Pemp pemp = new Pemp();
[Link](101, "Raj", 80000.89);
[Link]("IT", "Developer");
[Link](pemp);
}
}
-------------------------------------------------------------------------
WAP in multilevel Inheritance :
-------------------------------
Single File :
------------
[Link]
--------------------------
package [Link];

class GrandFather
{
public void land()
{
[Link]("1600 SQFT land");
}
}
class Father extends GrandFather
{
public void house()
{
[Link]("3 BHK house");
}
}

class Son extends Father


{
public void car()
{
[Link]("Audi car");
}
}
public class MultiLevelInheritance
{
public static void main(String[] args)
{
Son s1 = new Son();
[Link](); [Link](); [Link]();
}
}
------------------------------------------------------------------------
WAP in java to implement Hierarchical Inheritance :-
-----------------------------------------------------
[Link]
-----------------------------
package [Link];

class Employee
{
protected double salary;
}

class Developer extends Employee


{
public Developer(double salary)
{
[Link] = salary;
}

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

class Designer extends Employee


{
public Designer(double salary)
{
[Link] = salary;
}

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

public class HierarchicalInheritance


{
public static void main(String[] args)
{
[Link](new Developer(80000));
[Link](new Designer(25000));
}

}
-------------------------------------------------------------------------
05-Oct-23
---------
super keyword :
---------------
It is a keyword in java which is used to access the member of super class.

super keyword we can use in 3 ways in java :

1) To call the super class variable


2) To call the super class Method
*3) To call the super class constructor

1) To call the variable of the super class


--------------------------------------------
Whenever super class variable name and sub class variable name both are same
and if we create an object for the sub class then the sub class will provide more
priority to its own class variable, If we want to invoke the super class variable
then we should use super keyword. It is also known as variable shadow (Hiding of
variable)

super keyword always refers to its immediate super class.

Note :- We should use super keyword when the super class member name and sub
class member name both are same as welll as We can't use super keyword from static
context.

3 files :
----------
[Link]
------------
package [Link].super_var;

public class Father


{
protected double balance = 50000;
}

[Link]
--------
package [Link].super_var;

public class Son extends Father


{
protected double balance = 18000;

public Son()
{
[Link]("Son balance is :"+balance);
[Link]("Father balance is :"+[Link]);
}
}
[Link]
-------------
package [Link].super_var;

public class SuperVar


{
public static void main(String[] args)
{
Son s1 = new Son();
}
}
------------------------------------------------------------------------
2) To call the method of the super class
---------------------------------------------
Whenever super class method name and sub class method name both are same and if
we create an object for the sub class then by default it will invoke or call the
sub class method, if we want to call the super class method then we should use
super keyword.
-------------------------------------------------------------------------
1 file [Link]
------------------------
package [Link].super_method;

class A
{
public void show()
{
[Link]("Show method of super class...");
}
}

class B extends A
{
public void show()
{
[Link]("Show method of Sub class...");
[Link]();
}
}

public class SuperMethod


{
public static void main(String[] args)
{
new B().show();

}
}
--------------------------------------------------------------------
06-Oct-23
---------
*3) To call 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 constructor to the
class.

THE FIRST LINE OF ANY CONSTRUCTOR IS RESERVERD EITHER FOR super() or this()
keyword.
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() :- To call the no-argument constructor or default constructor of the super
class. It is automatically added by the compiler.

[Link] [Single File Approach]


-----------------------------------------------------
package [Link].super_this;

class A
{
public A()
{
[Link]("No Argument constructor of Super class");
}
}

class B extends A
{
public B()
{
[Link]("No Argument constructor of Sub class");
}
}

public class CallingNoArgsConstructor


{
public static void main(String[] args)
{
B b1 = new B();
}
}

Note :- From the above program it is clear that, super() is added by compiler to
the first line of constructor so, the control will reach to Object class first to
maintain the hierarchy.
----------------------------------------------------------------------
CASE 2 :-
----------
super("NIT") :- To call the parameterized constructor of super class

package [Link].super_this;

class Parent
{
public Parent(String str)
{
[Link]("My Institute Name is :"+str);
}
}

class Child extends Parent


{
public Child()
{
super("NIT");
[Link]("No Argument Constructor of Child class");
}
}
public class ParameterizedCall
{
public static void main(String[] args)
{
Child c = new Child();
}
}
----------------------------------------------------------------------
CASE 3 :-
---------
this() :- It is used to call no argument constructor of current class

[Link][Single File Approach]


-------------------------------------------------------
package [Link].super_this;

class Super
{
public Super()
{
[Link]("No-Args constructor of Super class");
}

public Super(String str)


{
this();
[Link]("Parameterized constructor :"+str);
}
}
class Sub extends Super
{
public Sub()
{
super("NIT");
[Link]("No-Args constructor of Sub class");
}
}

public class CallingNoArgumentOfSameClass


{
public static void main(String[] args)
{
Sub s1 = new Sub();
}

}
----------------------------------------------------------------------
CASE 4 :-
----------
this("Ravi") :- It is used to invoked parameterized constructor of
current class.

[Link][Single File Approach]


----------------------------------------------------------------------
package [Link].super_this;

class Base
{
public Base()
{
this(100,200);
[Link]("No argument constructor of Base class");
}

public Base(int x, int y)


{
[Link]("Sum is :"+(x+y));
}
}
class Derived extends Base
{
public Derived()
{
[Link]("No argument constructor of Derived class");
}
}
public class CallingParameterizedConstructorOfSameClass
{
public static void main(String[] args)
{
Derived d1 = new Derived();
}

}
----------------------------------------------------------------------
[Link][Single File Approach]

package [Link].super_this;

class Employee
{
private int empId;
private String empName;

public Employee()
{
this(222,"Rahul");
[Link] = 111;
[Link] = "Raj";
}

public Employee(int id, String name)


{

[Link](id);
[Link](name);
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + "]";
}

public class ConstructorChaining


{
public static void main(String[] args)
{
Employee e1 = new Employee();
[Link](e1);
}

}
----------------------------------------------------------------------
Program on super keyword, to call parameterized constructor of super class
by using Single level Inheritance
--------------------------------------------------------------------------
package [Link].super_ex;

import [Link];

class Shape
{
protected int x;
public Shape(int x)
{
this.x = x;
[Link]("x value is :"+x);
}
}

class Square extends Shape


{
public Square(int side) //5
{
super(side);
}

public void areaOfSquare()


{
[Link]("Area of Square is :"+(x*x));
}
}
public class SuperShapeExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the side of Square :");
int side = [Link]();

Square sq = new Square(side);


[Link]();
}

}
--------------------------------------------------------------------------
Program on super keyword, to call parameterized constructor of super class
by using Hierarchical Inheritance
--------------------------------------------------------------------------
package [Link].super_hierarchical;
class Shape
{
protected int x;
public Shape(int x)
{
this.x = x;
[Link]("x value is :"+x);
}
}
class Rectangle extends Shape
{
protected int breadth;
public Rectangle(int length, int breadth)
{
super(length);
[Link] = breadth;
}

public void areaOfRectangle()


{
[Link]("Area of Rectangle :"+(x*breadth));
}
}

class Circle extends Shape


{
protected final double PI=3.14;

public Circle(int radius)


{
super(radius);
}
public void areaOfCircle()
{
[Link]("Area of circle is :"+(PI*x*x));
}
}

public class ShapeExample {

public static void main(String[] args)


{
Rectangle rr = new Rectangle(10, 15);
[Link]();

Circle cr = new Circle(9);


[Link]();
}

}
--------------------------------------------------------------------------
Program on super keyword using Hierarchical Inheritance :
----------------------------------------------------------
4 files :
----------
[Link]
-------------
package [Link].super_hierarchical;

public class Employee


{
protected int employeeId;
protected String employeeName;
protected String employeeRole;

public Employee(int employeeId, String employeeName, String employeeRole) {


super();
[Link] = employeeId;
[Link] = employeeName;
[Link] = employeeRole;
}

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

[Link]
------------
package [Link].super_hierarchical;

public class Manager extends Employee


{
protected double managerSalary;

public Manager(int employeeId, String employeeName, String employeeRole, double


managerSalary) {
super(employeeId, employeeName, employeeRole);
[Link] = managerSalary;
}

@Override
public String toString() {
return [Link]()+"Manager [managerSalary=" + managerSalary +
"]";
}
}

[Link]
--------
package [Link].super_hierarchical;

public class HR extends Employee


{
protected double hrSalary;

public HR(int employeeId, String employeeName, String employeeRole, double


hrSalary) {
super(employeeId, employeeName, employeeRole);
[Link] = hrSalary;
}

@Override
public String toString() {
return [Link]()+"HR [hrSalary=" + hrSalary + "]";
}
}

[Link]
------------------
package [Link].super_hierarchical;

public class EmployeeDemo {

public static void main(String[] args)


{
Manager raj = new Manager(101,"Raj","Manager",80000);
[Link](raj);

HR sweta = new HR(201, "Sweta", "HR", 120000);


[Link](sweta);
}

}
-------------------------------------------------------------------------
07-Oct-23
---------
*Why java does not support multiple inheritance ?
-------------------------------------------------
Whenever a sub class wants to inherit the properties of two or more super classes
and both the super class contains same method name then it leads ambiguity problem
for the sub class to invoke the method of super classes as shown in our example
(diagram 07-OCT-23)

In our example two super classes i.e class A and class B contain doSum(int x, int
y) method and there is a sub class called C which try to extends two super classes
i.e A and B.

For sub class C, it is difficult to call doSum(int x , int y) method because there
would be an ambiguity problem.

That is the reason java does not support multiple inheritance using classes also
known as "Diamond Problem" in java, but same(multiple inheritance) we can achieve
by using interface concept later.
In java multiple inheritance is possible using interfaces but not by using the
classes.
--------------------------------------------------------------------------
IQ
--
class A
{
public A(double d)
{
[Link](d);
}
}
class Test extends A
{
public static void main(String[] args)
{
A a1 = new A(5);
}
}
--------------------------------------------------------------------------
10-Oct-23
----------
Access modifiers in java :
-----------------------------
An access modifiers describes the accessibility scope of the classes as well as the
member of the classes.

In java we have 4 access modifiers

1) private (Within the same class)

2) default (Within the same package)

3) protected (Accessible from another package but using inheritance)

4) public (No restriction, Accessible from everywhere)

private :-
---------
It is an access modifier and 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 and final 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.

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.

Note :- Both the classes are in different package

[Link] [Available in package [Link]]


package [Link];

public class Test


{
protected int x = 12;
}

[Link] [Available in package [Link]]


package [Link];

import [Link];

public class Access extends Test


{
public static void main(String[] args)
{
Access access = new Access();
[Link](access.x);

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.
--------------------------------------------------------------------------
Data types in java : [diagram 10-OCT-23]
----------------------------------------
Type casting in Java :
-----------------------
Type casting is nothing but converting one data type to another data type.
In java, type casting can be divided into two types

1) Implicit type casting OR Widening OR Automatic type casting

2) Explicit type casting OR Narrowing OR Manual type casting

Implicit type casting :-


------------------------
If we try to assign a smaller data type to bigger data type then by default,
compiler does not have any issue so it will be converted automatically This is the
reason it is known as Implicit or automatic type casting.

byte -> short -> char -> int -> long -> float -> double
Eg:- byte b = 12;
short s = b;
-----------------------------------------------------------------------------------
---------
//program on Implicit type casting

package [Link];

public class ImplicitEx1


{
public static void main(String[] args)
{
byte b = 15;
short s = b;
[Link]("value is :"+s);
}
}
-----------------------------------------------------------------------------------
-----------
package [Link];

public class ImplicitEx2


{
public static void main(String[] args)
{
int i = 4567;
long x = i;
[Link]("Value is :"+x);
}
}
-----------------------------------------------------------------------------------
----------
package [Link];

public class ImplicitEx3


{
public static void main(String[] args)
{
int x = 'A';
[Link]("x value is :"+x);
}

}
-------------------------------------------------------------------------

Explicit type casting :


-----------------------
Whenever we try to assign a bigger data type to smaller data type then by default,
compiler does not allow this but if we want to perform the explicit type casting
then we need to convert the bigger type into smaller type by performing manual type
casting.

While performing the explicit type casting there may be chance of loss of data if
the value for smaller data type will be beyond the range.

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

Eg:-
short s = 23;
byte b = s; //not possible short is bigger, byte is smaller

byte b = (byte) s; //converting short to byte type


-----------------------------------------------------------------------------------
----------
package [Link];

public class ExplicitEx1


{
public static void main(String[] args)
{
short s = 127;
byte b = (byte) s;
[Link]("value is :"+b);
}
}
-----------------------------------------------------------------------------------
-----------
package [Link];

public class ExplicitEx2 {

public static void main(String[] args)


{
long l = 1299L;

int x = (int) l;

[Link]("x value is :"+x);

}
-----------------------------------------------------------------------------------
----------
package [Link];

public class ExplicitEx3 {

public static void main(String[] args)


{
float f1 = (float)123.89;

float f2 = 234.78f;

float f3 = 1567.67F;

[Link]("f1 = "+f1+ " f2 = "+f2+ " f3 = "+f3);

}
--------------------------------------------------------------------------
HAS-A relation between the classes :
------------------------------------------
In order to acheive HAS-A relation concept we should use Association.

Association (Relationship between the classes through Object reference)


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

The following program explians about association and it contains 3 files

Note : In this Program a trainer wants to view the profile of the Student.

3 files :
---------

[Link]
------------
package [Link].association_demo;

public class Student


{
private int studentId;
private String studentName;
private long mobileNumber;

//GENERATE SETTER AND GETTER


public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId) //111
{
[Link] = studentId;
}
public String getStudentName()
{
return studentName;
}
public void setStudentName(String studentName)
{
[Link] = studentName;
}
public long getMobileNumber()
{
return mobileNumber;
}
public void setMobileNumber(long mobileNumber)
{
[Link] = mobileNumber;
}
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", mobileNumber=" + mobileNumber
+ "]";
}

[Link]
------------
package [Link].association_demo;

import [Link];

public class Trainer


{
public void viewStudentProfile(Student s) //s = s1
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Student Id :");
int id = [Link]();

if(id == [Link]())
{
[Link](s);
}
else
{
[Link]("Sorry!!! Student record is not available");
}

}
}

[Link]
----------
package [Link].association_demo;

public class Main


{
public static void main(String[] args)
{
Student s1 = new Student();

[Link](1);
[Link]("Pooja");
[Link](9812345678L);

Student s2 = new Student();


[Link](2);
[Link]("Raj");
[Link](9912345678L);

Trainer ravi = new Trainer();


[Link](s1);

}
}
--------------------------------------------------------------------------
Composition :
-------------
Composition relation is a restricted form of Aggregation in which two classes (or
entities) are highly dependent on each other; the composed object cannot exist
without the other entity. The composition can be described as a part-of
relationship.

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.
-------------------------------------------------------------------------
[Link]
------------
package [Link];
//Composition(Strong reference type)

public class Engine


{
private String engineType;
private int horsePower;

//Constructor
public Engine(String engineType, int horsePower)
{
super();
[Link] = engineType;
[Link] = horsePower;
}

//Getter Methods

public String getEngineType()


{
return engineType;
}
public int getHorsePower()
{
return horsePower;
}

@Override
public String toString() {
return "Engine [engineType=" + engineType + ", horsePower=" +
horsePower + "]";
}

}
[Link]
---------
package [Link];

public class Car


{
private String carName;
private Engine engine; //HAS-A Relation

public Car(String carName) //Car c1 = new Car("Naxon");


{
[Link] = carName;
[Link] = new Engine("Battery", 1000); //composition (Strong
Association)
}

//Generate toString() method


@Override
public String toString() {
return "Car [carName=" + carName + ", engine=" + engine + "]";
}
}

[Link]
---------
package [Link];

public class Main


{
public static void main(String[] args)
{
Car c1 = new Car("Ford");
[Link](c1);
}

}
-----------------------------------------------------------------------
11-Oct-23
----------
Aggregation (Weak Reference) :
-----------------------------------
Aggregation is a relation between two classes which can be built through entity
reference, It is a weak reference type that means one object entity does not
depend upon another object entity.

An aggregation is a form of Association, which is a one-way relationship or a


unidirectional association.

For example, customers can have orders but the reverse is not possible, hence
unidirectional in nature.

Example :-
------------
3 files :
---------
[Link]
-------------
package [Link].aggregation_demo;

public class Company


{
private String companyName;
private String companyLocation;

public Company(String companyName, String companyLocation)


{
super();
[Link] = companyName;
[Link] = companyLocation;
}

public String getCompanyName() {


return companyName;
}

public void setCompanyName(String companyName) {


[Link] = companyName;
}

public String getCompanyLocation() {


return companyLocation;
}

public void setCompanyLocation(String companyLocation) {


[Link] = companyLocation;
}

@Override
public String toString() {
return "Company [companyName=" + companyName + ", companyLocation=" +
companyLocation + "]";
}

[Link]
-------------
package [Link].aggregation_demo;

public class Employee


{
private Integer emoloyeeNumber;
private String employeeName;
private Double employeeSalary;
private Company company;

public Employee(Integer emoloyeeNumber, String employeeName, Double


employeeSalary, Company company)
{
super();
[Link] = emoloyeeNumber;
[Link] = employeeName;
[Link] = employeeSalary;
[Link] = company;
}

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

[Link]
----------
package [Link].aggregation_demo;

public class Main {

public static void main(String[] args)


{
Company company = new Company("TCS", "Hyderabad");

Employee e1 = new Employee(1, "Virat", 75000.89,company);


[Link](e1);

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

Example:-

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)

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


----------------------------------------------------------------------
Static Polymorphism :
------------------------
The polymorphism which exist at the time of compilation is called static
polymorphism.

In static polymorphism, compiler has very good idea that which method is going to
invoke(call) depending upon the type of parameter we have passed in the method.

This type of preplan polymorphism is called static polymorphism.

Example:- Method Overloading

----------------------------------------------------------------------
Dynamic Polymorphism :
----------------------------
The polymorphism which exist at runtime is called dynamic polymorphism.

In dynamic polymorphism, compiler does not have any idea about method calling, at
runtime JVM will decide that which method is invoked depending upon the class type.

This type of polymorphism is called dynamic polymorphism.(Dynamic Method


dispatched)

Example:- Method Overriding


----------------------------------------------------------------------
Note :- In static polynorphism method calling is done at the time of compilation
so it is also known as Early Binding.

On the other hand In dynamic Polymorphism method calling is done at the of


execution (after object creation by JVM) so it is also known as Late Binding.
-----------------------------------------------------------------------
IQ
---
Can we overload the main method ?
----------------------------------
We can overload the main method but JVM will always search the main method which
takes String array as a parameter.

Example :
------------
public static void main(String [] args) //JVM will serach this method
{
}
public static void main(String x)
{
}
public static void main(int y)
{
}

Program to show we can overload a main method :


----------------------------------------------
package [Link];

public class StaticPolymorphism


{
public static void main(String[] args)
{
[Link]("JVM calling main method");
main("NIT");
}

public static void main(String args)


{
[Link]("My Institute Name is "+args);
main(9);
}

public static void main(int y)


{
[Link](y);
}
}
-----------------------------------------------------------------------
12-Oct-23
---------
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.

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.

Example :-

public void add(int x, int y)


{
}

public void add(int a, int b, int c)


{
}
----------------------------------------------------------------------
Program on Constructor Overloading :
------------------------------------
2 Files :

[Link]
--------------
package [Link].constructor_overloading;

public class Addition


{
public Addition(int x, int y)
{
[Link]("Sum of two integer is :"+(x+y));
}

public Addition(int x, int y, int z)


{
[Link]("Sum of three integer is :"+(x+y+z));
}

public Addition(float x, float y)


{
[Link]("Sum of two float is :"+(x+y));
}
}

[Link]
---------
package [Link].constructor_overloading;

public class Main {

public static void main(String [] args)


{
new Addition(2.3f, 7.8F);
new Addition(10, 20, 30);
new Addition(12,90);
}
}
-----------------------------------------------------------------------
Program on Constructor Overloading by using Constructor Chaining :
-----------------------------------------------------------------
2 Files :

[Link]
--------------
package [Link].constructor_overloading1;

public class Addition


{
public Addition(int x, int y)
{
[Link]("Sum of two integer is :"+(x+y));
}

public Addition(int x, int y, int z)


{
this(100,200);
[Link]("Sum of three integer is :"+(x+y+z));
}

public Addition(float x, float y)


{
this(10,20,30);
[Link]("Sum of two float is :"+(x+y));
}
}

[Link]
---------
package [Link].constructor_overloading1;

public class Main {

public static void main(String [] args)


{
new Addition(2.3f, 7.8F);
}

}
-----------------------------------------------------------------------
Program on Method overloading that describes we can change the return type of the
method while Overloading a method.

[Link]
----------
package [Link].method_overload;

public class Sum


{
public int add(int x, int y)
{
int z = x+y;
return z;
}

public String add(String x, String y)


{
String z = x+y;
return z;
}

public double add(double x, double y)


{
double z = x+y;
return z;
}
}

[Link]
---------
package [Link].method_overload;

public class Main {

public static void main(String[] args)


{
Sum s1 = new Sum();
String add = [Link]("Data", "base");

int x = [Link](12, 12);

double y = [Link](12.89, 12.90);

[Link](add+" : "+x+" : "+y);

}
}
-----------------------------------------------------------------------
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.(var args must be the last argument)

We can use var-args as a method parameter only.


-----------------------------------------------------------------------
Program on var-args

2 Files

[Link]
---------
package [Link].var_args;

public class Test


{
public void input(int... x) //Array
{
[Link]("Var args executed");
}
}

[Link]
---------
package [Link].var_args;

public class Main {

public static void main(String ...x)


{
Test t1 = new Test();
[Link]();
[Link](12);
[Link](15,19);
[Link](10,20,30);
[Link](10,20,30,40);
[Link](10,20,30,40,50);

}
-----------------------------------------------------------------------
Program to add parameters values of a method at the time of calling

2 Files

[Link]
---------

package [Link].var_args1;

public class Test


{
public void acceptData(int ...x)
{
int sum =0;

for(int y : x)
{
sum = sum+ y;
}
[Link]("Sum of parameters are :"+sum);
}
}

[Link]
---------
package [Link].var_args1;

public class Main {

public static void main(String[] args)


{
Test t1 = new Test();
[Link]();
[Link](10,20);
[Link](10,20,30);
[Link](100,100,100,100);

}
-----------------------------------------------------------------------
Program that describes var args must be only one and last argument.

2 Files

[Link]
----------
package [Link].var_args2;

public class Test {

/*
* public void accept(float ...x, int ...y) //invalid {
*
* }
*
*
* public void accept(int ...x, int y) //Invalid {
*
* }
*/

public void accept(int x, int... y) // valid


{
[Link]("x value is :"+x);
for (int z : y)
{
[Link](z);
}
}
}
[Link]
----------
package [Link].var_args2;

public class Main {

public static void main(String[] args)


{
Test t1 = new Test();
[Link](10, 20,30,40,50);
}
}
-----------------------------------------------------------------------
Var-args can hold hetrogeneous types of data

[Link]
----------
package [Link].var_args3;

public class Test


{
public void acceptHetro(Object ...obj)
{
for(Object o : obj)
{
[Link](o);
}
}
}

[Link]
---------
package [Link].var_args3;

public class Main {

public static void main(String[] args)


{
new Test().acceptHetro("Ravi",true,45.90,12,'A');

}
-----------------------------------------------------------------------
13-Oct-23
---------
Ambiguity issues while overloading a method ?
----------------------------------------------
Points to remember :
--------------------
1) While Overloading if we get ambiguity issues compiler will provide more priority
to the nearest data type.

2) While ambiguity issues compiler will also provide the priority


on the basis of following (WAV)

[Widening -> Autoboxing -> var-args]

[Link]
---------
package [Link].ambigity_issues;
class Test
{
public void access(byte b)
{
[Link]("byte is executed :"+b);
}
public void access(short b)
{
[Link]("short is executed :"+b);
}

}
public class Main1 {

public static void main(String[] args)


{
Test t1 = new Test();
//[Link](15); //invalid, 15 is of type integer

[Link]((byte)29);
[Link]((short)22);

}
}
-----------------------------------------------------------------------
[Link]
----------
package [Link].ambigity_issues;
class A
{
public void access(String x)
{
[Link]("String is invoked :"+x);
}

public void access(Object x)


{
[Link]("Object is invoked :"+x);
}
}
public class Main2
{
public static void main(String[] args)
{
A a1 = new A();
[Link]("Ravi");
[Link](null);

}
}
-----------------------------------------------------------------------
package [Link].ambigity_issues;
class B
{
public void access(Integer x)
{
[Link]("Autoboxing is invoked :"+x);
}

public void access(long x)


{
[Link]("Widening is invoked :"+x);
}
}
public class Main3 {

public static void main(String[] args)


{
B b1 = new B();
[Link](15);
}
}
----------------------------------------------------------------------
package [Link].ambigity_issues;
class C
{
public void access(Integer x)
{
[Link]("Autoboxing is invoked :"+x);
}

public void access(int ...x)


{
[Link]("Var-Args is invoked :"+x);
}
}
public class Main4 {

public static void main(String[] args)


{
C c1 = new C();
[Link](15);

}
----------------------------------------------------------------------
package [Link].ambigity_issues;

class D
{
public void access(Integer x)
{
[Link]("Autoboxing is invoked :"+x);
}

public void access(String x)


{
[Link]("String is invoked :"+x);
}
}
public class Main5 {

public static void main(String[] args)


{
D d1 = new D();
//[Link](null); //Invalid

}
----------------------------------------------------------------------
package [Link].ambigity_issues;

class E
{
public void access(int x)
{
[Link]("int is invoked :"+x);
}

public void access(long x)


{
[Link]("long is invoked :"+x);
}

}
public class Main6 {

public static void main(String[] args)


{
E e1 = new E();
[Link](15);

}
}
------------------------------------------------------------------------
16-Oct-23
---------
Method Overriding :
-------------------
Writing two or more methods in the super and sub class in such a way that method
signature(method name along with method parameter) of both the methods must be same
in the super and sub classes.

While working with method overriding generally we can't change the return type of
the method but from JDK 1.5 onwards we can change the return type of the method in
only one case that is known as Co-Variant.

Without inheritance method overriding is not possible that means if there is no


inheritance there is no method overriding.
------------------------------------------------------------------------
Advantage of Method Overriding :
--------------------------------
Advantage of Method overriding is, Each class is specifying its own specific
behavior (Diagram 16-OCT-23).
------------------------------------------------------------------------
Upcasting :-
------------
It is possble to assign sub class object to super class reference variable using
dynamic polymorphism. It is known as Upcasting.

Example:- Animal a = new Dog(); //valid [upcasting]

Downcasting :
---------------
By default downcasting is not possible, Here we are trying to assign super class
object to sub class reference variable but the same we can achieve by using
explicit type casting. It is known as downcasting

Eg:- Dog d = new Animal(); //Invalid

Dog d =(Dog) new Animal(); //Valid because Explicit type casting.

But by using above statement (Downcasting) whenever we call a method we


will get a runtime exception called [Link]. [Animal cann't be
cast to Dog]
-------------------------------------------------------------------------
package [Link];

class Animal
{
public void eat()
{
[Link]("I cannot say");
}
}

class Dog extends Animal


{
public void eat()
{
[Link]("Non-Veg type");
}
}
public class AnimalDemo
{
public static void main(String[] args)
{
Animal a = new Dog(); [Link]();
}
}
------------------------------------------------------------------------
package [Link];

class Animal
{
public void eat()
{
[Link]("I cannot say");
}
}

class Dog extends Animal


{
public void eat()
{
[Link]("Non-Veg type");
}
}
public class AnimalDemo
{
public static void main(String[] args)
{
Animal a = new Dog(); [Link]();
}

}
-----------------------------------------------------------------------
17-Oct-23
---------
Program on Method Overriding by using Dynamic Method Dispatch:
--------------------------------------------------------------
class RBI
{
public void loan()
{
[Link]("Bank Should provide loan!!!");
}
}
class SBI extends RBI
{
public void loan()
{
[Link]("SBI provides loan @ 9.2%");
}
}
class BOB extends RBI
{
public void loan()
{
[Link]("BOB provides loan @ 10.4%");
}
}

public class MethodOverridingDemo


{
public static void main(String[] args)
{
RBI r;
r = new SBI(); [Link](); //Dynamic Method Dispatch
r = new BOB(); [Link](); //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 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 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 comment 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.
------------------------------------------------------------------------
class Shape
{
public void draw()
{
[Link]("No idea about shape");
}
}
class Rectangle extends Shape
{
@Override
public void draw()
{
[Link]("Drawing Rectangle");
}
}
class Square extends Shape
{
@Override
public void draw()
{
[Link]("Drawing Square");
}
}

public class ShapeDemo


{
public static void main(String[] args)
{
Shape s;
s = new Rectangle(); [Link]();
s = new Square(); [Link]();
}
}
-----------------------------------------------------------------------
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.

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 while overriding a method.

Note :- private access modifier is not availble (visible) in sub class so it is not
the part of method overriding.

[Link]
-------------------
class Super
{
public void show()
{
[Link]("Super class show method");
}
}
class Sub extends Super
{
@Override
protected void show() //error
{
[Link]("Sub class show method");
}
}
public class AccessModifier
{
public static void main(String[] args)
{
Super s = new Sub();
[Link]();
}
}
-----------------------------------------------------------------------
Co-variant concept in method overriding :
------------------------------------------------
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 as shown in the program below.

class Super
{
public void show()
{
[Link]("Super class show method ...");
}
}
class Sub extends Super
{
@Override
public int show() //error[int is not compatible with void]
{
[Link]("Sub class show method ");
return 0;
}
}
public class IncompatibleOverride
{
public static void main(String [] args)
{
Super s = new Sub();
[Link]();
}
}

Note :- The above program will generate compilation error because we


are trying to change the return type of the method while
overriding so int is not compatible 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 called Co-Variant as shown in the program below.
----------------------------------------------------------------------
class Animal
{
}
class Dog extends Animal
{
}

class Bird
{
public Animal fly()
{
[Link]("Bird is flying");
return new Dog();
}
}
class Parrot extends Bird
{
@Override
public Dog fly()
{
[Link]("Parrot is flying");
return new Dog();
}
}

public class CoVariant


{
public static void main(String[] args)
{
Bird b = new Parrot();
[Link]();
}
}
-----------------------------------------------------------------------

class Super
{
public Object display()
{
[Link]("Super class display method!!!");
return new Object();
}
}
class Sub extends Super
{
@Override
public String display()
{
[Link]("Sub class display method!!!");
return null;
}
}
class CoVariant1
{
public static void main(String[] args)
{
Super s = new Sub();
[Link]();
}
}
-----------------------------------------------------------------------
18-10-2023
----------
*Can we override main method?
OR
Can we override static method
OR
What is method hiding in java?

Points to remember :(4 points)


-------------------------------
1) We can't override static method because it is the part of the class but not the
part of the Object.

2) We can't overide static method with non-static (instance) method.

3) We can't overide non-static method with static method.

4) We can't override main method but we can overload the main method, Here JVM will
always search the main method which contains String array as a parameter.

Defination
----------
We can't override static method because it is not the part of the object it is
executed at the time of loading the .class file into JVM memory.

If a sub class defines a static method with the same signature with the static
method in the super class, the method in the sub class is hidden by the method in
the super class.

We can declare a static method with the same signature in the sub class as declared
in the super class which looks like we can override static methods but in java
static methods of super class are hidden from sub class which is known as Method
Hiding.

Note :- a) we can't override static and private methods.


------------------------------------------------------------------
//program on Method Hiding.

class Super
{
public static void display()
{
[Link]("Display Method of Super class");
}
}
class Sub extends Super
{
//Method Hiding
public static void display()
{
[Link]("Display Method of Sub class");
}
}
public class MethodHiding
{
public static void main(String[] args)
{
Super s = new Sub();
[Link]();
}
}
-------------------------------------------------------------------
Method Chaining :
-----------------
It provides a facility to call n number of methods in a single statement.

By using method chaining concept we can concise our code.

While calling the method, we always depend upon previous method return type and the
last invoked method will be final return type of the statement(18-OCT-23)

public class MethodChaining


{
public static void main(String[] args)
{
String str = "India";
int len = [Link]().concat(" is great").length();
[Link](len); //14
}
}
------------------------------------------------------------------
19-10-2023
-----------
final keyword in java :
-----------------------
In java we use final keyword to provide some kind of restrictions.

We can use final keyword in three ways in java

1) To declare a class as a final (Inheritance is not possible)

2) To declare a method as a final (We can't override)

3) To declare a variable(Field) as a final (Re-assignment is not possible)

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 only 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 declared as final class.
------------------------------------------------------------------
//Program that describes we can inherit final class
final class A
{
private int x = 100;
public void setData()
{
x = 120;
[Link](x);
}
}
class B extends A //error
{
}
public class FinalClassEx
{
public static void main(String[] args)
{
B b1 = new B();
[Link]();
}
}
------------------------------------------------------------------
final class Test
{
private int data = 100;

public void setData(int data)


{
[Link] = data;
[Link]("Data value is :"+data);
}
}
public class FinalClassEx1
{
public static void main(String[] args)
{
Test t1 = new Test();
[Link](200);
}
}

Note :- It is clear that we can create the object for final class as well as we can
modify the data of final class.
------------------------------------------------------------------
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;
[Link]("Sum is :"+sum);
}
}
class B extends A
{
public void calculate() //error
{
int mul = a*b;
[Link]("Mul is :"+mul);
}
}
public class FinalMethodEx
{
public static void main(String [] args)
{
A a1 = new B();
[Link]();
}
}
------------------------------------------------------------------
3) To declare a variable(field) as a final :(Re-assignment is not possible)
-----------------------------------------------------------------

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.

Some example of predefined final variables

Byte.MIN_VALUE -> MIN_VALUE is a static and final variable

Byte.MAX_VALUE -> MAX_VALUE is a static and final variable

Example:- final int DATA = 10; (Now we can not perform re-assignment )
------------------------------------------------------------------
class A
{
final int A = 10;
public void setData()
{
A = 10; //error re-assignment is not possible
[Link]("A value is :"+A);
}
}
class FinalVarEx
{
public static void main(String[] args)
{
A a1 = new A();

[Link]();
}
}
------------------------------------------------------------------
class FinalVarEx1
{
public static void main(String[] args)
{
final int A = 12;
byte b = A;
[Link](b);
}
}
------------------------------------------------------------------
Blank final variable :
-----------------------

1) final variables must be initialized at the time of declaration or later (only


constructor), after that we can't perform re-initialization.

2) A blank final variable can't be initialized by default constructor.

3) A blank final variable must be initialized by the user as a part of constructor.


If we have multiple constructor then final variable must be initialized with all
the constructor to provide values for the blank final variable to all the objects.
-----------------------------------------------------------------
public class BlankFinalVar
{
final int A; //Blank final variable

public static void main(String[] args)


{
BlankFinalVar fv = new BlankFinalVar();
[Link](fv.A);
}
}

Note :- From the above program it is clear that Blank final variable cannot be
initialized by default constructor.
------------------------------------------------------------------
class Demo
{
final int A; // blank final variable

public Demo() //No Argument constructor


{
A = 15;
[Link](A);
}

public Demo(int x) //parameterized constructor


{
A = x;
[Link](A);
}
}
public class BlankFinalVariable
{
public static void main(String[] args)
{
Demo d1 = new Demo();

Demo d2 = new Demo(8);


}
}
------------------------------------------------------------------
20-10-2023
----------
Object class and it's Method :
-----------------------------
There is a predefined class called Object available in [Link] package, this
Object class is by default the super class of all the classes we have in java.

class Test
{

Note :- Object is the super class for this Test class. by default this Object class
is super class so explicitly we need not to mention.

Since, Object is the super class of all the classes in java that means we can
override the method of Object class as well as we can use the methods of Object
class anywhere in java because every class is sub class of Object class.

The Object class provides some common behavior to each sub class Object like we can
compare two objects (equals(Object obj)), we can create clone (duplicate) objects
(clone()), we can print object properties(instance variable) by using toString(),
providing a unique number to each and every object(hashCode()) and so on.
------------------------------------------------------------------
public native int hashCode() :
------------------------------
It is a predefined method of Object class.

Every Object contains a unique number generated by JVM at the time of Object
creation is called hashCode.

we can find out the hashCode value of an Object by using hashCode() method of
Object class, return type of this method is int.

Program :
---------
[Link]
------------------
package [Link];

class Test
{
}

public class HashCodeDemo1


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

[Link]([Link]());
[Link]([Link]());
}
}

[Link]
------------------
package [Link];

class Student
{
private int studentId;
private String studentName;

public Student(int studentId, String studentName)


{
super();
[Link] = studentId;
[Link] = studentName;
}
}
public class HashCodeDemo2
{
public static void main(String[] args)
{
Student s1 = new Student(111, "Virat");
Student s2 = new Student(222, "Rohit");
Student s3 = s1;
[Link]([Link]() +" : "+[Link]()+" :
"+[Link]());
}
}
-------------------------------------------------------------------
public final native Class getClass() :-
------------------------------------------
It is a predefined method of Object class.

This method returns the runtime class of the object, the return type of this method
is [Link].

This method will provide the class keyword + fully qualified name
[fully qualified name = Package Name + class name]

This getClass() method return type is [Link] so further we can apply any
other method of [Link] class to this method.
-------------------------------------------------------------------
[Link]
-------------------
package [Link];

class Employee
{
}

public class GetClassDemo1


{
public static void main(String[] args)
{
Employee emp = new Employee();
Class cls = [Link]();
[Link](cls);
Integer i = 23;
cls = [Link]();
[Link](cls); //[class keyword + FQN]
}

}
-------------------------------------------------------------------
package [Link];

class Customer
{
}

public class GetClassDemo2


{
public static void main(String[] args)
{
Customer c1 = new Customer();
String name = [Link]().getName();
[Link]("CLASS NAME IS :"+name);

Double d1 = 89.67;
name = [Link]().getName();
[Link]("CLASS NAME IS :"+name);
}
}
------------------------------------------------------------------
21-10-2023
-----------
public String toString() :
----------------------------
It is a predefined method of Object class.

it returns a string representation of the object. In general, the toString method


returns a string that "textually represents" this object. The result should be a
concise but informative representation that is easy for a person to read

toString() method of Object class conatins following logic.

public String toString()


{
return getClass().getName()+" @ "+[Link](hashCode());
}

Please note internally the toString() method is calling the hashCode() and
getClass() method of Object class.

In java whenever we print any Object reference by using [Link]() then


internally it will invoke the toString() method of Object class as shown in the
following program.
-----------------------------------------------------------------
package [Link];

class Foo
{

}
public class ToStringDemo1
{
public static void main(String[] args)
{
Foo f1 = new Foo();
[Link]([Link]()); //toString();
}

Here in the above program, we are calling the toString() method


of Object class which will return the Object in String format.
-----------------------------------------------------------------
package [Link];

class Demo
{
@Override
public String toString()
{
[Link]();
return "Overridden toString() method";
}
}

public class ToStringDemo2


{
public static void main(String[] args)
{
Demo d1 = new Demo();
[Link](d1);

Object d2 = new Demo();


[Link](d2);

}
-----------------------------------------------------------------
public boolean equals(Object obj) :
----------------------------------

-----------------------------------------------------------------
package [Link];

class Customer
{
private int customerId;
private String customerName;

public Customer(int customerId, String customerName)


{
super();
[Link] = customerId;
[Link] = customerName;
}
}

public class EqualMethodDemo1


{
public static void main(String[] args)
{
Customer c1 = new Customer(111, "Virat");
Customer c2 = new Customer(111, "Virat");

[Link](c1==c2);
[Link]([Link](c2));
}
}

Note :- Here in both the cases we will get the output as a false because ==
operator always verify the memory address or momory reference on the other hand
equals(Object obj) method of Object class, internally uses == operator only so
equals() method will provide false.
-----------------------------------------------------------------
//Overriding the equals(Object obj) method for comparing the content of two
objects.
package [Link];
class Student
{
private int studentId;
private String studentName;

public Student(int studentId, String studentName)


{
super();
[Link] = studentId;
[Link] = studentName;
}
//Overriding the equals(Object obj) method for content comparison
@Override
public boolean equals(Object obj) //obj = s2
{
//Retrieving the data from 1st object (s1 variable)
int sid1 = [Link];
String sname1 = [Link];

//Retrieving the data from 2nd object (s2 variable)


Student s2 = (Student)obj; //Down casting
int sid2 = [Link];
String sname2 = [Link];

if(sid1 == sid2 && [Link](sname2))


{
return true;
}
else
{
return false;
}
}
}
public class EqualsMethodDemo2
{
public static void main(String[] args)
{
Student s1 = new Student(111,"Virat");
Student s2 = new Student(111,"Virat");
[Link]([Link](s2));
}
}

In the above program we have overridden equals(Object obj) method from Object class
for content comparison.

String class has an overridden method called equals(Object obj) method for
comparing the String content, return type of this method is boolean.
----------------------------------------------------------------
//Same as above program

package [Link];
class Player
{
int playerId;
String playerName;

public Player(int playerId, String playerName)


{
super();
[Link] = playerId;
[Link] = playerName;
}

//Overriding equals(Object obj) for content comparison


@Override
public boolean equals(Object obj)
{
Player p2 = (Player) obj;

if([Link] == [Link] &&


[Link]([Link]))
{
return true;
}
else
{
return false;
}
}
}

public class EqualsMethdDemo3


{
public static void main(String[] args)
{
Player p1 = new Player(222,"Rohit");
Player p2 = new Player(222,"Rohit");
[Link]([Link](p2));
}
}
------------------------------------------------------------------
package [Link].equals_demo;

class Student
{
private int studentId;
private String studentName;

public Student(int studentId, String studentName)


{
super();
[Link] = studentId;
[Link] = studentName;
}

@Override
public boolean equals(Object obj) //obj = e2
{
if(obj instanceof Student)
{
Student s2 = (Student) obj;
if([Link] == [Link] &&
[Link]([Link]))
{
return true;
}
else
{
return false;
}

}
else
{
[Link]("Sorry! Comparison is not possible");
return false;
}
}

class Employee
{
private int empId;
private String empName;

public Employee(int empId, String empName) {


super();
[Link] = empId;
[Link] = empName;
}
}

public class EqualsMethodDemo4


{
public static void main(String[] args)
{
Student s1 = new Student(111,"Virat");
Student s2 = new Student(111,"Virat");
Employee e2 = new Employee(111, "Virat");
[Link]([Link](e2));
[Link]([Link](null));
[Link]([Link](s2));
}
}
-----------------------------------------------------------------
25-10-2023
-----------
enum in java :
--------------
An enum is a keyword in java which is introduced from java 1.5v
onwards.

enum is used to represent Univarsal Constants.

Example :

enum Direction
{
EAST, WEST, NORTH, SOUTH //public + static + final
}

All the enum constants are public, static and final. We should write enum constants
inside the enum and every constant must be separated by comma.

An enum we can write outside of the class, inside of the class or even inside of
the method.

An enum defined inside a class can be declare private, protected, public and
static.

An enum by default extends from [Link] class so we can't inherit an enum.

By default an enum is final so of we try to extend it will generate compilation


error.

Enum keyword has provided the method values() through which we can fetch all the
enum constants.

In order to fetch the enum constant position we can use ordinal method of Enum
class. The return type of this method is int.

We can define a method or a constructor inside an enum but here ; is compulsory.

The first line of an enum is reserved for enum constants.

We can also write constructor inside an enum but it should not be declared as
public.

All enum constants are by default object of type enum.


------------------------------------------------------------------
public class Test1
{
public static void main(String[] args)
{
enum Month
{
JANUARY, FEBRUARY,MARCH //public + static + final
}

[Link]([Link]);
}
}
-----------------------------------------------------------------
enum Month
{
JANUARY,FEBRUARY,MARCH
}
public class Test2
{
enum Color { RED,BLUE,BLACK }

public static void main(String[] args)


{
enum Week {SUNDAY, MONDAY, TUESDAY }

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}

Note :- From the above Program it is clear that we can define an enum inside a
class, outside of a class and inside a method as well.
----------------------------------------------------------------
//Comapring the constant of an enum
public class Test3
{
enum Color { RED,BLUE }

public static void main(String args[])


{
Color c1 = [Link];
Color c2 = [Link];

if(c1 == c2)
{
[Link]("==");
}
if([Link](c2))
{
[Link]("equals");
}
}
}
------------------------------------------------------------------
public class Test4
{
private enum Season //private, public, protected, static
{
SPRING, SUMMER, WINTER, RAINY;
}

public static void main(String[] args)


{
[Link]([Link]);
}
}
------------------------------------------------------------------
//Interview Question
class Hello
{
int x = 100;
}

enum Direction extends Hello


{
EAST, WEST, NORTH, SOUTH
}

class Test5
{
public static void main(String[] args)
{
[Link]([Link]);
}
}

Note :- The above program will generate the error because by default every enum
extends [Link] class. Which is an abstract class.
------------------------------------------------------------------
//All enums are by default final so can't inherit

enum Color
{
RED, BLUE, PINK;
}
class Test6 extends Color
{
public static void main(String[] args)
{
[Link]([Link]);
}
}

Note :- enum is be default final so we can't inherit.


------------------------------------------------------------------
//values() to get all the values of enum

class Test7
{
enum Season
{
SPRING, SUMMER, WINTER, FALL, RAINY
}

public static void main(String[] args)


{
Season x []= [Link]();

for(Season y : x)
[Link](y);
}
}
-----------------------------------------------------------------
//ordinal() to find out the order position
class Test8
{
static enum Season
{
SPRING, SUMMER, WINTER, FALL, RAINY
}

public static void main(String[] args)


{
Season s1[] = [Link]();

for(Season x : s1)
[Link](x+" order is :"+[Link]());
}
}
------------------------------------------------------------------
//We can take main () inside an enum

enum Test9
{
TEST1, TEST2, TEST3; //Semicolon is compulsory

public static void main(String[] args)


{
[Link]("Enum main method");
}
}
----------------------------------------------------------------
//constant must be in first line of an enum

enum Test10
{
public static void main(String[] args)
{
[Link]("Enum main method");
}

HR, SALESMAN, MANAGER;


}
------------------------------------------------------------------
//Writing constructor in enum
enum Season
{
WINTER, SUMMER, SPRING, RAINY; //All are object of type enum

Season()
{
[Link]("Constructor is executed....");
}
}
class Test11
{
public static void main(String[] args)
{
[Link]([Link]);
[Link]([Link]);

}
}

Note :- All enum constants are by default Object of type enum so when JVM will
load enum to the memory all objects will be automatically loaded so for every enum
Object respective constructor will be executed.
------------------------------------------------------------------
//Writing constructor with message
enum Season
{
SPRING("Pleasant"), SUMMER("UnPleasent"), RAINY("Rain"), WINTER;

String msg;

Season(String msg)
{
[Link] = msg;
}

Season()
{
[Link] = "Cold";
}

public String getMessage()


{
return msg;
}
}
class Test12
{
public static void main(String[] args)
{
Season s1[] = [Link]();

for(Season x : s1)
[Link](x+" is :"+[Link]());
}
}
-----------------------------------------------------------------
enum MyType
{
ONE
{
@Override
public String toString()
{
return "this is one";
}
},

TWO
{
@Override
public String toString()
{
return "this is two";
}
}
}
public class Test13
{
public static void main(String[] args)
{
[Link]([Link]);
[Link]([Link]);

}
}
------------------------------------------------------------------
public class Test14
{
enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public static void main(String args[])


{
Day day=[Link];

switch(day)
{
case SUNDAY:
[Link]("Sunday");
break;
case MONDAY:
[Link]("Monday");
break;
default:
[Link]("other day");
}

}
}
-----------------------------------------------------------------
26-10-2023
-----------
Inner classes in java :
------------------------
In java it is possible to define a class (inner class) inside another class (outer
class). It is also called Nested class.

A nested class or an inner class is a class that exists within another class. In
other words, the inner class is a part of a class, just as variables and methods
are members of a class

An inner class, .class file will be represented by $ symbol.

Advantages of inner class :


--------------------------------
1) It helps us to logically divide the class and it's respective code.

2) It is used to achieve encapsulation.

3) It enhance the readability and maintainability of the code.

Java supports four kinds of inner classes :


-----------------------------------------------
1) Nested inner class OR Member class OR Regular class

2) Method local inner class


3) Static nested inner class

4) Anonymous inner class


------------------------------------------------------------------
1) Member Inner class OR Nested Inner class OR Regular class :
------------------------------------------------------------------
A non-static class that is created inside a class but outside of a method is called
Member Inner class OR Nested Inner class OR Regular class.

It can be declared with access modifiers like private, default, protected, public,
abstract and final.

It is also called as Regular Inner class.

An inner class can also access the private member of outer class.

Note :- The .class file of an inner class will be represented by $ symbol at the
time of compilation.

An outer class can be declared as public, abstract and final only.


------------------------------------------------------------------
class Outer
{
private int a = 15;

class Inner
{
public void displayValue()
{
[Link]("Value of a is " + a);
}
}
}
public class Test1
{
public static void main(String... args)
{
//Outer mo = new Outer(); //Outer class Object is created
//[Link] inner = [Link] Inner(); //Inner class object is created

[Link] inner = new Outer().new Inner();


[Link]();
}
}
------------------------------------------------------------------
class MyOuter
{
private int x = 7;
public void makeInner()
{
MyInner in = new MyInner();
[Link]("Inner y is "+in.y);
[Link]();
}

class MyInner
{
private int y = 15;
public void seeOuter()
{
[Link]("Outer x is "+x);
}
}
}
public class Test2
{
public static void main(String args[])
{
MyOuter m = new MyOuter();
[Link]();
}
}
-----------------------------------------------------------------
class MyOuter
{
private int x = 15;
class MyInner
{
public void seeOuter()
{
[Link]("Outer x is "+x);
}
}
}
public class Test3
{
public static void main(String args[])
{
//Creating inner class object in a single line
[Link] m = new MyOuter().new MyInner();
[Link]();
}
}
-----------------------------------------------------------------
class MyOuter
{
static int x = 7;
class MyInner
{
public static void seeOuter() //[Link]();
{
[Link]("Outer x is "+x);
}
}
}

public class Test4


{
public static void main(String args[])
{
[Link]();
}
}
-----------------------------------------------------------------
class OuterClass
{
int x;
public class InnerClass
{
int x;
}
}
public class Test5
{
}
Note :- We can declare an inner class as public.
---------------------------------------------------------------------
class OuterClass
{
int x;
protected class InnerClass
{
int x;
}
}
public class Test6
{
}
Note :- We can't declare an outer class as private and protected but an inner class
we can declare with private and protected access modifiers.
---------------------------------------------------------------------
class OuterClass
{
int x;
private class InnerClass
{
int x;
}
}
public class Test7
{
}

Note :- Inner class can be declared with private.


---------------------------------------------------------------------
class OuterClass
{
int x;
abstract class InnerClass
{
int x;
}
}
public class Test8
{
}
Note :- Inner class can be declared with abstract.
-------------------------------------------------------------------
class OuterClass
{
int x;
final class InnerClass
{
int x;
}
}
public class Test9
{
}

Note :- Inner class can be declared with final.


----------------------------------------------------------------
class OuterClass
{
private int x=200;
class InnerClass
{
public void display() //Inner class display method
{
[Link]("Inner class display method");
}

public void getValue()


{
display();
[Link]("Can access outer private var :"+x);
}
}

public void display() //Outer class display method


{
[Link]("Outer class display");
}
}
public class Test10
{
public static void main(String [] args)
{
[Link] inobj = new OuterClass().new InnerClass();
[Link]();

new OuterClass().display();
}
}
-----------------------------------------------------------------
27-10-2023
----------
2) Method local inner class :
-------------------------------
If a class is declared inside the method then it is called method local inner
class.

We cann't apply any access modifier on method local inner class but they can be
marked as abstract and final.

A local inner class we can't access outside of the method that means the scope of
method local inner class within the same method only.
-----------------------------------------------------------------
//program on method local inner class
class MyOuter3
{
private String x = "Outer class private data";

public void doSttuff()


{
String z = "local variable"; //must be final till JDK 1.7
class MyInner //only final and abstract is possible
{
public void seeOuter()
{
[Link]("Outer x is "+x);
[Link]("Local variable z is : "+z);
}
}
MyInner mi = new MyInner();
[Link]();
}

}
public class Test11
{
public static void main(String args[])
{
MyOuter3 m = new MyOuter3();
[Link]();
}
}
----------------------------------------------------------------
//local inner class we can't access outside of the method
class MyOuter3
{
private String x = "Outer class Data";

public void doSttuff()


{
String z = "local variable";
class MyInner
{
String z = "CLASS variable";
public void seeOuter()
{
[Link]("Outer x is "+x);
[Link]("Local variable z is : "+z);
}
}
MyInner mi = new MyInner();
[Link]();

}
public class Test12
{
public static void main(String args[])
{
MyOuter3 m = new MyOuter3();
[Link]();
}
}

Note :- Method local inner class object must be created inside the method only.
-----------------------------------------------------------------
3) Static Nested Inner class :
---------------------------------
A static inner class which is declared with static keyword inside an outer class is
called static Nested inner class.

It cann't access non-static variables and methods i.e (instance members) of outer
class.

For static nested inner class, Outer class object is not required.

If a static nested inner class contains static method then object is not required
for inner class. On the other hand if the static inner class contains instance
method then we need to create an object for static nested inner class.
-----------------------------------------------------------------
//static nested inner class
class BigOuter
{
static class Nest //static nested inner class
{
void go() //Instance method of static inner class
{
[Link]("Hello welcome to static nested class");
}
}
}
class Test13
{
public static void main(String args[])
{
[Link] n = new [Link]();
[Link]();

}
}
-----------------------------------------------------------------
class Outer
{
static int x=15;

static class Inner


{
void msg()
{
[Link]("x value is "+x);
}
}
}
class Test14
{
public static void main(String args[])
{
[Link] obj=new [Link]();
[Link]();
}
}
-----------------------------------------------------------------
class Outer
{
static int x = 25;
static class Inner
{
static void msg()
{
[Link]("x value is "+x);

}
}
}
class Test15
{
public static void main(String args[])
{
[Link]();
}
}
-----------------------------------------------------------------
class Outer
{
int x=15; //error (not possible because try to access instance variable)
static class Inner
{
void msg()
{
[Link]("x value is "+x);
}
}
}
class Test16
{
public static void main(String args[])
{
[Link] obj=new [Link]();
[Link]();
}
}
-----------------------------------------------------------------
4) Anonymous inner class :
------------------------------
It is an inner class without a name and for this kind of inner class only single
Object is created. (Singleton class)

*A normal class can implement any number of interfaces but an anonymous inner class
can implement only one interface at a time.

A normal class can extend one class and implement any number of interfaces at the
same time but an anonymous inner class can extend one class or can implement one
interface at a time.
-----------------------------------------------------------------
package [Link];

class Vehicle
{
public void run()
{
[Link]("Vehicle is running");
}
}
public class Anonymous {

public static void main(String[] args)


{
//Anonymous inner class
Vehicle car = new Vehicle()
{
@Override
public void run()
{
[Link]("Car is running");
}

};

//Anonymous inner class


Vehicle bike = new Vehicle()
{
@Override
public void run()
{
[Link]("Bike is running");
}

};

[Link](); [Link]();

}
-----------------------------------------------------------------
28-10-2023
-----------
Abstract class and abstract methods :
-------------------------------------
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 class.

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)
-----------------------------------------------------------------
//Program on abstract class and abstract method

abstract class Shape


{
public abstract void draw();
}

class Rectangle extends Shape


{
@Override
public void draw()
{
[Link]("Drawing Rectangle");
}
}
class Square extends Shape
{
@Override
public void draw()
{
[Link]("Drawing Square");
}
}

public class ShapeDemo


{
public static void main(String[] args)
{
Shape s ;

s = new Rectangle(); [Link]();

s = new Square(); [Link]();


}
}
-----------------------------------------------------------------
package [Link];

abstract class Car


{
protected int speed = 100;

public Car()
{
[Link]("Car class Constructor!!!");
}

public void getDetails()


{
[Link]("Car has 4 wheels");
}

public abstract void run();

class Honda extends Car


{
@Override
public void run()
{
[Link]("Running Safely");
}
}
public class InterviewQuestion
{
public static void main(String[] args)
{
Car c = new Honda();
[Link]("Speed of car is :"+[Link]);
[Link]();
[Link]();
}
}

Note :- In the above program Car class constructor will be executed by super
keyword of Honda class using default constructor.

Abstract class constrcutor will be executed with the help of sub class object.
-----------------------------------------------------------------
31-10-2023
----------
Program that describes, all the abstract method defined in the super class must be
overridden in the sub class

[Link]
---------------------
package [Link].abstract_demo;

abstract class A
{
public abstract void show();
public abstract void demo();
}
abstract class B extends A
{
@Override
public void show() // + demo();
{
[Link]("Show method implemented in class B");
}
}
class C extends B
{
@Override
public void demo()
{
[Link]("Demo method implemented in class C");
}
}

public class AbstractExample


{
public static void main(String[] args)
{
C c1 = new C(); [Link](); [Link]();
}

}
------------------------------------------------------------------
//Program to describe common abstract method must be overridden
in the sub classes.

package [Link].abstract_demo;

abstract class Shape


{
public abstract void area();
}
class Rectangle extends Shape
{
private int length, breadth;

public Rectangle(int length, int breadth)


{
super();
[Link] = length;
[Link] = breadth;
}

@Override
public void area()
{
double area = [Link] * [Link];
[Link]("Area of Rectangle is :"+area);
}
}
class Circle extends Shape
{
private final double PI = 3.14;
private int radius;

public Circle(int radius)


{
super();
[Link] = radius;
}

@Override
public void area()
{
double area = PI * radius * radius;
[Link]("Area of Circle is :"+area);
}
}

public class ShapeDemo


{
public static void main(String[] args)
{
Shape s;

s = new Rectangle(3, 5); [Link]();


s = new Circle(5); [Link]();
}
}
-------------------------------------------------------------------
What is the advantage of writing constructor in the abstract class ?
----------------------------------------------------------------
If my abstract class contains any properties (state OR Data) then we can initialize
those properties of abstract class with the help of sub class object by using super
keyword as shown in the below
program.

[Link]
-----------------

package [Link].abstract_demo;

abstract class Vehicle


{
protected String vehicleNumber;

public Vehicle(String vehicleNumber)


{
super();
[Link] = vehicleNumber;
}

public abstract void run();


}

class Car extends Vehicle


{
private String carName;

public Car(String carName)


{
super("TS 09 6578");
[Link] = carName;
}

@Override
public void run()
{
[Link]([Link] + " Car is running!!");
}

@Override
public String toString() {
return "Car [carName=" + carName + ", vehicleNumber=" + vehicleNumber +
"]";
}
}

public class VehicleDemo


{
public static void main(String[] args)
{
Vehicle v = new Car("Naxon");
[Link]();
[Link](v);
}
}
--------------------------------------------------------------------
Implementing the abstract method with the help of anonymous inner class.
package [Link].abstract_demo;

abstract class Bird


{
public abstract void fly();
}

public class AnonymousDemo


{
public static void main(String[] args)
{
//Anonymous inner class
Bird parrot = new Bird()
{
@Override
public void fly()
{
[Link]("Parrot can fly");
}

};

//Anonymous inner class


Bird sparrow = new Bird()
{
@Override
public void fly()
{
[Link]("Sparrow can fly");
}

};

//Anonymous inner class


Bird peacock = new Bird()
{
@Override
public void fly()
{
[Link]("Peacock can fly");
}
};
[Link](); [Link](); [Link]();

}
----------------------------------------------------------------
interface :
-----------
interface (Upto 1.7) :-
------------------------
An interface is a keyword in java which is similar to a class.

Upto JDK 1.7 an interfcae contains only abstract method that means there is a
gurantee 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 acheive 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 class 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 interfcae we can acheive multiple inheritance in java.

Note :- inside an interface we can't declare any blocks (instance, static) as well
as we can't write constructor inside an interface.
----------------------------------------------------------------
3 files :
---------
[Link](I)
-----------------
package [Link];

public interface Moveable


{
int SPEED = 90; //public, static and final

void move(); //public and abstract


}

[Link](C)
-----------
package [Link];

public class Car implements Moveable


{
@Override
public void move()
{
//SPEED = 120; Invalid because variable is final
[Link]("Car speed is :"+SPEED);
}

[Link](C)
------------
package [Link];

public class Main


{
public static void main(String[] args)
{
Moveable m = new Car();
[Link]();
[Link]("My Car speed is :"+[Link]);
}

}
---------------------------------------------------------------
3 files :

[Link](I)
---------------
package [Link].interface_demo;

public interface Client


{
void doSum(int x, int y);
void doSub(int x, int y);
void doMul(int x, int y);
}

[Link](C)
-----------------
package [Link].interface_demo;

public class Developer implements Client


{

@Override
public void doSum(int x, int y)
{
int sum = x + y;
[Link]("Addition is :"+sum);
}

@Override
public void doSub(int x, int y)
{
int sub = x - y;
[Link]("Subtraction is :"+sub);
}
@Override
public void doMul(int x, int y)
{
int mul = x * y;
[Link]("Multiplication is :"+mul);
}

[Link](C)
-----------------
package [Link].interface_demo;

public class Tester {

public static void main(String[] args)


{
Client c = new Developer();
[Link](12, 10);
[Link](12, 5);
[Link](12, 12);
}

}
---------------------------------------------------------------
H.W

interface Bank
{
void deposit(int amount);
void withdraw(int amount);
}
----------------------------------------------------------------
Program on loose coupling :
---------------------------
IQ
--
How to achieve loose coupling using interfaces :
------------------------------------------------
Loose Coupling :- If the degree of dependency from one class object to another
class is very low then it is called loose coupling.

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.

The following program explains how to achieve loose coupling :


--------------------------------------------------------------
6 files :-
----------
[Link](I)
----------------
package [Link].loose_coupling;
public interface HotDrink
{
public abstract void prepare();
}

[Link]
-----------
package [Link].loose_coupling;

public class Tea implements HotDrink


{
@Override
public void prepare()
{
[Link]("Preparing Tea!!!");
}

[Link]
-----------
package [Link].loose_coupling;

public class Coffee implements HotDrink


{
@Override
public void prepare()
{
[Link]("Preparing Coffee!!!");
}

[Link]
--------------
package [Link].loose_coupling;

public class Horlicks implements HotDrink


{
@Override
public void prepare()
{
[Link]("Preparing Horlicks!!");
}

[Link]
---------------
package [Link].loose_coupling;

public class Restaurant


{
public static void createObject(HotDrink drink)
{
[Link]();
}
}

package [Link].loose_coupling;

public class Main {

public static void main(String[] args)


{
[Link](new Tea());

[Link](new Coffee());

[Link](new Horlicks());
}

------------------------------------------------------------------
Note :- We can also take return type of the method as an interface so that method
can return the object of all the sub classes which are implementing from that
particular interface.

public HotDrink accept()


{

return new Tea(); OR new Coffee(); OR null OR new Horlicks(); .....(future)


}
----------------------------------------------------------------
02-11-2023
------------
Multiple inheritance by using interface :
------------------------------------------
Upto java 7, interface does not contain any method body that means all the methods
are abstract method so we can achieve multiple inheritance by providing the logic
in the implementer class as shown in the below program [02-NOV-23]

package [Link].interface_demo;

interface A
{
void m1();
}
interface B
{
void m1();
}
class Implementer implements B,A
{
@Override
public void m1()
{
[Link]("Multiple Inheritance using interface..");
}
}
public class MultipleInheritance
{
public static void main(String[] args)
{
Implementer i = new Implementer();
i.m1();
}
}
------------------------------------------------------------------

package [Link].interface_demo;

interface C
{
void doSum(int x, int y);
}
interface D extends C
{
void doSub(int x, int y);
}
class Calculate implements D
{
@Override
public void doSum(int x, int y)
{
int sum = x+y;
[Link]("Sum is :"+sum);

@Override
public void doSub(int x, int y)
{
int sub = x-y;
[Link]("Sub is :"+sub);
}
}
public class ExtendingInterface
{
public static void main(String[] args)
{
Calculate c = new Calculate();
[Link](12, 12);
[Link](100, 50);
}

}
------------------------------------------------------------------
Extending one interface to another interface :
-----------------------------------------------
One interface can extends another interface but one interface can't implement
another interface.

The following program explains how one interface can extends another interface

package [Link].interface_demo;

interface C
{
void doSum(int x, int y);
}
interface D extends C
{
void doSub(int x, int y);
}
class Calculate implements D
{
@Override
public void doSum(int x, int y)
{
int sum = x+y;
[Link]("Sum is :"+sum);

@Override
public void doSub(int x, int y)
{
int sub = x-y;
[Link]("Sub is :"+sub);
}
}
public class ExtendingInterface
{
public static void main(String[] args)
{
Calculate c = new Calculate();
[Link](12, 12);
[Link](100, 50);
}

}
------------------------------------------------------------------
Overriding interface method by using anonymous inner class :
-----------------------------------------------------------
By using anonymous inner class without using an external class, inside the ELC
class only we can take an anonymous class to override the super class
method/abstract class method/ interface method.

package [Link].interface_demo;

interface Student
{
void writeExam();
}

public class AnonymousInner


{
public static void main(String[] args)
{
//Anonymous inner class
Student science = new Student()
{
@Override
public void writeExam()
{
[Link]("Science Student is Writing Exam");

};

//Anonymous inner class


Student commerce = new Student()
{
@Override
public void writeExam()
{
[Link]("Commerce Student is Writing Exam");

};
[Link]();
[Link]();
}
}
-----------------------------------------------------------------
java 8 features : (March 2014)
-----------------------------
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
as shown in the program below.
-----------------------------------------------------------------
4 Files :
---------
[Link](I)
---------------
package [Link].java_8;

public interface Vehicle


{
void run();
void horn();

default void digitalMeter() //From java 1.8 onwards


{
[Link]("Digital Meter Facility");
}
}

[Link](C)
------------
package [Link].java_8;

public class Car implements Vehicle


{
@Override
public void run()
{
[Link]("Car is Running");
}

@Override
public void horn()
{
[Link]("Car has horn");
}

@Override
public void digitalMeter() //From java 1.8 onwards
{
[Link]("Car has Digital Meter Facility");
}
}

[Link](C)
------------
package [Link].java_8;

public class Bike implements Vehicle


{
@Override
public void run()
{
[Link]("Bike is Running");
}

@Override
public void horn()
{
[Link]("Bike has horn");
}
}
[Link](C)
------------
package [Link].java_8;

public class Tester


{
public static void main(String[] args)
{
Vehicle v;
v = new Car(); [Link](); [Link](); [Link]();
v = new Bike(); [Link](); [Link]();

Note :-
--------
Here in the Vehicle interface we have added dafault method digitalMeter() so now
for Car class as well as Bike class, there is no boundation to override this
default method.

If an implementer class is really required it then that class can override it.
-----------------------------------------------------------------
03-11-2023
----------
interface from JDK 1.8 onwards :
------------------------------------
Upto JDK 1.7 we can use only abstract methods inside an interface, as we know all
the abastrct methods must be overridden in the sub class otherwise the sub class
will become as an abstract class.
This facility of abstract methods leads to maintenance problem because if we add
any new abstract method inside an existing interface then that method has to
override by all the sub classes or the classes which are implementing from that
particular interface.

To avoid this boundation problem java software people has introduced default and
static method inside an interface so from JDK 1.8 onwards we can define the body of
the method inside an interface by declaring those method as default method and
static method or both.
-------------------------------------------------------------------
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 for specific class method implementation

interface HotDrink
{
void prepare();

default void expressPrepare() //possible from jdk 1.8


{
[Link]("Preparing with premium");
}
}
class Tea implements HotDrink
{
@Override
public void prepare()
{
[Link]("Preparing Tea");
}

@Override
public void expressPrepare() //public is compulsory here
{
[Link]("Preparing premium Tea");
}
}
class Coffee implements HotDrink
{
@Override
public void prepare()
{
[Link]("Preparing Coffee");
}
@Override
public void expressPrepare() //public is compulsory here
{
[Link]("Preparing Filter Coffee");
}
}
public class DefaultMethod
{
public static void main(String[] args)
{
HotDrink hk;
hk = new Tea(); [Link](); [Link]();
hk = new Coffee(); [Link](); [Link]();
}
}
------------------------------------------------------------------
The following program explains that default methods are having low priority than
normal methods (Concrete Method). class is having more power than interface.

interface I
{
default void demo()
{
[Link]("Demo Method in interface I1");
}
}

class A
{
public void demo()
{
[Link]("Demo Method in class A");
}
}

class B extends A implements I


{

public class DefaultMethod1


{
public static void main(String[] args)
{
B b1 = new B();
[Link](); [Link]();
}
}
------------------------------------------------------------------
Multiple Inheritance using default method :
--------------------------------------------
interface I1
{
default void m1()
{
[Link]("Default method of I1 interface...");
}
}
interface I2
{
default void m1()
{
[Link]("Default method of I2 Interface...");
}
}
class MyClass implements I1,I2
{
@Override
public void m1()
{
[Link]("m1 method of MyClass");
[Link].m1();
[Link].m1();
}
}
class MultipleInheritance
{
public static void main(String[] args)
{
MyClass m = new MyClass();
m.m1();
}
}

Note :- MI is possible by using default method of interface but here we need to use
super keyword.
------------------------------------------------------------------

Methods We can write inside an interface :


------------------------------------------
package [Link].static_method;

public interface Callable


{
public abstract void m1(); //abstract method

default void m2() //default method


{
}

public static void main(String[] args)


{
[Link]("Static method inside interface");
}

private void m4() //private non-static method


{
}

private static void m5() //private static method


{
}
}
-----------------------------------------------------------------
04-11-2023
----------
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 where it is defined that means
we cannot invoke static method from the implementer classes.

It is used to provide common functionality which we can apply/invoke from any ELC
class.
------------------------------------------------------------------
package [Link].static_demo;

interface Calculate
{
public static int doSum(int x, int y)
{
return (x+y);
}
public static int doSub(int x, int y)
{
return (x-y);
}
}

public class StaticMethodDemo1


{
public static void main(String[] args)
{
int result = [Link](12, 67);
[Link]("Sum is :"+result);

result = [Link](200, 100);


[Link]("Sub is :"+result);
}

}
------------------------------------------------------------------
interface Callable
{
public static void access()
{
[Link]("static method available inside interface");
}
}
public class StaticDemo2 implements Callable
{
public static void main(String[] args)
{
[Link]();

[Link](); //error

StaticDemo2 sm = new StaticDemo2();


[Link](); //error
}
}

Note :- In the above program we will get compilation error because static method is
available to Callable interface only so, implementer class cannot invoke static
method access.
------------------------------------------------------------------
What is Functional interface ?
-------------------------------
@FunctionalInterface Annotation :
---------------------------------------
If an interface contains only one abstract method then we can say that interface is
Functional Interface.

Functional Interface can be defined by @FunctionInterface annotation.

Functional Interface may contain default method and static method but it must
contain only one abstract method.

@FunctionalInterface
interface Printable
{
void print1();//SAM [Single Abstract Method]

default void print2()


{
}
}
------------------------------------------------------------------
Lambda Expression :
----------------------
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.

Independently Lamda Expression is not a statement.

It requires a target variable i.e functional interface reference

Lamda target can't be class or abstract class, it will work with functional
interface only.
------------------------------------------------------------------
package [Link];
@FunctionalInterface
interface Drawable
{
void draw();
}

public class Lambda1


{
public static void main(String[] args)
{
Drawable d = () -> [Link]("Drawing");
[Link]();
}
}
------------------------------------------------------------------
package [Link];

@FunctionalInterface
interface Calculate
{
void doSum(int x, int y);
}
public class Lambda2
{
public static void main(String[] args)
{
Calculate c = (p,q)-> [Link]("Sum is :"+(p+q));
[Link](10, 20);
}
}
------------------------------------------------------------------
package [Link];

interface Length
{
int getLength(String str);
}

public class Lambda3


{
public static void main(String[] args)
{
Length l = str -> [Link]();
[Link]("Length is :"+[Link]("India"));
}

}
--------------------------------------------------------------------------------
06-11-2023
----------
Programs on Lambda :
--------------------
@FunctionalInterface
interface Moveable
{
void move(); //SAM (Single Abstract Method)
}
public class Lambda1
{
public static void main(String[] args)
{
Moveable car = () -> [Link]("Moving With Car......");

[Link]();

Moveable bike = () -> [Link]("Moving with Bike");


[Link]();

Moveable bus = () -> [Link]("Moving with Bus");


[Link]();
}
}
---------------------------------------------------------------------------------
@FunctionalInterface
interface Calculate
{
void add(int a, int b, double c);
}
public class Lambda2
{
public static void main(String[] args)
{
Calculate calc = (x, y, z) -> [Link](x+y+z);
[Link](12,12,12.78);
}
}
--------------------------------------------------------------------------------
import [Link];

@FunctionalInterface
interface Length
{
int getLength(String str);
}

public class Lambda3


{
public static void main(String[] args)
{
Length l = str -> [Link]();

Scanner sc = new Scanner([Link]);


[Link]("Enter your Name :");
String name = [Link]();
[Link]("Your Name length is :"+[Link](name));
}
}
--------------------------------------------------------------------------------
@FunctionalInterface
interface Calculate
{
int getSquare(int num);
}

public class Lambda4


{
public static void main(String[] args)
{
Calculate c = x -> x*x;

[Link]("Square is :"+[Link](4));
}
}
------------------------------------------------------------------------
Working with predefined functional interfaces provided by java software people :
------------------------------------------------------------------------
Java software prople has provided a predefined functional interaface called
Runnable available in [Link] package, it contains only one abstract method i.e
run() so, it is a functional interface.

@FunctionalInterface
public interface Runnable
{
public abstract void run();
}
------------------------------------------------------------------------
Implementation of predefined Runnable interafce using Lambda :
--------------------------------------------------------------
public class Test
{
public static void main(String []a)
{
Runnable r1 = ()-> [Link]("Run method implemnted!!!");
[Link]();
}
}
------------------------------------------------------------------------
Working with predifined fuctional interfaces which are taking type parameter :
------------------------------------------------------------------------
Type Parameter in Java :
---------------------------
Java software people take this concept from C++ to make our variables are
independent of data type which is known as Type Parameter<T>.

Type parameter will accept Wrapper type OR User-defined class type, it will not
accept primitive type.

Program on Type Parameter :


---------------------------
package [Link].type_parameter;

class Accept<T> //T can accept any type Wrapper + User-Defined (No primitive)
{
private T var; //var = new Student();

public Accept(T var) //var = new Student();


{
super();
[Link] = var;
}

public T getVar()
{
return var;
}
}
class Student
{
@Override
public String toString()
{
return "Student -> With Type Parameter";
}
}

public class TypeParameter


{
public static void main(String[] args)
{
Accept<Integer> intType = new Accept<Integer>(12);
[Link]("Integer Object :"+[Link]());

Accept<Double> doubleType = new Accept<Double>(12.90);


[Link]("Double Object :"+[Link]());

Accept<Boolean> boolType = new Accept<Boolean>(true);


[Link]("Boolean Object :"+[Link]());

Accept<Student> studentType = new Accept<Student>(new Student());


[Link]([Link]());
}

In the above program we can accept only Wrapper type and User-defined class type as
a parameter we cannot accept primitive type as a parameter.
------------------------------------------------------------------------
07-11-2023
----------
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>
2) Consumer<T>
3) Function<T,R>
4) Supplier<T>

Note :-
-------
All these predefined functional interfaces are provided as a part of
[Link] sub package.

Predicate<T> funactional interface :


-------------------------------------------
It is a predefined functional interface available in [Link] 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.


---------------------------------------------------------------------
Program to verify whether a number is even or odd using Predicate.

package [Link].predicate_interface;
import [Link];
import [Link];

//Verify a number is even or odd


public class PredicateDemo1
{
public static void main(String[] args)
{
Predicate<Integer> evenOrOdd = num -> num % 2==0;

Scanner sc = new Scanner([Link]);


[Link]("Enter a Number :");
int no = [Link]();

boolean test = [Link](no);


if(test)
{
[Link](no + " is Even");
}
else
{
[Link](no + " is Odd");
}
[Link]();
}

}
-----------------------------------------------------------------------
Write a program to verify whether a name starts with 'A' or not ?
---------------------------------------------------------------
package [Link].predicate_interface;

import [Link];
import [Link];

public class PredicateDemo2


{
public static void main(String[] args)
{
Predicate<String> startsWith = str -> [Link]("A");

Scanner sc = new Scanner([Link]);


[Link]("Enter Your Name :");
String name = [Link]();

boolean test = [Link](name);

if(test)
{
[Link](name +" starts with A");
}
else
{
[Link](name +" does not start with A");
}
}
}
----------------------------------------------------------------------
WAP to verify whether a person is eligible 4 voting or not ?
------------------------------------------------------------
package [Link].predicate_interface;

import [Link];

public class PredicateDemo3 {

public static void main(String[] args)


{
Predicate<Integer> p = age -> age >=18;
[Link]("Person is eligible for vote :"+[Link](16));

}
}
----------------------------------------------------------------------
WAP to verify my name is Ravi or not ?
--------------------------------------
package [Link].predicate_interface;

import [Link];
import [Link];

public class PredicateDemo4


{
public static void main(String[] args)
{
Predicate<String> p = str -> [Link]("Ravi");

Scanner sc = new Scanner([Link]);


[Link]("Enter your Name :");
String name = [Link]();
[Link]("Are you Ravi :"+[Link](name));
}

}
---------------------------------------------------------------------
//Leap Year or Not ?

package [Link].predicate_interface;

import [Link];

public class PredicateDemo5


{
public static void main(String[] args)
{
Predicate<Integer> leapOrNot = year -> year %4 ==0;
[Link]("leap year ?"+[Link](2024));
}

}
-----------------------------------------------------------------------
Consumer<T> functional interface :
-----------------------------------------
It is a predefined functional interface available in [Link] 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);
}
------------------------------------------------------------------------
//Program on Consumer to accept multiple values :
import [Link].*;
public class ConsumerDemo1
{
public static void main(String [] args)
{
Consumer<Integer> printInt = x -> [Link](x);
[Link](15);

Consumer<String> printString = x -> [Link](x);


[Link]("Naresh i Technology");

Consumer<Double> printDouble = x -> [Link](x);


[Link](78.90);

Consumer<Boolean> printBoolean = x -> [Link](x);


[Link](true);

Consumer<Character> printChar = x -> [Link](x);


[Link]('A');

Consumer<Student> printStudent = x -> [Link](x);


[Link](new Student());
}
}

class Student
{
@Override
public String toString()
{
return "Consumer Student Object";
}
}
-------------------------------------------------------------------------
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 [Link] sub


[Link] 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>
{
R apply(T x);
}
-------------------------------------------------------------------------
//Square of the number

package [Link].function_interface;

import [Link];
import [Link];

public class FunctionDemo1


{
public static void main(String[] args)
{
Function<Integer,Integer> fn1 = x -> x*x;

Scanner sc = new Scanner([Link]);


[Link]("Enter a Number :");
int no = [Link]();

[Link]("Square of "+no+" is "+[Link](no));

}
-------------------------------------------------------------------------
//Length of the name + Name starst with particular String or not

package [Link].function_interface;

import [Link];

public class FunctionDemo2


{
public static void main(String[] args)
{
//Finding the length
Function<String,Integer> fn2 = str -> [Link]();
[Link]("Length is :"+[Link]("Ravi"));

//My name starts with R or not


Function<String,Boolean> fn3 = str -> [Link]("R");
[Link]("Starting with R :"+[Link]("Ravi"));

}
------------------------------------------------------------------------
08-11-2023
----------
Supplier<T> interface :
---------------------------
It is a predefined functional interface available in [Link] 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();
}
--------------------------------------------------------------------------
//Here Supplier get() method is returning Player object
package [Link].supplier_interface;

import [Link];

class Player
{
int pid;
String pname;
public Player(int pid, String pname) {
super();
[Link] = pid;
[Link] = pname;
}
@Override
public String toString() {
return "Player [pid=" + pid + ", pname=" + pname + "]";
}

public class SupplierDemo {

public static void main(String[] args)


{
Supplier<Player> p = ()-> new Player(111, "Virat");

[Link]([Link]());

}
------------------------------------------------------------------------
//Here Supplier get() method is returning String object
package [Link].supplier_demo;

import [Link];

public class SupplierDemo2 {

public static void main(String[] args)


{
Supplier<String> s2 = ()-> 10+20+" Ravi "+40+40;
String data = [Link]();
[Link](data);
}

}
------------------------------------------------------------------------
//Here Supplier get() method is returning Employee object

2 files :
---------
[Link]
-------------
package [Link].supplier_demo;

public class Employee


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

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


super();
[Link] = employeeId;
[Link] = employeeName;
[Link] = employeeSalary;
}

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

public int getEmployeeId() {


return employeeId;
}

public String getEmployeeName() {


return employeeName;
}

public double getEmployeeSalary() {


return employeeSalary;
}

[Link]
-----------------
package [Link].supplier_demo;

import [Link];

public class SupplierDemo


{
public static void main(String[] args)
{
Supplier<Employee> emp = ()->
{
Employee e1 = new Employee(1, "Ankita", 24000);
return e1;
};

Employee employee = [Link]();


[Link](employee);
}

}
-------------------------------------------------------------------
Can a functional interface contains the method of Object class?
---------------------------------------------------------------
Yes, Functional interface may contain the method of Object class. The main reason
to re-declare Object class method inside functional ineterface to follow the
contract.

package [Link].functional_interface;

@FunctionalInterface
public interface Callable
{
public abstract void call();

public String toString();

public int hashCode();

public boolean equals(Object obj);

From the avove interface, It is clear that inside a Functional interface we can re-
declare the method of Object class.
--------------------------------------------------------------
Can we override Object class methods inside a functional interface as a default
method?

No, We cannot override Object class method as a default method inside a functional
interface, we can only re-declare as showm in interface below.

package [Link].functional_concept;

@FunctionalInterface
public interface Printable
{
void print();

public default String show()


{
return "";
}

public default String toString()


{
return "";
}
}

--------------------------------------------------------------
Can we write private method inside an inetrafce?

Yes, From java 9 onwards we can also write private static and private non-static
methods inside an interface.

These private methods will improve code re-usability inside interfaces.


For example, if two default methods needed to share 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 [Link].supplier_demo;

interface CustomInterface
{
public abstract void method1(); //abstract method

public default void method2() //java 8


{
method4(); //private non -static method
method5(); //private static method
[Link]("default method");
}

public static void method3() //java 8


{
method5(); //static method inside other static method
[Link]("static method");

private void method4() //java 9


{
[Link]("private non -static method");
}

private static void method5() //java9


{
[Link]("private static method");
}
}

public class PrivateMethod implements CustomInterface {

@Override
public void method1() {
[Link]("abstract method");
}

public static void main(String[] args){


CustomInterface instance = new PrivateMethod();
instance.method1();
instance.method2();
CustomInterface.method3();
}
}
--------------------------------------------------------------------
What is marker interface ?
-------------------------------
An interface which does not contain any method and field is called marker
interface. In other words, an empty interface is known as marker interface or tag
interface.

It describes run-time type information about objects, so the JVM have additional
information about the object. [like object is clonable OR object is serializable]

Example :
----------
public interface Drawable //Marker interface
{
}

Note :-In java we have Clonable and Serializable are predefined marker interface.
--------------------------------------------------------------------
*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) We can write concrete method inside an abstract class but inside an interface we
can't write concrete public method, only abstract , default, static and private
methods are allowed.
----------------------------OOPS ENDED--------------------------------

09-11-2023
-----------
Class loader sub system with JVM Architecture :
------------------------------------------------------
The three main components of JVM

1) class loader sub system

2) Runtime Data Areas

3) Execution engine

class loader sub system internally performs 3 task

a) Loading b) Linking c) Initialization (Diagram 9th NOV)

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 to load the required .class file from java API that means all the
predfined classes (provided by java software people) .class file will be loaded by
Bootstrap class loader.
It is the super class of Extension class loader as well as It has the highest
priority among all the class loader.

Extension/Platform class Loader :-


--------------------------------------
It is responsible to load the required .class files from ext (extension) folder.
Inside the extension folder we have jar file(Java level zip file) given by some
third party or user defined jar file.
It is the super class of Application class loader as well as It has more priority
than Application class loader.

Note :- Command to create the jar file

jar cf [Link] [Link]

Application/System class Loader :-


--------------------------------------
It is responsible to load the required .class file from class path level i.e
Environment variable. It has lowest priority as well as It is the sub class of
Extension/Platform class loader.

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 [Link].
----------------------------------------------------------------------
10-11-2023
-----------
//Write a program in java which shows that our userdefined .class file will be
loaded by Application class loader

public class ClassLoaderDemo


{
public static void main(String[] args)
{
[Link]("This ClassLoaderDemo class is loaded
by :"+[Link]());

[Link]("Parent or Super class for Application class loader


is :"+[Link]().getParent());

[Link]("Parent or Super class for Platform class loader is


:"+[Link]().getParent().getParent()); //null
}
}
/* getClassLoader() is a predefined method of class called Class available in
[Link] package and it's return type is ClassLoader.

getParent() is a predefined method of ClassLoader class in java, available in


[Link] package. It is an abstract class.
*/
----------------------------------------------------------------------
The following program explains that any .class file return type is
[Link]

package [Link].jvm_architecture;

class Customer{}
class Employee{}

public class Loader {

public static void main(String[] args)


{
Class cls = [Link];
[Link]([Link]());

cls = [Link];
[Link]([Link]());

}
----------------------------------------------------------------------
Linking :
---------
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 an
exception i.e [Link].

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.

[Link] is the sub class of [Link]

---------------------------------------------------------------------
prepare:
---------
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 and now it will initialize with
default value i.e 0.
----------------------------------------------------------------------
Resolve :-
-----------
All the symbolic references will be converted to direct references or actual
reference.

javap -verbose [Link]


Note :- By using above command we can read the internal details of .class file.
----------------------------------------------------------------------
Initialization :-
-----------------
In Initialization, all the static data member will get their actual (Original)
value as well as if any static block is present in the class then the static block
will be exceuted here.

static block :-
---------------
It is a very special block in java which will be executed automatically at the time
of loading the .class file into JVM memory by class loader sub system.

Example:-

static
{

The main purpose of static block to initialize the static data member of the class.

static block will be executed only once because class loading is possible only once
in java.

If we have multiple static blocks are present in a class then It will be executed
according to order (Top to bottom).

static block will be executed before the main method.

We can't access static field before it is declared otherwise we will get illegal
forward reference error but we can initialize in the static block before
declaration.

[Initialization is possible but accessing is not possible]


----------------------------------------------------------------------
11-11-2023
----------
//static block
class Foo
{
Foo()
{
[Link]("No Argument constructor..");
}

{
[Link]("Instance block..");
}

static
{
[Link]("Static block...");
}
}
public class StaticBlockDemo
{
public static void main(String [] args)
{
[Link]("Main Method Executed ");
}
}

Note :- In the above program [Link] file is not loaded into JVM memory so the
static block of [Link] file will not be executed.
---------------------------------------------------------------------
class Test
{
static int x;

static
{
x = 100;
[Link]("x value is :"+x);
}

static
{
x = 200;
[Link]("x value is :"+x);
}

static
{
x = 300;
[Link]("x value is :"+x);
}

static
{
x = 400;
[Link]("x value is :"+x);
}
}
public class StaticBlockDemo1
{
public static void main(String[] args)
{
[Link](Test.x);
}
}

Note -: From the above program it is clear that static blocks are executed
according to order i.e top to bottom
--------------------------------------------------------------------
class Foo
{
static int x;
static
{
[Link]("x value is :"+x);
}
}

public class StaticBlockDemo2


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

Note :- The program says that static variables are also initialized with default
value.
---------------------------------------------------------------------
class Demo
{
// static blank final variable
static final int a;

static
{
a = 10; //Initialization is compulsory becuae final blank static
}
}
public class StaticBlockDemo3
{
public static void main(String[] args)
{
[Link]("a value is :"+Demo.a);
}
}

static final blank variable, initialization is compulsory before use.


----------------------------------------------------------------------
class A
{
static
{
[Link]("A");
}

{
[Link]("B");
}

A()
{
[Link]("C");
}
}
class B extends A
{
static
{
[Link]("D");
}

{
[Link]("E");
}

B()
{
[Link]("F");
}

}
public class StaticBlockDemo4
{
public static void main(String[] args)
{
new B();
}
}

Note :- The programs Syas 2 things

a) Always the super class wil be loaded first then only sub class will be loaded
into JVM Memory.
b) The first two line of any constructor is reserved for super() and
non-static block i.e instance block.
----------------------------------------------------------------------
//illegal forward reference

class Demo
{
static
{
i = 10; //valid
//i = i + 19; //error
//[Link](i); //error
}

static int i;
}

public class StaticBlockDemo5


{

public static void main(String[] args)


{
[Link](Demo.i);
}
}

Note :- This program says :


If we declare static block before static variable declaration then inside
the static block we can initialize the static variable but we can't access that
means in other words we can perform write operation but we cannot perform read
operation.
----------------------------------------------------------------------
class Demo
{
static
{
i = 10; //before defining initialization is possible
}

static int i;
}
public class StaticBlockDemo6
{

public static void main(String[] args)


{
[Link](Demo.i);
}
}

Note :- This program says :


static variables memory allocation and initialization both are done at
prepare phase so inside a static block we can initialize the static data member
before declaration.
---------------------------------------------------------------------
Can we execute a Java program without main method ?
---------------------------------------------------------------
We can't execute a java program without main method, Upto jdk 1.6 it was possible
to execute a java program without main method by writing the static block.

From JDK 1.7 onwards now we can't execute java program without main method because
JVM checks the presence of the main method before initializing the class.

Eg:-
class WithoutMain
{
static
{
[Link]("Hello world");
[Link](0);
}
}
The above program was possible to execute upto JDK 1.6.
----------------------------------------------------------------------
How many ways we can load the .class file into JVM memory :
-----------------------------------------------------------
There are so many ways we can load our .class file into JVM memory, Here we have
few example

1) By using Java command

class Test
{
}

javac [Link] (Compile the [Link])


java Test (Here java command will make a request to load [Link] file
into JVM memory)

2) By Using Constructor [Object creation]

class Test
{
}
class ELC
{
public static void main(String [] args)
{
new Test(); [Making a request to JVM to load the [Link] file]
}
}

3) By accessing the static data member of the class :


class Test
{
static int x = 100;
}
class ELC
{
public static void main(String [] args)
{
[Link](Test.x); [Making a request to JVM to load the
[Link] file]
}
}

4) By using Inheritance :

class Alpha
{
}
class Beta extends Alpha
{
}

class ELC
{
public static void main(String [] args)
{
new Beta(); [Before [Link], first of all [Link] file will
be loaded and then [Link] file will be loaded]
}
}

5) By using Reflection API.

[Link](String className);

----------------------------------------------------------------------
1) By using Java tools
javac [Link]
java Test [Load the [Link] file into JVM memoy]

2) By using Constructor [Object creation].

3) By Calling static variable and static method using class name.

class Demo
{
static int x = 10;
static
{
[Link]("Static Block of Demo class Executed!!! :"+x);
}
}
public class ClassLoading
{
public static void main(String[] args)
{
[Link](Demo.x);
}
}
---------------------------------------------------------------------
13-11-2023
-----------
4) By using Inheritance :
-------------------------
By using Inheritance concept, whenever we want to load sub class .class file then
first of all super class .class file will be loaded and then only syb class .class
file will be loaded.

class A
{
static
{
[Link]("Static Block of super class A!!");
}
}
class B extends A
{
static
{
[Link]("Static Block of Sub class B!!");
}
}
class InheritanceLoading
{
public static void main(String[] args)
{
new B();
}
}
----------------------------------------------------------------------
By Using Reflection API :
--------------------------
In [Link] package, there is a predefined class called Class. This class called
Class contains one predefined static method forName(String className) which is used
to LOAD THE SPECIFIED .CLASS INTO JVM MEMORY DYNAMICALLY. [In eclipse, class name
must be Fully Qualified Name]

forName() method is throwing a checked execption i.e ClassNotFoundException.

This predefined static method forName(String className) returns [Link]


itself, the method whose rturn type is same class name
known as Factory Methods.

This Package contains two files :


---------------------------------
[Link]
---------
package [Link].dynamic_class_loading;

public class Foo


{
static
{
[Link]("Foo class static block");
}
}

[Link]
--------------------
package [Link].dynamic_class_loading;

public class DynamicLoading {

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


{
//In Eclise IDE Fully Qualified class name reqd
[Link]("[Link].dynamic_class_loading.Ravi");
}

}
---------------------------------------------------------------------
* What is the difference [Link] and
[Link].

[Link] :
----------------------------------
In Java whenever we try to load the .class file dynamically at runtime by using
[Link]() or loadClass() method of ClassLoader class and if the
required .class file is not availavle at RUNTIME then it will generate an execption
i.e [Link]

Note :- [Link](String className) does not have any concern with


compile time.

Program :
----------
class Foo
{
static
{
[Link]("static block gets executed...");
}
}
public class ClassNotFoundExceptionDemo
{
public static void main(String[] args) throws ClassNotFoundException
{
[Link]("Player");
}
}

In the above program [Link] will be generated because


[Link] file is not available at runtime.

[Link] :
--------------------------------
In this approach the class name is available at the time of compilation but after
compilation the .class file ([Link]) will be deleted by user manually or It
was re-located from one package to another package then at the time of execution
the required .class file is not available hence we will get
[Link].

Plaese notice, class was present at the time of compilation but at runtime the
required .class file is not available.

class Message
{
public void greet()
{
[Link]("Hello Everyone I hope you are fine..");
}
}
public class NoClassDefFoundErrorDemo
{
public static void main(String[] args)
{
Message m = new Message();
[Link]();
}
}

//After compilation delete the [Link] file mannually.


---------------------------------------------------------------------
What is the drawback on "new" keyword ?
OR
How to create the Object for the classes which are coming from the database or from
file.
OR
What is newInstance() method?

"new" keyword is suitable for creating the object for the classes which are
available at compilation time or at the time of writing the source code (.java
file) but on the other hand it is not suitable for
the classes are coming from database or some file at runtime dynamically.

In order to create the object for the classes which are coming from the database or
file at runtime we need to use newInstance() method available in [Link].

class Customer
{

}
class ObjectAtRuntime
{
public static void main(String [] args) throws Exception
{
Object obj = [Link](args[0]).newInstance();
[Link]([Link]().getName());
}
}

javac [Link]
java ObjectAtRuntime Customer

/* getclass() is the method of Object class and its return type is Class, so we can
apply any method of class called Class, getName() is the method of Class class.
*/
----------------------------------------------------------------------
class Customer
{
public void greet()
{
[Link]("Hello Batch 24");
}
}
class ObjectAtRuntime1
{
public static void main(String [] args) throws Exception
{
Object obj = [Link](args[0]).newInstance();
Customer c1 = (Customer) obj;
[Link]();
}
}

javac [Link]
java ObjectAtRuntime Customer
----------------------------------------------------------------------
14-11-2023
-----------
Runtime Data Areas :
--------------------
Once the .class file is loaded successfully in the JVM memory then the content of
the class is divided into different memory areas which are as follows :

a) Method Area
b) HEAP Area
c) Stack Area
d) PC Register
e) Native Method Stack

a) Method Area :
-------------------
In this area all class level information is available. Actually the .class file is
dumpped here hence we have all kinds of information related to class is available
like name of the class, name of the immediate super class, package name, method
name , variable name, static variable, all method available in that particular
class and so on.

This method area returns type [Link] class , this [Link] class
object can hold any .class file
(Class c = [Link])

There is only one method area per JVM.


----------------------------------------------------------------------
Methods of [Link] :
-----------------------------
1) public String getName() :- It is used to provide the class name
without class keyword.

2) public String getPackageName() :- It is used to provide the package


name from where the class is belonging.
3) public Method [] getDeclaredMethods() :- It will provide all the
declared methods available in the specified class. The return type of this
method is Method array.

4) public Field [] getDeclaredFields() :- It will provide all the


declared fields(variable static + non static ) available in the specified class.
The return type of this method is Field array.

Note :- Method and Field both are predefined classes available [Link]
package. Both contain getName() method to get the name of the method and name of
the field.

This package contains two files :


---------------------------------
[Link]
---------
package [Link].method_area;

import [Link];

public class Load


{
private int x = 10;
static int y = 20;
Scanner sc = new Scanner([Link]);

public void m1() {}

public void m2() {}

public void m3() {}

public void m4() {}

public void m5() {}

public void m6() {}


}

[Link]
----------------------
package [Link].method_area;

import [Link];
import [Link];

public class ClassDescription


{
public static void main(String[] args) throws Exception
{
Class cls = [Link](args[0]);

//Getting Complete information


[Link]("Class Name is :"+[Link]());

[Link]("Package Name is :"+[Link]());

[Link]("Methods Are :");


Method[] methods = [Link]();
int methodCount = 0;
for (Method method : methods)
{
[Link]([Link]());
methodCount++;
}
[Link]("Total Methods are :"+methodCount);

[Link]("Fields Are :");


Field[] fields = [Link]();

int fieldCount = 0;
for(Field field : fields)
{
[Link]([Link]());
fieldCount++;
}
[Link]("Total Fields are :"+fieldCount);
}
}
----------------------------------------------------------------------
Why static method does not act on instance variable ?
-----------------------------------------------------
All the static data member like static variable, static block, static nested inner
class and static method are executed at the time of loading .class file into JVM
memory, At the time of execution of these static data member, object is not
available and we known instance variables are the part of the object so, we cannot
act on instance variable using static area.

[Link]
----------
public class Demo
{
int x = 100;

public static void main(String[] args)


{
[Link]("x value is :"+x);
}
}
--------------------------------------------------------------------
class Test
{
private int x;

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

public static void access()


{
[Link]("x value is :"+x);
}

}
public class StaticTest
{
public static void main(String[] args)
{
Test t1 = new Test(10);
[Link]();
}
}

From the above two programs it is clear that we cannot access instance variables
from static area even object is already created.
----------------------------------------------------------------------
HEAP Area :
-----------
In java whenever we create the Object, all object related data like instance
variable and instance methods are strored in HEAP Area.
This is the 2nd layer architecture of JVM so from this area we can access the
static memeber of the class but vice versa is not possible.

We have only one Heap Area per JVM.


----------------------------------------------------------------------
Stack Area :
------------
In java all the methods are executed as a part of Stack Area. Whenever we call a
method then it creates Stack Frame. Each Stack Frame contains 3 parts
a) Local variable.
b) Frame Data.
c) Operand Stack.

We have n number of stack area in one JVM.


----------------------------------------------------------------------
24-11-2023
-----------
Garbage Collector :-
----------------------
In older languages like C++, It is the responsibility of the programmer to allocate
the memory as well as to de-allocate the memory otherwise there may be chance of
getting OutOfMemoryError.

But in Java a user is not responsible to de-allocate the memory that means memory
allocation is the responsibility of user but memory de-allocation is automatically
done by Garbage Collector.

Garbage collection is the process of looking at heap memory, identifying which


objects are in use and which are not, and deleting the unused objects (The object
which does not contain any references).

It is an automatic memory management in java. JVM internally contains a thread


called Garbage collector which is daemon thread, It is responsible to delete the
unused objects or the objects which are not containing any references in the heap
memory.

Note :- GC uses an algorithm mark and sweep to make an un-used objects eligible for
Garbage Collection.

The garbage Collector thread is visiting our program at regular interval to delete
the unused objects but as a programmer we can call garbge collector explicitly to
visit our program by using the following code.

[Link](); //explicitly calling the garbage collector


gc() is a predefined static method of System class.
--------------------------------------------------------------
There are 3 ways to make an Object eligible for Garbage Collector:
----------------------------------------------------------------
1) Assigning a null literal to reference variable

Employee e1 = new Employee();


e1 = null;

2) Creating an object inside the method

public void createObject()


{
Employee e2 = new Employee();
}
Note :- Once the method execution is over automatically Object is eligible for
Garbage Collector

3) Assigning new object to the Existing reference variable

Employee e3 = new Employee();

e3 = new Employee();

HEAP and Stack Diagram :


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

[Link] (Diagram 24-NOV-23)


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

class Customer
{
private String name;
private int id;

public Customer(String name , int id) //constructor


{
[Link]=name;
[Link]=id;
}

public void setId(int id) //setter


{
[Link]=id;
}

public int getId() //getter


{
return id;
}
}

public class CustomerDemo


{
public static void main(String[] args)
{
int val=100;
Customer c = new Customer("Ravi",2);
m1(c);

//GC [only one object 3000x is eligible for GC]

[Link]([Link]());
}

public static void m1(Customer cust)


{
[Link](5);

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

[Link](9);
[Link]([Link]());
}
}

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

[Link](s2.i1);
}
public static Sample modify(Sample s)
{
s.i1=9;
s = new Sample();
s.i1= 20;
[Link](s.i1);
s=null;
return s;
}
}

//20 9
-----------------------------------------------------------------------
25-11-2023
----------
HEAP and STACK diagram for [Link]
-----------------------------------------
public class Employee
{
int id=100;
public static void main(String[] args)
{
int val = 200;

Employee e1 = new Employee();

[Link]=val;

update(e1);

[Link]([Link]);

Employee e2 = new Employee();

[Link]=500;

switchEmployees(e2,e1);

//GC [2 objects 2000x and 4000x are eligible for GC]

[Link]([Link]);
[Link]([Link]);
}

public static void update(Employee e)


{
[Link]=500;
e=new Employee();
[Link]=400;
}

public static void switchEmployees(Employee e1,Employee e2)


{
int temp=[Link];
[Link]=[Link]; //500
e2= new Employee();
[Link]=temp;
}
}

//500 500 500


-------------------------------------------------------------------------
HEAP and STACK diagram for [Link]
-------------------------------------
public class Test
{
Test t;
int val;

public Test(int val)


{
[Link] = val;
}

public Test(int val, Test t)


{
[Link] = 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; //3000x


t3.t = t4; //4000x
t1.t = t2.t; //3000x
t2.t = t4.t; //2000x

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}

}
//300 200 400 200
--------------------------------------------------------------------------
HEAP and STACK Diagram for [Link]
------------------------------------
class Alpha
{
int val;
static int sval = 200;
static Beta b = new Beta();

Alpha(int val)
{
[Link] = 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;
[Link](ar[0].val);
[Link](ar[1].val);
}

public static Alpha[] fill(Alpha a1, Alpha a2)


{
[Link] = 15;

Alpha fa[] = new Alpha[]{a2, a1};


return fa;
}
}

//15 15
--------------------------------------------------------------------------
Runtime Data Areas :
--------------------
a) Method Area
b) Heap Area
c) Stack Area
d) PC register
e) Native Method Stack

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
------------
In java, JVM is an interpreter which executes the program line by line. JVM
(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 and
make it available to JVM at the time of execution so the overall execution becomes
very fast.
--------------------------------------------------------------------------
27-11-2023
----------
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.

Exception Hierarchy :
--------------------
This Exception hierarchy is available in the diagram (Exception_Hierarchy.png)

Criteria for Exception in Java :


---------------------------------
1) [Link]

int x = 10;
int y = 0;
int z = x /y; [Dividing a number by zero (int value) then we will get
[Link]]

2) [Link]
int []arr = {10,20,30};
[Link](arr[3]); [Accessing the index which is out of the
bound]

3) [Link]
String str = null;
[Link]([Link]()); [calling any method on null literal]

4) [Link]
String str = "Ravi";
int no = [Link](str);

-----------------------------------------------------------------------
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 is the super class of all the execptions whether it is a predefined
exception or user-defined exception in Java.
-----------------------------------------------------------------------
WAP that describes that Exception is the super class of all the exceptions we have
in java :

package [Link];

public class ExceptionSuper


{
public static void main(String[] args)
{
Exception e1 = new ArithmeticException("Dividing a number by zero");
[Link](e1);

Exception e2 = new ArrayIndexOutOfBoundsException("Index is out of


Bounds");
[Link](e2);
}
}
------------------------------------------------------------------------
WAP that describes that whenever an exception encounter in the program then program
will be terminated in the middle.

package [Link];

import [Link];

public class Test


{
public static void main(String[] args)
{
[Link]("Main method started!!!");
Scanner sc = new Scanner([Link]);

[Link]("Enter the value of x :");


int x = [Link]();

[Link]("Enter the value of y :");


int y = [Link]();

int result = x /y; //if y is 0 then program will halt


[Link]("Result is :"+result);
[Link]("Main method completed!!!");
[Link]();
}
}

Note :- In the above program if the value of y will be 0 then our program will halt
in the middle, it is called abnormal termination so, JVM is having default
exception handler, which will terminate the program and provide the appropriate
message.
------------------------------------------------------------------------
In order to work with Exception, Object Oriented Programming has provided the
following keywords :

1) try
2) catch
3) finally (try with resources [java 1.7])
4) throw
5) throws

-----------------------------------------------------------------------
28-11-2023
-----------
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 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.

WAP in java to implement try catch


-----------------------------------
package [Link];

import [Link];

public class TryDemo {

public static void main(String[] args)


{
[Link]("Main method started....");
Scanner sc = new Scanner([Link]);
try
{
[Link]("Enter the value of x :");
int x = [Link]();

[Link]("Enter the value of y :");


int y = [Link]();

int result = x /y;

[Link]("Result is :"+result);
[Link]("End of try block");

}
catch(Exception e)
{
[Link]("Inside catch Block");
[Link](e);
}
[Link]();
[Link]("Main method ended....");
}
}

In the above program, even exception encounter but program will be terminated
normally.
-----------------------------------------------------------------------
package [Link];

public class ThrowException


{
public static void main(String[] args)
{
try
{
//[Link](10/0); //new ArithmeticException();
throw new ArithmeticException();

}
catch(Exception e)
{
[Link]("Inside catch");
[Link](e);
}
}
}
-----------------------------------------------------------------------
Program that describes we should provide user-friendly message to our client

package [Link];

import [Link];

public class CustomerDemo


{
public static void main(String[] args)
{
[Link]("Hello Client, Welcome to my application!!");

Scanner sc = new Scanner([Link]);


try
{
[Link]("Enter the value of x :");
int x = [Link]();

[Link]("Enter the value of y :");


int y = [Link]();

int z = x/y;
[Link]("z value is :"+z);

}
catch(Exception e)
{
[Link]("Please don't put zero");
}
[Link]("Thank you 4 visiting!!");
[Link]();

}
}
-------------------------------------------------------------------------
29-11-2023
----------
Methods of Throwable class :
----------------------------
The Throwable class has provided the following methods to work with Exception.

1) public void printStackTrace() :


-------------------------------
By using this method we can get the complete details of an exception
like, exception name, exception error message, package name, class name, method
name, line number where exactly the exception encounter.

2) public String getMessage() :


---------------------------
It is used to provide only the error message.

[Link]
---------------------
package [Link];

public class PrintStackTrace


{
public static void main(String[] args)
{
[Link]("Main method started...");
try
{
String x = "Ravi";
int y = [Link](x);
[Link](y);
}
catch(Exception e)
{
[Link](); //For complete Exception details
[Link]("---------------------------");
[Link]([Link]()); //only for Exception message

}
[Link]("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,
NullPointerException and so on) which will handle only one type i.e specific type
of exception.

package [Link];

import [Link];
import [Link];

public class SpecificException


{
public static void main(String[] args)
{
[Link]("Main started");
Scanner sc = new Scanner([Link]);

try
{
[Link]("Enter your Roll :");
int roll = [Link]();
[Link]("Your roll Number is :"+roll);
}
catch(InputMismatchException e)
{
[Link]("Input is not in a proper format!!");
[Link]();
}

[Link]();
[Link]("Main ended");
}
}
-------------------------------------------------------------------------
Working with Infinity and Not a number(NaN) :
---------------------------------------------
10/0 -> Infinity ([Link])
10/0.0 -> Infinity

0/0 -> Undefined ([Link])


0/0.0 -> Undefined

While working Integral literal in both the cases i.e Infinity (10/0) and
Undefined (0/0) we will get [Link] because java software
people has not provided any final variable support to deal with
Infinity and Undefined.

On the other hand while working with floating point literal in the both cases i.e
Infinity (10/0.0) and Undefined (0/0.0) we have final 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

[Link]
---------------------------
package [Link];

public class InfinityFloatingPoint


{
public static void main(String[] args)
{
[Link]("Main method started");

[Link](10/0.0);
[Link](-10/0.0);
[Link](0/0.0);

[Link](0/0);
[Link](10/0);

[Link]("Main method 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 [Link];
public class MultipleTryCatch
{
public static void main(String[] args)
{
[Link]("Main method started!!!!");

try
{
int arr[] = {10,20,30};
[Link](arr[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array is out of limit!!!");
}

try
{
String str = null;
[Link]([Link]());
}
catch(NullPointerException e)
{
[Link]("ref variable is pointing to null");
}

[Link]("Main method ended!!!!");


}
}
-----------------------------------------------------------------------
* Multiple catch block with single try block :
--------------------------------------------
According to industry standard we should write try with multiple catch block so we
can provide proper information for each and every exception.

While working with multiple catch block always the super class catch block must be
last catch block.

From java 1.7 this multiple catch block we can also represent by using | symobl.

package [Link];
public class MultyCatch
{
public static void main(String[] args)
{
[Link]("Main Started...");
try
{
int a=10,b=3,c;
c=a/b;

[Link]("c value is :"+c);

int []x = {12,78,56};


[Link](x[5]);

}
catch(ArrayIndexOutOfBoundsException e1)
{
[Link]("Array is out of limit...");
}
catch(ArithmeticException e1)
{
[Link]("Divide By zero problem...");
}
catch(Exception e1)
{
[Link]("General");
}
[Link]("Main Ended...");
}
}
-----------------------------------------------------------------------
01-12-2023
----------
Multiple catch block using single try with Java 7 using | symbol.

package [Link];

public class MultyCatch1


{
public static void main(String[] args)
{
[Link]("Main method started!!!");
try
{
String str1 = "India";
[Link]([Link]());

String str2 = "nit";


int x = [Link](str2);
[Link]("Number is :"+x);
}
catch(NumberFormatException | NullPointerException e)
{
[Link]();
}

[Link]("Main method ended!!");


}

}
-----------------------------------------------------------------------
finally block :
---------------
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.

//Program with the combination of try and finally


package [Link];

public class FinallyBlock


{
public static void main(String[] args)
{
[Link]("Main method started");

try
{
[Link](10/0);
}
finally
{
[Link]("Finally Block");
}

[Link]("Main method ended");


}

//Program with the combination of try-catch and finally


--------------------------------------------------------
package [Link];

public class FinallyWithCatch


{
public static void main(String[] args)
{
try
{
int []x = new int[-2]; //We can't pass negative size of an array
in negative
x[0] = 12;
x[1] = 15;
[Link](x[0]+" : "+x[1]);
}
catch(NegativeArraySizeException e)
{
[Link]("Array Size is in negative value...");
}
finally
{
[Link]("Resources will be handled here!!");
}
[Link]("Main method ended!!!");
}
}
-----------------------------------------------------------------------
Limitation of finally block :
-----------------------------
The following are the limitations of finally block :

1) User is responsible to close the resources manually.


2) Due to finally block the length of the code will be increased.
3) While using finally block we should declare all our resources
outside of the try block otherwise the resourses will become
block level variable.

package [Link];

import [Link];
import [Link];

public class FinallyLimitation


{
public static void main(String[] args) throws Exception
{
[Link]("Main method started!!");
Scanner sc = new Scanner([Link]);
try
{
[Link]("Enter Employee Number :");
int empNo = [Link]();
[Link]("Employee Number is :"+empNo);

}
catch(InputMismatchException e)
{
[Link]("Input is not matching");
}
finally
{
[Link]();
[Link]("Finally Ended");
}
[Link]("Main Ended");
}

}
-----------------------------------------------------------------------
02-12-2023
-----------
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 :
----------
try(resource1 ; resource2) //Resources and Exception both will be
{ //handled
}
catch(Exception e)
{
}
There is a predefined interface available in [Link] package called AutoCloseable
which contains predefined abstract method i.e close()
which throws Exception.

There is another predefined interface available in [Link] package called


Closeable, this Closeable interface is the sub interface for Auto Closeable
interface.

public interface [Link]


{
public abstract void close() throws Exception;
}
public interface [Link] extends [Link]
{
}

Whenever we pass any resourse class as part of try with resources 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.

try(ResourceClass rc = new ResourceClass()) //This ResourceClass must


{ implements either
Closeable or AutoCloseable interface
} so, try block will
catch(Exception e) automatically call the
{ close() method.

The following program explains how try block is invoking the close() method
available in DatabaseResource class and FileResource class.

This package contains 3 files :


-------------------------------
[Link]
---------------------
package [Link].try_resource;

public class DatabaseResource implements AutoCloseable


{
@Override
public void close() throws Exception
{
[Link]("Database Resource closed");

[Link]
-----------------
package [Link].try_resource;

import [Link];
import [Link];

public class FileResource implements Closeable


{
@Override
public void close() throws IOException
{
[Link]("File Resource Closed");
}

[Link]
---------------------
package [Link].try_resource;

public class TryWithResource


{
public static void main(String[] args)
{
DatabaseResource dr = new DatabaseResource();
FileResource fr = new FileResource();
try(dr; fr)
{
[Link](10/0);
}
catch(Exception e)
{
[Link]();
}
[Link]("Main Method Ended");
}

}
-----------------------------------------------------------------------
Program on try-with Resources :
-------------------------------
package [Link].try_resource;

import [Link];
import [Link];

public class TryWithResourceDemo


{
public static void main(String[] args)
{
//From java 9 we can write resources outside of try
Scanner sc = new Scanner([Link]);

try(sc)
{
[Link]("Enter your Age :");
int age = [Link]();
[Link]("Your Age is :"+age);
}
catch(InputMismatchException e)
{
[Link]();
}
[Link]("Main Method Ended!!!");
}

}
Here in the above program we need to close Scanner class manually, it
will be taken care by try with resources.
----------------------------------------------------------------------
Exception propagation :-
--------------------------
Whenever we call a method and if the the callee method contains any kind of
exception and if callee method doesn't contain any kind of exception handling
mechanism (try-catch) then JVM will propagate the exception to caller method for
handling purpose. This is called Exception Propagation.

If the caller method also does not contain any exception handling mechanism then
JVM will terminate the method from the stack frame hence the remaining part of the
method(m1 method) will not be executed even if we handle the exception in another
caller method like main.

If any of the the caller method does not contain any exception handling mechanism
then exception will be handled by JVM, JVM has default exception handler which will
provide the exception message and terminates the program abnormally.

package [Link].try_resource;

public class ExceptionPropagationDemo


{
public static void main(String[] args)
{
[Link]("Main method started!!");
try
{
m1();
}
catch(ArithmeticException e)
{
[Link]("Handled in Main Method");
}
[Link]("Main method ended!!");
}
public static void m1()
{
[Link]("m1 method started!!");
m2();
[Link]("m1 method ended!!");
}
public static void m2()
{
[Link](10/0);
}
}
-----------------------------------------------------------------------
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 [Link];

public class NestedTryBlock


{
public static void main(String[] args)
{
try //outer try
{
String x = "India";
[Link]("It's length is :"+[Link]());

try //inner try


{
String y = "Ravi";
int z = [Link](y);
[Link]("z value is :"+z);

}
catch(NumberFormatException e)
{
[Link]("Number is not in a proper format");
}
}
catch(NullPointerException e)
{
[Link]("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 be executed.

package [Link];

import [Link];
import [Link];

public class TryWithCatchInsideCatch


{

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
try(sc)
{
[Link]("Enter your Roll number :");
int roll = [Link]();
[Link]("Your Roll is :"+roll);

}
catch(InputMismatchException e)
{
[Link]("Provide Valid input!!");

try
{
[Link](10/0);
}
catch(ArithmeticException e1)
{
[Link]("Divide by zero problem");
}

}
}

}
---------------------------------------------------------------------
05-12-2023
----------
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 finally block we cannot write any kind of statement.
(Unrechable)

package [Link];
public class ReturnExample
{
public static void main(String[] args)
{
[Link](methodReturningValue());
}

@SuppressWarnings("finally")
public static int methodReturningValue()
{
try
{
[Link]("Try block");
return 10/0;
}
catch (Exception e)
{
[Link]("catch block");
return 10/0;
}
finally
{
[Link]("Finally block");

}
}
-----------------------------------------------------------------------
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 otherwise we will get compilation error if we want to use
the local variable.

package [Link];

public class VariableInitialization


{
public static void main(String[] args)
{
int x;
try
{
x = 12;
[Link](x);
}
catch(Exception e)
{
x = 12; //Variable initialization is compulsory here
[Link](x);
}

[Link]("Main completed!!!");
}

}
-----------------------------------------------------------------------
* Difference between Checked Exception and Unchecked Exception :
----------------------------------------------------------------
Checked Exception :
----------------------
In java some exceptions are very common exceptions are called Checked excption 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 [Link]

Eg:
---
FileNotFoundException, IOException, InterruptedException,ClassNotFoundException,
SQLException and so on

Unchecked Exception :-
--------------------------
The exceptions which are rarely occurred in java and for these kinds of exception
compiler does not take very much 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

Eg:
---
ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
NumberFormatException, ClassCastException, ArrayStoreException and so on.
-------------------------------------------------------------------------
06-12-2023
-----------
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 [Link]

Unchecked Exception :
----------------------
1) Rare Exception
2) Comiler will not take any care
3) Handling is not Compulsory
4) Sub class of RuntimeException

When we should declare the method as throws and when we should write
--------------------------------------------------------------------
try-catch
---------
When to provide try-catch or declare the method as throws :-
---------------------------------------------------------------------
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 but on the other hand we
should declare the method as throws when we are not interested to handle the
exception and try to send it to the JVM for handling purpose.

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 )


FileNotFoundException(We are depending upon the file)
InterruptedException (Thread related problem)
ClassNotFoundException (class related problem)
SQLException (SQL related or database related problem)
-------------------------------------------------------------------------
* What is the difference between throw and throws :
----------------------------------------------------
throw :
--------
In case of predefined exception try block is responsible to create the exception
object and throw the exception object to the nearest catch block but it works with
predefined exception only.

If a user wants to throw an exception based on his own requirement and


specification by using userdefined exception then we should write throw keyword to
throw the user defined exception object explicitly. (throw new
LowBalanceException())

THROWING THE EXCEPTION OBJCET EXPLICITLY.

throws :-
---------
In case of checked Exception if a user is not interested to handle the exception
and wants to throw the exception to JVM, wants to skip from the current situation
then we should declare the method as throws.
It is mainly used to work with Checked Exception.
-------------------------------------------------------------------------
Types of exception in java :
-------------------------------
Exception can be divided into two types :

1) Predefined Exception OR Built-in Exception

2) Userdefined Exception OR Custom Exception

Predefined Exception :-
-------------------------
The Exceptions which are already defined by Java software people for some specific
purposes are called predefined Exception or Built-in exception.
Ex :
----
IOException, ArithmeticException and so on

Userdefined Exception :-
---------------------------
The exceptions which are defined by user according to their own use and requirement
are called User-defined Exception.

Ex:-
----
InvalidAgeException, GreaterMarksException
------------------------------------------------------------------------
Steps to create userdefined exception :
------------------------------------------
In order to create user defined exception we should follow the following steps.

1) A userdefined exception class must extends either Exception(Checked Exception)


Or RuntimeException(Unchecked Exception) as a super class.

a) If our userdefined class extends RuntimeException that menas we are creating


UncheckedException.

b) If our userdefined class extends Exception that menas we are creating


checkedException and exception handling is compulsory here.

2) The userdefined class must contain No argument constructor as well as


parameterized construtor(in case we want to pass some userdefined message).

We should take No argument constructor if we don't want to send any message


where as we should take parameterized constructor with super keyword if we want to
send the message to the super class.

3) We should use throw keyword to throw the Exception object manually


-------------------------------------------------------------------------
Program on user-defined Checked Exception :
-------------------------------------------
package [Link].userdefined_exception;

import [Link];

@SuppressWarnings("serial")
class InvalidAgeException extends Exception //Checked Exception
{
public InvalidAgeException()
{
}

public InvalidAgeException(String message)


{
super(message);
}
}

public class CustomCheckedException


{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
try(sc)
{
[Link]("Enter your age :");
int age = [Link]();

if(age < 18)


{
throw new InvalidAgeException("Invalid Age");
}
else
{
[Link]("Welcome to Vote");
}
}
catch(InvalidAgeException e)
{
[Link](e);
}
}
}

Program on user-defined UnChecked Exception :


-------------------------------------------
package [Link].userdefined_exception;

import [Link];

@SuppressWarnings("serial")
class GreaterMarksException extends RuntimeException
{
public GreaterMarksException()
{
}

public GreaterMarksException(String message)


{
super(message);
}
}
public class CustomUnChecked
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
try(sc)
{
[Link]("Enter the marks :");
int marks = [Link]();

if(marks > 100)


{
throw new GreaterMarksException("Invalid Marks");
}
else
{
[Link]("Your Marks is :"+marks);
}
}
catch(GreaterMarksException e)
{
[Link]();
}

[Link]("Main Completed");
}

}
------------------------------------------------------------------------
07-12-2023
----------
Some important rules to follow :
---------------------------------
a) If the try block does not throw any checked exception then in the corresponding
catch block we can't handle checked [Link] will generate compilation error
i.e "exception never thrown from the corresponding try statement"

Example :-

try
{
//try block is not throwing any checked Exception
}
catch(IOException e) //Error
{

}
-----------------------------------------------------------------------
package [Link].method_related_rule;

import [Link];
public class CatchingCheckedWithoutThrow
{
public static void main(String[] args)
{
try
{
throw new IOException();
}
catch(IOException e)
{
[Link]();
}

}
------------------------------------------------------------------------
b) If the try block does not throw any exception then in the corresponding catch
block we can write Exception, Throwable because both are the super classes for all
types of Exception whether it is checked or unchecked.

package [Link].method_related_rule;

import [Link];
import [Link];

public class CatchingWithSuperClass


{
public static void main(String[] args)
{
try
{
//throw new IOException();
}
catch(Exception e)
{
[Link]();
}

}
------------------------------------------------------------------------
c) At the time of method overriding if the super class method does
not reporting or throwing checked exception then the overridden method of sub
class not allowed to throw checked exception. otherwise it will generate
compilation error.(Sub class method can throws un-checked Exception)

package [Link].method_related_rule;
class Super
{
public void show()
{
[Link]("Super class method not throwing checked
Exception");
}
}
class Sub extends Super
{
@Override
public void show() //throws [Link]
{
[Link]("Sub class method should not throw checked
Exception");
}
}

public class MethodOverridingWithChecked {

public static void main(String[] args) {


// TODO Auto-generated method stub

}
------------------------------------------------------------------------
d) If the super class method declare with throws keyword to throw a checked
exception, then at the time of method overriding sub class method may or may not
use throws keyword.
If the Overridden method is also using throws
keyword to throw checked exception then it must be either same exception class or
sub class, it should not be super class as well as we can't add more exceptions in
the overridden method.

package [Link].method_related_rule;

import [Link];
import [Link];

class Base
{
public void show() throws IOException
{
[Link]("Super class method ");
}
}
class Derived extends Base
{
//throws is applicable but must be equal or sub class
public void show() throws FileNotFoundException
{
[Link]("Sub class method ");
}
}

public class MethodOverridingWithThrows


{
public static void main(String[] args)
{
[Link]("Overridden method may or may not throw checked
exception but if it is throwing then must be same or sub class");
}

}
------------------------------------------------------------------------
package [Link].method_related_rule;
class Parent
{
public void m1() throws InterruptedException
{
[Link]("Parent class m1 method");
}
}

class Child extends Parent


{
public void m1()
{
//super.m1(); //error becoz no protection
[Link]("Child class m1 method");
}
}

public class CallingSuperClassMethodWithThrows {

public static void main(String[] args) {


// TODO Auto-generated method stub

Note :- In the above program we are calling super class method which is throwing a
checked Exception but the caller method does not have any protection so compilation
error hence provide either try-catch or declare the method as throws.
----------------------------------------------------------------------
package [Link].method_related_rule;

import [Link];

class Parent1
{
public void m1() throws IOException
{
[Link]("Parent class m1 method");
}
}

class Child1 extends Parent1


{
public void m1() throws IOException
{
super.m1();
[Link]("Child class m1 method");
}
}

public class CallingSuperClassMethodWithThrows1 {

public static void main(String[] args)


{
[Link]("Main");

}
}

Here we are calling the super class method by declaring the method as
throws.
------------------------------------------------------------------------

package [Link].method_related_rule;

import [Link];

class Parent2
{
public void m1() throws InterruptedException
{
[Link]("Parent class m1 method");
}
}

class Child2 extends Parent2


{

public void m1()


{
try
{
super.m1();
}
catch(InterruptedException e)
{
[Link]();
}
}
}
public class CallingSuperClassMethodWithThrows2 {

public static void main(String[] args)


{
[Link]("main");

}
}

So the Conclusion is, if we are calling any method and that method is throwing any
checked exception then the caller method must have either try-catch or throws
(Protection is reqd).
------------------------------------------------------------------------
Input Output in java :
-----------------------
In order to work with input and output concept, java software people has provided a
separate package called [Link] package.

By using this [Link] package we can read the data from the user, creating file,
reading/writing the data from the file and so on.

How to take the input from the user using [Link] package :
------------------------------------------------------------
Scanner class is available from java 1.5 onwards but before 1.5, In order to read
the data we were using the following two classes which are available in [Link]
package.

1) DataInputStream (Deprecated)
2) BufferedReader

How to create the object :


--------------------------
DataInputStream :
-----------------
DataInputStream d = new DataInputStream([Link]);

BufferedRedaer :
----------------
It provides more faster technique because it internally stores the data in a buffer
and it is always recomended to read the data from the buffer.

InputStreamReader isr = new InputStreamReader([Link]);


BufferedReader br = new BufferedReader(isr);
OR
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

Working with Methods :


----------------------
1) public int read() :- It is used to read a single character from
the source and return the UNICODE value of
the character.
If the data is not available from the source then it will return
-1.

2) public String readLine() :- It is used to read multiple characters


or complete line from the source. The
return type of this method is String.

Program to read name from the keyboard :


-----------------------------------------
package [Link].input_data;

import [Link];

public class ReadName


{
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception
{
DataInputStream dis = new DataInputStream([Link]);
[Link]("Enter your Name :");
String name = [Link]();
[Link]("Your Name is :"+name);

}
}
-----------------------------------------------------------------------
Program to read age from the keyboard :
package [Link].input_data;

import [Link];
import [Link];
import [Link];

public class ReadAge


{

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


{
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter your Age :");
int age = [Link]([Link]());
[Link]("Age is :"+age);

}
-----------------------------------------------------------------------
Program to read the salary from the keyboard :
----------------------------------------------
package [Link].input_data;

import [Link];
import [Link];
import [Link];

public class ReadSalary {

public static void main(String[] args)


{
var br = new BufferedReader(new InputStreamReader([Link]));
try(br)
{
[Link]("Enter your Salary :");
double sal = [Link]([Link]());
[Link]("Salary is :"+sal);

}
catch(IOException e)
{
[Link]();
}

}
-----------------------------------------------------------------------
Program to read the character (gender) from the keyboard :
-----------------------------------------------------------
package [Link].input_data;

import [Link];
import [Link];
import [Link];

public class ReadGender {

public static void main(String[] args)


{
var br = new BufferedReader(new InputStreamReader([Link]));
try(br)
{
[Link]("Enter your Gender :");
char gender = (char) [Link]();
[Link]("Your Gender is :"+gender);

}
catch(IOException e)
{
[Link]();
}

}
-----------------------------------------------------------------------
Program to read the Employee Data :
-----------------------------------
package [Link].input_data;

import [Link];
import [Link];

public class EmployeeData


{
public static void main(String[] args) throws Exception
{
var br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter Employee Id :");
int id = [Link]([Link]());

[Link]("Enter Employee Gender :");


char gen = [Link]().charAt(0); //Here there will be buffer
problem if we use read() method.

[Link]("Enter Employee Name :");


String name = [Link]();

[Link]("Employee Data :");


[Link]("Id is :"+id);
[Link]("Gender is :"+gen);
[Link]("Name is :"+name);
}
}
------------------------------------------------------------------------
File Handling :
---------------
What is the need of File Handling ?
-----------------------------------
As we know variables are used to store some meaningful value in our program but
once the execution of the program is over, now we can't get those values so to hold
those values permanently in our memory we use files.

Files are stored in the secondary storage devices so, we can use/read the data
stored in the file anytime according to our requirement.

In order to work with File system java software people has provided number of
predefined classes like File, FileInputStream, FileOutputStream and so on. All
these classes are available in [Link] package. We can read and write the data in
the form of Stream.

-----------------------------------------------------------------
Streams in java :
--------------------
A Stream is nothing but flow of data or flow of characters to both the end.
Stream is divided into two categories

1) byte oriented Stream :-


------------------------
It used to handle characters, images, audio and video file in binary format.

2) character oriented Stream :-


--------------------------------
It is used to handle the data in the form of characters or text.

Now byte oriented or binary Stream can be categorized as "input stream" and "output
stream". input streams are used to read or receive the data where as output streams
are used to write or send the data.

Again Character oriented Stream is divided into Reader and Writer. Reader is used
to read() the data from the file where as Writer is used to write the data to the
file.

All Streams are represented by classes in [Link] package.

InputStream is the super class for all kind of input operation where as
OutputStream is the super class for all kind of output Operation for byte oriented
stream.

Where as Reader is the super class for all kind reading operation where as Writer
is the super class for all kind of writing operation in character oriented Stream.
---------------------------------------------------------------------
11-12-2023
----------
File :-
-----
It is a predefined class in [Link] package through which we can create file and
directory. By using this class we can verify whether the file is existing or not.

File f = new File("[Link]");

The above statement will not create any file, It actually create the file object
and perform one of the following two task.
a) If [Link] does not exist, It will not create it
b) if [Link] does exist, the new file object will be refer to the referenec
variable f

Now if the file does not exist and to create the file we should use createNewFile()
method as shown below.

File f = new File("[Link]");


[Link]();

File class has also provided a method called exists() through which we can verify
the corresponding file is available or not. The return type of this method is
boolean.

Note :- The return type of both the methods i.e exists() and createNewFile() are
boolean.

File class has also a predefined method called getName(), to get the name of the
file.
---------------------------------------------------------------
//Create a file and verify file is existing or not?
import [Link].*;
public class File0
{
public static void main(String[] args)
{
try
{
File f = new File("C:\\new\\[Link]");

if([Link]())
{
[Link]("File is existing");
}
else
{
[Link]("File is not existing");
}

if ([Link]())
{
[Link]("File created: " +
[Link]());
}
else
{
[Link]("File is already existing....");
}
}
catch (IOException e)
{
[Link](e);
}
}
}

H.W :- With the help of File class create directory.


------------------------------------------------------------------------
FileOutputStream : (Creating the file + Writing the data to the file)
----------------------------------------------------------------------
It is a predefined class available in [Link] package. The main purpose of this
class to create a new file and write the data to the file.

Whenever we want to write the data into the file using FileOutputStream class then
data must be available into the form of byte because It is byte-oriented class.

Note :- String class has provided a method called getBytes() through which we can
read the String data in byte format and the return type of this method is byte[].
(byte array)

Eg:-
String x = "India is Great";
byte b [] = [Link]();
Note :- try with resources are used to automatically close our resources.
-----------------------------------------------------------------------
//Creating and writing the data to the file

import [Link].*;
public class File1
{
public static void main(String args[]) throws IOException
{
var fout = new FileOutputStream("C:\\new\\[Link]");
try(fout)
{
String s = "Hyderabad is a nice city";
byte b[] = [Link]();

[Link](b);

[Link]("Success....");
}
catch(Exception e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
In binary Stream, whenever we want to write the data, the data must be available in
byte format, If we want to print the data
on the console(Monitor) the data must be converted into char.
---------------------------------------------------------------
FileInputStream :-
-----------------
It is a predefined class available in [Link] package. It is used to read the file
data/content. If we want to print the file data in console then data must be
available in char format.

//Reading tha data from the file


import [Link].*;
public class File2
{
public static void main(String s[]) throws IOException
{
var fin = new FileInputStream("C:\\new\\[Link]");

try(fin)
{
int i = 0;
while(true)
{
i = [Link]();
if(i==-1)
break;
[Link]((char)i);
}

}
catch(Exception e)
{
[Link](e);
}
[Link]();
}
}
----------------------------------------------------------------------
//wap in java to read the data from one file and to write the data to another file.
import [Link].*;
class File3
{
public static void main(String s[]) throws IOException
{
//Outside of try (Java 9 enhancement in try with resource)

var fin = new FileInputStream("[Link]");

var fout = new FileOutputStream("C:\\new\\[Link]");

try(fin; fout)
{
while(true)
{
int i = [Link]();
if(i==-1) break;
[Link]((char)i);
[Link]((byte)i);
}
}
catch(IOException e)
{
[Link]();
}
}
}
---------------------------------------------------------------------
Limitation of FileInputStream class :
-------------------------------------
As we know FileInputStream class is used to read the content from the file but it
can read the data from a single file only that means if we want to read the data
from two files at the same time then we should use a separate Stream called
SequenceInputStream.

SequenceInputStream :
-------------------------
It is a predefined class available in [Link] package. This class is used to read
the data from two files at the same time.

//Proram to read the data from two files at the same time
import [Link].*;
public class File4
{
public static void main(String args[]) throws IOException
{
var f1 = new FileInputStream("[Link]");
var f2 = new FileInputStream("[Link]");

var s = new SequenceInputStream(f1,f2);

try(f1; f2; s)
{
int i;
while(true)
{
i = [Link]();
if(i==-1)
break;
[Link]((char)i);
}
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
//Reading the data from two files and writing the data to a single file
import [Link].*;
public class File5
{
public static void main(String x[]) throws IOException
{
var f1 = new FileInputStream("[Link]");
var f2 = new FileInputStream("[Link]");

var fout = new FileOutputStream("C:\\new\\[Link]");

var s = new SequenceInputStream(f1,f2);

int i;
try(f1; f2; fout; s)
{
while(true)
{
i = [Link]();
if(i==-1)
break;
[Link]((char)i);
[Link]((byte)i);
}
}
catch(IOException e)
{
[Link]();
}
[Link]("File Created Successfully");
}
}
---------------------------------------------------------------------
12-12-2023
----------
Limitation of FileOutputStream :-
-----------------------------------
It is used to write the data to a single file only. It is not suitable if we want
to write the data more then one file at a time. In order to write the data more
than one file we should use a seperate Stream called ByteArrayOutputStream.

ByteArrayOutputStream :-
---------------------------
It is a predefined class available in [Link] package. By using this class we can
write the data to multiple files. ByteArrayOutputStream class provides a method
called writeTo(), through which we can write the data to multiple files.

//Program to write the data on multiple files.


import [Link].*;
public class File6
{
public static void main(String args[]) throws IOException
{
var fin = new FileInputStream("[Link]");

var f1 = new FileOutputStream("C:\\new\\[Link]");


var f2 = new FileOutputStream("C:\\new\\[Link]");
var f3 = new FileOutputStream("C:\\new\\[Link]");

var bout = new ByteArrayOutputStream();

try(fin; f1; f2; f3; bout)


{
int i;
while((i = [Link]()) != -1)
{
[Link]((byte)i); //writing tha data to ByteArrayOutputStream
}

[Link](f1);
[Link](f2);
[Link](f3);

[Link](); //clear the buffer for reusing of ByteArrayOutputStream


[Link]("Success");
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
//Working with images
import [Link].*;
public class File7
{
public static void main(String[] args) throws IOException
{
var fin = new FileInputStream("C:\\new\\image\\[Link]");

var f1 = new FileOutputStream("C:\\new\\image\\[Link]");


var f2 = new FileOutputStream("C:\\new\\image\\[Link]");
var f3 = new FileOutputStream("C:\\new\\image\\[Link]");

var bout = new ByteArrayOutputStream();

try(fin; f1; f2; f3; bout)


{
int i;
while((i = [Link]()) != -1)
{
[Link]((byte)i);
}
[Link](f1);
[Link](f2);
[Link](f3);
[Link]("success...");
[Link]();
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
BufferedOutputStream :-
--------------------------
It is a predefined class available in [Link] package.

Whenever we use the class FileOutputStream the data will be available on the Stream
but not in the buffer so there may be chance of miss memory management, It is
always preferable that the data should be available in the buffer.

By using this BufferedOutputStrean now the data is in the buffer so the execution
will become more faster.
----------------------------------------------------------------------
//Program to put the data in the buffer for fast execution
import [Link].*;
class File8
{
public static void main(String args[]) throws IOException
{
var fout = new FileOutputStream("C:\\new\\[Link]");

var bout = new BufferedOutputStream(fout);

try(fout ; bout)
{
String s = "Hyderabad is a nice city";
byte b[] = [Link]();
[Link](b);
[Link]("success...");
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
BufferedInputStream :-
-------------------------
It is a predefined class available in [Link] package. Whenever we use
FileInputStream to read the data/content from the file the data will be available
on the Stream but not in the buffer so there may be a chance of miss memory
management so we should take the data into the buffer by using BufferedInputStream
class so overall the execution will become faster.

//BufferedInputStream
import [Link].*;
public class File9
{
public static void main(String args[]) throws IOException
{
var fin = new FileInputStream("[Link]");
var bin = new BufferedInputStream(fin);

try(fin ; bin)
{
int i;
while((i = [Link]()) != -1)
{
[Link]((char)i);
}
}
catch(IOException e)
{
[Link]();
}
[Link]();
}
}
-----------------------------------------------------------------------
Writing and Reading the primitive data to the files :-
----------------------------------------------------------
It is possible to write the primitive data(byte,short,int, long, float, double,
char and boolean) to the file.

In order to write primitive data to the file we should use a predefined class
available in [Link] package called DataOutputStream.

It provides various methods like writeByte(), writeShort(), writeInt() and so on to


write the data to the file.

If we want to read the primitive data from the file we can use a predefined class
available in [Link] package called DataInputStream, this class provides various
methods like readByte(), readShort(), readInt() and so on.

Note :- For writing String into a file we have writeBytes() and to read the String
data from the file we have readLine() method.

[DataInputStream class readLine() is deprecated now, so compilation warning ]


-----------------------------------------------------------------------
//DataOutputStream and DataInputStream
import [Link].*;
public class File10
{
public static void main(String args[]) throws IOException
{
var fout = new FileOutputStream("C:\\new\\[Link]");
var dout = new DataOutputStream(fout);

try(fout ; dout)
{
[Link](true);
[Link]('A');
[Link](Byte.MAX_VALUE);
[Link](Short.MAX_VALUE);
[Link](Integer.MAX_VALUE);
[Link](Long.MAX_VALUE);
[Link](Float.MAX_VALUE);
[Link]([Link]);//PI is a final static variable
[Link]("Hello India...");
[Link]();//For reuse purpose
}
catch(IOException e)
{
[Link]();
}

[Link]("Reading the Primitive data from the file!!!");

var fin = new FileInputStream("C:\\new\\[Link]");


var din = new DataInputStream(fin);
try(fin ; din)
{
boolean f = [Link]();
char c = [Link]();
byte b = [Link]();
short s = [Link]();
int i = [Link]();
long l = [Link]();
float ft = [Link]();
double d = [Link]();
String x= [Link]();//for reading String (deprecated)

[Link](f +"\n"+c+"\n"+b+"\n"+s+"\n"+i+"\n"+l+"\n"+ft+"\
n"+d+"\n"+x);
}
catch(IOException e)
{
[Link]();
}

}
}
----------------------------------------------------------------------
* Serialization and De-Serialization :
--------------------------------------

---------------------------------------
It is a technique through which we can store the object data in a file. Storing the
object data into a file is called Serialization on the other hand Reading the
object data from a file is called De-serialization.

In order to perform serialization, a class must implements Serializable interfcae,


predefined marker interface in [Link] package.

[Link] package has also provided a predfined class called ObjectOutputStream to


perform serialization i.e writing Object data to a file using writeObject() method.

where as ObjectInputStream is also a predefined class available in [Link] package


through which we can read the Object data from a file using readObject(). The
return type of readObject() is Object.
---------------------------------------------------------------------
3 files :
----------
[Link]
--------------
package [Link].ser_der;

import [Link];
import [Link];

public class Employee implements Serializable


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

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


super();
[Link] = employeeId;
[Link] = employeeName;
[Link] = employeeSalary;
}

public static Employee getEmployeeObject()


{
Scanner sc = new Scanner([Link]);
[Link]("Enter Employee Id :");
int id = [Link]();

[Link]("Enter Employee Name :");


String name = [Link]();
name = [Link]();

[Link]("Enter Employee Salary :");


double sal = [Link]();

Employee e1 = new Employee(id, name, sal);


return e1;
}

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

[Link]
------------------------

package [Link].ser_der;

import [Link];
import [Link];
import [Link];
import [Link];
public class StoreEmployeeObject {

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


{
Scanner sc = new Scanner([Link]);
[Link]("How many Employee Objects we want to write :");
int no = [Link]();

var fout = new FileOutputStream("C:\\new\\[Link]");


var oos = new ObjectOutputStream(fout);

try(fout ; oos; sc)


{
for (int i=1; i<=no ; i++)
{
Employee obj = [Link]();
[Link](obj);
}
}
catch(Exception e)
{
[Link]();
}

[Link]
---------------------------
package [Link].ser_der;

import [Link];
import [Link];
import [Link];

public class RetrieveEmployeeObject {

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


{
var fin = new FileInputStream("C:\\new\\[Link]");
var ois = new ObjectInputStream(fin);

try(fin ; ois)
{
Employee emp = null;
while((emp = (Employee)[Link]())!=null)
{
[Link](emp);
}
}
catch(Exception e)
{
[Link]("End of File reached :"+e);
}

}
}
-----------------------------------------------------------------------
13-12-2023
----------
transient keyword :
------------------
If we don't want to perform serialization operation on a prticular field then we
should declare that field with transient keyword so we will get the default value
for that particular field.

class Product
{
private transient int productId; -> 0
private transient String productId; -> null
}

3 files :
---------
[Link]
----------
package [Link].ser_der_demo;

import [Link];
import [Link];
import [Link];
import [Link];

public class Bank implements Serializable


{
private transient int bankIfscCode;
private String bankName;
private transient String branchLocation;

public Bank(int bankIfscCode, String bankName, String branchLocation) {


super();
[Link] = bankIfscCode;
[Link] = bankName;
[Link] = branchLocation;
}

@Override
public String toString() {
return "Bank [bankIfscCode=" + bankIfscCode + ", bankName=" + bankName
+ ", branchLocation=" + branchLocation
+ "]";
}

public static Bank getBankObject() throws NumberFormatException, IOException


{
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter Bank IFSC CODE :");


int code = [Link]([Link]());

[Link]("Enter Bank Name :");


String name = [Link]();

[Link]("Enter Bank Location :");


String location = [Link]();

return new Bank(code, name, location);


}

[Link]
------------------------
package [Link].ser_der_demo;

import [Link];
import [Link];
import [Link];
import [Link];

public class StoringBankObject


{
public static void main(String[] args) throws IOException
{
var fout = new FileOutputStream("C:\\new\\[Link]");
var oos = new ObjectOutputStream(fout);
Scanner sc = new Scanner([Link]);

try(fout; oos; sc)


{
[Link]("How many Objects ?");
int obj = [Link]();

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


{
Bank object = [Link]();
[Link](object);
}

}
catch([Link] e)
{
[Link]("Serialization is not possible :"+e);
}
catch(Exception e)
{
[Link]("general Exception");
}

[Link]("Bank Object stored in the file");


}

[Link]
--------------------------
package [Link].ser_der_demo;

import [Link];
import [Link];
import [Link];
import [Link];

public class RetrievingBankObject {

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


{
var fin = new FileInputStream("C:\\new\\[Link]");
var ois = new ObjectInputStream(fin);

try(fin ; ois)
{
Bank obj;

while((obj = (Bank) [Link]())!=null)


{
[Link](obj);
}

}
catch(EOFException e)
{
[Link]("File ended :"+e);
}
catch(Exception e)
{
[Link]("general Exception");
}
}

H.W :- Perform Serialization and De-serialization on Product class


----------------------------------------------------------------------
Working with Character Stream :
-------------------------------
FileWriter class :
------------------
It is a predefined class available in [Link] package, Using this class we can
directly write String (collection of characters) to the file.

Actually It is a character oriented Stream where as if we work with


FileOutputStream class, It is byte oriented Stream.
---------------------------------------------------------------------
//FileWriter
import [Link].*;
public class File11
{
public static void main(String args[]) throws IOException
{
var fw = new FileWriter("C:\\new\\[Link]");
var bw = new BufferedWriter(fw);

try(fw; bw)
{
[Link]("It is in Asia");
[Link]("Success....");
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
//FileWriter
import [Link].*;
class File12
{
public static void main(String args[]) throws IOException
{
var fw = new FileWriter("C:\\new\\[Link]");
var bw = new BufferedWriter(fw);

try(fw;bw)
{
char c[ ] = {'H','E','L','L','O', ' ',' ','W','O','R','L','D'};

[Link](c);
[Link]("Success....");
}
catch(Exception e)
{
[Link]();
}
}
}
---------------------------------------------------------------------
FileReader class :
--------------------
It is a predefined class available in [Link] package, It is a character oriented
Stream. The main purpose of this class to read the data in the character format
directly from the file.
---------------------------------------------------------------
//FileReader
import [Link].*;
public class File13
{
public static void main(String args[]) throws IOException
{
var fr = new FileReader(args[0]); //Command Line Arg
var br = new BufferedReader(fr);
try(fr ; br)
{
while(true)
{
int i = [Link]();
if(i == -1)
break;
[Link]((char)i);
}
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
import [Link].*;
public class File14
{
public static void main(String[] args) throws IOException
{
var fr = new FileReader("C:\\new\\[Link]");
var fw = new FileWriter("C:\\new\\[Link]");

try(fr;fw)
{
int i;
while((i=[Link]())!= -1)
{
[Link](i);
}
}
catch(Exception e)
{
}
}
}

Note :- Here we are trying to write the image file using FileWriter class which is
not possible because image internally contains binary data and FileWriter is used
to write character Stream.
---------------------------------------------------------------------
PrintWriter :
--------------
It is a predefined class available in [Link] package. The main purpose of this
class to write the primitive data into text format.

Methods :
-----------
printf() :- It is a predefined method of PrintWriter class which takes two
parameter
a) Specification of the data so we can print the data according to
specification(Formatted String)
b) Parameter to print the actual data.

//PrintWriter
import [Link].*;
public class File15
{
public static void main(String[] args) throws IOException
{
PrintWriter writeData = new PrintWriter("C:\\new\\[Link]");

try(writeData)
{
int roll = 15;
//Writing primitive data into text format
[Link]("My roll number is : %d ", roll);
}
catch(Exception e)
{
[Link]();
}
}
}
--------------------------------------------------------------------
import [Link];
import [Link];
import [Link];

public class File16


{
public static void main(String[] args) throws IOException
{
var filename = "C:\\new\\[Link]";
var fileWriter = new FileWriter(filename, true);
var bufferedWriter = new BufferedWriter(fileWriter);

try(fileWriter;bufferedWriter)
{

// Append text to the file


String textToAppend = "My Name is Raj";
[Link](textToAppend);

//Moving the cursor to the next line


[Link]();

textToAppend = "I lives in hyderabad";


[Link](textToAppend);

[Link]("Text appended successfully to the file.");


}
catch (IOException e)
{
[Link]("An error occurred while appending the text to the
file: " + [Link]());
}
}
}
----------------------------------------------------------------------
14-12-2023
-----------
String Handling in java :
-------------------------
A string literal in Java is basically a sequence of characters. These characters
can be anything like alphabets, numbers or symbols which are enclosed with double
quotes. So we can say String is a collection of alpha-numeric character.

How we can create String in Java :-


-----------------------------------
In java String can be created by using 3 ways :-

1) By using String Literal

String x = "Ravi";

2) By using new keyword

String y = new String("Hyderabad");

3) By using character array


char z[] = {'H','E','L','L','O'};
-----------------------------------------------------------------------
Immutability in String (Diagram 14-DEC-23)
-------------------------------------------
In java Strings Objects are immutable means unchanged so, whenever we create a
String object in java it can't be modifiable.

Strings literals are created in a very special memory of HEAP called String
Constant Pool(SCP) and it is not eligible for garbage collection.

String once created can't be modifiable.


--------------------------------------------------------------------
Facts about String and memory :-
--------------------------------------
In java Whenever we create a new String object by using String literal, first of
all JVM will verify whether the String we want to create is pre-existing (already
available ) in the String constant pool or not.

If the String is pre-existing (already available) in the String Constant pool then
JVM will not create any new String object, the same old existing String object
would be refer by new reference variable as shown in the diagram(14-DEC)

Note :- In SCP area we can't have duplicate String Object.


--------------------------------------------------------------------
* Why String objects are immutable :
-------------------------------------
As we know a String object in the String constant pool can be refer by multiple
reference variables, if any of the reference variable will modify the String Object
value then it would be very difficult for the another reference variables pointing
to same String object to get the original value, what they have defined earlier as
shown in the diagram.(09-SEP)
That is the reason Strings are immutable in java .
----------------------------------------------------------------------
WAP that describes String objects are eligible or not 4 GC.

package [Link];

public class StringGCEligibility


{
public static void main(String[] args) throws InterruptedException
{
String str1 = "india";
[Link]([Link]());

str1 = null;
[Link](); //Calling GC explicitly

[Link]("Main thread is waiting here for 5 sec ");


[Link](5000);
[Link]("Main thread wake up ");

String str2 = "india";


[Link]([Link]());
}

From the above program it is clear that String objects are not eligible for GC.
-----------------------------------------------------------------------
15-12-2023
----------
Working with String class methods :
-----------------------------------
//Three Ways to create the String Object
public class Test
{
public static void main(String[] args)
{
String s1 = "Hello World"; //Literal
[Link](s1);

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


[Link](s2);

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


[Link](s3);
}
}
-----------------------------------------------------------------------
//Solution of immutability [assigning to reference variable]
class Test2
{
public static void main(String[] args)
{
String x = new String("india");
String y = [Link]();
[Link](x);
[Link](y);
}
}
----------------------------------------------------------------------
//String is collection of alpha-numeric character
public class Test3
{
public static void main(String[] args)
{
String x="B-61 Hyderabad";
[Link](x);

String y = "123@$5";
[Link](y);

String z = "67.90";
[Link](z);

String p = "A";
[Link](p);
}
}
-----------------------------------------------------------------------
Working with methods of String :-
--------------------------------------
String class has provided number of predefined methods to work with String which
are as follows :-

1) public char charAt(int indexPosition) :-


--------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to extract or fetch or retrieve a single character from the given String.

We need to pass the index position as a parameter to the method and based on the
index position it will extract the character. The return type of this method is
char.

//Program on charAt(int indexPosition)


class Test4
{
public static void main(String[] args)
{
String x = "Hello Hyderabad";

char ch1 = [Link](6);


[Link](ch1); //H

ch1 = [Link](4);
[Link](ch1); //o

ch1 = [Link](9);
[Link](ch1); //e
}
}
----------------------------------------------------------------------
public String concat(String str) :-
--------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to concat or append two Strings. This can be also done by using
concatenation operator '+'.

This method takes String as a parameter and the return type of this method is
String.

//Program on concat(String str)


public class Test5
{
public static void main(String[] args)
{
String s1 = "Data";
String s2 = "base";
String s3 = [Link](s2);
[Link]("String after concatenation :"+s3);

String s4 = "Tata";
String s5 = "Nagar";
String s6 = s4+s5;
[Link]("String after concatenation :"+s6);

String s7 = "Naresh";
[Link]([Link](" Technology"));
}
}
----------------------------------------------------------------------
public boolean equals(Object obj) :-
--------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to verify whether two Strings are equal or not based on the content.

If both the Strings are equal it will return true otherwise it will return [Link]
is case sensitive method.

It takes Object as a parameter because it is an overridden [Link] is overridden


from Object class.
----------------------------------------------------------------------
//static Authentication using boolean equals(Object str)

public class Test6


{
public static void main(String[] args)
{
String username = args[0];

if([Link]("Ravi"))
{
[Link]("Welcome Ravi");
}
else
{
[Link]("Sorry! wrong username /Password");
}
}
}
-----------------------------------------------------------------------
package [Link];

import [Link];
import [Link];

public class Main


{
public static void main(String[] args)
{
Predicate<String> p1 = str -> [Link]("NIT");

Scanner sc = new Scanner([Link]);


[Link]("Enter the Institute Name :");
String name = [Link]();
[Link]("Are u the student of NIT :"+[Link](name));
[Link]();
}

}
-----------------------------------------------------------------------
public boolean equalsIgnoreCase(String str) :-
--------------------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to Compare two Strings based on the content by ignoring the case.
This method takes String as a parameter and return type of this method is boolean.
It comapres two Strings by ignoring the case so it is not a case sensitive method.

Hence for this method 'A' and 'a' both are same.

//Program on boolean equalsIgnoreCase(String s)


public class Test7
{
public static void main(String[] args)
{
String username = args[0];
if([Link]("Raviinfotech"))
{
[Link]("Welcome to Raviinfotech channel");
}
else
{
[Link]("Sorry! wrong username /Password");
}
}
}
-----------------------------------------------------------------------
IQ
What is differenec b/w == operator and equals(Object obj) method of String class

equals(object obj) method of String class compares two strings based on the content
because it is an overriden method where as == operator compares two Strings based
on the reference i.e memory address.

//IQ
public class Test8
{
public static void main(String[] args)
{
String s1="India";
String s2="India";
String s3=new String("India");

[Link](s1==s2); //true
[Link](s1==s3); //false

[Link]([Link](s2)); //true
[Link]([Link](s3)); //true
}
}

Note :- String class has overridden equals(Object obj) method from Object class
because Object class equals(Object obj) method meant for memory address comparison
but this overridden String class equals(Object obj) meant for content comparison.

Note :- String is a final class in java


-----------------------------------------------------------------
public int length() :-
----------------------
It is a predefined method available in the String class. The main purpose of this
method to find out the length of the given String. The return type of this method
is int.

Note :-
-------
Length and Size always start from 1 where as index of the character String always
starts from 0.

//Program on public int length()


class Test9
{
public static void main(String[] args)
{
String x = "Naresh Tech";
int len = [Link]();
[Link]("The length of "+x+" is :"+len);
}
}
----------------------------------------------------------------------
public String replace(char old, char new) :-
----------------------------------------------------
It is a predefined overloaded method available in the String class. The main
purpose of this method to replace a character or a String with another character or
String. The return type of this method is String.

By using this method we can replace a single character or a complete String from
the given String.

//replace() :-Replaces occurrences of a character with a new character


//public String replace(char old, char new)
public class Test10
{
public static void main(String [] args)
{
String x = "oxoxoxox";
[Link]("String before replacement :"+x);

[Link]("String after replacement :"+[Link]('x','X'));

String y="Manager";
[Link]([Link]("Man","Dam"));
}
}
-----------------------------------------------------------------------
public int compareTo(String s) :-
-------------------------------------
It is a predefined method available in the String class. The main purpose of this
method two compare two String based on character by character, comparison of two
Strings chracter by chracter based on the UNICODE values are called Lexicographical
comparison or dictionary comparison or alphabetical comparison(String case).

The return type of this method is [Link] takes String as a parameter.

If s1 and s2 are two valid Strings

if s1==s2 -> 0

if s1>s2 -> +ve

if s1<s2 -> -ve A B


----------------------------------------------------------------------
//public int compareTo(String s)
public class Test11
{
public static void main(String [] args)
{
String s1="Sachin"; //PQRS S > R
String s2="Sachin";
String s3="Ratan";

[Link]([Link](s2)); //0
[Link]([Link](s3)); //1 [Sachin with Ratan]
[Link]([Link](s1)); //-1 [Ratan With Sachin]

String s4 = "Apple";
String s5 = "apple";
[Link]([Link](s5)); // -32 [65 to 97]
[Link]([Link](s4)); // 32 [97 to 65]

String s6 = "Ravi";
String s7 = "Raj";
[Link]([Link](s7)); //+-ve [j to v]

}
}
-----------------------------------------------------------------------
public String substring(int startIndex) :-

public String substring(int startIndex, int endIndex) :-


-------------------------------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to extract the part of the specified string based on the index position.

In this method the startIndex starts from 0 whereas endIndex starts from 1.

Both index will be inclusive for printing the value

If end index will be less than start index then we will get an exception i.e
StringIndexOutOfBoundsException
substring(5,2);

If start index and end index both are equal, nothing will print

Nither start index nor end index will accept (-ve) value otherwise
StringIndexOutOfBoundsException.

public class Test12


{
public static void main(String [] args)
{
String x="HYDERABAD";
[Link]([Link](2,7)); //DERAB

[Link]([Link](3)); //ERABAD

[Link]([Link](3,3));

//[Link]
//[Link]([Link](6,3));

//[Link]
[Link]([Link](6, -3));
}
}
-----------------------------------------------------------------------
public boolean isEmpty() :-
------------------------------
It is a predefined method available in the String class. The main purpose of this
method to check whether a String is empty or not. This method returns true if the
String is empty that means length is 0, otherwise it will return false.
The return type of this method is boolean.
----------------------------------------------------------------
//public boolean isEmpty()

public class Test13


{
public static void main(String args[])
{
String str1 = "Java by James Gosling";
String str2 = "";

[Link]([Link]());
[Link]([Link]());
}
}
----------------------------------------------------------------------
public String intern() :
---------------------------
It is a predefined method available in the String class. The main purpose of this
method to return canonical representation for the string object that means String
interning ensures that all strings having the same contents use the same memory
location.

The return type of this method is String

//public String intern()


//Returns the Canonical representation for the String object.
public class Test14
{
public static void main(String args[])
{
String s1 = new String("india");
String s2 = new String("india");
[Link](s1 == s2);

s1 = [Link]();
s2 = [Link]();
[Link](s1 == s2);

String s3 = "Hyd";
String s4 = new String("Hyd");
[Link](s3 == s4);
s4 = [Link]();
[Link](s3 == s4);

}
}

Note :- Java automatically interns the string literals but we can manually use the
intern() method on String object created by new keyword so all the Strings which
are having same content will get the same String and return the same memory
address(Canonical representation for the String ).

From the above program it is clear that, All that String having same content will
represent the same memory address so the hashcode value will be same.
public class EnumTest {

public static void main(String[] args)


{

String s1 = new String("india");


String s2 = new String("india");
String s3 = "india";

[Link]([Link]()+" : "+[Link]()+" : "+[Link]());


}

}
--------------------------------------------------------------------
//IQ
public class Test15
{
public static void main(String args[])
{
String x = "india";
[Link]("it's length is :"+[Link]); //error

String [] y = new String[10];


[Link]("it's length is :"+[Link]()); //error
}
}

With array variable we have length property where as with String ref variable we
have length() method.
----------------------------------------------------------------------

//public boolean startsWith(String prefix)


//public boolean endsWith(String suffix)

Both the methods are available in String class.

startsWith() is used to verify that the given String is Starting with prefix String
or not, if yes it will return true otherwise it will return false.

endsWith() is used to verify that the given String is ending with suffix String or
not, if yes it will return true otherwise it will return false.

Both the methods are case-sensitive.

Both methods take String as a parameter and return type is boolean.

//public boolean startsWith(String prefix)


//public boolean endsWith(String suffix)

public class Test16


{
public static void main(String args[])
{
String s="Sachin Tendulkar";
[Link]([Link]("Sa"));
[Link]([Link]("r"));
}
}
----------------------------------------------------------------------
public int indexOf(String str) :-
---------------------------------
It is a predefined method available in the String class. The main purpose of this
method to find out the index position of the specified String in the existing
String.

It will serach the index position of the first occurrance of the specified String
as a parameter.

It takes String as a parameter and return type of this method is int.

//public int indexOf(String x)


public class Test17
{
public static void main(String args[])
{
String str = "India is my country and It is in Asia";
int index = [Link]("is");
[Link]("First Occurrance of is :"+index);
}
}
---------------------------------------------------------------------
public int lastIndexOf(String x) :-
--------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to find out the last index position of the Specified String in the existing
String.

It will serach the index position of the last occurrance of the String.

It takes String as a parameter and return type of this method is int.

//public int lastIndexOf(String x)


public class Test18
{
public static void main(String args[])
{
String s1 = "it is a nice city";
int lastIndex = [Link]("it");
[Link]("Last occurrance of it, is :"+lastIndex+ "th
position");
}
}
---------------------------------------------------------------------
18-12-2023
-----------
//public String toUpperCase() :- converts to upper case letter
public class Test19
{
public static void main(String args[])
{
String str = "india";
[Link]([Link]());
}
}
----------------------------------------------------------------------
//public String toLowerCase() converts to lower case.
public class Test20
{
public static void main(String args[])
{
String str = "INDIA";
[Link]([Link]()); //india
}
}
---------------------------------------------------------------------
public String trim() :-
-------------------------
It is a predefined method available in the String class. The main purpose of this
method to remove the white spaces from the begning (heading) and end (trailing)
from the String.

It will not remove any white space in the between the String. The return type of
this method is String.
--------------------------------------------------------------
//program on trim()
public class Test21
{
public static void main(String args[])
{
String s1=" Tata ";
[Link](s1+"Nagar"); // Tata Nagar

s1 = " Hello Data ";


[Link]([Link]() +"Base"); //Hello DataBase

}
}
----------------------------------------------------------------------
public String [] split (String delimiter) :
-----------------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to split or break the given String based on specified delimiter(Criteria).

The return type of this method is String array because It returns the collection of
String tokens or multiple Strings.

//public String [] split(String delimiter)

public class Test22


{
public static void main(String args[])
{
String s1="Hyderabad is a nice city";
String [] words = [Link](" "); //Space is Delimiter
for(String word : words)
{
[Link](word);
}
[Link]("..............");

String s2="Hyderabad is a nice city";


words = [Link]("a");

for(String word : words)


{
[Link](word);
}
}
}
----------------------------------------------------------------------
/* There is a predefined class called StringTokenizer available in [Link]
package, is also used to split the String */

public int countTokens()


public boolean hasMoreTokens()
public String nextToken()

import [Link].*;
public class STDemo
{
public static void main(String [] args)
{
String str ="Hyderabad is a lovely place";
StringTokenizer st = new StringTokenizer(str,"a");

[Link]("Number of tokens :"+[Link]());


[Link]("The tokens are :");

while([Link]())
{
String token = [Link]();
[Link](token);
}
}
}
----------------------------------------------------------------------
public char[] toCharArray() :-
--------------------------------
It is a predefined method available in the String class. The main purpose of this
method to convert the given string into a sequence of characters. The returned
array length is equal to the length of the string.

This method does not take any parameter and return type is character array.
---------------------------------------------------------------
//public char[] toCharArray()
public class Test23
{
public static void main(String args[])
{
String str = "Java technology";
char ch [] = [Link]();

for(char c : ch)
{
[Link](c+" ");
}
[Link]();
}
}
---------------------------------------------------------------------
package [Link];

public class StringToCharacter


{
public static void main(String[] args)
{
String str = "ab";
char ch1 = [Link](0);
char ch2 = [Link](1);

[Link](ch1 + ch2); //195


}
}
---------------------------------------------------------------------
public byte [] getBytes() :-
-------------------------------
It is a predefined method available in the String class. The main purpose of this
method encode the string into bytes. It converts the string into a sequence of
bytes and returns an array of bytes.

//public byte [] getBytes()


//encode the String into sequence of bytes

public class Test24


{
public static void main(String args[])
{
String str = "ABCDEF";

byte [] b = [Link]();

for(byte a : b)
{
[Link](a);
}
}
}
---------------------------------------------------------------------
StringBuffer :-
----------------
While working with String class the drawback is memory consumption is very high
because it is immutable so whenever we want to perform some operation on the
existing String Object, a new String object will be created.

In order to solve the problem of immutability as well as high memory consumption,


java software people has introdued a separate class called StringBuffer available
in [Link] packge from 1.0 onwards.

StringBuffer is a mutable class so we can modify the existing StringBuffer object


hence automatically the memory consumption will be low but we have some performance
issue because almost all the methods of StringBuffer class are synchronized so at a
time only one thread can access the method of StringBuffer hence it is Thread-safe.
In order to solve this performance issue problem java software people has
introduced StringBuilder class from 1.5v onwards.

StringBuilder :-
-----------------
It is a predefined class available in [Link] packge. It is also mutable class.
The only difference between StringBuffer and StringBuilder is, almost all the
methods of StringBuffer are synchronized where as all the methods of StringBuilder
are non-synchronized hence performance wise StringBuilder is more better than
StringBuffer.

StringBuffer and StringBuilder both are sharing the same API hence methods name,
paramater and return type are same.
---------------------------------------------------------------------
** What is difference between String, StringBuffer and StringBuilder.

Difference is available in paint Diagram


---------------------------------------------------------------------
//String, StringBuffer and StringBuilder Objects comparison
public class Test25
{
public static void main(String args[])
{
StringBuilder sb1=new StringBuilder("Data"); //mutable
[Link]("Base");
[Link](sb1);

StringBuffer sb2=new StringBuffer("Data"); //mutable


[Link]("Base");
[Link](sb2);

String sb3 = new String("Data"); //immutable


[Link]("Base");
[Link](sb3);
}
}
---------------------------------------------------------------------
public int capacity() :
-------------------------
StringBuffer class contains capacity method() through which we can find out the
initial capacity of StringBuffer class in the form of Characters.

StringBuffer sb = new StringBuffer(); //default capacity is 16

new capacity = (current capacity * 2) + 2

new Capacity = (16 * 2) + 2 = 34


-----------------------------------------------------------------
//public int capacity()
//new capacity = ( current capacity*2)+2.
public class Test26
{
public static void main(String args[])
{
StringBuffer sb1 = new StringBuffer();
[Link]([Link]()); //16

StringBuffer sb2 = new StringBuffer("India"); //21 (16+5)


[Link]([Link]());

[Link]("is great. It is in Asia"); //44 (21*2)+2 = 44


[Link]([Link]());

}
}
----------------------------------------------------------------------
//public StringBuffer insert(int position, String str)
//Based on the index position we can insert the String
public class Test27
{
public static void main(String args[])
{
StringBuffer sb1=new StringBuffer("Hello");
[Link](1,"JSE");
[Link](sb1); //HJSEello

StringBuilder sb2=new StringBuilder("Hello");


[Link](1,"JEE");
[Link](sb2); //HJEEello
}
}
---------------------------------------------------------------------
//public AbstractStringBuilder reverse()
//Used to reverse the given String
class Test28
{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer("Hello");
[Link]();
[Link](sb1); //olleH

StringBuilder sb2=new StringBuilder("Java");


[Link]();
[Link](sb2);
}
}

---------------------------------------------------------------------
//Program to demonstrate the performance of StringBuffer and StringBuilder classes.

package [Link];

public class ObjectComparison


{
public static void main(String[] args)
{
long startTime = [Link]();

StringBuffer sb1 = new StringBuffer("Java");


for(int i=1; i<=1000000; i++)
{
[Link](" Technology");
}

long endTime = [Link]();

[Link]("Total time taken by StringBuffer class is :"+


(endTime-startTime)+ " ms");

startTime = [Link]();

StringBuilder sb2 = new StringBuilder("Java");


for(int i=1; i<=1000000; i++)
{
[Link](" Technology");
}

endTime = [Link]();
[Link]("Total time taken by StringBuilder class is :"+
(endTime-startTime)+ " ms");
}

Note :- System is a predefined class available in [Link] package and it contains


a predefined static method currentTimeMillis() , the return type of this method is
long, actually it returns the current time of the system in ms.
--------------------------------------------------------------
----------------------------------------------------------------------
Constructor of String class :
-----------------------------
The following are the commonly used constructor available in String class

1) String s1 = new String();

2) String s2 = new String("Hello");

3) String s3 = new String(char [] ch);

4) String s4 = new String(byte [] b);

5) String s5 = new String(StringBuffer sb);

6) String s6 = new String(StringBuilder sb);


---------------------------------------------------------------------
Logical Program on Strings :
-----------------------------
*********//Reverse a String
//String class Constructor
//WAP in java to reverse a String
import [Link];
public class Test1
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String to reverse :");
String str = [Link]();

for(int i=[Link]()-1; i>=0; i--) //i =0


{
[Link]([Link](i));
}
[Link]();
}
}
---------------------------------------------------------------------
//WAP in java to reverse a String
import [Link];
public class Test2
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String to reverse :");
String input = [Link]();
StringBuilder sb = new StringBuilder();
[Link](input);
[Link]([Link]());
}
}
----------------------------------------------------------------------
//Program to find out the duplicate characters in String as well as count it in a
String
import [Link].*;
public class Test3
{
public static void main(String ...x)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String :");
String str = [Link](); //ravishankar

int count = 0;
char[] arr = [Link](); //{'r','a'....}

[Link]("Duplicate Characters are:");

for (int i = 0; i < [Link](); i++) //i=0 length = 11


{
for (int j = i + 1; j < [Link](); j++) //j=3
{
if (arr[i] == arr[j]) //
{
[Link](arr[j]);
count++;
break;
}
}
}
[Link]("Total duplicate characters are :"+count);
}
}
----------------------------------------------------------------------
//Remove a specified character from the given String
import [Link].*;
public class Test4
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String :");
String str = [Link](); //ravi

[Link]("Enter a character you want to remove :");


char removeChar = [Link]().charAt(0); //v

StringBuilder result = new StringBuilder(); //rai

for (char c : [Link]()) // {'r', 'a', 'v', 'i'}


{
if (c != removeChar) // i != v
{
[Link](c);
}
}
[Link](result);
}
}
----------------------------------------------------------------------
31-01-2024
-----------
//Program to check whether a String contains vowels or not?
import [Link].*;
public class Test5
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String :");
String str = [Link](); //SKY - sky

boolean containsVowel = false;

for (char c : [Link]().toCharArray())


{
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
containsVowel = true;
break;
}
}

if (containsVowel)
{
[Link]("The string contains a vowel.");
}
else
{
[Link]("The string does not contain a vowel.");
}
}
}
----------------------------------------------------------------------
//How to sort a String data
import [Link];
public class Test6
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String :");
String str = [Link](); //mango

char[] chars = [Link]();

for (int i = 0; i < [Link]; i++)


{
for (int j = i + 1; j < [Link]; j++)
{
if (chars[i] > chars[j])
{
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
}
[Link](new String(chars));
}
}
---------------------------------------------------------------------
//count the occurrence of a given character in the existing String
import [Link].*;

public class Test7


{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String :");
String str = [Link](); //apple

[Link]("Enter a character :");


char target = [Link]().charAt(0); //p

int count = 0;

for (int i = 0; i < [Link](); i++) // i = 0 length = 5


{
if ([Link](i) == target) //e == p
{
count++; //2
}
}
[Link]("The character '" + target + "' appears " + count + "
times in the string '" + str + "'");
}
}
---------------------------------------------------------------------
Character class in java :
------------------------
It is a predefined Wrapper class available in [Link] package. It contains the
following static methods to check whether a chracter is digit or not , in uppercase
or not as well as in lowercase or not?

public static boolean isDigit(char ch); //ravi1ui

public static boolean isUpperCase(char ch);

public static boolean isLowerCase(char ch);


---------------------------------------------------------------------
//Program to find out a String contains digit or not
//public static boolean isDigit(char ch)

import [Link].*;
public class Test8
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String :");
String str = [Link]();

boolean containsDigits = false;

for (int i = 0; i < [Link](); i++) ///Ravi123


{
if ([Link]([Link](i)))
{
containsDigits = true;
break;
}
}

if (containsDigits)
{
[Link]("The string contains digits.");
}
else
{
[Link]("The string does not contain digits.");
}
}
}
---------------------------------------------------------------------
//program to count capital and small letter from the given String
//public static boolean isUpperCase(char ch)
//public static boolean isLowerCase(char ch)

import [Link];
public class Test9
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link](); //RaVi

int upperCase = 0, lowerCase = 0;

for (int i = 0; i < [Link](); i++)


{
char ch = [Link](i);

if ([Link](ch))
{
upperCase++;
}
else if ([Link](ch))
{
lowerCase++;
}
}
[Link]("Uppercase letters: " + upperCase);
[Link]("Lowercase letters: " + lowerCase);
}
}
----------------------------------------------------------------------
//Program to count the consonants and vowels in the given String
import [Link];
public class Test10
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

int vowels = 0, consonants = 0;

for (int i = 0; i < [Link](); i++)


{
char c = [Link](i);

if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||


c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
{
vowels++;
}
else
{
consonants++;
}
}
[Link]("Vowels: " + vowels);
[Link]("Consonants: " + consonants);
}
}
----------------------------------------------------------------------
//check a String is palindrome or not
import [Link];
public class Test11
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link](); // madam

boolean isPalindrome = true;

for(int i = 0; i < [Link]() / 2; i++) //i =2 i< 2


{
if ([Link](i) != [Link]([Link]() - i - 1)) //a != a
{
isPalindrome = false;
break;
}
}

if (isPalindrome)
{
[Link](str + " is a palindrome.");
}
else
{
[Link](str + " is not a palindrome.");
}
}
}
---------------------------------------------------------------------
01-02-2024
-----------
Multithreading
--------------
Uniprocessing :-
----------------
In uniprocessing, only one process can occupy the memory So the
major drawbacks are

1) Memory is westage
2) Resources are westage
3) Cpu is idle

To avoid the above said problem, multitasking is intrroduced.

Multitasking is further divided into two categories (31-JAN-24)

a) Process based Multitasking


b) Thread based Multitasking

Process based Multitasking :


----------------------------
If a CPU is switching from one subtask(Thread) of one process to
another subtask of another process then it is called Process based Multitasking.

Thread based Multitasking :


---------------------------
If a CPU is switching from one subtask(Thread) to another subtask within the same
process then it is called Thread based Multitasking.

---------------------------------------------------------------------
Thread :
--------
A thread is the basic unit of CPU which can run concurrently with another thread at
the same time within the same process.

It is well known for independent execution. The main purpose of multithreading to


boost the execution sequence.

A thread can run with another thread at the same time so our task will be completed
as soon as possible.

Every time we create a thread in java, the thread will be executed in a different
Stack memory.
---------------------------------------------------------------------
In java whenever we define a main method then JVM internally creates a thread
called main thread.

Thread is a predefined class available in [Link] package and it contains


currentThread() which is a static method of Thread class, by using this method we
can find out the currently executing Thread at that particular line or place.

It is a factory method.
--------------------------------------------------------------------
[Link]
----------------
package [Link];

public class MainThread


{
public static void main(String[] args)
{
String name = [Link]().getName();
[Link]("Current thread name is :"+name);

Note :- In Java, whenever we define main method then Internally one


thread is created and the responsibility of this main thread
to execute the entire main method.
---------------------------------------------------------------------
How to create a userdefined Thread in java ?
---------------------------------------------
As we know whenever we define the main method then JVM internally creates a thread
called main thread.

The purpose of main thread to execute the entire main method so at the time of
execution of main method a user can create our own userdefined thread.

In order to create the userdefined Thread we can use one of the following two
ways :-

1) By extending [Link] class


2) By implementing [Link] interface

Note :- Thread is a predefined class available in [Link] package where as


Runnable is a predefined interface available in [Link] Package.
---------------------------------------------------------------------
public synchronized void start() :
-----------------------------------
start() is a predefined method of Thread class and this method internally performs
two tasks

1) It makes a request to opearting system to assign a new thread to perform


concurrent execution.

2) It internally invokes the run() method as a part a separate Stack.

Note :- For every individual thread, JVM creates a separate runtime stack.

The following program explains how to create a userdefined Thread by extending


Thread approach.

package [Link];

class Test extends Thread


{
@Override
public void run()
{
[Link]("Child thread is running in a separate Stack");
}
}
public class CustomThread
{
public static void main(String[] args)
{
[Link]("Main thread started");

Test t1 = new Test();


[Link]();

[Link]("Main thread ended");


}

In the above program main thread and Thread-0 threads are created both threads are
executing their own Stack Memory as shown in the diagram
(01-FEB-24)
---------------------------------------------------------------------
public boolean isAlive() :
--------------------------
It is a predefined method of Thread class through which we can find out whether a
thread has started or not ?

As we know a new thread is created after calling start() method so if we use


isAlive() method before start() method, it will return false but if the same
isAlive() method if we invoke after the start() method, it will return true.

We can't restart a thread in java if we try to restart then It will generate an


exception i.e [Link]
---------------------------------------------------------------------

package [Link];

class Demo extends Thread


{
@Override
public void run()
{
[Link]("Child Thread is running!!!");
}
}

public class IsAlive


{
public static void main(String[] args)
{
Demo d1 = new Demo();
[Link]("Thread started :"+[Link]());

[Link]();
[Link]("Thread started :"+[Link]());

[Link](); //[Link]
}
}
----------------------------------------------------------------------
//Exception while executing the thread
package [Link];

class Stuff extends Thread


{
@Override
public void run()
{
[Link]("Child Thread is Running!!!!");
}
}
public class ExceptionDemo
{
public static void main(String[] args)
{
[Link]("Main Thread Started");

Stuff s1 = new Stuff();


Stuff s2 = new Stuff();

[Link]();
[Link]();

[Link](10/0);

[Link]("Main Thread Ended");


}

Note :- Here main thread is interrupted due to AE but still child thread will be
executed because child thread is executing with separate Stack.
----------------------------------------------------------------------
Loop program by using Multithreading :
--------------------------------------
package [Link];

class Sample extends Thread


{
@Override
public void run()
{
String name = [Link]().getName();

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


{
[Link]("i value is :"+i+" by "+name+" thread" );
}
}
}
public class ThreadLoop
{
public static void main(String[] args)
{
[Link]("Main thread started.....");

Sample s = new Sample();


[Link]();//child thread is created
String name = [Link]().getName();

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


{
[Link]("i value is :"+i+" by "+name+ " thread");
}

int x =1;
do
{
[Link]("Hello");
x++;
}
while(x<=10);
}
}

---------------------------------------------------------------------
How to set and get the name of the Thread :
--------------------------------------------------
Whenever we create a Thread in java then by default JVM assigns the name of thread
is Thread-0, Thread-1, Thread-2 and so on.

If a user wants to assign some user defined name of the Thread, then Thread class
has provided a predefined method called setName(String name) to set the name of the
Thread.

On the other hand we want to get the name of the Thread then Thread class has
provided a predefined method called getName().

public void setName(String name)

public String getName()


----------------------------------------------------------------------
package [Link];
class Test extends Thread
{
@Override
public void run()
{
String name = [Link]().getName();
[Link](name +" thread is running Here!!!!");
}
}
public class ThreadName
{
public static void main(String[] args)
{
Test t1 = new Test();
Test t2 = new Test();

[Link]();
[Link]();

[Link]([Link]().getName()+" thread is
running.....");
}
}

Note :- In the above program we have not assigned userdefined name to Thread so by
default the name of the Thread woud be Thread-0 and Thread-1
----------------------------------------------------------------------
package [Link];
class Demo extends Thread
{
@Override
public void run()
{
[Link]([Link]().getName()+" thread is
running.....");
}
}
public class ThreadName1
{
public static void main(String[] args)
{
Thread t = [Link]();
[Link]("Parent");//changing the main thread name

Demo d1 = new Demo();


Demo d2 = new Demo();

[Link]("Child1");
[Link]("Child2");

[Link]();
[Link]();

[Link]([Link]().getName()+" thread is
running!!!!");
}
}
----------------------------------------------------------------------
[Link](long milisecond) :
-------------------------------
If we want to put a thread into temporarly waiting state then we should use sleep()
method.

The waiting time of the Thread depends upon the time specified by the user as
parameter to sleep() method.

[Link](1000); //Thread will wait for 1 second

It is a static method of Thread class.

It is throwing a checked Exception i.e InterruptedException because there may be


chance that this sleeping thread may be interrupted by some another thread.
----------------------------------------------------------------------
package [Link];

class Sleep extends Thread


{
@Override
public void run()
{
for(int i=1; i<=10; i++)
{
[Link]("i value is :"+i);
try
{
[Link](1000);
}
catch (InterruptedException e)
{
[Link]("Thread is Interrupted");
[Link]();
}
}
}

}
public class SleepDemo
{
public static void main(String[] args)
{
[Link]("Main Thread started...");
Sleep s = new Sleep();
[Link]();
[Link]();

[Link]("Main Thread ended...");


}
}
----------------------------------------------------------------------
package [Link];

class MyTest extends Thread


{
@Override
public void run()
{
for (int i = 1; i <= 5; i++)
{
//Child 1 and Chiild2
try
{

[Link](1000);
}
catch(Exception e)
{
[Link]("thread has interrupted");
}

[Link](i + " by " +


[Link]().getName());
}
}
}
public class SleepDemo1
{
public static void main(String[] args)
{
[Link]([Link]().getName() + " thread");

MyTest t1 = new MyTest();


MyTest t2 = new MyTest();

[Link]("Child1");
[Link]("Child2");

[Link]();
[Link]();
}
}

----------------------------------------------------------------------
package [Link];

class MyTest extends Thread


{
@Override
public void run()
{
for (int i = 1; i <= 5; i++)
{
//Child 1 and Chiild2
try
{

[Link](1000);
}
catch(Exception e)
{
[Link]("thread has interrupted");
}

[Link](i + " by " +


[Link]().getName());
}
}
}
public class SleepDemo1
{
public static void main(String[] args)
{
[Link]([Link]().getName() + " thread");

MyTest t1 = new MyTest();


MyTest t2 = new MyTest();

[Link]("Child1");
[Link]("Child2");

[Link]();
[Link]();

}
}
----------------------------------------------------------------
Thread Life cycle :
-------------------
Thread life cycle in java :
-----------------------------
As we know a thread is well known for Independent execution and it contains a life
cycle which internally contains 5 states (Phases). During the life cycle of a
thread, It can pass from thses 5 states. At a time a thread can reside to only one
state of the given 5 states.

1) NEW State (Born state)

2) RUNNABLE state (Ready to Run state) [Thread Pool]

3) RUNNING state

4) WAITING / Blocked state

5) EXIT/Dead state

New State :-
-------------
Whenever we create a thread instance(Thread Object) a thread comes to new state OR
born state. New state does not mean that the Thread has started yet only the object
or instance of Thread has been created.

Runnable state :-
-------------------
Whenever we call start() method on thread object, A thread moves to Runnable state
i.e Ready to run state. Here Thread schedular is responsible to select/pick a
particular Thread from Runnable state and sending that particular thread to Running
state for execution.

Running state :-
-----------------
If a thread is in Running state that means the thread is executing its own run()
method.

From Running state a thread can move to waiting state either by an order of thread
schedular or user has written some method(wait(), join() or sleep()) to put the
thread into temporarly waiting state.

From Running state the Thread may also move to Runnable state directly, if user has
written [Link]() method explicitly.

Waiting state :-
------------------
A thread is in waiting state means it is waiting for it's time period to complete.
Once the time period will be completed then it will re-enter inside the Runnable
state to complete its remaining task.

Dead or Exit :
----------------
Once a thread has successfully completed its run method then the thread will move
to dead state. Please remember once a thread is dead we can't restart a thread in
java.

IQ :- If we write [Link](1000) then exactly after 1 sec the Thread will re-
start?

Ans :- No, We can't say that the Thread will directly move from waiting state to
Running state.

The Thread will definetly wait for 1 sec in the waiting mode and then again it will
re-enter into Runnable state which is control by Thread Schedular so we can't say
that the Thread will re-start just after 1 sec.
-----------------------------------------------------------------------
package [Link];

class NIT extends Thread


{
@Override
public void run()
{
[Link]([Link]().getState());

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


{
try {
[Link](1000);
[Link]([Link]().getState());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
[Link]();
}
}
}

public class ThreadState {

public static void main(String[] args)


{
NIT n = new NIT();
[Link]([Link]()); //NEW
[Link]();

Note :- From JDK 1.5 we have State enum which defines both the states i.e Runnable
and Running into single state i.e RUNNABLE.
----------------------------------------------------------------------
join() method of Thread class :
------------------------------------
The main purpose of join() method to put the one thread into waiting mode until the
other thread finish its execution.

Here the currently executing thread stops its execution and the thread goes into
the waiting state. The current thread remains in the wait state until the thread on
which the join() method is invoked has achieved its dead state.

It also throws checked exception i.e InterruptedException so better to use try


catch or declare the method as throws.

It is an instance method so we can call this method with the help of Thread object
reference.
package [Link];

class Join extends Thread


{
@Override
public void run()
{
for(int i=1; i<=5; i++)
{
[Link](i);
try
{
[Link](500);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}

public class JoinDemo


{
public static void main(String[] args) throws InterruptedException
{
[Link]("Main Thread Started!!!!!");

Join j1 = new Join();


Join j2 = new Join();
Join j3 = new Join();

[Link]();

[Link](); //putting the main thread into Waiting mode

[Link]();

[Link]();

[Link]("Main thread completed!!!!");

}
}
----------------------------------------------------------------------
package [Link];

public class JoinDemo1


{
public static void main(String[] args) throws InterruptedException
{
[Link]("Main thread started");
Thread thread = [Link]();
String name = [Link]();

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


{
[Link](i + " by "+name+ " thread ");

}
[Link](); //Deadlock

[Link]("Main thread ended");

Here in the above program the main thread is waiting for main thread
only so it is a deadloack state.
-----------------------------------------------------------------------
package [Link];

class Alpha extends Thread


{
@Override
public void run()
{
Thread t = [Link]();
String name = [Link](); //Alpha_Thread

Beta b1 = new Beta();


[Link]("Beta_Thread");
[Link]();
try
{
[Link](); //Alpha thread is in Halt mode
}
catch (InterruptedException e)
{
[Link]();
}

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


{
[Link](i+" by "+name);
}

}
}

public class JoinDemo2 {

public static void main(String[] args)


{
Alpha a1 = new Alpha();
[Link]("Alpha_Thread");
[Link]();
}
}

class Beta extends Thread


{
@Override
public void run()
{
Thread t = [Link]();
String name = [Link]();
for(int i=1; i<=10; i++)
{
[Link](i+" by "+name);
}
[Link](".............");
}
}
-----------------------------------------------------------------------
05-02-2024
-----------
How to create a Thread by using Runnable interface approach :
-------------------------------------------------------------
In this approach we need to pass the sub class object reference to the constructor
of Thread class (Passing Object reference to the constructor)
----------------------------------------------------------------
package [Link].stream_intermediate;

class Test implements Runnable


{
@Override
public void run()
{
[Link]("Test class run method");
}
}

public class RunnableDemo


{
public static void main(String[] args)
{
[Link]("Main Thread is running");
Test t1 = new Test();

Thread th = new Thread(t1);


[Link]();

}
------------------------------------------------------------------
Anonymous class Approach :
---------------------------
Creating Anonymous inner class for Thread class with reference :

[Link]
----------------------------------
package [Link];

public class AnonymousThreadWithReference {

public static void main(String[] args)


{
Thread t1 = new Thread()
{
@Override
public void run()
{
String name = [Link]().getName();
[Link]("Name is : "+name);
}
};
[Link]();

}
----------------------------------------------------------------------
Creating Anonymous innner Thread class without reference :
----------------------------------------------------------
package [Link];

public class AnonymousThreadWithoutReference {

public static void main(String[] args)


{
new Thread()
{
@Override
public void run()
{
String name = [Link]().getName();
[Link]("Name is : "+name);
}

}.start();

}
-----------------------------------------------------------------------
Anonymous inner class uisng Runnable approach :
-----------------------------------------------
package [Link];

public class AnonymousRunnableDemo {

public static void main(String[] args)


{
Runnable r1 = new Runnable()
{
@Override
public void run()
{
String name = [Link]().getName();
[Link](name);
}
};
Thread t1 = new Thread(r1,"T1"); [Link]();
}

}
----------------------------------------------------------------------
//Lambda Expression
package [Link];

public class LambdaByRunnable {

public static void main(String[] args)


{
Runnable r1 = ()->
[Link]([Link]().getName());

Thread t1 = new Thread(r1,"T1");


[Link]();

}
----------------------------------------------------------------------
package [Link];

public class LambdaByParameter {

public static void main(String[] args)


{
new Thread(()->
[Link]([Link]().getName()),"T1").start();
}

}
-----------------------------------------------------------------------
* In between extends Thread and implements Runnable, which one is better and why?

In between extends Thread and implements Runnable approach, implements Runnable is


more better due to the following reasons

1) When we use extends Thread, all the methods and properties of Thread class is
available to sub class so it is heavy weight but this is not the case while
implementing Runnable interface.

2) As we know Java does not support multiple inheritance using classes so in the
extends Thread approach we can't extend another class but if we use implments
Runnable interface still we have chance to extend another class and we can also
implement one or more interfaces.

3) implements Runnable is a better approach to create multiple threads on a single


sub class object.

4) We can implement Lambda for Runnable interface (Functional interface)

----------------------------------------------------------------
Thread class Constructor (Total 9 constructors):
-------------------------------------------------
The following are the commonly used constructor available in Thread class :

1) Thread()
2) Thread(String name)
3) Thread(Runnable target)
4) Thread(Runnable target, String name)
5) Thread(ThreadGroup threadGroup, Runnable target, String name)
----------------------------------------------------------------
06-02-2024
----------
Problem with multithreading :-
----------------------------------
Multithreading is very good to complete our task as soon as possible but in some
situation, It provides some wrong data or wrong result.

In Data Race or Race condition, all the threads try to access the resource at the
same time so the result will be corrupted.

In multithreading if we want to perform read operation and data is not updatable


then multithreading is good but if the data is updatable data (modifiable data)
then multithreading may produce some wrong result or wrong data as shown in the
diagram.(05-FEB-24)

---------------------------------------------------------------
package [Link].multithreading_limitation;

class Customer implements Runnable


{
private int noOfSeat = 1;
private int wantedSeat;

public Customer(int wantedSeat)


{
[Link] = wantedSeat;
}

@Override
public void run()
{
String name = null;

if(noOfSeat >= wantedSeat)


{
name = [Link]().getName();
[Link](wantedSeat + " seat is reserved for "+name);
noOfSeat = noOfSeat - wantedSeat;

}
else
{
name = [Link]().getName();
[Link]("Sorry !!"+name+" seats are not available");
}

public class RailwayReservation


{
public static void main(String[] args)
{
Customer c1 = new Customer(1);

Thread t1 = new Thread(c1,"Rohit");


Thread t2 = new Thread(c1,"Virat");

[Link](); [Link]();

Here both the Threads are getting the Ticket.


---------------------------------------------------------------
Threads are also not suitable for performing parallel task.

package [Link];

class MyThread implements Runnable


{
private String str;

public MyThread(String str)


{
[Link]=str;
}

@Override
public void run()
{
for(int i=1; i<=10; i++)
{
[Link](str+ " : "+i);
try
{
[Link](100);
}
catch (Exception e)
{
[Link](e);
}
}
}
}
public class Theatre
{
public static void main(String [] args)
{
MyThread obj1 = new MyThread("sell the Ticket");
MyThread obj2 = new MyThread("Allocate the Seat");

Thread t1 = new Thread(obj1);


Thread t2 = new Thread(obj2);

[Link]();
[Link]();
}
}
---------------------------------------------------------------
Assignment :
------------
Two thread are trying to withdraw the amount from same account. Use multithreading
with Lambda to implement this logic.
----------------------------------------------------------------
Synchronization :
----------------
In order to solve the problem of multithreading java software people has introduced
synchronization concept.

In order to acheive synchronization in java we have a keyword called


"synchronized".

It is a technique through which we can control multiple threads but accepting only
one thread at all the time.

Synchronization allows only one thread to enter inside the synchronized area for a
single object.

Synchronization can be divided into two categories :-

1) Method level synchronization

2) Block level synchronization

Method level synchronization :-


-----------------------------------
In method level synchronization, the entire method gets synchronized so all the
thread will wait at method level and only one thread will enter inside the
synchronized area as shown in the diagram.(06-FEB-24)

Block level synchronization :-


---------------------------------
In block level synchronization the entire method does not get synchronized, only
the part of the method gets synchronized so all the thread will enter inside the
method but only one thread will enter inside the synchronized block as shown in the
diagram (06-FEB-24)

Note :- In between method level synchronization and block level synchronization,


block level synchronization is more preferable because all the threads can enter
inside the method so only the PART OF THE METHOD GETS synchronized so only one
thread will enter inside the synchronized block.

How synchronization controls multiple threads :


------------------------------------------------
Every Object has a lock(monitor) in java environment and this lock can be given to
only one Thread at a time.

The thread who acquires the lock from the Object will enter inside the synchronized
area, it will complete its task without any disturbance because at a time there
will be only one thread is allowed inside the synchronized area(for single Object).
This is known as Thread-safety in java.

The thread which is inside the synchronized area, after completion of its task
while going back will release the lock so the other threads (which are waiting
outside for the lock) will get a chance to enter inside the synchronized area by
again taking the lock from the Object and submitting it to the synchronized
keyword.

This is how synchronization mechanism controls multiple Threads.

Note :- Synchronization logic can be done by senior programmers in the real time
industry because due to poor synchronization there may be chance of getting
deadlock.
----------------------------------------------------------------
Program on Method level synchronization :
------------------------------------------
package [Link];

class Table
{
public synchronized void printTable(int num)
{
for(int i=1; i<=10; i++)
{
[Link](num+" X "+i+" = "+(num*i));
try
{
[Link](500);
}
catch(InterruptedException e)
{
[Link]();
}
}
[Link](".................");
}
}
public class MethodLevelSynchronization
{
public static void main(String[] args)
{
Table obj = new Table(); //lock is created

Thread t1 = new Thread()


{
@Override
public void run()
{
[Link](5);
}
};

Thread t2 = new Thread()


{
@Override
public void run()
{
[Link](9);
}
};

[Link](); [Link]();
}

In method level synchronization the entire method will be synchronized so we should


use block level synchronization, hence all the thread will enter inside method but
only one thread will enter inside synchronized block.
----------------------------------------------------------------
[Link]
--------------------------
package [Link];

//Block level synchronization

class ThreadName
{
public void printThreadName()
{
//This area is accessible by all the threads (c1 c2)
String name = [Link]().getName();
[Link]("Thread inside the method is :"+name);

synchronized(this) //synchronized Block


{
for(int i=1; i<=9; i++)
{
[Link]("i value is :"+i+" by :"+name);
}
[Link](".............................");
}
}
}
public class BlockSynchronization
{
public static void main(String[] args)
{
ThreadName obj1 = new ThreadName(); //lock is created

Runnable r1 = () -> [Link]();

Thread t1 = new Thread(r1,"Child1");


Thread t2 = new Thread(r1,"Child2");
[Link](); [Link]();
}
}
---------------------------------------------------------------
Problem with Object level synchronization :-
-------------------------------------------------
From the given diagram it is clear that there is no interference between t1 and t2
thread because they are passing throgh Object1 where as on the other hand there is
no interferenec even in between t3 and t4 threads because they are also passing
through Object2 (another object).

But there may be chance that with t1 Thread, t3 or t4 thread can enter inside the
synchronized area at the same time, simillarly it is also possible that with t2
thread, t3 or t4 can enter inside the synchronized area so the conclusion is
synchronization mechanism does not work with multiple Objects.(Diagram 07-FEB-24)

[Link]

package [Link];
class PrintTable
{
public synchronized void printTable(int n)
{
for(int i=1; i<=10; i++)
{
[Link](n+" X "+i+" = "+(n*i));
try
{
[Link](500);
}
catch(Exception e)
{
}
}
[Link](".......................");
}
}

public class ProblemWithObjectLevelSynchronization


{
public static void main(String[] args)
{
PrintTable pt1 = new PrintTable(); //lock1
PrintTable pt2 = new PrintTable(); //lock2

Thread t1 = new Thread() //Anonymous inner class concept


{
@Override
public void run()
{
[Link](2); //lock1
}
};

Thread t2 = new Thread()


{
@Override
public void run()
{
[Link](3); //lock1
}
};

Thread t3 = new Thread()


{
@Override
public void run()
{
[Link](6); //lock2
}
};

Thread t4 = new Thread()


{
@Override
public void run()
{
[Link](9); //lock2
}
};
[Link](); [Link](); [Link](); [Link]();
}
}
---------------------------------------------------------------
Static Synchronization :
---------------------------
If We declare a synchronized method as a static method then it is called static
synchronization.

Now with static synchronization lock will be available at class level but not
Object level.

To call the static synchronized method, object is not required so we can call the
static method with the help of class name.

Unlike objects we can't create multiple classes for the same application.

package [Link];
class MyTable
{
public static synchronized void printTable(int n) //static synchronization
{
for(int i=1; i<=10; i++)
{
try
{
[Link](100);
}
catch(InterruptedException e)
{
[Link]("Thread is Interrupted...");
}
[Link](n+" X "+i+" = "+(n*i));
}
[Link]("------------------------");
}
}
public class StaticSynchronization
{
public static void main(String[] args)
{
Thread t1 = new Thread()
{
@Override
public void run()
{
[Link](5);
}
};

Thread t2 = new Thread()


{
@Override
public void run()
{
[Link](10);
}
};

Runnable r3 = new Runnable()


{
@Override
public void run()
{
[Link](15);

}
};
Thread t3 = new Thread(r3);

[Link]();
[Link](); [Link]();

}
}
----------------------------------------------------------------
08-02-2024
----------
*Inter Thread Communication (ITC) :
----------------------------------
It is a mechanism to communicate two synchronized threads within the context to
achieve a particular task.

In ITC we put a thread into wait mode by using wait() method and other thread will
complete its corresponding task, after completion of the task it will call notify()
method so the waiting thread will get a notification to complete its remaining
task.

ITC can be implemented by the following method of Object class.

1) public final void wait() throws InterruptedException

2) public native final void notify()

3) public native final void notifyAll()

public final void wait() throws InterruptedException :-


-------------------------------------------------------------
It will put a thread into temporarly waiting state and it will release the lock.
It will wait till the another thread invokes notify() or notifyAll() for this
object.

public native final void notify() :-


-------------------------------------
It will wake up the single thread that is waiting on the same object.

public native final void notifyAll() :-


----------------------------------------
It will wake up all the threads which are waiting on the same object.

*Note :- wait(), notify() and notifyAll() methods are defined in Object class but
not in Thread class because these methods are related to lock(because we can use
these methods from the synchronized area ONLY) and Object has a lock so, all these
methods are defined inside Object class.

*What is the difference between sleep() and wait()


----------------------------------------------------------
(Given in the diagram 08-FEB-24)
-----------------------------------------------------------------
Program that describes if we don't use ITC then problem would be
----------------------------------------------------------------
//Program that describes if we don't use ITC then the problem is ...

class Test implements Runnable


{
int var = 0;
@Override
public void run()
{
for(int i=1; i<=10; i++)
{
var = var + i; //var = 1 3 6 10 15 21 28
try
{
[Link](200);
}
catch (Exception e)
{
}
}

}
}
public class ITCProblem
{
public static void main(String[] args)
{
Test t = new Test();
Thread t1 = new Thread(t);
[Link]();
try
{
[Link](500);
}
catch (Exception e)
{
}

[Link]([Link]);
}
}
-----------------------------------------------------------------
//Communication between main thread and child thread using ITC

class SecondThread extends Thread


{
int x = 0;

@Override
public void run()
{
//Child Thread is waiting here for the lock
synchronized(this)
{
for(int i=1; i<=100; i++)
{
x = x + i;
}
[Link]("Sending notification");
notify(); //will give notification to waiting thread
}
}
}
public class InterThreadComm
{
public static void main(String [] args)
{
SecondThread b = new SecondThread();
[Link]();

synchronized(b) //lock is taken by main thread


{
//suspended
try
{
[Link]("Waiting for b to complete...");
[Link](); // after releasing the lock, waiting here
[Link]("Main thread wake up");
}
catch (InterruptedException e)
{
}
[Link]("Value is: " + b.x);
}
}
}
-----------------------------------------------------------------
class Customer
{
int balance = 10000;

public synchronized void withdraw(int amount) //amount = 15000


{
[Link]("going to withdraw...");
if(balance < amount)
{
[Link]("Less balance; waiting for deposit...");

try
{
wait(); //waiting and releasing the lock
}
catch(Exception e){}
}
balance = balance - amount;
[Link]("withdraw completed..."+balance+" is remaining
balance");
}

public synchronized void deposit(int amount) //amount = 9000


{
[Link]("going to deposit...");
balance = balance + amount;
[Link]("Balance after deposit is :"+balance);
[Link]("deposit completed... ");
notify();
}
}
public class InterThreadBalance
{
public static void main(String args[])
{
Customer c = new Customer(); //lock is created here

Thread son = new Thread() //anonymous class concept


{
@Override
public void run()
{
[Link](15000);
}
};
[Link]();

Thread father = new Thread()


{
public void run()
{
[Link](9000);
}
};

[Link]();
}
}
-----------------------------------------------------------------
Thread Priority :
------------------
Thread Priority :
------------------
It is possible in java to assign priority to a Thread.

Thread class has provided two predefined methods setPriority(int newPriority) and
getPriority() to set and get the priority of the thread respectively.

In java we can set the priority of the Thread in number from 1- 10 only where 1 is
the minimum priority and 10 is the maximum priority.

Whenever we create a thread in java by default its priority would be 5 that is


normal priority.

The userdefined thread created as a part of main thread will acquire the same
priority of main Thread.

Thread class has also provided 3 final static variables which are as follows :-

Thread.MIN_PRIORITY :- 01

Thread.NORM_PRIORITY : 05

Thread.MAX_PRIORITY :- 10

Note :- We can't set the priority of the Thread beyond the limit(1-10) so if we set
the priority beyond the limit (1 to 10) then it will generate an exception
[Link].
-----------------------------------------------------------------
package [Link];

public class MainPriority


{
public static void main(String[] args)
{
Thread t = [Link]();

[Link]("Main thread priority is :"+[Link]());

Thread t1 = new Thread();


[Link]("User thread priority is :"+[Link]());
}

}
Any thread which is created as a part of main thread will get the
priority of main thread.
-----------------------------------------------------------------
package [Link];

class ThreadP extends Thread


{
@Override
public void run()
{
int priority = [Link]().getPriority();

[Link]("Child Thread priority is :"+priority);


}
}
public class MainPriority1
{
public static void main(String[] args)
{
Thread t = [Link]();
[Link](8);

// [Link](11); Invalid [Link]

[Link]("Main thread priority is :"+[Link]());

ThreadP t1 = new ThreadP();


[Link]();
}
}

Note :- If we change the priority of main thread then the thread crearted as a part
of main thread will get same priority of main thread
-----------------------------------------------------------------
package [Link];

class ThreadPrior1 extends Thread


{
@Override
public void run()
{

int count = 0;
for(int i=1; i<=1000000; i++)
{
count++;
}

[Link]("Thread name is:"+[Link]().getName());


[Link]("Thread priority
is:"+[Link]().getPriority());
}

public static void main(String args[])


{
ThreadPrior1 m1 = new ThreadPrior1();
ThreadPrior1 m2 = new ThreadPrior1();

[Link](Thread.MIN_PRIORITY);//1
[Link](Thread.MAX_PRIORITY);//10

[Link]("Last");
[Link]("First");

[Link]();
[Link]();
}
}
-----------------------------------------------------------------
[Link]() :
----------------
It is a static method of Thread class .

It will send a notification to thread schedular to stop the currently executing


Thread (In Running state) and provide a chance to Threads which are in Runnable
state to enter inside the running state having same priority or highest priority.
Here The running Thread will directly move from Running state to Runnable state.

The Thread schedular can ignore this notification message given by currently
executing Thread.

Here there is no guarantee that after using yield() method the running Thread will
move to Runnable state and from Runnable state the thread can move to Running
state.

If the thread which is in runnable state is having low priority then the same
running thread will continue its execution.

class Test implements Runnable


{
@Override
public void run()
{
for(int i=1; i<=10; i++)
{
String name = [Link]().getName();

[Link]("i value is :"+i+" by thread :"+name);

if([Link]("Child1"))
{
[Link](); //Give a chance to Child2 Thread
}

}
}
}
public class ThreadYieldMethod
{
public static void main(String[] args)
{
Test obj = new Test();

Thread t1 = new Thread(obj, "Child1");


Thread t2 = new Thread(obj, "Child2");

[Link](); [Link]();
}
}
-----------------------------------------------------------------
09-02-2024
----------

interrupt() method of Thread class :


------------------------------------
It is a predefined method of Thread class. The main purpose of this method to
disturb the execution of the Thread, if the thread is in waiting or sleeping state.

Whenever a thread is interupted then it throws InterruptedException so the thread


(if it is in sleeping or waiting mode) will get a chance to come out from a
particular logic.

Points :-
---------
If we call interrupt method and if the thread is not in sleeping or waiting state
then it will behave normally.

If we call interrupt method and if the thread is in sleeping or waiting state then
we can stop the thread gracefully.

*Overall interrupt method is mainly used to interrupt the


thread safely so we can manage the resources easily.

Methods :
---------
1) public void interrupt () :- Used to interrupt the Thread but the thread must be
in sleeping or waiting mode.

2) public boolean isInterrupted() :- Used to verify whether thread is interrupted


or not.
----------------------------------------------------------------
class Interrupt extends Thread
{
@Override
public void run()
{
Thread t = [Link]();
[Link]([Link]());

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


{
[Link](i);
try
{
[Link](1000);
}
catch (InterruptedException e)
{
[Link]("Thread is Interrupted ");
[Link]();
}
}
}
}
public class InterruptThread
{
public static void main(String[] args)
{
Interrupt it = new Interrupt();
[Link]([Link]()); //NEW STATE
[Link]();
[Link](); //main thread is interrupting the child thread
}
}
----------------------------------------------------------------
class Interrupt extends Thread
{
public void run()
{
try
{
[Link]().interrupt();

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


{
[Link]("i value is :"+i);
[Link](1000);
}

}
catch (InterruptedException e)
{
[Link]("Thread is Interrupted :"+e);
}
[Link]("Child thread completed...");
}
}
public class InterruptThread1
{
public static void main(String[] args)
{
[Link]("Main thread is started");
Interrupt it = new Interrupt();
[Link]();
[Link]("Main thread is ended");
}
}
----------------------------------------------------------------
public class InterruptThread2
{
public static void main(String[] args)
{
Thread thread = new Thread(new MyRunnable());
[Link]();

try
{
[Link](2000); //main thread is waiting for 2 sec
}
catch (InterruptedException e)
{
[Link]();
}

[Link]();
}
}

class MyRunnable implements Runnable


{
@Override
public void run()
{
try
{
while (![Link]().isInterrupted())
{
[Link]("Thread is running...");
[Link](500);
}
}
catch (InterruptedException e)
{
[Link]("Thread interrupted gracefully.");
}
finally
{
[Link]("Thread resource can be release here.");
}
}
}

Note :- Here main thread is in sleeping mode for 5 sec, after wake up main thread
is interrupting child thread so child thread will come out from infinite loop and
if any resource is attached with child thread that will be released because child
thread execution completed.
finally block is there to close the resource.
-----------------------------------------------------------------
Thread Group :-
--------------
There is a predefined class called ThreadGroup available in [Link] package.

In Java it is possible to group multiple threads in a single object so, we can


perform a particular operation on a group of threads by a single method call.

The Thread class has the following constructor for ThreadGroup


new Thread(ThreadGroup groupName, Runnable target, String name);

public class ThreadGroupDemo1


{
public static void main(String[] args)
{
ThreadGroup myThreadGroup = new ThreadGroup("NIT_Thread");

// Create and start threads within the ThreadGroup

Thread thread1 = new Thread(myThreadGroup, new MyRunnable(), "Thread 1");

Thread thread2 = new Thread(myThreadGroup, new MyRunnable(), "Thread 2");

Thread thread3 = new Thread(myThreadGroup, new MyRunnable(), "Thread 3");

Thread thread4 = new Thread(myThreadGroup, new MyRunnable(), "Thread


4");

[Link]();
[Link]();
[Link]();
[Link]();

// Display information about the ThreadGroup and its threads


[Link]("ThreadGroup Name: " + [Link]());

[Link]("Active Count: " + [Link]());


}

static class MyRunnable implements Runnable //static nested inner


{
@Override
public void run()
{
for (int i = 1; i <= 3; i++)
{
[Link]([Link]().getName() + ": " + i);
try
{
[Link](1000);
}
catch (InterruptedException e)
{
[Link]();
}
}
}
}
}
------------------------------------------------------------------
Deadlock :
------------
It is a situation where two or more than two threads are in blocked state forever,
here threads are waiting to acquire another thread resource without releasing it's
own resource.

This situation happens when multiple threads demands same resource without
releasing its own attached resource so as a result we get Deadlock situation and
our execution of the program will go to an infinite state as shown in the diagram.
(09-FEB-24)

public class DeadlockExample


{
public static void main(String[] args)
{
String resource1 = "Ameerpet";
String resource2 = "Hyderabad";

// t1 tries to lock resource1 then resource2

Thread t1 = new Thread()


{
@Override
public void run()
{
synchronized (resource1)
{
[Link]("Thread 1: locked resource 1");
try
{
[Link](1000);
}
catch (Exception e)
{}

synchronized (resource2) //Nested synchronized block


{
[Link]("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread()
{
@Override
public void run()
{
synchronized (resource2)
{
[Link]("Thread 2: locked resource 2");
try
{
[Link](1000);
}
catch (Exception e)
{}

synchronized (resource1) //Nested synchronized block


{
[Link]("Thread 2: locked resource 1");
}
}
}
};
[Link]();
[Link]();
}
}
------------------------------------------------------------------
class Demo
{
public static void main(String[] args) throws InterruptedException
{
Thread t = [Link]();
for(int i =1; i<=10; i++)
{
[Link](i);
[Link]();
}
}
}
In the above program main thread is blocking it self.
------------------------------------------------------------------
Daemon Thread :
---------------

Daemon Thread [Service Level Thread]:


--------------------------------------
Daemon thread is a low- priority thread which is used to provide background
maintenance.

The main purpose of of Daemon thread to provide services to the user thread.

JVM can't terminate the program till any of the non-daemon (user) thread is active,
once all the user thread will be completed than JVM will terminate all Daemon
threads, which are running in the background to support user threads.

The example of Daemon thread is Garbage Collection thread, which is running in the
background for memory management.

In order to make a thread as a Daemon thread , we should use setDaemon(true)


public class DaemonThreadDemo1
{
public static void main(String[] args)
{
[Link]("Main Thread Started...");
Thread daemonThread = new Thread(() ->
{
while (true)
{
[Link]("Daemon Thread is running...");
try
{
[Link](1000);
}
catch (InterruptedException e)
{
[Link]();
}
}
});

[Link](true);
[Link]();

Thread userThread = new Thread(() ->


{
for (int i = 1; i <= 9; i++)
{
[Link]("User Thread: " + i);
try
{
[Link](2000);
}
catch (InterruptedException e)
{
[Link]();
}
}
});

[Link]();

[Link]("Main Thread Ended...");


}
}
----------------------------------------------------------------
10-02-2024
-----------
Remaining Method of Object class :
----------------------------------
Object cloning in java :
----------------------------
Object cloning is the process of creating an exact copy of an existing object in
the memory.

Object cloning can be done by the following process :

1) Creating Shallow copy

2) Creating Deep copy

3) Using clone() method of [Link] class

4) Passing Object reference to the Constructor

Shallow Copy :
-----------------
In shallow copy, we create a new reference variable which will point to same old
existing object so if we make any changes through any of the reference variable
then original object content will be modified.

Here we have one object and multiple reference variables.


package [Link].clone_method;

class Student
{
int id;
String name;

@Override
public String toString()
{
return "Id is :" + id + "\nName is :" + name ;
}

}
public class ShallowCopy
{
public static void main(String[] args)
{
Student s1 = new Student();
[Link] = 111;
[Link] = "Ravi";

[Link](s1);

[Link]("After Shallow Copy");

Student s2 = s1; //shallow copy


[Link] = 222;
[Link] = "Shankar";

[Link](s1);
[Link](s2);

[Link]([Link]());
[Link]([Link]());
}

In Shallow copy, one object will be created and it is refered by multiple referenec
variable so, hashcode will be same.

------------------------------------------------------------------
Deep Copy :
--------------
In deep copy, We create a copy of object in a different memory location. This is
called a Deep copy.

Here objects are created in two different memory locations so if we modify the
content of one object it will not reflect another object.

package [Link].clone_method;

class Employee
{
int id;
String name;

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

public class DeepCopy


{
public static void main(String[] args)
{
Employee e1 = new Employee();
[Link] = 111;
[Link] = "Ravi";

Employee e2 = new Employee();


[Link] = [Link];
[Link] = [Link];

[Link](e1 +" : "+e2);

[Link] = 222;
[Link] = "shankar";
[Link](e1 +" : "+e2);

[Link]([Link]() +" : "+[Link]());


}

Note :- hash code of both the obejcts will be different.


------------------------------------------------------------------
protected native Object clone() throws CloneNotSupportedException
----------------------------------------------------------------
Object cloning in Java is the process of creating an exact copy of the original
object. In other words, it is a way of creating a new object by copying all the
data and attributes from the original object.

The clone method of Object class creates an exact copy of an object.

In order to use clone() method , a class must implements Clonable interface because
we can perform cloning operation on Cloneable objects only [JVM must have
additional information].

We can say an objeect is a Cloneable object if the corresponding class implements


Cloneable interface.

It throws a checked Exception i.e CloneNotSupportedException

Note :- clone() method is not the part of Clonable interface[marker interface],


actually it is the method of Object class.

clone() method of Object class follow deep copy concept so hashcode will be
different.

package [Link].clone_method;

class Customer implements Cloneable


{
int id;
String name;

@Override
protected Object clone() throws CloneNotSupportedException
{
return [Link]();
}

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

public class CloneMethod


{
public static void main(String[] args) throws CloneNotSupportedException
{
Customer c1 = new Customer();
[Link] = 222;
[Link] = "Rahul";

Customer c2 = (Customer) [Link]();


[Link] = 333;
[Link] = "Rohit";

[Link](c1);
[Link](c2);

[Link]([Link]());
[Link]([Link]());

}
-----------------------------------------------------------------
protected void finalize() throws Throwable :
---------------------------------------------
It is a predefined method of Object class.

Garbage Collector automatically call this method just before an object is eligible
for garbage collection to perform clean-up activity.

Here clean-up activity means closing the resources associated with that object like
file connection, database connection, network connection and so on we can say
resource de-allocation.

Note :- JVM calls finalize method only one per object.

package [Link].finalize_method;

public class Student


{
int id;
String name;
public Student(int id, String name)
{
[Link]= id;
[Link] = name;
}

@Override
public String toString()
{
return "Id is :"+id+"\nName is :"+name;
}

@Override
protected void finalize()
{
[Link]("JVM call this finalize method...");
}

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


{
Student s1 = new Student(111,"Ravi");
[Link]([Link]());
[Link](s1);

s1 = null;
[Link](); //Explicitly calling Garbage Collector
[Link](3000);
[Link](s1);
}

}
-----------------------------------------------------------------

*What is the difference between final, finally and finalize

final :- It is a keyword which is used to provide some kind of


restriction like class is final, Method is
final,variable is final.

finally :- if we open any resource as a part of try block then


that particular resource must be closed inside
finally block otherwise program will be terminated ab-normally and the
corresponding resource will not be closed (because the remaining lines of try block
will not be executed)

finalize() :- It is a method which JVM is calling automatically just


before object destruction so if any resource
(database, file and network) is associated with
that particular object then it will be closed
or de-allocated by JVM by calling finalize().
-----------------------------------------------------------------
19-12-2023
----------
Collection framework :
----------------------
Collections framework is nothing but handling individual Objects(Collection
Interface) and Group of objects(Map interface).
We know only object can move from one network to another network.

A collections framework is a class library to handle group of Objects.

It is implemented by using [Link] package.

It provides an architecture to store and manipulate group of objects.

All the operations that we can perform on data such as searching, sorting,
insertion and deletion can be done by using collections framework because It is the
data structure of Java.

The simple meaning of collections is single unit of Objects.

It provides the following sub interfaces :

1) List (Accept duplicate elements)


2) Set (Not accepting duplicate elements)
3) Queue (Storing and Fetching the elements based on some order i.e FIFO)

Note :- Collection(I) is a predefined interface but Collections(C) is a predefined


class.
------------------------------------------------------------------------
Methods of Collection interface :
---------------------------------
a) public boolean add(Object element) :- It is used to add an item/element in the
collection.

b) public boolean addAll(Collection c) :- It is used to insert the specified


collection elements in the existing collection(For merging the Collection)

c) public boolean remove(Object element) :- It is used to delete an element from


the collection.

d) public boolean removeAll(Collection c) :- It is used to delete all the elements


from the existing collection.

e) public boolean retainAll(Collection c) :- It is used to retain all the elements


from existing element. (Common Data)

f) public int size() :- It is used to find out the size of the Collection.

g) public void clear() :- It is used to clear all the elements at once from the
Collection.
----------------------------------------------------------------------
20-12-2023
----------
List interface :
----------------
a) It is the sub interface of Collection interface

b) It can accept duplicate elements

c) We can perform sorting Operation on List interface manually.

d) It stores the elements on the basis of index just like an array.


-----------------------------------------------------------------------
Methods of List interface :
------------------------------
1) public boolean isEmpty() :- Verify whether List is empty or not

2) public void clear() :- Will clear all the elements

3) public int size() :- To get the size of the Collections

4) public void add(int index, Object o) :- Insert the element based on the index
position.

5) public boolean addAll(int index, Collection c) :- Insert the Collection based on


the index position

6) public Object get(int index) :- To retrieve the element based on the index
position

7) public Object set(int index, Object o) :- To override or replace the existing


element based on the index position

8) public Object remove(int index) :- remove the element based on the index
position

9) public boolean remove(Object element) :- remove the element based on the object
element, It is the Collection interface method extended by List interface

10) public int indexOf() :- index position of the element

11) public int lastIndex() :- last index position of the element

12) public Iterator iterator() :- To fetch or iterate or retrieve the elements from
Collection in forward direction only.

13) public ListIterator listIterator() :- To fetch or iterate or retrieve the


elements from Collection in forward and backward direction

----------------------------------------------------------------------
Behaviour of List interface Specific classes :
-----------------------------------------------
1) It will store the elements based on the index.
2) It can accept hetrogeneous types of elements.
3) It will accept duplicate elements.
4) With generics concept we can eliminate the compilation warning and
still we can take hetrogeneous types of elements. (<>)
5) IT IS DYNAMICALLY GROWABLE.
6) It can accept null values.
7) It stores everything in the form of Object.
----------------------------------------------------------------------
21-12-2023
-----------
How many ways we can fetch Collection Object from Collections Framework.

There are 7 ways to fetch the Collection Object from Collections Framework :

1) Enumeration interface (JDK 1.0)


2) Ordinary for loop
3) For each loop (JDK 1.5)
4) Iterator Interface (JDK 1.2)
*5) ListIterator
*6) For Each Method (JDK 1.8)
*7) Method Reference (::)
Among all these 7, Enumeration, Iterator and ListIterator are the cursors so they
can traverse.
------------------------------------------------------------------------
Enumeration :
----------------
It is a predefined interface available in [Link] package from JDK 1.0 onwards.

We can use Enumeration interface to fetch or retrieve the Objects one by one from
the Collection because it is a cursor.

We can create Enumeration object by using elements() method of the respective


Collection class.

public Enumeration elements();

Enumeration interface contains two methods :


---------------------------------------------------
1) public boolean hasMoreElements() :- It will return true if the Collection is
having more elements.

2) public Object nextElement() :- It will return collection object so return type


is Object.
----------------------------------------------------------------------
Iterator interface :
----------------------
It is a predefined interface available in [Link] package available from 1.2
version.

It is used to fetch/retrieve the elements from the Collection in forward direction


only.

public Iterator iterator();

Example :
-----------
Iterator itr = [Link]();

Now, Iterator interface has provided two methods

public boolean hasNext() :-

It will verify the element is available in the next position or not, if available
it will return true otherwise it will return false.

public Object next() :- It will return the collection object.


-----------------------------------------------------------------------------------
-
ListIterator interface :
-------------------------
It is a predefined interface available in [Link] package and it is the sub
interface of Iterator.

It is used to retrieve the Collection object in both the direction i.e in forward
direction as well as in backward direction.

public ListIterator listIterator();


Example :
-----------
ListIterator lit = [Link]();

1) public boolean hasNext() :-


It will verify the element is available in the next position or not, if available
it will return true otherwise it will return false.

2) public Object next() :- It will return the next position collection object.

3) public boolean hasPrevious() :-


It will verify the element is available in the previous position or not, if
available it will return true otherwise it will return false.

4) public Object previous () :- It will return the previous position collection


object.

Note :- Apart from these 4 methods we have add(), set() and remove() method in
ListIterartor interface.

-----------------------------------------------------------------------
By using forEach() method :
--------------------------------
From java 1.8 onwards every collection class provides a method forEach() method,
this method takes Consumer functional interface as a parameter
as shown in the follwing program.

The following program explains how forEach(Consumer cons) method works internally.

package [Link].fetching_collection_object;

import [Link];
import [Link];

public class ForEachInternalMechanism {

public static void main(String[] args)


{
Vector<String> v = new Vector<>();
[Link]("Apple");
[Link]("Orange");
[Link]("Grapes");
[Link]("Papaya");
[Link]("Kiwi");

// Consumer<String> cons = str -> [Link](str);


//[Link](cons);

[Link](str -> [Link](str));

}
------------------------------------------------------------------------
//7 ways to fetch the Collection Object Data

package [Link].fetching_collection_object;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class RetrieveCollectionObject


{
public static void main(String[] args)
{
Vector<String> v = new Vector<>();
[Link]("Apple");
[Link]("Orange");
[Link]("Grapes");
[Link]("Papaya");
[Link]("Kiwi");
[Link](v); //sort is a static method

[Link]("RETRIEVING USING ENUMERATION INTERFACE");

Enumeration<String> elements = [Link]();


while([Link]())
{
[Link]([Link]());
}

[Link]("RETRIEVING USING ORDINARY FOR LOOP");

for(int i=0; i<[Link](); i++)


{
[Link]([Link](i));
}

[Link]("RETRIEVING USING FOR EACH LOOP");

for(String fruit : v)
{
[Link](fruit);
}

[Link]("RETRIEVING USING ITERATOR INTERFACE");

Iterator<String> itr = [Link]();

while([Link]())
{
[Link]([Link]());
}

[Link]("RETRIEVING USING LISTITERATOR INTERFACE");

ListIterator<String> lt = [Link]();

[Link]("IN FORWARD DIRECTION");

while([Link]())
{
[Link]([Link]());
}
[Link]("IN BACKWARD DIRECTION");

while([Link]())
{
[Link]([Link]());
}

[Link]("RETRIEVING USING FOREACH METHOD");


[Link](x-> [Link]([Link]()));

[Link]("RETRIEVING USING METHOD REFERENCE");

[Link]([Link]::println);

}
}
-----------------------------------------------------------------------
ArrayList :
-----------
public class ArrayList<E> extends AbstractList<E> implements List<E>,
Serializable, Clonable, RandomAccess

It is a predefined class available in [Link] package under List interface.

It accepts duplicate elements and null values.

It is dynamically growable array.

It stores the elements on index basis so it is simillar to dynamic array.

Initial capacity of ArrayList is 10. The new capacity of Arraylist can be


calculated by using the formula
new capacity = (current capacity * 3/2) + 1

*All the methods declared inside an ArrayList is not synchronized so multiple


thread can access the method of ArrayList.

*It is highly suitable for fetching or retriving operation when duplicates are
allowed and Thread-safety is not required.

It implements List,Serializable, Clonable, RandomAccess interfcaes

Constructor of ArrayList :
----------------------------
In ArrayList we have 3 types of Constructor:
Constructor of ArrayList :
----------------------------
We have 3 types of Constructor in ArrayList

1) ArrayList al1 = new ArrayList();


Will create ArrayList object with default capacity 10.

2) ArrayList al2 = new ArrayList(int initialCapacity);


Will create an ArrayList object with user specified Capacity

3) ArrayList al3 = new ArrayList(Collection c)


We can copy any Collection interface implemented class data to the current
object reference (Coping one Collection data to another)
---------------------------------------------------------------
Note :- Collections is a predefined class in [Link] where as Collection is an
interface in [Link].

package [Link];

import [Link].*;
public class ArrayListDemo
{
public static void main(String... a)
{
ArrayList<String> arl = new ArrayList<>();//Generic type
[Link]("Apple");
[Link]("Orange");
[Link]("Grapes");
[Link]("Mango");
[Link]("Guava");
[Link]("Mango");

[Link]("Contents :"+arl); //toString() [Apple,....]

[Link](2); //based on the index position


[Link]("Guava"); //based on the Object

[Link]("Contents After Removing :"+arl);


[Link]("Size of the ArrayList:"+[Link]());

[Link](arl);

[Link]( x -> [Link](x));


}
}

Note :- sort(List x) is a static method of Collections class available in [Link]


package.
----------------------------------------------------------------------
Program that describes how to work with Custom class(Product) :
--------------------------------------------------------------
[Link]
-------------------
package [Link];

import [Link];
import [Link];

class Product
{
private Integer productId;
private String productName;
private Double productPrice;

public Product(Integer productId, String productName, Double productPrice) {


super();
[Link] = productId;
[Link] = productName;
[Link] = productPrice;
}

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

public class ArrayListDemo1 {

public static void main(String[] args)


{
ArrayList<Product> al = new ArrayList<>();
[Link](new Product(333, "Camera", 75000.89));
[Link](new Product(111, "Mobile", 34000.89));
[Link](new Product(222, "Laptop", 84000.89));

//By using Iterator


Iterator<Product> itr = [Link]();
[Link](p-> [Link](p));

[Link](".............");
//By using forEach method
[Link](p-> [Link](p));

}
----------------------------------------------------------------------
package [Link];

//Program to merge and retain of two collection


import [Link].*;
public class ArrayListDemo2
{
public static void main(String args[])
{
ArrayList<String> al1=new ArrayList<>();
[Link]("Ravi");
[Link]("Rahul");
[Link]("Rohit");

ArrayList<String> al2=new ArrayList<>();


[Link]("Pallavi");
[Link]("Sweta");
[Link]("Puja");

[Link](al2);

[Link](x -> [Link]([Link]()));

[Link](".................................");

ArrayList<String> al3=new ArrayList<>();


[Link]("Ravi");
[Link]("Rahul");
[Link]("Rohit");

ArrayList<String> al4=new ArrayList<>();


[Link]("Pallavi");
[Link]("Rahul");
[Link]("Raj");

[Link](al4);

[Link](x -> [Link](x));


}
}
-----------------------------------------------------------------------
//Program to fetch the elements in forward and backward
//direction using ListIterator interface

package [Link];

import [Link].*;
public class ArrayListDemo3
{
public static void main(String args[])
{
//Arrays class is having static method asList()
List<String> list =
[Link]("Ravi","Rahul","Sweta","Ananya","Bina");

[Link](list);
[Link](list);

ListIterator<String> itr=[Link]();

[Link]("traversing elements in forward direction...");


while([Link]())
{
[Link]([Link]());
}

[Link]("traversing elements in backward direction...");


while([Link]())
{
[Link]([Link]());
}
}
}
-----------------------------------------------------------------------
23-12-2023
-----------
Program on Serialization and De-serialization using ArrayList class

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

class Prod implements Serializable


{
private Integer productId;
private String productName;
private Double productPrice;

public Prod(Integer productId, String productName, Double productPrice) {


super();
[Link] = productId;
[Link] = productName;
[Link] = productPrice;
}

public Integer getProductId() {


return productId;
}

public String getProductName() {


return productName;
}

public Double getProductPrice() {


return productPrice;
}

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

public class ArrayListSerialization


{
public static void main(String[] args) throws IOException
{
ArrayList<Prod> listOfProduct = new ArrayList<>();
[Link](new Prod(333, "Laptop", 82890.89));
[Link](new Prod(222, "Camera", 82890.89));
[Link](new Prod(111, "Mobile", 82890.89));

//Serialization
var fos = new FileOutputStream("C:\\new\\[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);

//De-Serialization
var fin = new FileInputStream("C:\\new\\[Link]");
ObjectInputStream ois = new ObjectInputStream(fin);

try(fos; oos; fin; ois)


{
[Link](listOfProduct);
[Link]("Object Stored successfully");

[Link]("Reading the Data from the obejct");

ArrayList<Prod> list =(ArrayList<Prod>) [Link]();


[Link](list);

}
catch(Exception e)
{
[Link]();
}
}

}
-----------------------------------------------------------------------
//Serialization and De-serialization on ArrayList Object
package [Link];

import [Link].*;
import [Link].*;
public class ArrayListDemo4
{
public static void main(String [] args) throws IOException
{
ArrayList<String> al=new ArrayList<>();
[Link]("Nagpur");
[Link]("Vijaywada");
[Link]("Hyderabad");
[Link]("Jamshedpur");

//Serialization
FileOutputStream fos=new FileOutputStream("C:\\new\\[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);

//De-serialization
FileInputStream fis=new FileInputStream("C:\\new\\[Link]");

ObjectInputStream ois=new ObjectInputStream(fis);

try (fos; oos; fis; ois)


{
[Link](al); //Serialization

ArrayList<String> list = (ArrayList<String>)


[Link]();
[Link](list);
}
catch(Exception e)
{
[Link](e);
}

}
}
-----------------------------------------------------------------------
public void ensureCapacity(int minimumCapacity) :-
-----------------------------------------------
It is a predefined method of ArrayList class, by using this method we can resize
the capacity of ArrayList Object.

Here by specifying the parameter it ensures that it can hold at least the number of
elements specified by the minimum capacity argument.
-------------------------------------------------------------------
package [Link];
import [Link];

public class ArrayListDemo5


{
public static void main(String[] args)
{
ArrayList<String> city= new ArrayList<>();//default capacity is 10
[Link](3);//resized the arraylist to store 3 elements.

[Link]("Hyderabad");
[Link]("Mumbai");
[Link]("Delhi");

[Link]("Kolkata");
[Link]("ArrayList: " + city);
}
}
-----------------------------------------------------------------------
package [Link];

//Program on ArrayList that contains null values as well as we can pass the element
based on the index position
import [Link].*;
public class ArrayListDemo6
{
public static void main(String[] args)
{
ArrayList<Object> al = new ArrayList<>(); //Generic type
[Link](12);
[Link]("Ravi");
[Link](12);
[Link](3,"Hyderabad"); //add(int index, Object o)method of List
interface
[Link](1,"Naresh");
[Link](null);
[Link](11);
[Link](al); //12 Naresh Ravi 12 Hyderabad
}
}
----------------------------------------------------------------------
Limitation of ArrayList :
-------------------------
The time complexcity of ArrayList to insert and delete an element from the middle
would be O(n) because 'n' number of elements will be re-located so it is not a good
choice to perform insertion and deletion operation in the middle of the List.

On the other hand ArryList is good choice for retrieval operation because by using
index we can retrieve the element in O(1).

To avoid this we introduced LinkedList.


----------------------------------------------------------------------
LinkedList :
------------
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>,
Deque<E>, Cloneable, Serializable

It is a predefined class available in [Link] package under List interface.

It is ordered by index position like ArrayList except the elements (nodes) are
doubly linked to one another. This linkage provide us new method for adding and
removing the elements from the middle of LinkedList.

*The important thing is, LikedList may iterate more slowely than ArrayList but
LinkedList is a good choice when we want to insert or delete the elements
frequently in the list.

From jdk 1.5 onwards LinkedList class has been enhanced to support basic queue
operation by implementing Deque<E> interface.

ArrayList is using Array data structure but LinkedList class is using LinkedList
data structure.

Constructor:
-------------
It has 2 constructors

1) LinkedList list1 = new LinkedList();


It will create a LinkedList object with 0 capacity.

2) LinkedList list2 = new LinkedList(Collection c);


Interconversion between the collection

Methods of LinkedList class:


-------------------------------
1) void addFirst(Object o)
2) void addLast(Object o)

3) Object getFirst()
4) Object getLast()

5) Object removeFirst()
6) Object removeLast()

Note :- It stores the elements in non-contiguous memory location.

The time complexcity for insertion and deletion is O(1)

The time complexcity for seraching O(n)


---------------------------------------------------------------------
//Program that describes LinkedList class works on the basis of index.
package [Link].linked_list;

import [Link];
import [Link];
public class LinkedListDemo
{
public static void main(String args[])
{
List<Object> list=new LinkedList<>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link](null);
[Link](42);

[Link]("0th Position Element is :"+[Link](0));

[Link](x -> [Link](x));


}
}
----------------------------------------------------------------------
package [Link].linked_list;

import [Link].*;
public class LinkedListDemo1
{
public static void main(String args[])
{
LinkedList<String> list= new LinkedList<>(); //generic
[Link]("Item 2");//2
[Link]("Item 3");//3
[Link]("Item 4");//4
[Link]("Item 5");//5
[Link]("Item 6");//6
[Link]("Item 7");//7

[Link]("Item 9"); //10

[Link](0,"Item 0");//0
[Link](1,"Item 1"); //1

[Link](8,"Item 8");//8
[Link](9,"Item 10");//9
[Link](list);

[Link]("Item 5");

[Link](list);

[Link]();
[Link](list);

[Link]();
[Link](list);

[Link](0,"Ajay"); //set() will replace the existing value


[Link](1,"Vijay");
[Link](2,"Anand");
[Link](3,"Aman");
[Link](4,"Suresh");
[Link](5,"Ganesh");
[Link](6,"Ramesh");
[Link](x -> [Link](x));

}
}
---------------------------------------------------------------------
package [Link].linked_list;

//Methods of LinkedList class


import [Link];
public class LinkedListDemo2
{
public static void main(String[] argv)
{
LinkedList<String> list = new LinkedList<>();
[Link]("Ravi");
[Link]("Rahul");
[Link]("Anand");

[Link]([Link]());
[Link]([Link]());

[Link]();
[Link]();

[Link](list);
}
}
---------------------------------------------------------------------
ListIterator interface Methods:
-------------------------------
package [Link].linked_list;
//ListIterator methods
import [Link].*;
public class LinkedListDemo3
{
public static void main(String[] args)
{
LinkedList<String> city = new LinkedList<> ();
[Link]("Kolkata");
[Link]("Bangalore");
[Link]("Hyderabad");
[Link]("Pune");
[Link](city);

ListIterator<String> lt = [Link]();

while([Link]())
{
String cityName = [Link]();

if([Link]("Kolkata"))
{
[Link]();
}
else if([Link]("Hyderabad"))
{
[Link]("Ameerpet");
}
else if([Link]("Pune"))
{
[Link]("Mumbai");
}
}
[Link]([Link]::println);
}
}

----------------------------------------------------------------------
package [Link].linked_list;

//Insertion, deletion, displaying and exit


import [Link];
import [Link];

public class LinkedListDemo4


{
public static void main(String[] args)
{
LinkedList<Integer> linkedList = new LinkedList<>();
Scanner scanner = new Scanner([Link]);

while (true)
{
[Link]("Linked List: " + linkedList);
[Link]("1. Insert Element");
[Link]("2. Delete Element");
[Link]("3. Display Element");
[Link]("4. Exit");
[Link]("Enter your choice: ");

int choice = [Link]();


switch (choice)
{
case 1:
[Link]("Enter the element to insert: ");
int elementToAdd = [Link]();
[Link](elementToAdd);
break;
case 2:
if ([Link]())
{
[Link]("Linked list is empty. Nothing to
delete.");
}
else
{
[Link]("Enter the element to delete: ");
int elementToDelete = [Link]();
//Converting the primitive to Wrapper object
boolean remove =
[Link]([Link](elementToDelete));

if(remove)
{
[Link]("Element "+elementToDelete+ " is
deleted Successfully" );
}
else
{
[Link](elementToDelete+" not available is
the LinkedList");
}

}
break;
case 3:
[Link]("Elements in the linked list.");
[Link](linkedList);
break;
case 4:
[Link]("Exiting the program.");
[Link]();
[Link](0);
default:
[Link]("Invalid choice. Please try again.");
}
}
}
}
---------------------------------------------------------------------
Merging of two Collection data :
----------------------------------
package [Link].linked_list;

import [Link];
import [Link];
import [Link];
import [Link];

public class LinkedListDemo5 {

public static void main(String[] args)


{
List<String> listOfName = [Link]("Ravi","Rahul","Ankit",
"Rahul");

LinkedList<String> list = new LinkedList<String>(listOfName);


[Link]([Link]::println);
[Link](".......");

}
----------------------------------------------------------------------
Vector :
--------
public class Vector<E> extends AbstractList<E> implements List<E>, Serializable,
Clonable, RandomAccess

Vector is a predefined class available in [Link] package under List interface.

Vector is always from java means it is available from jdk 1.0 version.

Vector and Hashtable, these two classes are available from jdk 1.0, remaining
Collection classes were added from 1.2 version. That is the reason Vector and
Hashtable are called legacy(old) classes.

The main difference between Vector and ArrayList is, ArrayList methods are not
synchronized so multiple threads can access the method of ArrayList where as on the
other hand most the methods are synchronized in Vector so performance wise Vector
is slow.

*We should go with ArrayList when Threadsafety is not required on the other hand we
should go with Vector when we need ThreadSafety for reterival operation.

It also stores the elements on index [Link] is dynamically growable with initial
capacity 10. The next capacity will be 20 i.e double of the first capacity.

new capacity = current capacity * 2;


Just like ArrayList it also implements List, Serializable, Clonable, RandomAccess
interfaces.

Constructors in Vector :
-------------------------
We have 4 types of Constructor in Vector

1) Vector v1 = new Vector();


It will create the vector object with default capacity is 10

2) Vector v2 = new Vector(int initialCapacity);


Will create the vector object with user specified capacity.

3) Vector v3 = new Vector(int initialCapacity, int incrementalCapacity);


Eg :- Vector v = new Vector(1000,5);

Initially It will create the Vector Object with initial capacity 1000 and then
when the capacity will be full then increment by 5 so the next capacity would be
1005, 1010 and so on.

4) Vector v4 = new Vector(Collection c);


Interconversion between the Collection.

----------------------------------------------------------------------
Capacity method of Vector :
---------------------------
//Vector Program on capacity

package [Link];

import [Link].*;
public class VectorDemo1
{
public static void main(String[] args)
{
Vector<Integer> v = new Vector<>(100, 10); //initial capacity is 100
[Link]("Initial capacity is :"+[Link]());

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


{
[Link](i);
}

[Link]("After adding 100 elements capacity is :"+[Link]());


[Link](101);
[Link]("After adding 101th elements capacity is :"+[Link]());

for(Integer i : v)
{
[Link](i+"\t");
if(i%5==0)
[Link]();
}
}
}
----------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];

class Employee
{
private Integer employeeId;
private String employeeName;
private Double employeeSalry;

public Employee(Integer employeeId, String employeeName, Double


employeeSalry) {
super();
[Link] = employeeId;
[Link] = employeeName;
[Link] = employeeSalry;
}

public Integer getEmployeeId() {


return employeeId;
}

public void setEmployeeId(Integer employeeId) {


[Link] = employeeId;
}

public String getEmployeeName() {


return employeeName;
}

public void setEmployeeName(String employeeName) {


[Link] = employeeName;
}

public Double getEmployeeSalry() {


return employeeSalry;
}

public void setEmployeeSalry(Double employeeSalry) {


[Link] = employeeSalry;
}

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

public class VectorDemo2


{
public static void main(String[] args)
{
Vector<Employee> emp = new Vector<>();
[Link](new Employee(111, "Ravi", 49000.78));
[Link](new Employee(222, "Rahul", 37000.78));
[Link](new Employee(333, "Anjali", 26000.78));
[Link](new Employee(222, "Rahul", 57000.78));
[Link](new Employee(222, "Rahul", 57000.78));
[Link](new Employee(222, "Ankit", 67000.78));

//Stream API
[Link]().filter(e1 -> [Link]()<40000.00).forEach(d->
[Link](d));

}
}
----------------------------------------------------------------------
27-12-2023
----------
package [Link];
//Array To Collection
import [Link].*;
public class VectorDemo3
{
public static void main(String args[])
{
Vector<Integer> v = new Vector<>();

int x[]={22,20,10,40,15,58};

//Adding array values to Vector


for(int i=0; i<[Link]; i++)
{
[Link](x[i]);
}
[Link](v);
[Link]("Maximum element is :"+[Link](v));
[Link]("Minimum element is :"+[Link](v));
[Link]("Vector Elements :");
[Link](y -> [Link](y));
}
}
---------------------------------------------------------------------
System is a predefined class available in [Link] package and it contains a
predefined static method currentTimeMillis() , the return type of this method is
long, actually it returns the current time of the system in ms.

//Program to describe that ArrayList is better then Vector in performance

package [Link];

import [Link];
import [Link];

public class VectorDemo4


{
public static void main(String[] args)
{
long startTime = [Link]();
ArrayList<Integer> al = new ArrayList<>();
for(int i=0; i<=1000000; i++)
{
[Link](i);
}
long endTime = [Link]();
[Link]("The total time taken by ArrayList to complete the
task :"+(endTime - startTime)+" ms");

startTime = [Link]();
Vector<Integer> v = new Vector<>();
for(int i=0; i<=1000000; i++)
{
[Link](i);
}
endTime = [Link]();
[Link]("The total time taken by Vector to complete the task
:"+(endTime - startTime)+" ms");
}
}
----------------------------------------------------------------------
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Vector5 {

public static void main(String[] args)


{
List<Integer> v = [Link](89,56,34,12,9,15,3,89,34);

//Fetching all the even number without Java 8


Vector<Integer> evenNum = new Vector<>();

for(Integer i : v)
{
if(i%2==0)
{
[Link](i);
}
}
[Link]([Link]::println);
[Link]("............");
//Java 8 Stream API
List<Integer> collect = (List<Integer>) [Link]().filter(n-> n
%2==0).sorted().collect([Link]());
[Link]([Link]::println);

}
}
----------------------------------------------------------------------
Stack :

Stack :
------
public class Stack<E> extends Vector<E>

It is a predefined class available in [Link] package. It is the sub class of


Vector class.
It is a linear data structure that is used to store the Objects in LIFO (Last In
first out) order.

Inserting an element into a Stack is known as push operation where as extracting


an element from the top of the stack is known as pop operation.

It throws an unchecked exception called EmptyStackException, if Stack is empty and


we want to fetch the element.

It has only one constructor as shown below

Stack s = new Stack();


----------------------------------------------------------------------
//Program to insert and fetch the elements from stack
package [Link];
import [Link].*;
public class Stack1
{
public static void main(String args[])
{
Stack<Integer> s = new Stack<>();
try
{ [Link](12);
[Link](15);
[Link](22);
[Link](33);
[Link](49);
[Link]("After insertion elements are :"+s);

[Link]("Fetching the elements using pop method");


[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());

[Link]("After deletion elements


are :"+s); //[]
[Link]("Is the Stack empty ? :"+[Link]());
}
catch(EmptyStackException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
//add(Object obj) is the method of Collection
package [Link];
import [Link].*;
public class Stack2
{
public static void main(String args[])
{
Stack<Integer> st1 = new Stack<>();
[Link](10);
[Link](20);
[Link](x -> [Link](x));

Stack<String> st2 = new Stack<>();


[Link]("Java");
[Link]("is");
[Link]("programming");
[Link]("language");
[Link](x -> [Link](x));

Stack<Character> st3 = new Stack<>();


[Link]('A');
[Link]('B');
[Link](x -> [Link](x));

Stack<Double> st4 = new Stack<>();


[Link](10.5);
[Link](20.5);
[Link](x -> [Link](x));
}
}
---------------------------------------------------------------------
package [Link];
import [Link];

public class Stack3


{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
[Link]("Apple");
[Link]("Grapes");
[Link]("Mango");
[Link]("Orange");
[Link]("Stack: " + stk);

String fruit = [Link]();


[Link]("Element at top: " + fruit);
[Link]("Stack elements are : " + stk);
}
}
----------------------------------------------------------------------
//Searching an element in the Stack
package [Link];
import [Link];
public class Stack4
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
[Link]("Apple");
[Link]("Grapes");
[Link]("Mango");
[Link]("Offset Position is : " +
[Link]("Mango")); //1
[Link]("Offser Position is : " +
[Link]("Banana")); //-1
[Link]("Is stack empty ? "+[Link]()); //false

[Link]("Index Position is : " +


[Link]("Mango")); //2
}
}
----------------------------------------------------------------------
Set interface :
---------------
It is the sub interface of Collection interface.

It does not accept duplicate elements because internally it invokes equals(Object


obj) method of Object class for comparing two objects.

It does not maintain any order.

We can't perform sorting operation manually.(sort(List l))

ListIterator interface will not work with Set because it does not maintain any
order while retrieving the element.
---------------------------------------------------------------------
Hierarchy of Set interafce :
----------------------------
Available in the Diagram (27-DEC-23)
----------------------------------------------------------------------
28-12-2023
-----------
Methods of Set interface :
--------------------------
a) int size(): Returns the number of elements in this set.

b) boolean isEmpty(): Returns true if this set contains no elements.

c) boolean contains(Object o): Returns true if this set contains the specified
element.

d)boolean add(E e): Adds the specified element to this set if it is not already
present (optional operation).

e) boolean remove(Object o): Removes the specified element from this set if it is
present (optional operation).

f) boolean containsAll(Collection<?> c): Returns true if this set contains all of


the elements of the specified collection.

g) boolean addAll(Collection<? extends E> c): Adds all of the elements in the
specified collection to this set if they're not already present

h) boolean retainAll(Collection<?> c): Retains only the elements in this set that
are contained in the specified collection . In other words, removes from this set
all of its elements that are not contained in the specified collection.

i) boolean removeAll(Collection<?> c): Removes from this set all of its elements
that are contained in the specified collection .

j) void clear(): Removes all of the elements from this set (optional operation).
The set will be empty after this call returns.
---------------------------------------------------------------------
HashSet (UNSORTED, UNORDERED , NO DUPLICATES)
---------------------------------------------
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Clonabale,
Serializable
It is a predefined class available in [Link] package under Set interface.

It is an unsorted and unordered set.

It accepts hetrogeneous kind of data.

*It uses the hashcode of the object being inserted into the Collection. Using this
hashcode it finds the bucket location.

It doesn't contain any duplicate elements as well as It does not maintain any order
while iterating the elements from the collection.

It can accept null value.

HashSet is used for fast searching operation.

It contains 4 types of constructor

1) HashSet hs1 = new HashSet();


It will create the HashSet Object with default capacity is 16. The default load
fator or Fill Ratio is 0.75 (75% of HashSet is filled up then new HashSet Object
will be created having double capacity)

2) HashSet hs2 = new HashSet(int initialCapacity);


will create the HashSet object with user specified capacity

3) HashSet hs3 = new HashSet(int initialCapacity, float loadFactor);


we can specify our own initialCapacity and loadFactor(by default load factor is
0.75%)

4) HashSet hs = new HashSet(Collection c);


Interconversion of Collection
-----------------------------------------------------------------------
//Unsorted, Unordered and no duplicates
import [Link].*;
public class HashSetDemo
{
public static void main(String args[])
{
HashSet<Integer> hs = new HashSet<>();
[Link](67);
[Link](89);
[Link](33);
[Link](45);
[Link](12);
[Link](35);

[Link](str-> [Link](str));
}
}
----------------------------------------------------------------------
//HashSet does not maintain any order to fetch the elements
import [Link].*;
public class HashSetDemo1
{
public static void main(String[] argv)
{
HashSet<String> hs=new HashSet<>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
[Link]("Palavi");
[Link]("Sweta");
[Link](null);
[Link](null);
[Link](str -> [Link](str));

}
}
----------------------------------------------------------------------
import [Link].*;
public class HashSetDemo2
{
public static void main(String[] args)
{
boolean[] ba = new boolean[6];

Set<Object> s = new HashSet<>();


ba[0] = [Link]("a");
ba[1] = [Link](42);
ba[2] = [Link]("b");
ba[3] = [Link]("a");
ba[4] = [Link]("new Object()");
ba[5] = [Link](new Object());

for(int x = 0; x<[Link]; x++)


[Link](ba[x]+" ");

if([Link](42)) //Searching a particular object in the Set


{
[Link]("Object 42 is available ...");
}
else
{
[Link]("42 is not available ...");
}

[Link]("Fetching the elements of HashSet");


[Link](str -> [Link](str));
}
}

Note :- From this program it is clear that add(Object o) method return type is
boolean.
----------------------------------------------------------------------
import [Link];
import [Link];

public class HashSetDemo3


{
public static void main(String[] args)
{
HashSet<String> hashSet = new HashSet<>();
Scanner scanner = new Scanner([Link]);
while (true)
{
[Link]("Options:");
[Link]("1. Add element");
[Link]("2. Delete element");
[Link]("3. Display HashSet");
[Link]("4. Exit");

[Link]("Enter your choice (1/2/3/4): ");


int choice = [Link]();

switch (choice)
{
case 1:
[Link]("Enter the element to add: ");
String elementToAdd = [Link]();
if ([Link](elementToAdd))
{
[Link]("Element added successfully.");
}
else
{
[Link]("Element already exists in the
HashSet.");
}
break;
case 2:
[Link]("Enter the element to delete: ");
String elementToDelete = [Link]();
if ([Link](elementToDelete))
{
[Link]("Element deleted successfully.");
}
else
{
[Link]("Element not found in the HashSet.");
}
break;
case 3:
[Link]("Elements in the HashSet:");
for (String element : hashSet) {
[Link](element);
}
break;
case 4:
[Link]("Exiting the program.");
[Link]();
[Link](0);
default:
[Link]("Invalid choice. Please try again.");
}

[Link]();
}
}
}
-----------------------------------------------------------------------
LinkedHashSet
-------------
public class LinkedHashSet extends HashSet implements Set, Clonable, Serializable

It is a predefined class in [Link] package under Set interface.

It is the sub class of HashSet class.

It is an orderd version of HashSet that maintains a doubly linked list across all
the elements.

We should use LinkedHashSet class when we want to maintain an order.

When we iterate the elements through HashSet the order will be unpredictable, while
when we iterate the elments through LinkedHashSet then the order will be same as
they were inserted in the collection.

It accepts hetrogeneous and null value is allowed.

It has same constructor as HashSet class.


----------------------------------------------------------------------
import [Link].*;
public class LinkedHashSetDemo
{
public static void main(String args[])
{
LinkedHashSet<String> lhs=new LinkedHashSet<>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
[Link]("Pawan");
[Link]("Shiva");
[Link](null);
[Link]("Ganesh");
[Link](str -> [Link](str));
}
}
----------------------------------------------------------------------
import [Link];

public class LinkedHashSetDemo1


{
public static void main(String[] args)
{
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();

[Link](10);
[Link](5);
[Link](15);
[Link](20);
[Link](5);

[Link]("LinkedHashSet elements: " + linkedHashSet);

[Link]("LinkedHashSet size: " + [Link]());

int elementToCheck = 15;


if ([Link](elementToCheck))
{
[Link](elementToCheck + " is present in the
LinkedHashSet.");
}
else
{
[Link](elementToCheck + " is not present in the
LinkedHashSet.");
}

int elementToRemove = 10;


[Link](elementToRemove);
[Link]("After removing " + elementToRemove + ", LinkedHashSet
elements: " + linkedHashSet);

[Link]();
[Link]("After clearing, LinkedHashSet elements: " +
linkedHashSet);
}
}
----------------------------------------------------------------------
29-12-2023
----------
SortedSet interface :
---------------------
1) It is the sub interface of Set interface

2) If we don't want duplicate elements and want to store the elements based on some
sorting order i.e default natural sorting order then we should go with SortedSet(I)

3) default natural sorting means, if it is number then ascending order and if it is


String then dictionary order or Alphabetical order.

4) We have two interfaces Comparable(available in [Link] package) and Comparator


(available in [Link] package) to compare two objects.
---------------------------------------------------------------
*What is the difference between Comparable and Comparator interface
-------------------------------------------------------------------
Available in the paint Diagram (29-DEC-23)

Program on Comparable :
-----------------------
2 Files :
---------
[Link]
--------------
package [Link];

public class Employee implements Comparable<Employee>


{
private Integer employeeId;
private String employeeName;
private Double employeeSalary;

public Employee(Integer employeeId, String employeeName, Double employeeSalary) {


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

/*Sorting based on the Employee Name


@Override
public int compareTo(Employee e2)
{
return [Link]([Link]);
} */

//Sorting logic based on EmployeeID


@Override
public int compareTo(Employee e2)
{
return [Link] - [Link];
}
}

[Link]
-----------------------
package [Link];

import [Link];
import [Link];

public class EmployeeComparable


{
public static void main(String[] args)
{
ArrayList<Employee> listOfEmployee = new ArrayList<>();
[Link](new Employee(333, "Ankit", 40000.89));
[Link](new Employee(111, "Zuber", 40000.89));
[Link](new Employee(222, "Ravi", 40000.89));

[Link](listOfEmployee);

[Link](emp-> [Link](emp));

}
---------------------------------------------------------------------
Limitation of Comparable interface :
-----------------------------------------
1) We need to modify the original source code (BLC class), If the source code is
not available then it is not possible to perform sorting operation.

2) We can provide only one sorting logic if we want to provide mutiple sorting
logic then it is not possible.

To avoid the above said problems we introduced Comparator interface available in


[Link] package.
Program on Comparator :
------------------------
2 Files :
---------
[Link]
-------------
package [Link];

public class Product


{
private Integer productId;
private String productName;
private Double productPrice;

public Product() {
super();
// TODO Auto-generated constructor stub
}

public Product(Integer productId, String productName, Double productPrice) {


super();
[Link] = productId;
[Link] = productName;
[Link] = productPrice;
}

public Integer getProductId() {


return productId;
}

public void setProductId(Integer productId) {


[Link] = productId;
}

public String getProductName() {


return productName;
}

public void setProductName(String productName) {


[Link] = productName;
}

public Double getProductPrice() {


return productPrice;
}

public void setProductPrice(Double productPrice) {


[Link] = productPrice;
}

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

}
[Link]
-----------------------
package [Link];

import [Link];
import [Link];
import [Link];

public class ProductComparator


{
public static void main(String[] args)
{
ArrayList<Product> listOfProduct = new ArrayList<>();
[Link](new Product(333, "Camera", 12000.89));
[Link](new Product(111, "Mobile", 12000.89));
[Link](new Product(222, "Laptop", 12000.89));

//Sorting based on Product ID


Comparator<Product> cmpId = new Comparator<Product>()
{
@Override
public int compare(Product p1, Product p2)
{
return [Link]() - [Link]();
}
};
[Link]("SORTING BASED ON THE PRODUCT ID");
[Link](listOfProduct, cmpId);
[Link](prod -> [Link](prod));

[Link]("............................");

//Sorting based on the Product Name(Lambda)


Comparator<Product> cmpName =(p1, p2)->
[Link]().compareTo([Link]());

[Link](listOfProduct, cmpName);
[Link]("SORTING BASED ON THE PRODUCT NAME");
[Link](prod -> [Link](prod));

--------------------------------------------------------------------
Program that describes, how to provide descending order for Integer object using
Comparator interface.

package [Link];

import [Link];
import [Link];
import [Link];

public class IntegerDescending {


public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<>();
[Link](78);
[Link](68);
[Link](47);
[Link](33);
[Link](15);

Comparator<Integer> cmp = (i1, i2)-> -(i1 - i2);

[Link](al, cmp);
[Link]([Link]::println);
}

}
---------------------------------------------------------------------
30-12-2023
-----------
TreeSet :
----------
TreeSet :
----------
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet, Clonable,
Serializable

It is a predefined class available in [Link] package under Set interface.

TreeSet, TreeMap and PriorityQueue are the three sorted collection in the entire
Collection Framework so these classes never accepting hetrogeneous kind of the
data.

It will sort the elements in natural sorting order i.e ascending order in case of
number, and alphabetical order or Dictionary order in the case of String. In order
to sort the elements It uses Comparator interface.

It does not accept duplicate and null value ([Link]).

It does not accept hetrogeneous type of data if we try to insert it will throw a
runtime exception i.e [Link]

TreeSet implements NavigableSet.

NavigableSet extends SortedSet.

It contains 4 types of constructor :


----------------------------------------
1) TreeSet t1 = new TreeSet();
create an empty TreeSet object, elements will be inserted in a natural sorting
order.

2) TreeSet t2 = new TreeSet(Comparator c);


Customized sorting order

3) TreeSet t3 = new TreeSet(Collection c);

4) TreeSet t4 = new TreeSet(SortedSet s);


-----------------------------------------------------------------------
//program that describes TreeSet provides default natural sorting order
import [Link].*;
public class TreeSetDemo
{
public static void main(String[] args)
{
SortedSet<Integer> t1 = new TreeSet<>();
[Link](4);
[Link](7);
[Link](2);
[Link](1);
[Link](9);

[Link](t1);

NavigableSet<String> t2 = new TreeSet<>();


[Link]("Orange");
[Link]("Mango");
[Link]("Banana");
[Link]("Grapes");
[Link]("Apple");
[Link](t2);
}
}
----------------------------------------------------------------------
import [Link].*;
public class TreeSetDemo1
{
public static void main(String[] args)
{
TreeSet<String> t1 = new TreeSet<>();
[Link]("Orange");
[Link]("Mango");
[Link]("Pear");
[Link]("Banana");
[Link]("Apple");
[Link]("In Ascending order");
[Link](i -> [Link](i));

TreeSet<String> t2 = new TreeSet<>();


[Link]("Orange");
[Link]("Mango");
[Link]("Pear");
[Link]("Banana");
[Link]("Apple");

[Link]("In Descending order");


Iterator<String> itr2 = [Link](); //for descending
order

[Link](x -> [Link](x));


}
}

Note :- descendingIterator() is a predefined method of TreeSet class which will


traverse in the descending order and its return type is Iterator interface.
------------------------------------------------------------------------
import [Link].*;
public class TreeSetDemo2
{
public static void main(String[] args)
{
Set<String> t = new TreeSet<>();
[Link]("6");
[Link]("5");
[Link]("4");
[Link]("2");
[Link]("9");
Iterator<String> iterator = [Link]();
[Link](x -> [Link](x));

//From 1.8 to replace hasNext() and next() method


}
}
-----------------------------------------------------------------------
import [Link].*;

public class TreeSetDemo3


{
public static void main(String[] args)
{
Set<Character> t = new TreeSet<>();
[Link]('A');
[Link]('C');
[Link]('B');
[Link]('E');
[Link]('D');
Iterator<Character> iterator = [Link]();
[Link](x -> [Link](x));
}
}
------------------------------------------------------------------------
Program that describes how to use Comparator as a constructor parameter
-----------------------------------------------------------------------
[Link]
------------
package [Link].treeset_comp;

public class Student


{
private Integer studentId;
private String studentName;
private Double studentFees;

public Student(Integer studentId, String studentName, Double studentFees) {


super();
[Link] = studentId;
[Link] = studentName;
[Link] = studentFees;
}

public Integer getStudentId() {


return studentId;
}

public void setStudentId(Integer studentId) {


[Link] = studentId;
}
public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {


[Link] = studentName;
}

public Double getStudentFees() {


return studentFees;
}

public void setStudentFees(Double studentFees) {


[Link] = studentFees;
}

@Override
public String toString()
{
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentFees=" + studentFees
+ "]";
}
}

[Link]
------------------------------
package [Link].treeset_comp;

import [Link];
import [Link];

//Sorting student Id in ascending order


class IdAscendingComparator implements Comparator<Student>
{
@Override
public int compare(Student s1, Student s2)
{
return [Link]() - [Link]();
}
}

//Sorting student Id in descending order


class IdDescendingComparator implements Comparator<Student>
{
@Override
public int compare(Student s1, Student s2)
{
return -([Link]() - [Link]());
}
}

//Sorting student name in ascending order


class NameAscendingComparator implements Comparator<Student>
{
@Override
public int compare(Student s1, Student s2)
{
return [Link]().compareTo([Link]());
}
}

//Sorting student name in descending order


class NameDescendingComparator implements Comparator<Student>
{
@Override
public int compare(Student s1, Student s2)
{
return -([Link]().compareTo([Link]()));
}
}

public class TreeSetStudentComparator


{
public static void main(String[] args)
{
TreeSet<Student> ts1 = new TreeSet<>(new IdAscendingComparator());
[Link](new Student(111, "Zuber", 12000.90));
[Link](new Student(444, "Satish", 15000.90));
[Link](new Student(222, "Rahul", 13000.90));
[Link](new Student(333, "Aniket",14000.90));

[Link]([Link]::println);

[Link](".....................");
TreeSet<Student> ts2 = new TreeSet<>(new IdDescendingComparator());
[Link](new Student(111, "Zuber", 12000.90));
[Link](new Student(444, "Satish", 15000.90));
[Link](new Student(222, "Rahul", 13000.90));
[Link](new Student(333, "Aniket",14000.90));

[Link]([Link]::println);

[Link](".....................");
TreeSet<Student> ts3 = new TreeSet<>(new NameAscendingComparator());
[Link](new Student(111, "Zuber", 12000.90));
[Link](new Student(444, "Satish", 15000.90));
[Link](new Student(222, "Rahul", 13000.90));
[Link](new Student(333, "Aniket",14000.90));

[Link]([Link]::println);

[Link](".....................");
TreeSet<Student> ts4 = new TreeSet<>(new NameDescendingComparator());
[Link](new Student(111, "Zuber", 12000.90));
[Link](new Student(444, "Satish", 15000.90));
[Link](new Student(222, "Rahul", 13000.90));
[Link](new Student(333, "Aniket",14000.90));

[Link]([Link]::println);
}

}
------------------------------------------------------------------------
HW :- Re-write the same program using Lambda
-----------------------------------------------------------------------
Methods of SortedSet interface :
--------------------------------
public E first() :- Will fetch first element

public E last() :- Will fetch last element

public SortedSet headSet(int range) :- Will fetch the values which are less than
specified range

public SortedSet tailSet(int range) :- Will fetch the values which are equal and
greater than the specified range.

public SortedSet subSet(int startRange, int endRange) :- Will fetch the range of
values where startRange is inclusive and endRange is exclusive

import [Link].*;
public class SortedSetMethodDemo
{
public static void main(String[] args)
{
TreeSet<Integer> times = new TreeSet<>();
[Link](1205);
[Link](1505);
[Link](1545);
[Link](1600);
[Link](1830);
[Link](2010);
[Link](2100);

SortedSet<Integer> sub = new TreeSet<>();

sub = [Link](1545,2100);
[Link]("Using subSet() :-"+sub);//[1545, 1600,1830,2010]
[Link]([Link]());
[Link]([Link]());

sub = [Link](1545);
[Link]("Using headSet() :-"+sub); //[1205, 1505]

sub = [Link](1545);
[Link]("Using tailSet() :-"+sub); //[1545 to 2100]
}
}
------------------------------------------------------------------------
NavigableSet(I) :
-----------------
With the help of SortedSet interface method we can find out the range of values but
we can't navigate among those elements.

Now to frequently navigate among those range of elements, Java software people
introduced new interface called NavigableSet from 1.6V
-------------------------------------------------------------
import [Link].*;

public class NavigableSetDemo


{
public static void main(String[] args)
{
NavigableSet<Integer> ns = new TreeSet<>();
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link](6);

[Link]("lower(3): " + [Link](3));//Just below than the


specified element or null

[Link]("floor(3): " + [Link](0)); //Equal or less or null

[Link]("higher(3): " + [Link](3));//Just greater than


specified element or null

[Link]("ceiling(3): " + [Link](3));//Equal or greater or


null

}
}
-----------------------------------------------------------------------
01-01-2024
-----------
Map interface :
---------------
As we know Collection interface is used to hold single Or individual object but Map
interface will hold group of objects in the form key and value pair.

Map interface is not the part the Collection.

Before Map interface We had Dictionary(abstract class) class and it is implemented


Hashtable class in JDK 1.0V

Map interface works with key and value pair introduced from 1.2V.

Here key and value both are objects.

Here key must be unique and value may be duplicate.

Each key and value pair is creating one Entry.(Entry is nothing but the combination
of key and value pair)

interface Map
{

interface Entry
{
}
}

How to represent this entry interface ([Link]) [Map$Entry]


----------------------------------------------------------------------
Map Hierarchy :
----------------
Available in the diagram [30-DEC-23]
---------------------------------------------------------------
Methods of Map interface :
--------------------------
1) Object put(Object key, Object value) :- To insert one entry in the Map
collection. It will return the old object value if the key is already
available(Duplicate key).

2) void putAll(Map m) :- Merging of two Map collection

3) int size() :- To count the pair of key and value or Entry

4) void clear() :- Used to clear the Map

5) boolean isEmpty() :- To verify Map is empty or not?

6) boolean containsKey(Object key) :- To Search a particular key

7) boolean containsValue(Object value) :- To Search a particular value

8) Object get(Object key) :- It will return corresponding value of key, if the key
is not present then it will return null.

9) Object getOrDefault(Object key, Object defaultValue) :- To avoid null value this


method has been introduced, here we can pass some defaultValue to avoid the null
value.

10) remove(Object key) :- One complete entry will be removed.

11) putIfAbsent(Object key, Object value) :- It will insert an entry if and only if
key is not present , if the key is already available then it will not insert the
Entry to the Map Collection

Collection views Methods :


------------------------------
public Set keySet() :- Will return only keys (Set of keys)

Collection values() :- Will return all values.

Set<[Link]> entrySet() :- It will return key and value pair in the form of
Entry.

a) getKey() b) getValue() c) setValue()


--------------------------------------------------------------------
IQ
--
How HashMap works internally :
------------------------------
a) While working with HashSet or HashMap every object must be compared because
duplicate objects are not allowed.

b) Whenever we add any new key to verify whether key is unique or duplicate,
HashMap internally uses hashCode(), == operator and equals method.

c) While adding the key object in the HashMap, first of all it will invoke the
hashCode() method to retrieve the corresponding key hashcode value.
Example :- [Link](key,value);
then internally [Link]();

d) If the newly added key and existing key hashCode value both are same (Hash
collision), then only == operator is used for comparing those keys by using
reference or memory address, if both keys references are same then existing key
value will be replaced with new key value.

If the reference of both keys are different then equals(Object obj) method
is invoked to compare those keys by using state(data).

If the equals(Object obj) method returns true (content wise both keys are
same), this new key is duplicate then existing key value will be replaced.

If equals(Object obj) method returns false, this new key is unique, new entry
(key-value) will be inserted.

Note :- equals(Object obj) method is invoked only when two keys are having
same hashcode as well as their references are different.

e) Actually by calling hashcode method we are not comparing the objects, we are
just storing the objects in a group so the currently adding key object will be
compared with its HASHCODE GROUP objects, but not with all the keys which are
available in the Map.

f) The main purpose of storing objects into the corresponding group to decrease the
number of comparison so the efficiency of the program will increase.

g) To insert an entry in the HashMap, HashMap internally uses Hashtable data


structure

h) Now, for storing same hashcode object into a single group, hash table data
structure internally uses one more data structure called Bucket.

i) The Hash table data structure internally uses Node class array object.

j) The bucket data structure internally uses LinkedList data structure, It is a


single linked list again implemented by Node class only.

k) A bucket is group of entries of same hash code keys.

l) Performance wise LinkedList is not good to serach, so from java 8 onwards


LinkedList is changed to Binary tree to decrease the number of comparison within
the same bucket hashcode if the number of entries are greater than 8.
-----------------------------------------------------------------------
* equals() and hashCode() method contract :
-----------------------------------------
Both the methods are working together to find out the duplicate objects in the Map.

*If equals() method invoked on two objects and it returns true then hashcode of
both the objects must be same.
-----------------------------------------------------------------
package [Link].abstract_ex;

import [Link];
import [Link];

public class HashMapInternals


{

public static void main(String[] args)


{
Map<String,String> map = new HashMap<>();
[Link]("Ravi","Ampt");
[Link](new String("Ravi"),"Hyd");
[Link](map);

Integer i1 = 128;
Integer i2 = 128;
[Link]([Link](i2));
[Link](i1==i2);

Map<Integer,String> map = new HashMap<>();


[Link](128,"Ampt");
[Link](new Integer(128),"Hyd");
[Link]([Link]());

}
----------------------------------------------------------------------
HashMap [Unsorted, Unordered, No Duplicate keys]
--------------------------------------------------
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,
Serializable, Clonable

It is a predefined class available in [Link] package under Map interface.

It gives us unsorted and Unordered map. when we need a map and we don't care about
the order while iterating the elements through it then we should use HashMap.

It inserts the element based on the hashCode of the Object key using hashing
technique [hasing alogorithhm]

It does not accept duplicate keys but value may be duplicate.

It accepts only one null key(because duplicate keys are not allowed) but multiple
null values are allowed.

HashMap is not synchronized.

Time complexcity of search, insert and delete will be O(1)

We should use HashMap to perform searching opeartion.

It contains 4 types of constructor

1) HashMap hm1 = new HashMap();


It will create the HashMap Object with default capacity is 16. The default load
fator or Fill Ratio is 0.75 (75% of HashMap is filled up then new HashMap Object
will be created having double capacity)

2) HashMap hm2 = new HashMap(int initialCapacity);


will create the HashMap object with specified capacity

3) HashMap hm3 = new HashMap(int initialCapacity, float loadFactor);


we can specify our own initialCapacity and loadFactor(by default load factor is
0.75%)
4)HashMap hm4 = new HashMap(Map m);
Interconversion of Map Collection

----------------------------------------------------------------------
import [Link].*;
class Employee
{
int eid;
String ename;

Employee(int eid, String ename)


{
[Link] = eid;
[Link] = ename;
}

@Override
public boolean equals(Object obj) //obj = e2
{
if(obj instanceof Employee)
{
Employee e2 = (Employee) obj; //downcasting

if([Link] == [Link] && [Link]([Link]))


{
return true;
}
else
{
return false;
}
}
else
{
[Link]("Comparison is not possible");
return false;
}
}

public String toString()


{
return " "+eid+" "+ename;
}
}
public class HashMapDemo8
{
public static void main(String[] args)
{
Employee e1 = new Employee(101,"Aryan");
Employee e2 = new Employee(102,"Pooja");
Employee e3 = new Employee(101,"Aryan");
Employee e4 = e2;

HashMap<Employee,String> hm = new HashMap<>();


[Link](e1,"Ameerpet");
[Link](e2,"S.R Nagar");
[Link](e3,"Begumpet");
[Link](e4,"Panjagutta");
[Link]((k,v)-> [Link](k+" : "+v));
}
}
----------------------------------------------------------------------
03-01-2024
----------
//Program that shows HashMap is unordered
import [Link].*;
public class HashMapDemo
{
public static void main(String[] a)
{
Map<String,String> map = new HashMap<>();
[Link]("Ravi", "12345"); //Ravi is key and 12345 is value
[Link]("Rahul", "12345");
[Link]("Aswin", "5678");
[Link](null, "6390");
[Link]("Ravi","1529");

[Link](map); //{}

[Link]([Link](null)); //6390
[Link]([Link]("Virat")); //null becoz key is not a

[Link]((k,v)-> [Link]("Key is :"+k+" value is


"+v));

}
}
-----------------------------------------------------------------------
//Program to search a particular key and value in the Map collection
import [Link].*;
public class HashMapDemo1
{
public static void main(String args[])
{
HashMap<Integer,String> hm = new HashMap<>();
[Link](1, "JSE");
[Link](2, "JEE");
[Link](3, "JME");
[Link](4,"JavaFX");
[Link](5,null);
[Link](6,null);

[Link]("Initial map elements: " + hm);


[Link]("key 2 is present or not :"+[Link](2));

[Link]("JME is present or not :"+[Link]("JME"));

[Link]("Size of Map : " + [Link]());


[Link]();
[Link]("Map elements after clear: " + hm);
}
}
-----------------------------------------------------------------------
//Collection view methods [keySet(), values(), entrySet()]
import [Link].*;
public class HashMapDemo2
{
public static void main(String args[])
{
Map<Integer,String> map = new HashMap<>();
[Link](1, "C");
[Link](2, "C++");
[Link](3, "Java");
[Link](4, ".net");

[Link]((k,v)->[Link]("Key :"+k+" Value :"+v) );

[Link]("Return Old Object


value :"+[Link](4,"Python"));

for([Link] m : [Link]())
{
[Link]([Link]()+" : "+[Link]());
}
}
}

-----------------------------------------------------------------------
//Program on remove(Object key) method
import [Link].*;
public class HashMapDemo3
{
public static void main(String args[])
{
HashMap<Integer,String> map = new HashMap<>(10,8.5f);
[Link](1, "Java");
[Link](2, "is");
[Link](3, "best");
[Link](3); //will remove the complete Entry
String val=(String)[Link](3);
[Link]("Value for key 3 is: " + val);
[Link]((k,v)->[Link](k +" : "+v));
}
}
----------------------------------------------------------------------
//To merge two Map Collection (putAll)
import [Link].*;
public class HashMapDemo4
{
public static void main(String args[])
{
HashMap<Integer,String> newmap1 = new HashMap<>();

HashMap<Integer,String> newmap2 = new HashMap<>();

[Link](1, "SCJP");
[Link](2, "is");
[Link](3, "best");

[Link]("Values in newmap1: "+ newmap1);

[Link](4, "Exam");

[Link](newmap1);
[Link]((k,v)->[Link](k+" : "+v));
}
}
----------------------------------------------------------------------
Collection views method :
-------------------------
import [Link].*;
public class HashMapDemo5
{
public static void main(String[] argv)
{
Map<String,String> map = new HashMap<>(9, 0.85f);
[Link]("key", "value");
[Link]("key2", "value2");
[Link]("key3", "value3");
[Link]("key7","value7");

Set keys = [Link]();//keySet return type is Set


[Link](keys ); //[]

Collection val = [Link](); //values return type is collection


[Link](val);

[Link]((k,v)-> [Link](k+" : "+v));

}
}
-----------------------------------------------------------------------
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class HashMapDemo


{
public static void main(String[] args)
{
HashMap<String,String> map = new HashMap<>();
[Link]("raj@[Link]", "raj_@#");
[Link]("ravi@[Link]", "ravi_@#");
[Link]("rahul@[Link]", "rahul_@#");

[Link]([Link]("ravi@[Link]"));
[Link]([Link]("ravi_@#"));

Set<String> setOfKeys = [Link]();


[Link](setOfKeys);

Collection<String> values = [Link]();


[Link](values);

for([Link]<String,String> entry : [Link]())


{
[Link]([Link]()+" : "+[Link]());
}
}

}
----------------------------------------------------------------------
//getOrDefault() method
import [Link].*;
public class HashMapDemo6
{
public static void main(String[] args)
{
Map<String, String> map = new HashMap<>();
[Link]("A", "1");
[Link]("B", "2");
[Link]("C", "3");
//if the key is not present, it will return default value .It is used to
avoid null
String value = [Link]("D","Key is not available");
[Link](value);
[Link](map);
}
}
----------------------------------------------------------------------
//interconversion of two HashMap
import [Link].*;
public class HashMapDemo7
{
public static void main(String args[])
{
HashMap<Integer, String> hm1 = new HashMap<>();

[Link](1, "Ravi");
[Link](2, "Rahul");
[Link](3, "Rajen");

HashMap<Integer, String> hm2 = new HashMap<>(hm1);

[Link]("Mapping of HashMap hm1 are : " + hm1);

[Link]("Mapping of HashMap hm2 are : " + hm2);


}
}
-----------------------------------------------------------------------
LinkedHashMap :
---------------
LinkedHashMap :
------------------
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

It is a predefined class available in [Link] package under Map interface.

It is the sub class of HashMap class.

It maintains insertion order. It contains a doubly linked with the elements or


nodes so It will iterate more slowly in comparison to HashMap.

It uses Hashtable and LinkedList data structure.

If We want to fetch the elements in the same order as they were inserted then we
should go with LinkedHashMap.
It accepts one null key and multiple null values.

It is not synchronized.

It has also 4 constructors same as HashMap

1) LinkedHashMap hm1 = new LinkedHashMap();


will create a LinkedHashMap with default capacity 16 and load factor 0.75

2) LinkedHashMap hm1 = new LinkedHashMap(iny initialCapacity);

3) LinkedHashMap hm1 = new LinkedHashMap(iny initialCapacity, float loadFactor);

4) LinkedHashMap hm1 = new LinkedHashMap(Map m);


-----------------------------------------------------------------------
import [Link].*;
public class LinkedHashMapDemo
{
public static void main(String[] args)
{
LinkedHashMap<Integer,String> l = new LinkedHashMap<>();
[Link](1,"abc");
[Link](3,"xyz");
[Link](2,"pqr");
[Link](4,"def");
[Link](null,"ghi");
[Link](l);
}
}
----------------------------------------------------------------------
import [Link];
import [Link];

public class LinkedHashMapDemo1


{
public static void main(String[] a)
{
Map<String,String> map = new LinkedHashMap<>();
[Link]("Ravi", "1234");
[Link]("Rahul", "1234");
[Link]("Aswin", "1456");
[Link]("Samir", "1239");

[Link]((k,v)->[Link](k+" : "+v));
}
}
-----------------------------------------------------------------------
Hashtable :
------------
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Clonable,
Serializable

It is predefined class available in [Link] package under Map interface.

Like Vector, Hashtable is also form the birth of java so called legacy class.

It is the sub class of Dictionary class which is an abstract class.


The major difference between HashMap and Hashtable is, HashMap methods are un-
synchronized where as Hastable methods are synchronized. HashMap can accept one
null key and multiple null values where as Hashtable does not contain anything as a
null(key and value both). if we try to add null value JVM will throw an exception
i.e NullPointerException.

The initial default capacity of Hashtable class is 11 where as loadFactor is 0.75.

It has also same constructor as we have in HashMap.(4 constructors)

1) Hashtable hs1 = new Hashtable();


It will create the Hashtable Object with default capacity as 11 as well as load
factor is 0.75

2) Hashtable hs2 = new Hashtable(int initialCapacity);


will create the Hashtable object with specified capacity

3) Hashtable hs3 = new Hashtable(int initialCapacity, float loadFactor);


we can specify our own initialCapacity and loadFactor

4) Hashtable hs = new Hashtable(Map c);


Interconversion of Map Collection
-----------------------------------------------------------------------
import [Link].*;
public class HashtableDemo
{
public static void main(String args[])
{
Hashtable<Integer,String> map=new Hashtable<>();
[Link](1, "Java");
[Link](2, "is");
[Link](3, "best");
[Link](4,"language");

//[Link](5,null);

[Link](map);

[Link](".......................");

for([Link] m : [Link]())
{
[Link]([Link]()+" = "+[Link]());
}
}
}
-----------------------------------------------------------------------
import [Link].*;
public class HashtableDemo1
{
public static void main(String args[])
{
Hashtable<Integer,String> map=new Hashtable<>();
[Link](1,"Priyanka");
[Link](2,"Ruby");
[Link](3,"Vibha");
[Link](4,"Kanchan");

[Link](5,"Bina");
[Link](24,"Pooja");
[Link](26,"Ankita");

[Link](1,"Sneha");
[Link]("Updated Map: "+map);
}
}
-----------------------------------------------------------------------
WeakHashMap :
-------------
public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>

It is a predefined class in [Link] package under Map [Link] was introduced


from JDK 1.2v onwards.

While working with HashMap, keys of HashMap are of strong reference type. This
means the entry of map will not be deleted by the garbage collector even though
the key is set to be null and still it is not eligible for Garbage Collector.

On the other hand while working with WeakHashMap, keys of WeakHashMap are of weak
reference type. This means the entry of a map is deleted by the garbage collector
if the key value is set to be null because it is of weak type.

So, HashMap dominates over Garbage Collector where as Garbage Collector dominates
over WeakHashMap.

It contains 4 types of Constructor :


---------------------------------------
1) WeakHashMap wm1 = new WeakHashMap();

Creates an empty WeakHashMap object with default capacity is 16 and load fator
0.75

2) WeakHashMap wm2 = new WeakHashMap(int initialCapacity);

3) WeakHashMap wm3 = new WeakHashMap(int initialCapacity, float loadFactor);

Eg:- WeakHashMap wm = new WeakHashMap(10,0.9);

capacity - The capacity of this map is 10. Meaning, it can store 10 entries.

loadFactor - The load factor of this map is 0.9. This means whenever our
hashtable is filled up by 90%, the entries are moved to a new hashtable of double
the size of the original hashtable.

4) WeakHashMap wm4 = new WeakHashMap(Map m);


-----------------------------------------------------------------------
import [Link].*;
public class WeakHashMapDemo
{
public static void main(String args[]) throws Exception
{
WeakHashMap<Test,String> map = new WeakHashMap<>();

Test t = new Test();


[Link](t," Rahul ");

[Link](map); //{Test Nit = Rahul}

t = null;

[Link](); //Explicitly calling garbage collector

[Link](5000);

[Link](map); //{}
}
}

class Test
{
@Override
public String toString()
{
return "Test Nit";
}

@Override
public void finalize() //called automaticaly if an object is eligible 4 GC
{
[Link]("finalize method is called");
}
}

If the corresponding object will be deleted from one end then the entry will be
deleted from map collection but map collection must be of WeakHashMap type.
-----------------------------------------------------------------------
04-01-2024
-----------
IdentityHashMap :
-----------------
public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,
Clonable, Serializable.

It was introduced from JDK 1.4 onwards.

The IdentityHashMap uses == operator to compare keys.

As we know HashMap uses equals() and hashCode() method for comparing the keys based
on the hashcode of the object it will serach the bucket location and insert the
entry their only.

So We should use IdentityHashMap where we need to check the reference or memory


address instead of logical equality.

HashMap uses hashCode of the "Object key" to find out the bucket loaction in
Hashtable, on the other hand IdentityHashMap does not use hashCode() method
actually It uses [Link](Object o)

IdentityHashMap is more faster than HashMap in case of Comparison.

It has three constrcutors, It does not contain loadFactor specific constructor.

-----------------------------------------------------------------------
import [Link].*;
public class IdentityHashMapDemo
{
public static void main(String[] args)
{
HashMap<String,Integer> hm = new HashMap<>();

IdentityHashMap<String,Integer> ihm = new IdentityHashMap<>();

[Link]("Ravi",23);
[Link](new String("Ravi"), 24);

[Link]("Ravi",23);
[Link](new String("Ravi"), 27); //compares based on == operator

[Link]("HashMap size :"+[Link]()); //1


[Link](hm);
[Link]("........................");
[Link]("IdentityHashMap size :"+[Link]()); //2
[Link](ihm);

}
-----------------------------------------------------------------------
SortedMap(I)
---------------
It is a predefined interface available in [Link] package under Map interface.

We should use SortedMap interface when we want to insert the key element based on
some sorting order i.e the default natural sorting order.
------------------------------------------------------------------
TreeMap :
----------
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V> ,
Clonable, Serializable

It is a predefined class avaialble in [Link] package under Map interface.

It is a sorted map that means it will sort the elements by natural sorting order
based on the key using Comparator interface.

It will accept homogeneous keys (comparable keys as an Object) only because it will
sort the entry of TreeMap based on the key.

It does not accept null key but null value allowed.

TreeMap implements NavigableMap and NavigableMap extends SortedMap. SortedMap


extends Map interface.

TreeMap contains 4 types of Constructors :

1) TreeMap tm1 = new TreeMap(); //creates an empty TreeMap

2) TreeMap tm2 = new TreeMap(Comparator cmp); //user defined soting logic

3) TreeMap tm3 = new TreeMap(Map m);

4) TreeMap tm4 = new TreeMap(SortedMap m);


----------------------------------------------------------------------
import [Link].*;
public class TreeMapDemo
{
public static void main(String[] args)
{
TreeMap t = new TreeMap();
[Link](4,"Ravi");
[Link](7,"Aswin");
[Link](2,"Ananya");
[Link](1,"Dinesh");
[Link](9,"Ravi");
[Link](3,"Ankita");
[Link](5,null);

[Link](t);
}
}
----------------------------------------------------------------------
import [Link].*;
public class TreeMapDemo1
{
public static void main(String args[])
{
TreeMap map = new TreeMap();
[Link]("one","1");
[Link]("two",null);
[Link]("three","3");
[Link]("four",4);

displayMap(map);

[Link]((k, v) -> [Link]("Key = " + k + ", Value = " + v));

}
static void displayMap(TreeMap map)
{
Collection c = [Link](); //Set<[Link]>

Iterator i = [Link]();
[Link](x -> [Link](x));
}
}
----------------------------------------------------------------------
//firstKey() lastKey() headMap() tailMap() subMap()

import [Link].*;
public class TreeMapDemo2
{
public static void main(String[] argv)
{
Map map = new TreeMap();
[Link]("key2", "value2");
[Link]("key3", "value3");
[Link]("key1", "value1");

[Link](map);

SortedMap x = (SortedMap) map;


[Link]("First key is :"+[Link]());
[Link]("Last Key is :"+[Link]());
}
}
----------------------------------------------------------------------
Customized sorting order using Comaparator as a constructor parameter

2 Files :
---------
[Link]
-------------
package [Link].tree_map_customized;

public class Student


{
private Integer studentId;
private String studentName;
private Integer studentAge;
public Student(Integer studentId, String studentName, Integer studentAge) {
super();
[Link] = studentId;
[Link] = studentName;
[Link] = studentAge;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
[Link] = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
[Link] = studentName;
}
public Integer getStudentAge() {
return studentAge;
}
public void setStudentAge(Integer studentAge) {
[Link] = studentAge;
}
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentAge=" + studentAge + "]";
}

[Link]
-----------------------
package [Link].tree_map_customized;

import [Link];

public class TreeMapCustomized {


public static void main(String[] args)
{
TreeMap<Student,String> tm1 = new TreeMap<>((s1,s2)->
[Link]()- [Link]());
[Link](new Student(222,"Ankit",24), "S R Nagar");
[Link](new Student(111,"Zuber",26), "Koti");
[Link](new Student(333,"Rahul",25), "Ameerpet");
[Link]("Sorting based on the ID");
[Link]((k,v)-> [Link](k+" :"+v));

TreeMap<Student,String> tm2 = new TreeMap<>((s1,s2)->


[Link]().compareTo([Link]()));
[Link](new Student(222,"Ankit",24), "S R Nagar");
[Link](new Student(111,"Zuber",26), "Koti");
[Link](new Student(333,"Rahul",25), "Ameerpet");
[Link]("Sorting based on the Name");
[Link]((k,v)-> [Link](k+" :"+v));

TreeMap<Student,String> tm3 = new TreeMap<>((s1,s2)->


[Link]() - [Link]());
[Link](new Student(222,"Ankit",24), "S R Nagar");
[Link](new Student(111,"Zuber",16), "Koti");
[Link](new Student(333,"Rahul",32), "Ameerpet");
[Link]("Sorting based on the Age");
[Link]((k,v)-> [Link](k+" :"+v));

}
----------------------------------------------------------------------
package [Link].treemap_comparator;

import [Link];

public class TreeMapDescending


{
public static void main(String[] args)
{
TreeMap<Integer,String> map=new TreeMap<>((i1,i2)-> -(i1-i2));
[Link](100,"Amit");
[Link](101,"Ravi");
[Link](102,"Vijay");
[Link](103,"Rahul");

[Link]((k,v)-> [Link](k+" : "+v));


}

----------------------------------------------------------------------
Methods of SortedMap interface :
--------------------------------
1) firstKey() //first key

2) lastKey() //last key

3) headMap(int keyRange) //less than the specified range


4) tailMap(int keyRange) //equal to or greater than the specified range

5) subMap(int startKeyRange, int endKeyRange) //the range of key where startKey


will be inclusive and endKey will be exclusive.

return type of headMap(), tailMap() and subMap() would be SortedMap(I)


----------------------------------------------------------------
import [Link].*;
public class SortedMapMethodDemo
{
public static void main(String args[])
{
SortedMap<Integer,String> map=new TreeMap<>();
[Link](100,"Amit");
[Link](101,"Ravi");
[Link](102,"Vijay");
[Link](103,"Rahul");

[Link]("First Key: "+[Link]()); //100


[Link]("Last Key "+[Link]()); //103
[Link]("headMap: "+[Link](102)); //100 101
[Link]("tailMap: "+[Link](102)); //102 103
[Link]("subMap: "+[Link](100, 102)); //100 101

}
}
----------------------------------------------------------------------
NavigableMap method (H.W)
---------------------------
Properties :
------------
Properties class:
-----------------
Properties class is used to maintain the data in the key-value form. It takes both
key and value as a string. Properties class is a subclass of Hashtable and avilable
in [Link] package.

It provides the methods to store properties in a properties file and to get the
properties from the properties file. [Link]() returns the all system
properties.

Here we need to create a file with with extension .properties

[Link]
-------------
driver = [Link]
user = system
password = tiger

import [Link].*;
import [Link].*;
public class PropertiesExample1
{
public static void main(String[] args)throws Exception
{
FileReader reader=new FileReader("[Link]");

Properties p=new Properties();


[Link](reader);
[Link]([Link]("user"));
[Link]([Link]("password"));
[Link]([Link]("driver"));
}
}

Properties class provides a method called getProperty() where we will pass the key
of properties file and it will return the corresponding key value from that key.

Here after making changes in the property file we need not to re-compile the source
code as shown in the above program.
----------------------------------------------------------------------
import [Link].*;
import [Link].*;
public class PropertiesExample2
{
public static void main(String[] args)throws Exception
{
Properties p=[Link]();
Set set=[Link]();

Iterator itr=[Link]();
while([Link]())
{
[Link] entry=([Link])[Link]();
[Link]([Link]()+" = "+[Link]());
}

} }

By using getProperties() static method of System class we can get the complete
properties of the System
----------------------------------------------------------------------*Generics :
-----------
Why generic came into picture :
------------------------------------
As we know our compiler is known for Strict type checking because java is a
statically typed checked language.

The basic problem with collection is It can hold any kind of Object.

ArrayList al = new ArrayList();


[Link]("Ravi");
[Link]("Aswin");
[Link]("Rahul");
[Link]("Raj");
[Link]("Samir");

for(int i =0; i<[Link](); i++)


{
String s = (String) [Link](i);
[Link](s);
}

By looking the above code it is clear that Collection stores everything in the form
of Object so here even after adding String type only we need type casting as shown
below.
import [Link].*;
class Test1
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
[Link](12);
[Link](15);
[Link](18);
[Link](22);
[Link](24);

for (int i=0; i<[Link](); i++)


{
Integer x =(Integer) [Link](i);
[Link](x);
}

Even after type casting there is no guarantee that the things which are coming from
ArrayList Object is Integer only because we can add anything in the Collection as a
result [Link] as shown in the program below.
----------------------------------------------------------------------
import [Link].*;
class Test2
{
public static void main(String[] args)
{
ArrayList t = new ArrayList(); //raw type
[Link]("alpha");
[Link]("beta");
for (int i = 0; i < [Link](); i++)
{
String str =(String) [Link](i);
[Link](str);
}

[Link](1234);
[Link](1256);
for (int i = 0; i < [Link](); ++i)
{
String obj= (String)[Link](i); //we can't perform type casting
here
[Link](obj);
}
}
}
----------------------------------------------------------------------
To avoid all the above said problem Generics came into picture from JDK 1.5 onwards

-> It deals with type safe Object so there is a gurantee of both the end i.e
putting inside and getting out.

Example:-
ArrayList<String > al = new ArrayList<>();
Now here we have a gurantee that only String can be inserted as well as only
String will come out from the Collection so we can perform String related
operation.

Advantages :-
---------------
a) Type safe Object (No compilation warning)

b) Strict compile time checking (Type erasure)

c) No need of type casting

24-01-2024
----------
import [Link].*;
public class Test3
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<>(); //Generic type
[Link]("Ravi");
[Link]("Ajay");
[Link]("Vijay");

for(int i=0; i<[Link](); i++)


{
String name = [Link](i); //no type casting is required
[Link]([Link]());
}
}
}
------------------------------------------------------------------------
//Program that describes the return type of any method can be type safe
//[We can apply generics on method return type]

import [Link].*;
public class Test4
{
public static void main(String [] args)
{
Dog d1 = new Dog();
Dog d2 = [Link]().get(2);
[Link](d2);
}
}
class Dog
{
public List<Dog> getDogList()
{
ArrayList<Dog> d = new ArrayList<>();
[Link](new Dog());
[Link](new Dog());
[Link](new Dog());
return d;
}
}
Note :- In the above program the compiler will stop us from returning anything
which is not compaitable List<Dog> and there is a gurantee that only "type safe
list of Dog object" will be returned so we need not to provide type casting as
shown below
Dog d2 = (Dog) [Link]().get(0); //before generic.
-----------------------------------------------------------------
//Mixing generic with non-generic
import [Link].*;

class Car
{
}
public class Test5
{
public static void main(String [] args)
{
ArrayList<Car> a = new ArrayList<>();
[Link](new Car());
[Link](new Car());
[Link](new Car());

ArrayList b = a; //assigning Generic to raw type

[Link](b);
}
}
------------------------------------------------------------------------
//Mixing generic to non-generic
import [Link].*;
public class Test6
{
public static void main(String[] args)
{
List<Integer> myList = new ArrayList<>();
[Link](4);
[Link](6);
[Link](5);

UnknownClass u = new UnknownClass();


int total = [Link](myList);
[Link]("The sum of Integer Object is :"+total);
}
}
class UnknownClass
{
public int addValues(List list) //safe Object to unsafe object OR generic to
raw type
{
Iterator it = [Link]();
int total = 0;
while ([Link]())
{
int i = ((Integer)[Link]());
total += i; //total = 15
}
return total;
}
}
Note :-
In the above program the compiler will not generate any warning message because
even though we are assigning type safe Integer Object to unsafe or raw type List
Object but this List Object is not inserting anything new in the collection so
there is no risk to the caller.
------------------------------------------------------------------------
//Mixing generic to non-generic
import [Link].*;
public class Test7
{
public static void main(String[] args)
{
List<Integer> myList = new ArrayList<>();

[Link](4);
[Link](6);
UnknownClass u = new UnknownClass();
int total = [Link](myList);
[Link](total);
}
}
class UnknownClass
{
public int addValues(List list)
{
[Link](5); //adding object to raw type
Iterator it = [Link]();
int total = 0;
while ([Link]())
{
int i = ((Integer)[Link]());
total += i;
}
return total;
}
}

Here Compiler will generate warning message because the unsafe object is inserting
the value 5 to safe object.
------------------------------------------------------------------------
*Type Erasure
------------
In the above program the compiler will generate warning message because the
unsafe List Object is inserting the Integer object 5 so the type safe Integer
object is getting value 5 from unsafe type so there is a problem to the caller
method.

By writing ArrayList<Integer> actually JVM does not have any idea that our
ArrayList was suppose to hold only Integers.

All the type safe information does not exist at runtime. All our generic code is
Strictly for compiler. There is a process done by java compiler called "Type
erasure" in which the java compiler converts generic version to non-generic type.

List<Integer> myList = new ArrayList<Integer>();

At the compilation time it is fine but at runtime for JVM the code becomes

List myList = new ArrayList();


Note :- GENERIC IS STRICTLY A COMPILE TIME PROTECTION.
------------------------------------------------------------------------
Behavior of Polymorphism with Array and Generics :
--------------------------------------------------
//Polymorphism with array

import [Link].*;
abstract class Animal
{
public abstract void checkup();
}

class Dog extends Animal


{
@Override
public void checkup()
{
[Link]("Dog checkup");
}
}

class Cat extends Animal


{
@Override
public void checkup()
{
[Link]("Cat checkup");
}
}

class Bird extends Animal


{
@Override
public void checkup()
{
[Link]("Bird checkup");
}
}

public class Test8


{
public void checkAnimals(Animal animals[])
{
for(Animal animal : animals)
{
[Link]();
}
}

public static void main(String[] args)


{
Dog []dogs={new Dog(), new Dog()};

Cat []cats={new Cat(), new Cat(), new Cat()};

Bird []birds = {new Bird(), new Bird()};

Test8 t = new Test8();


[Link](dogs);
[Link](cats);
[Link](birds);
}
}

Note :-From the above program it is clear that polymorphism(Upcasting) concept


works with array.
-----------------------------------------------------------------
import [Link].*;
abstract class Animal
{
public abstract void checkup();
}

class Dog extends Animal


{
@Override
public void checkup()
{
[Link]("Dog checkup");
}
}

class Cat extends Animal


{
@Override
public void checkup()
{
[Link]("Cat checkup");
}
}
class Bird extends Animal
{
@Override
public void checkup()
{
[Link]("Bird checkup");
}
}
public class Test9
{
public void checkAnimals(List<Animal> animals)
{
for(Animal animal : animals)
{
[Link]();
}
}
public static void main(String[] args)
{
List<Dog> dogs = new ArrayList<>();
[Link](new Dog());
[Link](new Dog());

List<Cat> cats = new ArrayList<>();


[Link](new Cat());
[Link](new Cat());
List<Bird> birds = new ArrayList<>();
[Link](new Bird());

Test9 t = new Test9();


[Link](dogs);
[Link](cats);
[Link](birds);

}
}

Note :- The above program will generate the compilation error.

So from the above program it is clear that polymorphism does not work in the same
way for generics as it does with arrays.

Eg:-

Parent [] arr = new Child[5]; //valid


Object [] arr = new String[5]; //valid

But in generics the same type is not valid

List<Object> list = new ArrayList<Integer>(); //Invalid


List<Parent> mylist = new ArrayList<Child>(); //Invalid
-----------------------------------------------------------------
import [Link].*;
public class Test10
{
public static void main(String [] args)
{
//ArrayList<Number> al = new ArrayList<Integer>(); [Compile time]
//ArrayList al = new ArrayList(); [Runtime]
//[Link]("Ravi");

Object []obj = new String[3]; //valid with Array


obj[0] = "Ravi";
obj[1] = "hyd";
obj[2] = 12; //[Link]
}
}

Note :- It will generate [Link] because we are trying to


insert 12 (integer value) into String array.

In Array we have an Exception called ArrayStoreException but the same Exception or


such type of exception, is not available with Generics that is the reason in
generics compiler does not allow upcasting concept.
(It is a strict compile time checking)
------------------------------------------------------------------------
import [Link].*;
class Parent
{
}
class Child extends Parent
{
}
public class Test11
{
public static void main(String [] args)
{
ArrayList<Parent> lp = new ArrayList<Child>(); //error

ArrayList<Parent> lp1 = new ArrayList<Parent>();

ArrayList<Child> lp2 = new ArrayList<>();

[Link]("Success");
}
}
------------------------------------------------------------------------
Wild card character(?) :
------------------------
<?> -: Many possibilities

<Animal>-: Only <Animal> can assign, but not Dog or sub type of animal

<? super Dog> -: Dog, Animal, Object can assign (Compiler has
surity)

<? extends Animal> -: Below of Animal(Child of Animal) means, sub classes of Animal
(But the compiler does not have surity because you can have many sub classes of
Animal in the future, so chances of wrong collections)
------------------------------------------------------------------------
//program on wild-card chracter
import [Link].*;
class Parent
{

}
class Child extends Parent
{
}
public class Test12
{
public static void main(String [] args)
{
List<?> lp = new ArrayList<Parent>();
[Link]("Wild card....");
}
}
------------------------------------------------------------------------
import [Link].*;
public class Test13
{
public static void main(String[] args)
{
List<? extends Number> list1 = new ArrayList<Double>();

List<? super Integer> list2 = new ArrayList<Object>();

List<? super Beta> list3 = new ArrayList<Alpha>();

List list4 = new ArrayList();


[Link]("yes");
}
}

class Alpha
{
}
class Beta extends Alpha
{
}
-------------------------------------------------------------------------
import [Link].*;
public class Test14
{
public static void main(String[] args)
{
try
{
List<Object> x = new ArrayList<>(); //Array of Object[java 9]
[Link](10);
[Link]("Ravi");
[Link](true);
[Link](34.89);
[Link](x);
}
catch (Exception e)
{
[Link](e);
}
}
}
------------------------------------------------------------------------
class MyClass<T>
{
T obj;
public MyClass(T obj) //Student obj
{
[Link]=obj;
}

T getObj()
{
return obj;
}
}
public class Test15
{
public static void main(String[] args)
{
Integer i=12;
MyClass<Integer> mi = new MyClass<Integer>(i);
[Link]("Integer object stored :"+[Link]());

Float f=12.34f;
MyClass<Float> mf = new MyClass<Float>(f);
[Link]("Float object stored :"+[Link]());

MyClass<String> ms = new MyClass<String>("Rahul");


[Link]("String object stored :"+[Link]());
MyClass<Boolean> mb = new MyClass<Boolean>(false);
[Link]("Boolean object stored :"+[Link]());

Double d=99.34;
MyClass<Double> md = new MyClass<Double>(d);
[Link]("Double object stored :"+[Link]());

MyClass<Student> mStd = new MyClass<Student>(new Student());


[Link]("Student Object Stored :"+[Link]());
}
}

class Student
{
@Override
public String toString()
{
return "Student toString";
}
}
-----------------------------------------------------------------------
25-01-2024
----------
//E stands for Element type
class Fruit
{
}
class Apple extends Fruit //Fruit is the super, Apple is sub class
{
}

class Basket<E> //E is of type Fruit


{
private E element;
public void setElement(E element) //Fruit element = new Apple();
{
[Link] = element;
}

public E getElement() //public Fruit getElement(){}


{
return [Link];
}
}

public class Test16


{
public static void main(String[] args)
{
Basket<Fruit> b = new Basket<Fruit>();
[Link](new Apple());
Apple x = (Apple)[Link]();
[Link](x);

Basket<Fruit> b1 = new Basket<Fruit>();


[Link](new Mango());
Mango y = (Mango)[Link]();
[Link](y);

}
}
class Mango extends Fruit
{
}
----------------------------------------------------------------------
Queue interface :-
-------------------
1) It is sub interface of Collection(I)

2) It works in FIFO(First In first out)

3) It is an ordered collection.

4) In a queue, insertion is possible from last is called REAR where as deletion is


possible from the starting is called FRONT of the queue.

5) From jdk 1.5 onwards LinkedList class implments Queue interface to handle the
basic queue operations.

PriorityQueue :
----------------
public class PriorityQueue extends AbstractQueue implements Serializable

It is a predefined class in [Link] package, available from Jdk 1.5 onwards.

It inserts the elements based on the priority HEAP (Using Binary tree).

The elements of the priority queue are ordered according to their natural ordering,
or by a Comparator provided at queue construction time, depending on which
constructor is used.

A priority queue does not permit null elements as well as It uses Binary tree to
insert the elements.

It provides natural sorting order so we can't take non-comparable


objects(hetrogeneous types of Object)

The initial capacity of PriorityQueue is 11.

Constructor :
--------------
1) PriorityQueue pq1 = new PriorityQueue();

2) PriorityQueue pq2 = new PriorityQueue(int initialCapacity);

3) PriorityQueue pq3 = new PriorityQueue(int initialCapacity, Comparator cmp);

4) PriorityQueue pq4 = new PriorityQueue(Collection c);

Methods :-
----------
add() / offer() :- Used to add an element in the Queue

poll() :- It is used to fetch the elements from top of the queue, after fetching it
will delete the element.
peek() :- It is also used to fetch the elements from top of the queue, Unlike poll
it will only fetch but not delete the element.

boolean remove(Object element) :- It is used to remove an element. The return type


is boolean.

import [Link];
public class PriorityQueueDemo3
{
public static void main(String[] argv)
{
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](11);
[Link](2);
[Link](4);
[Link](6);
[Link](pq);
}
}
-----------------------------------------------------------------------
import [Link];
public class PriorityQueueDemo1
{
public static void main(String[] argv)
{
PriorityQueue<String> pq = new PriorityQueue<>();
[Link]("9");
[Link]("8");
[Link]("7");
[Link]([Link]() + " "); //7 3 5 6
[Link]("6"); // 6 7 8 9
[Link]("5");
[Link]("3");

[Link]("1");
[Link]([Link]() + " ");
if ([Link]("2"))
[Link]([Link]() + " ");
[Link]([Link]() + " " + [Link]());
[Link](pq);
}
}
-----------------------------------------------------------------------import
[Link];
public class PriorityQueueDemo2
{
public static void main(String[] argv)
{
PriorityQueue<String> pq = new PriorityQueue<>();
[Link]("2");
[Link]("4");
[Link]("6"); // 6 9
[Link]([Link]() + " "); //2 2 3 4 4
[Link]("1");
[Link]("9");
[Link]("3");

[Link]("1");
[Link]([Link]() + " ");
if ([Link]("2"))
[Link]([Link]() + " ");
[Link]([Link]() + " " + [Link]()+" "+[Link]());
}
}
-----------------------------------------------------------------------
import [Link];

public class PriorityQueueDemo


{
public static void main(String[] argv)
{
PriorityQueue<String> pq = new PriorityQueue<>();
[Link]("Orange");
[Link]("Apple");
[Link]("Mango");
[Link]("Guava");
[Link]("Grapes");

[Link](pq);

}
}

Note :- The insertion of the elemenmts is based on Binary tree.


----------------------------------------------------------------------
*Stream API :
------------
Streams in java :
------------------
It is introduced from Java 8 onwards, the Stream API is used to process the
collection objects.

It contains classes for processing sequence of elements over Collection object and
array.

Stream is a predefined interface available in [Link] sub package

Package Information :
---------------------
[Link] -> Base package
[Link] -> Functional interfaces
[Link] -> Multithreaded support
[Link] -> Processing of Collection Object

forEach() method in java :


-----------------------------
The Java forEach() method is a technique to iterate over a collection such as
(list, set or map) and stream. It is used to perform a given action on each of the
element of the collection.

The forEach() method has been added in following places:

Iterable interface This makes [Link]() method available to all


collection classes. Iterable interface is the super interface of Collection
interface

Map interface This makes forEach() operation available to all map classes.
Stream interface This makes forEach() operations available to all types of
stream.
----------------------------------------------------------------------
Creation of Streams to process the data :
-----------------------------------------------
We can create Stream from collection or array with the help of stream() and of()
methods:

A stream() method is added to the Collection interface and allows creating a


Stream<T> using any collection object as a source

public [Link]<E> stream();

The return type of this method is Stream interafce available in [Link]


sub package.

Eg:-
List<String> items = new ArrayList<String>();
[Link]("Apple");
[Link]("Orange");
[Link]("Mango");
Stream<String> stream = [Link]();
-----------------------------------------------------------------------
import [Link].*; //Base package
import [Link].*; //Sub package
public class StreamDemo1
{
public static void main(String[] args)
{
List<String> items = new ArrayList<String>();

[Link]("Apple");
[Link]("Orange");
[Link]("Mango");

//Collections Object to Stream


Stream<String> strm = [Link]();
[Link](p -> [Link](p));
}
}
-----------------------------------------------------------------------
[Link]()
--------------
public static [Link] of(<T>)
-----------------------------------------------------
It is a static method of Stream interface through which we can create Stream of
arrays and Collection. The return type of this method is Stream interface
--------------------------------------------------------------
//[Link]()
import [Link].*;
public class StreamDemo2
{
public static void main(String[] args)
{
Stream<Integer> stream = [Link](1,2,3,4,5,6,7,8,9);
[Link](p -> [Link](p));

[Link]("...............................");
//Anonymous Array Object
Stream<Integer> strm = [Link]( new Integer[]{15,29,45,8,16} );
[Link](p -> [Link](p));
}
}
-----------------------------------------------------------------------
26-01-2024
-----------
Operation in Stream API :
-------------------------
In Java, the Stream API provides a wide range of operations that can be performed
on a stream of elements.

These operations can be categorized into two main types: intermediate operations
and terminal operations.

Intermediate Operations:
------------------------
filter(Predicate<T> predicate): Returns a new stream which contains filtered
elements based on the boolean expression using Predicate.

map(Function<T, R> mapper): Transforms elements in the stream using the provided
mapping function.

flatMap(Function<T, Stream<R>> mapper): Flattens a stream of streams into a single


stream.

distinct(): Returns a stream with distinct elements (based on their equals method).

sorted(): Returns a stream with elements sorted in their natural order.

sorted(Comparator<T> comparator): Returns a stream with elements sorted using the


specified comparator.

peek(Consumer<T> action): Allows us to perform an action on each element in the


stream without modifying the stream.

limit(long maxSize): Limits the number of elements in the stream to a specified


maximum size.

skip(long n): Skips the first n elements in the stream.

takeWhile(Predicate<T> predicate): Returns a stream of elements from the beginning


until the first element that does not satisfy the predicate.

dropWhile(Predicate<T> predicate): Returns a stream of elements after skipping


elements at the beginning that satisfy the predicate.

Working with Intermediate operations :


--------------------------------------
public abstract Stream<T> filter(Predicate p) :
----------------------------------------------------
It is a predfined method of Stream interface. It is used to select/filter elements
as per the Predicate passed as an argument. It is basically used to filter the
elements based on boolean condition.

public abstract <T> collect([Link] c)


----------------------------------------------------------------
It is a predfined method of Stream interface. It is used to return the result of
the intermediate operations performed on the stream. It is used to collect the data
after filteration and convert the data to the Collection.

Collectors is a predfined final class available in [Link] sub package


which conatins a static method toList() and toSet() to convert the data as a
List/Set i.e Collection object. The return type of this method is List/Set
interface.
-------------------------------------------------------------------------
//Filter all the even numbers from Collection
package [Link];
import [Link].*;
import [Link].*;
public class StreamDemo3
{
public static void main(String[] args)
{
List<Integer> list = [Link](1,2,3,4,5,6,7,8,9,10,3, 10);

//Without Stream
List<Integer> listEven = new ArrayList<Integer>();

for(Integer i : list)
{
if(i%2==0)
[Link](i);
}
[Link](listEven);
[Link](".........................................");

//With Stream which prints only even numbers


List<Integer> even = [Link]().filter(i -> i%2 ==
0).collect([Link]());
[Link](even);

//With Stream which prints only odd numbers


Set<Integer> odd = [Link]().filter(i -> i
%2==1).collect([Link]());
[Link](odd);
}
}
-------------------------------------------------------------------------
//Filtering the name
package [Link];
import [Link].*;
import [Link].*;
public class StreamDemo4
{
public static void main(String[] args)
{
List<String> list = [Link]("Ravi", "Rahul", "Akshar",
"Roshan","Raj","Ankit");

//Filter all the name which starts from R


List<String> collect = [Link]().filter(str ->
[Link]("A")).collect([Link]());
[Link](collect);
}
}
-------------------------------------------------------------------------
public Stream sorted(Comparator cmp) :
---------------------------------------------
It is a predfined method of Stream interface which is used to sort the data using
comparator interface.
----------------------------------------------------------------
//Sorting the data
package [Link];
import [Link].*;
import [Link].*;
public class StreamDemo5
{
public static void main(String[] args)
{
List<String> names = [Link]("Zaheer","Rahul","Aryan","Sailesh");

List<String> sortedName =
[Link]().sorted().collect([Link]());

[Link](str -> [Link](str));


}
}
-------------------------------------------------------------------------
package [Link];
import [Link].*;
class Customer
{
int id;
String name;
float bill;

public Customer(int id, String name, float bill)


{
[Link] = id;
[Link] = name;
[Link] = bill;
}
}
public class StreamDemo6
{
public static void main(String[] args)
{
List<Customer> customersList = new ArrayList<>();

[Link](new Customer(1,"Aryan",25000f));
[Link](new Customer(2,"Ravi",30000f));
[Link](new Customer(3,"Sailesh",28000f));
[Link](new Customer(4,"Rohan",28000f));
[Link](new Customer(5,"Raj",90000f));

// filtering data
[Link]()
.filter(Customer -> [Link] < 27000)
.forEach(Customer ->
[Link]([Link]));
}
}

Assignment : Create and Store the Product object and by using java 8 Stream API
filter the Product data based on the price where price of the Product must be
greater than 50K.
-------------------------------------------------------------------------
public Stream map(Function<T,R> mapper) :
-------------------------------------------------
It is a predefined method of Stream interface.

It takes Function (Predefined functional interafce ) as a parameter.

It performs intermediate operation and consumes single element from input Stream
and produces single element to output Stream.

Here mapper function is functional interface which takes one input and provides one
output.

//Find even numbers in stream and collect the cubes


package [Link];
import [Link];
import [Link];
import [Link];

public class StreamDemo7


{
public static void main(String[] args)
{
List<Integer> list = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

List<Integer> cubeOfNumbers = [Link]()


.filter(n -> n % 2 == 0)
.map(n -> n * n * n)
.collect([Link]());

[Link](cubeOfNumbers);
}
}
-------------------------------------------------------------------------
//Program on map(Function<T,R> mapped)
package [Link];
import [Link].*;
import [Link].*;
public class StreamDemo8
{
public static void main(String args[])
{
List<Player> listOfPlayers = createMyPlayerList();

// Using map function to convert Stream<Player> to Stream<String>


Set<String> listOfPlayerNames = [Link]()
.map(p -> [Link]())
.collect([Link]
t());
[Link]([Link]::println);
}

public static List<Player> createMyPlayerList()


{
List<Player> listOfPlayers=new ArrayList<>();
Player p1= new Player("Rohit",29);
Player p2= new Player("Virat",30);
Player p3= new Player("K L Rahul",27);
Player p4= new Player("Dhoni",34);
Player p5= new Player("Sachin",37);
Player p6= new Player("Rohit",37);
Player p7= new Player("Virat",30);
[Link](p1);
[Link](p2);
[Link](p3);
[Link](p4);
[Link](p5);
[Link](p6);
[Link](p7);
return listOfPlayers;
}
}

class Player
{
private String name;
private int age;

public Player(String name, int age)


{
super();
[Link] = name;
[Link] = age;
}

public String getName() {


return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
[Link] = age;
}
}
-------------------------------------------------------------------------
public Stream flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
---------------------------------------------------------
It is a predefined method of Stream interface.

The map() method produces one output value for each input value in the stream. So
if there are n elements in the stream, map() operation will produce a stream of n
output elements.

flatMap() is two step process i.e. map() + Flattening. It helps in converting


Collection<Collection<T>> to Collection<T> [to make flat i.e converting Collections
of collection into single collection or merging of all the collection]

//flatMap()
//map + Flattening [Converting Collections of collection into single collection]

//flatMap()
//map + Flattening [Converting Collections of collection into single collection]
package [Link];
import [Link].*;
import [Link].*;
public class StreamDemo9
{
public static void main(String[] args)
{
List<String> list1 = [Link]("A","B","C");
List<String> list2 = [Link]("D","E","F");
List<String> list3 = [Link]("G","H","I");

List<List<String>> listOfLists = [Link](list1, list2, list3);

List<String> listOfAllStrings = [Link]().flatMap(x ->


[Link]()).collect([Link]());

[Link](listOfAllStrings);
}
}
-------------------------------------------------------------------------
27-01-2024
-----------

//Flattening of prime, even and odd number


package [Link].flat_map;

import [Link];
import [Link];
import [Link];

public class FlatMapDemo1


{
public static void main(String[] args)
{
List<Integer> primeNumbers = [Link](5,7,11);
List<Integer> evenNumbers = [Link](2,4,6);
List<Integer> oddNumbers = [Link](1,3,5);

List<List<Integer>> numbers =
[Link](primeNumbers,evenNumbers,oddNumbers);

List<Integer> collect = [Link]().flatMap(num ->


[Link]()).collect([Link]());

[Link](collect);

}
}
-------------------------------------------------------------------------
//Fetching first character using flatMap()
package [Link].flat_map;

import [Link];
import [Link];
import [Link];
import [Link];

public class FlatMapDemo2


{
public static void main(String[] args)
{
List<String> asList = [Link]("Jyoti","Ankit","Vaibhab","Aman");

List<Character> collect = [Link]().flatMap(str ->


[Link]([Link](0))).collect([Link]());
[Link](collect);

}
-------------------------------------------------------------------------
package [Link].flat_map;

import [Link];
import [Link];

class Product
{
private Integer productId;
private List<String> listOfProducts;

public Product(Integer productId, List<String> listOfProducts) {


super();
[Link] = productId;
[Link] = listOfProducts;
}

public Integer getProductId() {


return productId;
}

public List<String> getListOfProducts() {


return listOfProducts;
}
}

public class FlatMapDemo3


{
public static void main(String[] args)
{
List<Product> listOfProduct = [Link](
new Product(1, [Link]("Camera", "Mobile","Laptop")),
new Product(2, [Link]("Bat", "Ball","Wicket")),
new Product(3, [Link]("Chair", "Table","Lamp")),
new Product(4, [Link]("Cycle", "Bike","Car"))

);

[Link]().flatMap(p ->
[Link]().stream()).forEach([Link]::println);

}
}
-------------------------------------------------------------------------
Difference between map() and flatMap()
--------------------------------------
map() method transforms each element into another single element.

flatMap() transforms each element into a stream of elements and then flattens those
streams into a single stream.

We should use map() when you want a one-to-one transformation, and we should use
flatMap() when dealing with nested structures or when you need to produce multiple
output elements for each input element.
------------------------------------------------------------------
public Stream distinct() :
--------------------------
It is a predefined method of Stream interface.

If we want to return stream from another stream by removing all the duplicates then
we should use distinct() method.
------------------------------------------------------------------------
package [Link];
import [Link];
public class StreamDemo10
{
public static void main(String[] args)
{
Stream<String> s = [Link]("Virat", "Rohit", "Dhoni", "Virat",
"Rohit","Aswin","Bumrah");
[Link]().sorted().forEach([Link]::println);

}
------------------------------------------------------------------------
public Stream<T> limit(long maxSize) :
----------------------------------------
It is a predefined method of Stream interface to work with sequence of elements.

The limit() method is used to limit the number of elements in a stream by providing
maximum size.

It creates a new Stream by taking the data from original Stream.

Elements which are not in the range or beyond the range of specified limit will be
ignored.

package [Link];
import [Link];
public class StreamDemo11
{
public static void main(String[] args)
{
Stream<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Stream<Integer> limitedStream = [Link](8);

[Link]([Link]::println);
}
}
-------------------------------------------------------------------------
public Stream<T> skip(long n) :
-------------------------------
It is a predefined method of Stream interface which is used to skip the elements
from begning of the Stream.

It returns a new stream that contains the remaining elements after skipping the
specified number of elements which is passed as a parameter.

package [Link];
import [Link];
public class StreamDemo12
{
public static void main(String[] args)
{
Stream<String> s = [Link]("Virat", "Rohit", "Dhoni", "Zaheer",
"Raina");
[Link](2).limit(3).forEach([Link]::println);
}
}
-------------------------------------------------------------------------
public Stream<T> peek(Consumer<? super T> action) :
--------------------------------------------
It is a predefined method of Stream interface which is used to perform a side-
effect operation on each element in the stream while the stream remains unchanged.

It is an intermediate operation that allows us to perform operation on each element


of Stream without modifying original.

The peek() method takes a Consumer as an argument, and this function is applied to
each element in the stream. The method returns a new stream with the same elements
as the original stream.

package [Link];

import [Link];
import [Link];
import [Link];

public class StreamDemo13


{
public static void main(String[] args)
{
Stream<String> numbers =
[Link]("Apple","Mango","Grapes","Kiwi","pomogranate");

List<Integer> doubledNumbers = numbers


.peek(num -> [Link]("Peeking from Original: " +
[Link]()))
.map(num -> [Link]())
.collect([Link]());
[Link]("-----------------");
[Link](doubledNumbers);

}
-------------------------------------------------------------------------
public Stream<T> takeWhile(Predicate<T> predicate) :
-----------------------------------------------------
It is a predefined method of Stream interface introduced from java 9 which is used
to perform a side-effect operation on each element in the stream while the stream
remains unchanged.

*It is used to create a new stream that includes elements from the original stream
only as long as they satisfy a given predicate.

package [Link];

import [Link];

public class StreamDemo14


{
public static void main(String[] args)
{
Stream<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9,
10,11,12,13,14);

Stream<Integer> resultStream = [Link](n -> n < 9);

[Link]([Link]::println);
}
}

Note :- With > symbol it is not working.


-------------------------------------------------------------------------
public Stream<T> dropWhile(Predicate<T> predicate) :
----------------------------------------------------
It is a predefined method of Stream interface introduced from java 9 which is used
to create a new stream by excluding elements from the original stream as long as
they satisfy a given predicate.

package [Link];

import [Link];

public class StreamDemo15 {

public static void main(String[] args)


{
Stream<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Stream<Integer> resultStream = numbers


.dropWhile(num -> num < 9);

[Link]([Link]::println);
}
}
-------------------------------------------------------------------------
Optional<T> class in Java :
------------------------
It is a predefined final and immutable class available in [Link] package from
java 1.8v.

It is a container object which is used represent an object (Optional object) that


may or may not contain a non-null value.
If the value is available in the container, isPresent() method will return true and
get() method will return the actual value.

It is very useful in industry to avoid NullPointerException.

Methods of Optional<T> class :


-------------------------------
1) public static Optional<T> ofNullable(T x) :
-------------------------------------------
It will return the object of Optional class with specified value. If the specified
value is null then this method will return an empty object of the optional class.

2) public boolean isPresent() :


--------------------------------
It will return true, if the value is available in the container otherwise it will
return false.

3) public T get() :
--------------------
It will get/fetch the value from the container, if the value is not available then
it will throw NoSuchElementException.

4) public T orElse(T defaultValue) :


-------------------------------------
It will return the value, if available otherwise it will return the specified
default value.

5) public static Optional<T> of (T value) :


--------------------------------------------
It will return the optional object with the specified value that is non- null
value.

6) public static Optional<T> empty() :


---------------------------------------
It will return an empty Optional Object.

[Link]
-------------------
//Program to verify whether the container has value or not
package [Link].optional_class_demo;

import [Link];

public class OptionalDemo1


{
public static void main(String[] args)
{
String str = null;

Optional<String> optional = [Link](str);


String orElse = [Link]("No value in container");
[Link]("Value by orElse :"+orElse);

//Optional is containing value or not?


if([Link]())
{
[Link]("Value by get :"+[Link]());
}
else
{
[Link]("No value is available");
}

}
---------------------------------------------------------------------------
29-01-2024
------------
//Writing different style of getter with Optional<T> class as a return
type

package [Link].optional_class_demo;
import [Link];
class Employee
{
private Integer empId;
private String empName;

public Employee() {}

public Employee(Integer empId, String empName)


{
super();
[Link] = empId;
[Link] = empName;
}

//Changing the style of writing getter method


public Optional<Integer> getEmpId()
{
return [Link](empId);
}

public Optional<String> getEmpName()


{
return [Link](empName);
}
}

public class OptionalDemo2


{
public static void main(String[] args)
{
Employee emp = new Employee(111,"Ravi");
//Employee emp = new Employee();

Optional<Integer> empId = [Link]();


if([Link]())
{
[Link]([Link]());
}
else
{
[Link]("No id value ");
}
Optional<String> empName = [Link]();
if([Link]())
{
[Link]([Link]());
}
else
{
[Link]("No name value ");
}

}
}
---------------------------------------------------------------------------
//Program to verify value is available or not
package [Link].optional_class_demo;

import [Link];
import [Link];
import [Link];

public class OptionalDemo3


{
public static void main(String[] args)
{
List<Optional<String>> optionalList = new ArrayList<>();

[Link]([Link]("Ameerpet"));
[Link]([Link]("S.R Nager"));
[Link]([Link]("Begumpet"));
[Link]([Link]("Koti"));
[Link]([Link]());

for (Optional<String> optional : optionalList)


{
if ([Link]())
{
[Link]([Link]());
}
else
{
[Link]("No data is available");
}
}
}
}
--------------------------------------------------------------------------

//Immutability of Optional class

package [Link].optional_class_demo;
import [Link];
public class OptionalDemo4
{
public static void main(String[] args)
{
Optional<String> initialOptional = [Link]("India");
[Link]([Link]());
Optional<String> modifiedOptional = modifyOptional(initialOptional);
[Link]([Link]());

// Check if the original Optional is still the same


[Link]("Address is :" + (initialOptional == modifiedOptional));

public static Optional<String> modifyOptional(Optional<String> optional)


{

if ([Link]())
{
return [Link]("Modified: " + [Link]());
}
else
{
return [Link]();
}
}
}
---------------------------------------------------------------------------
Record class :
--------------
public abstract class Record extends Object.

It is a new feature introduced from java 17.(In java 14 preview version)

As we know only objects are moving in the network from one place to another place
so we need to write BLC class with nessacery requirements to make BLC class as a
Data carrier class.

Records are immutable data carrier so, now with the help of record we can send our
immutable data from one application to another application.

It is also known as DTO (Data transfer object) OR POJO classes.

It is mainly used to concise our code as well as remove the boiler plate code.

In record, automatically constructor will be generated which is known as canonical


constructor and the variables which are known as components are by default final.

In order to validate the outer world data, we can write our own constructor which
is known as compact constructor.

Record will automatically generate the implemenation of toString(), equals(Object


obj) and hashCode() method.

We can define static and non static method as well as static variable inside the
record. We cannot define instance variable inside the record.

We cann't extend or inherit records because by default every record is implicilty


final. It is extending from [Link] class

We can implement an interface by using record.

[Link]
-------------------
package [Link];

import [Link];

public class CustomerClass {


private int id;
private String name;
private double bill;

public CustomerClass(int id, String name, double bill) {


super();
[Link] = id;
[Link] = name;
[Link] = bill;
}

@Override
public String toString() {
return "CustomerClass [id=" + id + ", name=" + name + ", bill=" + bill
+ "]";
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public double getBill() {


return bill;
}

public void setBill(double bill) {


[Link] = bill;
}

@Override
public int hashCode() {
return [Link](bill, id, name);
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
CustomerClass other = (CustomerClass) obj;
return [Link](bill) ==
[Link]([Link]) && id == [Link]
&& [Link](name, [Link]);
}

}
--------------------------------------------------------------------------
[Link]
--------------------
package [Link];

public record CustomerRecord(int id, String name, double bill)


{
//Compact Constructor
public CustomerRecord
{

if(id < 0)
{
throw new IllegalArgumentException("Id is invalid");
}
else
{

}
}
}
---------------------------------------------------------------------------
package [Link];

public class Main {

public static void main(String[] args)


{
CustomerClass c1 = new CustomerClass(1, "A", 23);
CustomerClass c2 = new CustomerClass(1, "A", 23);
[Link]([Link](c2));
[Link](c1);
String name = [Link]();
[Link](name);

[Link](".................");

CustomerRecord r1 = new CustomerRecord(2, "B", 40);


CustomerRecord r2 = new CustomerRecord(2, "B", 40);
[Link]([Link](r2));
[Link](r1);
String name2 = [Link]();
[Link](name2);
}
}
-----------------------------------------------------------------

You might also like