Java Programming Basics and Concepts
Java Programming Basics and Concepts
----------
javaravishanker@[Link]
9835647014
History of Java :
------------------
Java was developed by Sun microsystem but on 27th January 2010, Java was overtaken by Oracle
Corporation so now java is the product of
Oracle Corporation.
2) User-defined Function :
--------------------------
The functions which are defined by user for performing some specific task are called User-defined
function.
Advantages of Function :
-------------------------
1) Modularity :
---------------
Dividing the bigger task into number of smaller task.
2) Easy to understand :
-----------------------
Once the task is divided into number of independent modules then it is easy to understand the entire
module.
3) Reusability :
-----------------
We can reuse a particular module for ’n’ number of times.
===================================================================
Why we pass parameter to a function ?
-------------------------------------------
We should pass parameter to a function for getting more information regarding the function.
If We don’t pass parameter then the informations are not complete, It is partial information.
Example :
---------
public void deposit(double amount)
{
}
===================================================================
Why functions are called Method in java ?
------------------------------------------
In C++ language, there is a facility to write a function inside the class as well outside of the class by using
scope resolution operator (::) but in java we can write a function inside the class only, we can’t define a
function outside of the class, that is reason functions are called Method in java.
----------------------------------------------------------------
30-09-2024
-----------
**What is platform independency in java ?
----------------------------------------
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.
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.[30-SEP-24]
Note :- We have different JVM for different Operating System that means JVM is platform dependent
technology where as Java is platform Independent technology.
JVM internally contains an interpreter so it executes the code line by line. It is written in ’C’langugae
hance platform dependent.
----------------------------------------------------------------
**What is the difference between bit code and byte code ?
-------------------------------------------------------
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 appropriate machine understandable format.
[30-SEP-24]
JDK :
------
It stands for Java Devleopment Kit. It is a developer version that
means by using JDK we can develop as well as execute our java
programs.
In order to develop and execute it supports various JDK tools which are as follows :
JRE :
-----
It stands for Java Runtime Environment. It is a client version so
by using JRE we can only execute our java program.
From java 11 version we don’t have separate JRE folder, java software people removed this folder from
software so, from java 11 version we can directly execute our java program without compilation.
JVM :
-----
The main purpose of JVM to load and execute the byte code. It provides, security, memory management
by garbage collector, JIT compiler for fast execution and so on.
The .class file generated by java compiler first verified by ByteCode Verifier (One component of JVM) so
java is the most
secure language in IT market.
It holds the repeated code instrauction and native code instruction, It will directly provide these two
instrution at time
of line by line execution so our interpreter executes the code
in more efficient way hance the overall execution becomes very fast.
-----------------------------------------------------------------
What is data type in java ?
----------------------------
A data type describes, what type of value the varaiable will hold.
In hava we have 2 types of data types :
In these languages we can hold different kind of value during the execution of the program.
Ex:- Visual Basic, Javascript, Python
-----------------------------------------------------------------
What is comments in java ?
--------------------------
Comments are used to enhance the readability of the code. It is ignored by the compiler.
In java we have 3 types of commants :
2) Multiline Comment
/*
Java Source code.
*/
3) Documentation Comment
/**
Name of the Project : Online Shopping
Number of Modules : 36
Date of creation : 2nd Feb 2024
Last Modification : 30th Sep 2024
Author : Green Team
*/
------------------------------------------------------------------
WAP in Java to display welcome message :
----------------------------------------
public class Welcome
{
public static void main(String[] args)
{
[Link]("Welcome Batch 39!");
}
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 (syntax rule) to declare our methods as public.
------------------------------------------------------------------
static :
--------
As of now, In java we have 2 types of Methods :
class Sample
{
public static void greet()
{
[Link]("Good Morning All");
}
}
Case 2 :
---------
If a static method is declared in the same class where main method is available then we can call the static
method directly, Here class name is also not required.
Our main method must be declared as static so object is not required, JVM can call this main method with
the help of class name.
If we don’t declare our main method as static then code will compile but it will not be executed by JVM.
-----------------------------------------------------------------
03-10-2024
----------
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 method return type must be void because JVM will not accept any return value from the user.
-----------------------------------------------------------------
main() method :
---------------
It is a user-defined 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.
-----------------------------------------------------------------
Q) Can we write multiple method with same name ?
------------------------------------------------
Yes, We can write multiple methods with same name but parameter must be different otherwise code will
not compile.
Note :- We can also write multiple main methods with different parameter but JVM will always execute the
main method which takes String [] args (String array) as a parameter as shown in the program below.
IQ :
----
Why the main method of java accepts String array as a parameter ?
-----------------------------------------------------------------
String is a collection of alpha-numeric character so it can accept all different kind of values. Java software
people has
provided String array as a parameter so it can ACCEPT MULTIPLE
VALUES OF DIFFERENT TYPE, that means providing more wider scope to accept hetrogeneous types
of values.
-----------------------------------------------------------------
[Link]() :
----------------------
It is an output statement in java, By using this statement we can print different types of values on the
console.
In this statement System is a predefined class available in [Link] pacakage, out is a reference variable
of type PrintStream class available in [Link] package and println() is
a predefined method available in PrintStream class.
class System
{
final static PrintStream out; //HAS-A Relation
}
================================================================
WAP in java to add two numbers :
--------------------------------
public class Addition
{
public static void main(String[] args)
{
int x = 10;
int y = 20;
int z = x + y;
[Link](z);
}
}
Program
---------
public class AdditionWithMessage
{
public static void main(String[] args)
{
int x = 10;
int y = 20;
int z = x + y;
[Link]("Sum is :"+z);
}
}
-----------------------------------------------------------------
WAP to add two numbers without using 3rd Variable
--------------------------------------------------
public class AdditionWithout3rdVariable
{
public static void main(String[] args)
{
int x = 100;
int y = 200;
[Link]("Sum is :"+x+y); //100200
[Link](+x+y); //300
[Link](""+x+y);//100200
[Link]("Sum is :"+(x+y)); //Sum is 300
}
}
----------------------------------------------------------------
04-10-2024
----------
IQ
--
public class StringConcatenationDemo
{
public static void main(String[] args)
{
String str = 25 + 25 +"NIT"+ 50 + 50;
[Link](str);
}
}
----------------------------------------------------------------
Command Line Argument :
-----------------------
Whenever we pass any argument to the main method then it is called Command Line Argument.
Example :
The advantage of command line argument is, single time compilation and number of times execution with
different value.
=================================================================
//Program to accept the value from command line Argument
public class Command
{
public static void main(String[] args)
{
[Link](args[0]);
}
}
javac [Link]
java Command Scott Smith
Output is : Scott
-----------------------------------------------------------------
//Program to pass some numberic value as a String value
public class CommandValue
{
public static void main(String[] cmd)
{
[Link](cmd[1]);
}
}
javac [Link]
java CommandValue 100 200
Output is : 200
-----------------------------------------------------------------
//Accepting the full name from command Line Argument
javac [Link]
java FullNameUsingCommand "Virat Kohli"
javac [Link]
java Command [Not passing any value at runtime]
While working with command line argument, if we are using the index in the program but not passing any
value at runtime to
command line argument then we will get an exception
[Link].
-----------------------------------------------------------------
How to find out the length of an array variable ?
--------------------------------------------------
In order to find out the length of an array variable, Arrays class has provided a predefined variable OR
property called length as shown in the programs below.
javac [Link]
java ArrayLengthUsingCommand
Output : The length of array is 0
java ArrayLengthUsingCommand 12
Output : The length of array is 1
java ArrayLengthUsingCommand 12 14
Output : The length of array is 2
-------------------------------------------------------------------
//WAP to add two numbers by using Command Line Argument
public class CommandAdd
{
public static void main(String []args)
{
[Link](args[0] + args[1]);
}
}
javac [Link]
java CommandAdd 100 200
Output is : 100 200 [Here ’+’ works as String Concatenation Optr]
===============================================================
How to convert a String into integer value :
--------------------------------------------
There is a predefined class called Integer available in [Link] pacakge, It provides a predefined static
method called parseInt(String x) which accepts a single String type parameter and convert this String into
int type becauase the return type of this parseInt(String x) method is int type.
int sum = a + b;
javac [Link]
java CommandAddition 12 12
javac [Link]
java FindSquare 12
The main purpose of Eclipse IDE to reduce the development time, once the development time will be
reduced then automatically the cost of the project will be reduced.
If we arrange our java classes into a particular group by using pacakges (folders) then we will get the
following two advantages :
package sum;
public class Addition
{
[javac -d . [Link] ]
javac -d . [Link]
It will compile [Link], [Link] contains sum package, one package i.e folder called sum will
be created and automatically [Link] file will be placed inside the package or folder called sum.
Types of Packages :
---------------------------
1) Predefined OR Built-in package : The packages which are created by java software people for
arranging the programs are called predefined package.
2) Userdefined Package OR Custom package : The packages which are created by user for arranging the
user-defined programs are called user-defined package.
Example :
basic;
[Link];
[Link].online_shopping;
---------------------------------------------------------------
WAP in eclipse IDE for finding the area of the circle :
-------------------------------------------------------
package [Link].command_line_Argument;
}
Steps to execute the command Line Argument Program using Eclipse IDE
---------------------------------------------------------------------
Right click on the program -> Run As -> Run configuration -> Check your main class name -> select
argument tab -> pass the appropriate value -> Run
---------------------------------------------------------------
WAP to find out the area of rectangle :
----------------------------------------
package [Link].command_line_Argument;
}
--------------------------------------------------------------
WAP in java to pass some value from command line argument based on the following criteria :
package [Link].command_line_Argument;
}
}
---------------------------------------------------------------
WAP to show how exactly [Link] works internally ?
------------------------------------------------------------
package [Link].command_line_Argument;
class Integer
{
public static int getSquare(int num)
{
return num*num;
}
}
---------------------------------------------------------------
07-10-2024
----------
Naming convention in java ?
----------------------------
Naming convention provides two important characteristics :
Example :
ThisIsExampleOfClass
System
String
Integer
CommandAddition
ArrayIndexOutOfBoundsException
DataInputStream.
2) How to write a method in java :
----------------------------------
While writing a method in java we should follow camel case
naming convention, According to this naming convention first world will be in small and 2nd word
onwards, each word first character must be capital. In java a method represents verb.
Example :
thisIsExampleOfMethod()
read()
readLine()
parseInt()
charAt()
toUpperCase()
Example :
----------
rollNumber
customerName
customerBill
studentName
playerName
Example :
Integer.MIN_VALUE [MIN_VALUE is final and static variable]
Integer.MAX_VALUE [MAX_VALUE is final and static variable]
[Link]
[Link]
[Link]
===============================================================
Tokens in java :
----------------
Token is the smallest unit of the program which is identified by the compiler.
1) Keyword
2) Identifier
3) Literal
4) Punctuators (Seperators)
5) Operator
Keyword
--------
A keyword is a predefined word whose meaning is already defined by the compiler.
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.
Ex:-
class Fan
{
int coil ;
void switchOn()
{
}
}
Here Fan(Name of the class), coil (Name of the variable) and switchOn(Name of the Method) are
identifiers.
1) Integral Literal
2) Floating Point Literal
3) Boolean Literal
4) Character Literal
5) String Literal
Decimal Literal :
-----------------
By default our numeric literals are decimal literal. Here base is 10 so, It accepts 10 digits i.e. from 0-9.
Example :
int x = 20;
int y = 123;
int z = 234;
Octal Literal :
---------------
If any Integer literal starts with 0 (Zero) then it will become octal literal. Here base is 8 so it will accept 8
digits i.e 0 to 7.
Example :
Hexadecimal Literal :
---------------------
If any integric literal starts with 0X or 0x (Zero capital X Or 0 small x) then it is hexadecimal literal. Here
base is 16 so it will accept 16 digits i.e 0 to 9 and A to F OR [a to f]
Example :
Binary Literal :
---------------
If a numeric literal starts with 0B (Zero capital B) or 0b (Zero small b) then it will become Binary literal.
Binary literal is available from JDK 1.7v.
Here base is 2 so it will accept 2 digits i.e 0 and 1.
Example :
----------
int x = 0B101; //valid
int y = 0b111; //Valid
int z = 0B112; //Invalis [2 is out of range]
The deafult type is decimal literal so to generate the output for any different literal JVM converts into
decimal literal.
--------------------------------------------------------------
//Octal Litearl
public class OctalDemo
{
public static void main(String [] args)
{
int x = 015;
[Link](x); //13
}
}
--------------------------------------------------------------
//Hexadecimal Litear
public class HexadecimalDemo
{
public static void main(String[] args)
{
int a = 0xadd;
[Link](a);//2781
}
}
--------------------------------------------------------------
//Binary Literal
public class BinaryDemo
{
public static void main(String [] args)
{
int x = 0B101;
[Link](x); //5
}
}
--------------------------------------------------------------
08-10-2024
-----------
By default every integral literal is of type int only. byte and short are below than int so we can assign
integral literal(Which is by default int type) to byte and short but the values must be within the range. [for
Byte -128 to 127 and for short -32768 to 32767]
Actually whenever we are assigning integral literal to byte and short data type then compiler internally
converts into corresponding type.
In order to represent long value we should use either L OR l (Capital L OR Small l) as a suffix to integral
literal.
long l = 29L;
[Link]("l value = "+l);
}
}
-------------------------------------------------------------
Is java pure Object Oriented Language ?
---------------------------------------
No, Java is not a pure object oriented langauge because it is accepting primary data type, Actually any
language which accepts primary data type is not a pure object oriented language.
Only Objects are moving in the network but not the primary data type so java has introduced Wrapper
class concept to convert the primary data types into corresponding wrapper object.
Note : Apart from these 8 data types, Everything is an object in java so, if we remove all these 8 data
types then java will become pure OOP language.
-------------------------------------------------------------
//Wrapper claases
public class Test8
{
public static void main(String[] args)
{
Integer x = 24;
Integer y = 24;
Integer z = x + y;
[Link]("The sum is :"+z);
Boolean b = true;
[Link](b);
Double d = 90.90;
[Link](d);
Character c = ’A’;
[Link](c);
}
}
-------------------------------------------------------------
09-10-2024
----------
How to find out the minimum, maximum value as well as size of different data types :
The Warpper classes like Byte, Short, Integer and Long has provided predefined static and final variables
to represent minimum value, maximum value as well as size of the respective data type.
Example :
If we want to get the minimum value, maximum value as well as size of byte data type then Byte class
(Wrapper class) has provided the following final and static variables
Byte.MIN_VALUE : -128
Byte.MAX_VALUE : 127
}
}
-------------------------------------------------------------
Providing _ (underscore) in integeral Literal :
------------------------------------------------
In Order to enhance the readability of large numeric literals, Java software people has provided _
(underscore) from JDK 1.7v. While writing the big numbers to separate the numbers we can use _
We can’t start or end an integral literal with _ we will get compilation error.
x = 90;
[Link](x);
// x = "NIT"; //Invalid
}
}
-----------------------------------------------------------------
How to convert decimal number to Octal, Hexadecimal and Binary :
----------------------------------------------------------------
Integer class has provided the following static methods to convert decimal to octal, hexadecimal and
binary.
1) public static String toBinaryString(int x) : Will convert the decimal into binary in String format.
2) public static String toOctalString(int x) : Will convert the decimal into octal in String format.
3) public static String toHexString(int x) : Will convert the decimal into hexadecimal in String format.
-----------------------------------------------------------------
// Converting from decimal to another number system
public class Test12
{
public static void main(String[] argv)
{
//decimal to Binary
[Link]([Link](7)); //111
//decimal to Octal
[Link]([Link](15)); //17
//decimal to Hexadecimal
[Link]([Link](2781)); //add
}
}
=================================================================
floating point literal :
------------------------
If any numeric literal contains decimal or fraction then it is called floating point literal.
Example : 12.3, 90.7, 56.6
By default every floating point literal is of type double only so, the following statement will generate
compilation error.
float f1 = 1.2; //Invalid
* An integral literal we can represent in four different forms i.e decimal, octal, hexadecimal and binary but
floating point literal we can represent in only one form i.e decimal.
* An integral literal i.e byte, short, int and long we can assign to floating point literal but floating point literal
we can’t assign to integral literal.
-----------------------------------------------------------------
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 b = 15.29F;
float c = 15.25f;
float d = (float) 15.30;
}
}
----------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
double d = 15.15;
double e = 15d;
double f = 15.15D;
double y = 0167;
double z = 0178;
[Link](x+","+y+","+z);
}
}
----------------------------------------------------------------
class Test4
{
public static void main(String[] args)
{
double x = 0X29;
[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;
Boolean literal :
-----------------
It is used to represent two states i.e true or false.
In boolean literal we have only one data type i.e boolean data type which accepts 1 bit of memory as well
as it depends upon JVM implementation.
---------------------------------------------------------------
//Programs :
------------
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; //Invalid
boolean d = 1; //Invalid
[Link](c);
[Link](d);
}
}
--------------------------------------------------------------
public class Test3
{
public static void main(String[] args)
{
boolean x = "true";
boolean y = "false";
[Link](x);
[Link](y);
}
}
---------------------------------------------------------------
Char Literal :
--------------
It is also known as Character Literal.
In character Literal we have only one data type i.e char data type which accepts 16 bits of memory.
b) In older languages like C and C++, which supports ASCII format and the range is 0 - 255, On the
other hand java supports UNICODE format where the range is 0 - 65535. [0 is the minimum range and
65535 is the maximum range]
c) We can assign character literal to integral literal to know the UNICODE numeric value of that
particular character.
d) We can also represent a char literal in 4 digit hexadecimal number where the format is
char c = ’\n’;
---------------------------------------------------------------
public class Test1
{
public static void main(String[] args)
{
char ch1 = ’a’;
[Link]("ch1 value is :"+ch1);
}
}
--------------------------------------------------------------
public 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);
}
}
Note : We will get the output as ? because the equivalant language translator is not available in the
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) OR ’\uffff’
class Test6
{
public static void main(String[] args)
{
char ch1 = 65535;
[Link]("ch value is :"+ch1);
}
}
--------------------------------------------------------------
public class Test11
{
public static void main(String[] args)
{
[Link](Character.MIN_VALUE); //white space
[Link](Character.MAX_VALUE); //?
[Link]([Link]); //16 bits
}
}
------------------------------------------------------------
String Literal :
-----------------
String is a predefined class available in [Link] Package.
String is a collection of alpha-nemeric character which is enclosed by double quotes. These characters
can be alphabets, numbers, symbol or any special character.
}
}
---------------------------------------------------------------
//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
public class StringTest3
{
public static void main(String []args)
{
String s = 15+29+"Ravi"+40+40;
[Link](s);
}
}
---------------------------------------------------------------
4) Punctuators :
----------------
It is also called separators.
It is used to inform the compiler how things are grouped in the code.
() {} [] ; , . @ (var args)
---------------------------------------------------------------
5) Operators
------------
It is a symbol which describes that how a calculation will be performed on operands.
Types Of Operators :
------------------------
1) Arithmetic Operator (Binary Operator)
2) Unary Operators
3) Assignment Operator
4) Relational Operator
7) Bitwise Operators (^ ~)
8) Ternary Operator
Note : Increment and decrement operator we can apply on any primitive data type except boolean.
---------------------------------------------------------------
Local Variable in java ?
-------------------------
If we declare a variable inside a method OR block OR Constructor then it is called
local/Automatic/Temporary/Stack variable.
Example :
A local variable must be initialized by the developer before use because local variable does not have
default values.
We can’t apply any kind of access modifier on local variable except final.
As far as it’s accessibility is concerned, It is accessible within the same method only.
Program :
----------
class Test
{
public static void main(String[] args)
{
final int x = 100;
[Link](x);
}
}
---------------------------------------------------------------
Why we can’t use a local variable outside of the method OR block OR Constructor ?
----------------------
In java, Whenever we call a method then a separate Stack Frame will be created for each and every
method.[15-OCT]
package [Link].method_demo;
Note : In the above program, after providing the gender value, It is asking for Gender which is not a
recommended way.
There are so many ways to read the data from end user which are as follows :
1) [Link]
2) [Link]
3) [Link]();
4) [Link]
5) [Link]
package [Link].scanner_demo;
import [Link];
}
---------------------------------------------------------------
//WAP to read employee data using Scanner class
package [Link].scanner_demo;
[Link]("Employee Id is :"+id);
[Link]("Employee Name is :"+name);
[Link]();
}
---------------------------------------------------------------
Expression Conversion :
-----------------------
Whenever we are working with Arithmetic Operator (+,-,*,/,%) or unary minus operator, after expression
exeution the result will be converted (Promoted) to int type, Actually to store the result minimum 32 bits
format is required.
class Test
{
public static void main(String[] args)
{
byte b = 1;
byte c = 2;
byte d = b + c; //error
[Link](d);
After Arithmetic operator expression the result will be promoted to int type so, to hold the result minimum
32 bit data is required.
---------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
byte b = 1;
byte c = 2;
byte d = (byte)(b + c); //Valid
[Link](d);
}
--------------------------------------------------------------
Unary Minus Operator :
-----------------------
class Test
{
public static void main(String [] args)
{
int x = 15;
[Link](-x);
}
}
---------------------------------------------------------------
class Test
{
public static void main(String [] args)
{
byte b = 1;
short c = -b; //error
[Link](c);
In Arithmetic operator OR Unary minus operator, the result will be promated to int type (32 bits) so to hold
the result int data type is reqd.
---------------------------------------------------------------
class Test
{
public static void main(String [] args)
{
byte b = 1;
b += 2;
[Link](b);
}
In the above program we are using short hand operator so we will get the result in byte format also.
---------------------------------------------------------------
class Test
{
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
}
--------------------------------------------------------------
Program on Boolean AND operator :
----------------------------------
class Test
{
public static void main(String [] args)
{
int z = 5;
if(++z > 6 & ++z> 6)
{
[Link]("Inside If");
z++;
}
[Link](z);
}
---------------------------------------------------------------
Working with Bitwise AND(&), Bitwise OR(|) and Bitwise X-OR (^) :
---------------------------------------------------------------
class Test
{
public static void main(String [] args)
{
[Link](false ^ true);
}
Note : If both the inputs are alternate of each other then we will get true otherwise we will get false.[Same
input output will be false]
----------------------------------------------------------------
class Test
{
public static void main(String [] args)
{
[Link](5 & 6); //4
[Link](5 | 6); //7
[Link](5 ^ 6); //3
}
---------------------------------------------------------------
Bitwise Complement Operator (~) :
---------------------------------
It will not work with boolean type.
}
----------------------------------------------------------------
class Test
{
public static void main(String [] args)
{
[Link](~-5); // 4
[Link](~5); //-6
}
----------------------------------------------------------------
Member access operator (.) :
-----------------------------
It is called Member access operator, by using this we can access the member of the class.
In the following program we have static method in the Welcome class, in order to call the static method
we can use Welcome class and to access the static method of Welcome class we should use .(Dot)
operator.
package [Link];
class Welcome
{
static int x = 100;
public static void greet()
{
[Link]("Hello batch 39");
}
}
}
----------------------------------------------------------------
new Keyword :
-------------
It is also an operator.
It is used to create the object and initialize the non static member with default value.
package [Link];
class Welcome
{
int x = 100; //non static variable
public void greet() //non static method
{
[Link]("Hello batch 39");
}
}
}
----------------------------------------------------------------
17-10-2024
-----------
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.
break is optional but if we use break then the control will move from out of the switch body.
We can write default so if any statement is not matching then default will be executed.
In switch case we can’t pass long, float and double and boolean value.
We can pass String from JDK 1.7v and we can also pass enum from JDK 1.5v.
----------------------------------------------------------------
import [Link].*;
public class SwitchDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Please Enter a Character :");
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");
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();
case "rainy" :
[Link]("It is Rainy Season!!");
break;
}
}
}
----------------------------------------------------------------
switch(l)
{
case 12 :
[Link]("It is case 12");
break;
}
}
switch(x)
{
case y : //error
[Link]("It is case 12");
break;
}
}
switch(x)
{
case y :
[Link]("It is case 12");
break;
}
}
}
-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
byte b = 90;
switch(b)
{
case 128 : //error
[Link]("It is case 127");
break;
}
}
Note : Value 128 is out of the range of byte and same applicable for short data type
----------------------------------------------------------------
Loops in java :
---------------
A loop is nothing but repeatation of statements based on the
specified condition.
do-while loop :
----------------
class Test
{
public static void main(String [] args)
{
do
{
int x = 1; //block [Local Variable]
[Link](x);
x++;
}
while (x<=10); //error
}
Note : x variable is declared inside the do block so we can’t use outside of the block.
----------------------------------------------------------------
class Test
{
public static void main(String [] args)
{
int x = 1;
do
{
[Link](x);
x++;
}
while (x<=10);
}
}
----------------------------------------------------------------
Progran on while loop :
-----------------------
class Test
{
public static void main(String [] args)
{
int x = 10;
while(x>=-1)
{
[Link](x);
x--;
}
}
---------------------------------------------------------------
Program on for loop :
---------------------
public class ForLoop
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
[Link](i);
}
}
}
----------------------------------------------------------------
for-each loop in java :
------------------------
It is also known as enhaned for loop, introduced from JDK 1.5
It will fetch the values one be one from the Collection data so, It is known as for each loop.
----------------------------------------------------------------
import [Link].*;
public class ForEachDemo1
{
public static void main(String [] args)
{
int []arr = {50,40,30,20,10};
[Link](arr);
for(int x : arr)
{
[Link](x);
}
}
Example :
[Link](int []arr); //For sorting int array
[Link](Object []arr) //For sorting String array
[Link](cities);
for(Object x : arr)
{
[Link](x);
}
}
}
Example :
----------
//BLC
public class Calculate
{
//Here We are responsible to write the logic
}
ELC :
-----
It stands for Executable Logic class, It will not contain any logic but the execution of the program will start
from this ELC class because it contains main method.
Example :
---------
//ELC
public class Main
{
public static void main(String [] args)
{
}
}
----------------------------------------------------------------
How to reuse a class in java ?
-------------------------------
The slogan of java is "WORA" write once run anywhere.
A public class created in one package can be reuse from different packages also by using import
statement.
In a single java file, we can declare only one public class that must be our .java file and that class can be
reusable to all the packages.
*In a single java file, we can write only one public class and multiple non-public classes but it is not a
recommended approach because the non public class we can use within the same package only.
So the conclusion is, we should declare every java class in a separate file to enhance the reusability of
the BLC classes.
[Note we have 10 classes -> 10 java files]
Program that describes how to reuse a java BLC class in another package :
[Link] [BLC]
---------------------
package [Link].m1;
//BLC
public class Calculate
{
public static void getSquare(int x)
{
[Link]("Square of "+x+" is :"+(x*x));
}
}
[Link] [BLC]
----------------------
package [Link].m1;
[Link] [ELC]
---------------
package [Link].m2;
import [Link];
import [Link];
}
-----------------------------------------------------------------
How many .class file will be created in the above approach :
------------------------------------------------------------
For a public class in a single file, Only 1 .class file will be created.
For a public class in a single file which contains n number of non public classes then compiler will
generate n (number of .java) number of .class file.
Example :
----------
public class Test
{
class A
{
}
class B
{
}
class C
{
}
In order to call a static method, Object is not required, We can call static method directly with the help of
class name.
-----------------------------------------------------------------
//A static method can be directly call within the same class
package [Link].pack1;
Note : Any static method defined in the ELC class, we can direcytly call from main method.
-----------------------------------------------------------------
2 files :
----------
[Link]
---------------
package [Link].pack2;
//BLC
public class GetSquare
{
public static void getSquareOfNumber(int num)
{
[Link]("Square of "+num+" is :"+(num*num));
}
}
[Link]
-----------
package [Link].pack2;
import [Link];
//ELC
public class Test2
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the side :");
int side = [Link]();
[Link](side);
[Link]();
}
}
Note : In the above program there is no communication from BLC module to ELC module, ELC module is
sending the value to BLC module but BLC module is not returining any kind of value.
-----------------------------------------------------------------
2 files :
---------
[Link]
-----------------
//A static method returning integer value
package [Link].pack3;
//BLC
public class FindSquare
{
public static int getSquare(int x)
{
return (x*x);
}
}
[Link]
-----------
package [Link].pack3;
import [Link];
//ELC
public class Test3
{
public static void main (String[] arg)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the value of side :");
int side = [Link]();
package [Link].pack4;
//BLC
public class Calculate
{
public static int getSquareAndCube(int num)
{
if(num <=0)
{
return -1;
}
else if(num%2==0)
{
return num*num;
}
else
{
return num*num*num;
}
}
}
[Link]
------------
package [Link].pack4;
import [Link];
}
-----------------------------------------------------------------
2 files :
----------
[Link]
---------------
package [Link].pack5;
//BLC
public class Rectangle
{
public static double getAreaOfRectangle(double length, double breadth)
{
return (length * breadth);
}
[Link]
-----------
package [Link].pack5;
import [Link];
}
}
-----------------------------------------------------------------
2 files :
----------
[Link]
--------------
package [Link].pack6;
//BLC
public class EvenOrOdd
{
public static boolean isEven(int num)
{
return (num % 2 == 0);
}
}
[Link]
-----------
package [Link].pack6;
import [Link];
//ELC
public class Test6
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a Number :");
int num = [Link]();
isEven = [Link](num);
[Link](num+" is Even ?:"+isEven);
[Link]();
}
}
----------------------------------------------------------------
2 files :
----------
[Link]
-------------
//Area of Circle
//If the radius is 0 or Negative then return -1.
package [Link].pack7;
public class Circle
{
public static String getAreaOfCircle(double radius)
{
if(radius <=0)
{
return ""+(-1);
}
else
{
final double PI = 3.14;
double areaOfCircle = PI * radius * radius;
return ""+areaOfCircle;
}
}
}
[Link]
------------
package [Link].pack7;
import [Link];
import [Link];
[Link]();
}
}
-----------------------------------------------------------------
19-10-2024
-----------
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]
[Link]
-----------
package [Link].pack8;
Note : we can call any method whose return type is not void by using [Link]() method but we
can’t call a method whose return type is void.
class Alpha
{
public static void m1()
{
}
[Link](Alpha.m1()); //error
[Link](Alpha.m2()); //Valid
----------------------------------------------------------------
2 files :
---------
[Link]
------------
package [Link].pack9;
//BLC
public class Table
{
public static void printTable(int num) //5 X 1 = 5
{
for(int i=1; i<=10; i++)
{
[Link](num+" X "+i+" = "+(num*i));
}
[Link]("...................");
}
}
[Link]
-----------
package [Link].pack9;
//ELC
public class Test9
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
[Link](i);
}
}
}
-----------------------------------------------------------------
Types of Variables in java :
-----------------------------
In java, Based on the data types variables are divided into two
types :
1) Primitive Variables
2) Reference Variables
1) Primitive Variables :
------------------------
If a variable is declared with primitive data types like byte, short, int, long and so on then it is called
Primitive Variables.
Example :
byte x = 12;
int y = 90;
boolean isEmpty = false;
int y = 12;
y.m1(); //Invalid
Reference Variables :
---------------------
In java, If a variable is declared with class name then it is called reference variable.
Example :
Integer x = 19;
String str = "India";
Student st;
Customer c = null;
Based on the Declaration position, these two variables are further classified into 4 categories :
3) Local Variable
4) Parameter Variable
class Test
{
static int a; //static Field OR Class Variable
int b; //Non Static Field OR Instance Variable
}
}
public class PrimitiveVariablesDemo
{
public static void main(String[] args)
{
Test t1 = new Test();
[Link](300);
}
}
Output : 0
0
300
400
-----------------------------------------------------------------
Program on Reference Variable :
-------------------------------
package [Link].variable_type;
import [Link];
class Student
{
Student s1 = null; //Instance + Reference Variable
static Scanner sc = new Scanner([Link]); //Static + Reference Var
}
=================================================================
21-10-2024
----------
Object Oriented Programming (OOPs)
----------------------------------
What is an Object?
------------------
An object is a physical entity which exist in the real world.
Example :- Pen, Car, Laptop, Mouse, Fan and so on
OOP is a technique through which we can design or develop the programs using class and object.
Advantages of OOP :
--------------------
1) Modularity (Dividing the bigger task into smaller task)
2) Reusability (We can reuse the component so many times)
3) Flexibility (Easy to maintain [By using interface])
Features of OOP :
-----------------
1) Class
2) Object
3) Abstraction
4) Encapsulation
5) Inheritance
6) Polymorphism
================================================================
What is a class?
-----------------
A class is model/blueprint/template/prototype for creating the object.
A class is a user-defined data type which contains data member and member function.
----------------------------------------------------------------
WAP to initialize the Object properties using Object reference ?
2 files :
----------
[Link]
------------
package [Link];
//BLC
public class Student
{
String name; //Instance Variable
double height; //Instance Variable
int rollNumber; //Instance Variable
//Object Behavior
public void talk()
{
[Link]("Hello Everyone, My name is :"+name);
[Link]("My Roll number is :"+rollNumber);
[Link]("And my height is :"+height);
[Link]
-----------------
package [Link];
//ELC
public class StudentDemo
{
public static void main(String[] args)
{
Student raj = new Student();
[Link]("===================");
[Link]();
[Link]();
Step 1 :- Create the Object based on the BLC class inside ELC
class
Step 3 :- Initialize all the object properties with user friendly value by using reference variable.
2 files :
----------
[Link]
-------------
package [Link];
[Link]
-----------------
package [Link];
import [Link];
[Link]();
[Link]();
}
}
---------------------------------------------------------------
What is instance OR Non static variable :
-----------------------------------------
It is a class level variable so It has default value.
If a non static variable is defined inside a class but outside of a method then it is called instance variable.
Example :
----------
public class Student
{
int rollNumber; //Instance Variable [Object Properties]
An instance variable life starts at the time of creating the object, Without object we can’t think about
instance variable.
As far as its accessibility is concerned, It is accessible within the same class as well as depends upon the
access modifier applied on the instance variable.
---------------------------------------------------------------
Parameter Variable :
---------------------
It is a method level variable hence does not have default value.
If a variable is declared inside a method parameter (not inside method body) then it is called Parameter
Variable.
As far as it’s scope is concerned, It is accessible within the same method body only.
public void setEmployeeData(int id, String name, double sal, String addr)
{
employeeId = id;
employeeName = name;
employeeSalary = sal;
employeeAddress = addr;
}
[Link]
------------------
package [Link];
[Link]("================");
Employee smith = new Employee();
[Link](222, "Smith", 56000, "Ameerpet");
[Link]();
}
================================================================
Constructor [Introduction Only]
--------------------------------
If the name of the class and name of the method both are exactly same and it does not contain any return
type then it is called Constructor.
javac [Link]
------------------
public class Example
{
public Example() //Default Constructor added by compiler
{
}
}
Every java class must have at-least one constructor [We can’t think about java class without constructor]
either implicitly added by java compiler OR explicitly written by programmer.
The access modifer of default constructor (added by compiler) depends upon class access modifier, if
class is public then the access modifier of default constructor is also public.
Example :
----------
public class Demo
{
javac [Link]
javap [Link] [You Can see the constructor added by compiler]
----------------------------------------------------------------
Why compiler is adding default constructor to our class :
---------------------------------------------------------
We have 2 reasons that why compiler is adding default constructor :
1) Without default constructor, Object creation is not possible in java by using new keyword.
2) As we know only class level variables are having default values so, default constructor will initialize all
the instance variables with default values with the help of new keyword.
2 files :
----------
[Link]
--------------
package [Link];
[Link]
-----------------
package [Link];
Note : In the above program all the object properties are not
initialized with parameter variable, actually employeeGrade is initialized by employeeSalary.
----------------------------------------------------------------
Note : Upto Here we have alreday learned the followinbg ways to initialize the object properties :
Variable shadowing in Java occurs when a variable declared within a certain scope (like a method or a
block or Constructor) has the same name as a variable declared in an outer scope (class Level).
In variable Shadow, the variable in the inner scope hides the variables in Outer scope so known as
variable shadowing.
This means that within the inner scope (Method, block Or Constructor), when we refer to the variable
directly by name, We are actually referring to the inner variable, not the outer variable.
2 files :
----------
[Link]
--------------
package [Link];
}
[Link]
-----------------
package [Link];
}
----------------------------------------------------------------
this keyword in java :
----------------------
Whenever instance variable name and parameter variable name both are same then at the time of
instance variable initialization our runtime environment will provide more priority to parameter
variable/local variable, parameter variables are hiding the instance variables (Due to variable shadow)
To avoid the above said problen, Java software people introduced "this" keyword.
this keyword always refers to the current object and instance variables are the part of the object so by
using this keyword we can represent instance variable.
We cannot use this (non static member) keyword from static area (Static context).
2 files :
---------
[Link]
--------------
package [Link];
[Link]
------------------------
package [Link];
class Test
{
static int a = 100; //Class Variable OR Static Field
int b = 200; //Instance Variable OR Non static Field
}
---------------------------------------------------------------
How to print object properties by using toString() method :
-----------------------------------------------------------
If we want to print our object properties (Instance Variables) then we should generate(override) toString()
method in our class from Object class.
Now with the help of toString() method we need not to write any display kind of method to print the object
properties i.e instance variable.
In order to call this toString() method, we need to print the corresponding object reference by using
[Link]() statement.
2 files :
----------
[Link]
-------------
package [Link].to_string_demo;
@Override
public String toString()
{
return "Product [productId=" + productId + ", productName=" + productName + "]";
}
[Link]
-----------------
package [Link].to_string_demo;
}
--------------------------------------------------------------
25-10-2024
-----------
Role of instance variable while creating the Object :
-----------------------------------------------------
Whenever we create an object in java then a separate copy of all the instance variables will be created
with each and every object as shown in the program.[25-OCT]
package [Link].variable_copy_demo;
public class Test
{
int x = 100; //Non static field
++t1.x; --t2.x;
[Link](t1.x); //101
[Link](t2.x); //99
}
}
--------------------------------------------------------------
What is a static field ?
------------------------
It is a class level variable.
If a variable is declared with static modifier inside a class then it is called class variable OR static field.
A static field variable will be automatically initialized with default values and memory will be allocated
(even the variable is final) AT THE TIME OF LOADING THE CLASS INTO JVM MEMORY.
In order to access the static member, we need not to create an object, here class name is required.
---------------------------------------------------------------
Role of static variable with Object creation :
----------------------------------------------
Whenever we create an object then a single copy of static variable will be created for all the objects and
the same single copy of static variable will be sharable by all the objects as shown in the
program.[25-OCT]
package [Link].variable_copy_demo;
--d1.x; --d2.x;
[Link](d1.x); //98
[Link](d2.x); //98
}
}
If the value of the variable is different with respect to object then we should use instance variable OR non
static field.
Static Field :
---------------
If the value of the variable is common with respect to object
then we should use static field OR class variable.
Example1 :
---------
public class Student
{
int rollNumber; //NSV
String studentName; //NSV
String studentAddress//NSV
static String collegeName = "VIT"; //SV
static String courseName = "Java"; //SV
}
Example 2 :
------------
class Customer
{
long accountNumber; //NSV
String customerName; //NSV
long mobileNumber; //NSV
String customerAddress; //NSV
static String IFSCCode = "SBIHYD08590"; //SV
static String branchLocation = "Ameerpet"; //SV
}
Program :
----------
2 files :
---------
[Link]
-------------
package [Link].variable_copy_demo;
@Override
public String toString() {
return "Student [rollNumber=" + [Link] + ", studentName=" + [Link] + ",
studentAddress="
+ [Link] + ", College Name " + [Link] + ", Course Name " +
[Link]
+ " ]";
}
[Link]
-----------------
package [Link].variable_copy_demo;
[Link](raj);
[Link](priya);
[Link](scott);
}
--------------------------------------------------------------
Assignment :
-------------
Develop Bank and Customer application with valid SV and NSV
---------------------------------------------------------------
**What is Data Hiding ?
----------------------
Data hiding is nothing but declaring our data members with private access modifier so our data will not be
accessible from outer world that means no one can access our data directly from outside of the class.
*We should provide the accessibility of our data through methods so we can perform VALIDATION ON
DATA which are coming from outer world.
2 files :
----------
[Link]
---------------
package [Link].data_hiding;
}
[Link]
-----------------------
package [Link].data_hiding;
}
---------------------------------------------------------------
What is Constructor ?
---------------------
What is the advantage of writing constructor in our class ?
------------------------------------------------------------
If we don’t write a constructor in our program then variable initialization and variable re-initialization both
are done in two different lines.
If we write constructor in our program then variable initialization and variable re-initialization both are done
in the same line i.e at the time of Object creation. [26-OCT]
With Constructor approach, we need not to depend on method to re-initialize our instance variable with
user value.
---------------------------------------------------------------
Defination of Constructor :
---------------------------
If the name of the class and name of the method both are exactly same and It should not contain any
return type then it is called constructor.
The main purpose of constructor to initialize the object properties (Instance Variables) with user-defined
value.
Every class must contain at-least one constructor either implicitly added by compiler or explicitly written
by user.
Every time we create an object in java by using new keyword, at-least one constructor must be invoked.
Example :
package [Link];
class Student
{
public void Student() //Method
{
[Link]("I am Method");
}
A constructor may contain return keyword but not return keyword with value.
package [Link];
class Student
{
public Student()
{
[Link]("I am Constructor");
return;
}
A constructor is automatically called and executed at the time of creating the object.
================================================================
Types of constructor in java :
-------------------------------
We have 3 types of Constructors in java :
The access modifier of default constaructor would be same as class access modifier.
[Link]
--------------
public class Example
{
javac [Link]
[Link]
------------
public class Example
{
public Example() //default constructor
{
}
}
----------------------------------------------------------------
2) No Argument OR Parameter-less OR Non parameterized OR Zero
argument Constructor.
If a user defines a constructor inside a class without argument then it is called no argument constructor.
No argument constructor and default constructor, both look like same the only difference is, default
constructor means added by compiler and no argument constructor means written by user.
No argument constructor is not recommended to initialize our object properties because due to no
argument constructor all the object properties will be initialized with SAME VALUE as shown in the
program.
2 files :
----------
[Link]
-------------
package [Link];
@Override
public String toString()
{
return "Person [personId=" + personId + ", personName=" + personName + "]";
}
}
[Link]
---------------------------
package [Link];
[Link]("..............");
}
Note : Actually No argument constructor is used to initialize the object properties with default values.
---------------------------------------------------------------
Parameterized Constructor :
---------------------------
If we pass one or more argument to the constructor then it is called parameterized constructor.
By using parameterized constructor all the objects will be initialized with different values.
Example :
----------
public class Employee
{
int id;
String name;
@Override
public String toString() {
return "Dog [dogName=" + dogName + ", dogHeight=" + dogHeight + ", dogAge=" + dogAge + "]";
}
[Link]
------------------------------
package [Link];
}
---------------------------------------------------------------
What is setter and getter :
----------------------------
setter : Used to modify the existing object data.
getter : Used to read the private data from BLC class.
2 files :
----------
[Link]
--------------
package [Link].setter_getter;
@Override
public String toString()
{
return "Employee [employeeSalary=" + employeeSalary + "]";
}
}
[Link]
----------
package [Link].setter_getter;
[Link]([Link]()+10000);
[Link](scott);
FINAL CONCLUSION :
-------------------
Parameterized Constructor : To initialize the Object properties with user values.
Setter : To modify the existing object data.[Only one data at a time] OR Writing Operation
Getter : To read/retrieve private data value outside of BLC class. [Reading Operation]
----------------------------------------------------------------
28-10-2024
----------
*** What is Encapsulation
--------------------------
[Accessing our private data with public methods like setter and getter]
----------------------------------------------------------
Binding the private data with its associated method in a single unit is called Encapsulation.
Encapsulation ensures that our private data (Object Properties) must be accessible via public methods
like setter and getter.
It provides security because our data is private (Data Hiding) and it is only accessible via public methods
WITH PROPER DATA VALIDATION.
1) Declare all the data members with private access modifiers (Data Hiding OR Data Security)
2) Write public methods to perform read(getter) and write(setter) operation on these private data like
setter and getter.
Note : If we decalre all our data with private access modifier then it is called TIGHTLY ENCAPSULATED
CLASS. On the other hand if we declare our data other then private access modifier then it is called
Loosely Encapsulated class.
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentMarks=" +
studentMarks
+ ", studentAddress=" + studentAddress + "]";
}
[Link]
-----------------
package [Link].setter_getter;
}
--------------------------------------------------------------
Method return type as a class :
--------------------------------
While declaring a method in java, return type is compulsory.
As a method return type we have following options
3) Any class name/interface / enum / record we can take as a return type of the method.
Case 1 :
---------
package [Link].method_return_type;
Case 2 :
---------
package [Link].method_return_type;
Note : Here the return value depends upon the available constructor in the class.
----------------------------------------------------------------
What is a Factory Method :
--------------------------
If a method return type is class name menas it is returning the Object of the class then it is called Factory
Method.
---------------------------------------------------------------
2 files :
---------
[Link]
-------------
package [Link].method_return_type;
@Override
public String toString() {
return "Product [productId=" + productId + ", productName=" + productName + ", productPrice=" +
productPrice
+ "]";
}
}
[Link]
-----------------
package [Link].method_return_type;
In the avove program getProductObject() is providing only one product object so it is not recommended
because the main purpose of any method to provide re-usability as shown in the program below.
----------------------------------------------------------------
2 files :
---------
[Link]
---------
package [Link].method_return_type;
import [Link];
@Override
public String toString() {
return "Book [bookTitle=" + bookTitle + ", authorName=" + authorName + "]";
}
[Link]
-------------
package [Link].method_return_type;
import [Link];
[Link]();
}
}
--------------------------------------------------------------
29-10-2024
----------
What is Shallow and Deep copy in java :
----------------------------------------
Shallow Copy :
--------------
In Shallow copy, Only one Object will be created but the same object will be refered by multiple reference
variables.
If we modify the object properties by any of the reference variable then original object will be modified as
shown in the program.
2 files :
----------
[Link]
-------------
package [Link].shallow_copy;
@Override
public String toString()
{
return "Laptop [laptopBrand=" + laptopBrand + ", laptopPrice=" + laptopPrice + "]";
}
}
[Link]
---------------------
package [Link].shallow_copy;
[Link](laptop1);
[Link](laptop2);
}
-------------------------------------------------------------
Deep Copy :
-----------
In deep copy two different objects will be created, the 2nd object will copy the content of first object.
If we modify the object by using reference variable then only one object will be modified as shown below.
2 files :
----------
[Link]
-------------
package [Link].deep_copy;
public Product()
{
productId = 0;
productName = null;
}
@Override
public String toString() {
return "Product [productId=" + productId + ", productName=" + productName + "]";
}
[Link]
-------------------
package [Link].deep_copy;
[Link]("Before Modification...");
[Link](p1);
[Link](p2);
[Link]("After Modification...");
[Link](222);
[Link]("Camera");
[Link](p1);
[Link](p2);
Pass by value means we are sending the copy of orginal data to the method.
package [Link].pass_by_value;
}
--------------------------------------------------------------
package [Link].pass_by_value;
class Customer
{
private double customerBill = 12000;
Output : 18000
--------------------------------------------------------------
package [Link].pass_by_value;
class Customer
{
private double customerBill = 12000;
Output : 12000
==============================================================
What is Garbage Collector in java -----------------------------------
It is an automatic memory management technique in java.
In C++ language, A programmer is responsible to allocate as well as de-allocate the memory otherwise
we will get OutOfMemoryError.
In java language, Programmer is only responsible to allocate the memory, Memory de-allocation is
automatically done by garbage collector.
Garbage Collector is a daemon thread which is responsible to delete the objects from the HEAP Memory.
Actually It scans the heap memory and identifying which objects are eligible for Garbage Collector.[THE
OBJECTS WHICH DOES NOT CONTAIN ANY REFERENCES ONLY THOSE OBJECTS ARE ELIGIBLE
FOR GC]
It internally uses an algorithm called Mark and Sweep algorithm to delete the un-used objects.
As a developer we can also explicitly call garbage collector by writing the following code
[Link]();
==============================================================
How many ways we can make an object eligible for Garbage Collector :
---------------------------------------------------------------
There are 3 ways we can make an object eligible for GC.
Earlier e3 variable was poting to Employee object after that a new Employee Object is created which is
pointing to another memory location so the first object is eligible for GC.
==============================================================
30-10-2024
-----------
Memory in java :
------------------
In java, whenever we create an object then Object and its content (properties and behavior) are stroed in
a special memory called HEAP Memory. Garbage collector visits heap memory only.
All the local variables and parameters variables are executed in Stack Frame and available in Stack
Memory.
--------------------------------------------------------------
HEAP and STACK Diagram for [Link] :
------------------------------------------------
class Customer
{
private String name;
private int id;
m1(c);
[Link]([Link]());
}
[Link](9);
[Link]([Link]());
}
}
//Output 9 5
===============================================================
HEAP and STACK Diagram for [Link]
---------------------------------------
public class Sample
{
private Integer i1 = 900;
s1 = null;
//GC [4 objects 1000x,2000x, 5000x and 6000x are eligible for GC]
[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 Digram for [Link]
------------------------------------
public class Test
{
Test t;
int val;
t2.t = t3;
t3.t = t4;
t1.t = t2.t;
t2.t = t4.t;
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
---------------------------------------------------------------
01-11-2024
----------
HEAP and STACK Diagram for [Link]
--------------------------------------------
public class Employee
{
int id = 100;
[Link] = val;
update(e1);
[Link]([Link]);
[Link] = 900;
[Link]([Link]);
[Link]([Link]);
}
t1.m1(t2);
[Link](t1.x+"... "+t1.y);
[Link](t2.x+"... "+t2.y);
t2.m1(t1);
[Link](t1.x+"... "+t1.y);
[Link](t2.x+"... "+t2.y);
t1.m1(t1);
[Link](t1.x+"... "+t1.y);
[Link](t2.x+"... "+t2.y);
t2.m1(t2);
[Link](t1.x+"... "+t1.y);
[Link](t2.x+"... "+t2.y);
}
}
===============================================================
The following program explains how to copy the content of Employee object to initialize Manager class
properties :
3 files :
----------
[Link]
--------------
package [Link].copy_constructor;
@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + "]";
}
[Link]
-------------
package [Link].copy_constructor;
@Override
public String toString() {
return "Manager [managerId=" + managerId + ", managerName=" + managerName + "]";
}
[Link]
--------------------
package [Link].copy_constructor;
public class CopyConstructor
{
public static void main(String[] args)
{
Employee e1 = new Employee(111, "Scott");
Manager m1 = new Manager(e1);
[Link](m1);
}
Note : Here by using Employee class properties, we are initializing the Manager class properties.
The following program explains how to copy the content of one object of same class to another object of
same class only.
[Link]
-------------
package [Link].copy_constructor;
@Override
public String toString() {
return "Product [productId=" + productId + ", productName=" + productName + "]";
}
}
[Link]
-------------------------
package [Link].copy_constructor;
}
===============================================================
Constructor Overloading :
-------------------------
In the same class if we write more than one constructor where parameter must be different (If same,
compilation error will be generated) then it is called constructor Overloading.
In order to call overloaded constructor we need not to create multiple objects, we can call all the
overloaded constructors with one object only by using this() [this of]
this() is used to call current class overloaded constrcutor and it must be FIRST STATEMENT OF THE
CONSTRUCTOR BODY.
--------------------------------------------------------------
[Link]
---------------
package [Link].constructor_overloading;
public Calculate(int x)
{
this(100,200);
[Link]("Square of "+x+" is :"+(x*x));
}
}
package [Link].constructor_overloading;
}
--------------------------------------------------------------
02-11-2024
----------
What is an instance block OR instance initializer in java ?
------------------------------------------------------------
It is a special block in java which is automatically executed at the time of creating the Object.
Example :
{
//Instance OR Non static block
}
If a constructor contains first line as a super() statement then only compiler will add instance block in the
2nd line of constructor otherwise it will not be added by the compiler.
If constructor contains super() then non static block will be executerd before the body of the constructor.
The main purpose of instance block to initialize the instance variables (So It is called Instance Iniatilizer)
of the class OR to write a common logic which will be applicable to all the objects.
If a class contains multiple non static blocks then it will be executed according to the order [Top to
bottom]
Instance initializer must be executed normally that menas we can’t interrupt the execution flow of any
initializer hence we can’t write return statement inside non static block.
If a user defines non static block after the body of the constructor then compiler will not placed in the 2nd
line of the constructor. It will be executed as it is because compiler will search the NSB in the class level.
---------------------------------------------------------------
package [Link].instance_block;
class Sample
{
{
[Link]("Instance OR Non static block");
}
}
class Demo
{
public Demo()
{
[Link]("Demo class Constructor");
}
{
[Link]("NSB");
}
class Foo
{
Foo()
{
[Link]("No Argument Constructor");
}
Foo(int x)
{
[Link]("Parameterized Constructor");
}
{
[Link]("NSB");
}
Note : NSB will be placed inside all the constructors which contains super() in the first line.
--------------------------------------------------------------
package [Link].instance_block;
class Student
{
public Student()
{
this(101,"Scott");
[Link]("No Argument Constructor");
}
{
[Link]("Object creation is in process");
}
}
NOte : NSB will not be added to the constructor which contains this() as a first line of constructor.
--------------------------------------------------------------
package [Link].instance_block;
class Test
{
int x;
public Test()
{
x = 590;
[Link]("x value is :"+x);
}
{
x = 190;
[Link]("x value is :"+x);
}
}
class Customer
{
private double bill;
public Customer()
{
bill = 10000;
[Link](bill);
}
{
bill = 1000;
[Link](bill);
}
{
bill = 2000;
[Link](bill);
}
{
bill = 3000;
[Link](bill);
}
{
bill = 4000;
[Link](bill);
}
class Manager
{
int x = 10;
{
[Link]("Instance Initializer");
//return;
}
class Hello
{
public Hello()
{
[Link]("Constructor");
{
[Link]("NSB2");
}
}
{
[Link]("NSB1");
}
}
}
Note : If we wtite NSB after the body of the constructor then it will be executed as it is.
---------------------------------------------------------------
All the instance variables are initialized in the following order during the life cycle :
1) It will initialized with default value at the time of Object
creation. [new Demo(); Demo class instance variable will be initialized with default value, init method is
working internally]
2) Now control will verify whether, we have initailized at the time of variable declaration or not.
5) Now control will verify whether, we have initailized in the method body or not but it is not recommended
because Object is already created, we need to call the method explicitly, It is not the part of the object.
Default value [new keyword] => At the time of declaration => in the body of non static block => in the body
of constructor => Inside method body [Not Recommended]
package [Link].nsv_life_cycle;
class Test
{
int x = 100; //STEP 1
{
x = 200; //STEP 2
}
Test()
{
x = 300; //STEP 3
}
}
===============================================================
12-11-2024
----------
What is blank final field in java ?
------------------------------------
If a final instance variable is not initialized at the time of declaration then it is called blank final field.
final int A ; //Blank final field
A blank final field can’t be initialized by default constrcutor as shown in the program.
class Test
{
final int A; //Blank final field
A blank final field must be explicitly initialized by the user till the execution of constructor body[Till Object
creation]. It can be iniatialized in the following two places :
A blank final must be iniatilized explicitly by user in all the constructors available in the class.
----------------------------------------------------------------
package [Link].blank_final_field;
class Sample
{
final int x;
{
x = 123;
}
public Sample()
{
// x = 234;
}
}
}
}
A blank final field must be initialized by the non static block constructor body
===============================================================
package [Link].blank_final_field;
class Test
{
final int x; //blank final field
{
m1();
x = 100;
}
public Alpha()
{
x = 100;
[Link](x);
}
public Alpha(int y)
{
x = y;
[Link](y);
}
}
public class Test
{
public static void main(String[] args)
{
Alpha a1 = new Alpha();
Alpha a2 = new Alpha(200);
}
a) IS-A Relation
b) HAS-A Relation
IS-A Relation :
---------------
class Car
{
}
class Ford extends Car //[Ford IS-A car ]
{
}
HAS-A Relation :
-----------------
class Engine
{
}
class Car
{
private Engine engine; //Car HAS-A Engine.
}
It is one of the most imporatnt feature of OOPs which provides "CODE REUSABILITY".
Using inheritance mechanism the relationship between the classes is parent and child. According to Java
the parent class is called super class and the child class is called sub class.
Inheritance provides IS-A relation between the classes. IS-A relation is tightly coupled relation (Blood
Relation) so if we modify the super class content then automatically sub class content will also modify.
Inheritance provides us hierarchical classification of classes, In this hierarchy if we move towards upward
direction more generalized properties will occur, on the other hand if we move towards downwand more
specialized properties will occur.
--------------------------------------------------------------------
Types of Inheritance in java :
------------------------------
Java supports 5 types of inheritance :
class Father
{
public void house()
{
[Link]("2 BHK house");
}
}
class Son extends Father
{
public void car()
{
[Link]("Audi car");
}
}
}
---------------------------------------------------------------------
//Program on Single Level Inheritance :
---------------------------------------
package [Link].single_level_inheritance;
class Super
{
private int x,y;
}
class Sub extends Super
{
public void showData()
{
[Link]("x value is :"+getX());
[Link]("y value is :"+getY());
}
}
Note : By default private varaible of super class is not available to sub class, getter is required.
--------------------------------------------------------------
In order to initialize the super class properties we should use super keyword in the sub class as a first line
of constructor.
In order to access super class variable i.e super class memory, we should use super keyword as shown
in the program.
[Link]
------------------
package [Link].super_keyword;
class Father
{
protected double balance = 50000;
}
class Daughter extends Father
{
protected double balance = 18000; //Variable Hiding
}
public class SupervarDemo {
Note :
-------
From the above program, We will get two concepts
1) Compiler and JVM both will search the member of the class
from bottom to top
2) In order to access super class method (super class memory) we
should use super keyword in the sub class method body.
---------------------------------------------------------------------
3) To access the super class constructor (Constructor Chaining) :
----------------------------------------------------------------
Whenever we write a class in java and we don’t write any kind of constructor to the class then the java
compiler will automatically add one default no argument constructor to the class.
THE FIRST LINE OF ANY CONSTRUCTOR IS RESERVERD EITHER FOR super() or this() keyword
that means first line of any constructor is used to call another constructor of either same class OR super
class.
In the first line of any constructor if we don’t specify either super() or this() then the compiler will
automatically add super() to the first line of constructor.
Now the purpose of this super() [added by java compiler], to call the default constructor or No-Argument
constructor of the super class.
In order to call the constructor of super class as well as same class, we have total 4 cases.
Case 1:
-------
super() : Automatically added by java compiler to maintain the
hierarchy in the first line of the Constructor. It
is used to call default OR no argument constructor
of super class.
[Link]
----------------------
class Alpha
{
public Alpha()
{
super();
[Link]("Alpha class");
}
}
class Beta extends Alpha
{
public Beta()
{
super();
[Link]("Beta class");
}
}
public class CallingNoArgument
{
public static void main(String[] args)
{
Beta b = new Beta();
}
---------------------------------------------------------------------
Case 2 :
---------
super("Java") : Must be explicitly written by user in the
first line of constructor [not inside a method]. It is used to call the parameterized constructor of
super class.
package [Link].constructor_test;
class Super
{
public Super(String str)
{
[Link]("My Institute name is :"+str);
}
}
class Sub extends Super
{
public Sub()
{
super("NIT");
[Link]("No argument constructor of sub class");
}
}
public class ParameterizedConstructor {
}
--------------------------------------------------------------------
Program that describes default constructor and super() will be added by the compiler.
[Link]
---------------------
package [Link].super_demo;
class Alpha
{
public Alpha()
{
[Link]("Alpha class Constructor!!!");
}
}
class Beta extends Alpha
{}
}
-------------------------------------------------------------------
Case 3 :
--------
this() : Must be explicitly written by user in the
first line of constructor. It is used to call
no argument constructor of current class.
package [Link].constructor_test;
class Super
{
public Super()
{
[Link]("No argument constructor of Super class");
}
}
---------------------------------------------------------------------
Case 4 :
---------
this(15) : Must be explicitly written by user in the
first line of constructor. It is used to call
parameterized constructor of current class.
package [Link].constructor_test;
class Base
{
public Base()
{
this(15);
[Link]("No Argument Constructor of Base class");
}
public Base(int x)
{
[Link]("Parameterized Constructor of Base class :"+x);
}
}
}
=====================================================================
Program on super keyword :
---------------------------
package [Link].constructor_test;
class Shape
{
protected int x;
public Shape(int x)
{
this.x = x;
[Link]("x value is :"+this.x);
}
}
}
--------------------------------------------------------------------
15-11-2024
-----------
//Program on Hierarchical Inheritance
Note :- format is non static method of DecimalFormat class which accpts double as a parameter, and
return type of this method is
String.
package [Link].hierarchical_demo;
import [Link];
import [Link];
class Shape
{
protected int x;
public Shape(int x)
{
this.x = x;
[Link]("x value is :"+x);
}
}
class Circle extends Shape
{
final double PI = 3.14;
[Link]();
}
--------------------------------------------------------------------
//Program on Single Level Inheritance :
---------------------------------------
package [Link];
class TemporaryEmployee {
protected int employeeId;
protected String employeeName;
protected String employeeAddress;
@Override
public String toString() {
return "PermanentEmployee [employeeId=" + employeeId + ", employeeName=" + employeeName + ",
employeeAddress="
+ employeeAddress + ", department=" + department + ", designation=" + designation + "]";
}
}
--------------------------------------------------------------------
//Program on Hierarchical Inheritance :
package [Link].hierarchical_demo;
class Employee
{
protected double salary;
public Employee(double salary)
{
super();
[Link] = salary;
}
}
class Developer extends Employee
{
public Developer(double salary)
{
super(salary);
}
@Override
public String toString()
{
return "Developer [salary=" + salary + "]";
}
@Override
public String toString() {
return "Designer [salary=" + salary + "]";
}
}
public class HierarchicalDemo1 {
}
---------------------------------------------------------------------
Example :
Here the drawback is all objects will be initialized with same value.
-----------------------------------------------------------------------
Here we are getting different values with respect to object but here the program becomes more
complex.
---------------------------------------------------------------
3) By using methods :
Here the Drawback is initialization and re-initialization both are done in two different lines so
Constructor introduced.
----------------------------------------------------------------------
4) By using Constructor
This is the best way to initialize our instance variable because variable initialization and variable
re-initialization both will be done in the same line as well as all the objects will be initialized with different
values.
public Test()
{
[Link](x); //100
[Link](y); //200
}
//Instance block
{
x = 100;
y = 200;
}
------------------------------------------------------------------
5) By using super keyword :
class Super
{
int x,y;
new Sub();
=====================================================================
**Why java does not support multiple Inheritance ?
--------------------------------------------------
Multiple Inheritance is a situation where a sub class wants to inherit the properties two or more than two
super classes.
In every constructor we have super() or this(). When compiler will add super() to the first line of the
constructor then we have an ambiguity issue that super() will call which super class constructor as shown
in the diagram [15-NOV-24]
It is also known as Diamond Problem in java so the final conclusion is we can’t achieve multiple
inheritance using classes but same we can achieve by using interface [interface does not contain any
constructor]
---------------------------------------------------------------------
18-11-2024
----------
Access modifiers in java :
---------------------------
In order to define the accessibility level of the class as well as member of the class we have 4 access
modifiers :
In java outer class can be declared as public, abstract, final, sealed and non-sealed only.
default :-
----------
It is an access modifier which is less restrictive than private. It is such kind of access modifier whose
physical existance is not avaialble that means when we don’t specify any kind of access modifier before
the class name, variable name or method name then by default it would be default.
As far as its accessibility is concerned, default members are accessible within the same folder(package)
only. It is also known as private-package modifier.
protected :
------------
It is an access modifier which is less restrictive than default because the member declared as protected
can be accessible from the outside of the package (folder) too but by using inheritance concept.
2 files :
----------
[Link] [It is available in [Link].m1 package]
----------------------------------------------------
package [Link].m1;
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.
In order to load the .class file into JVM Memory, It uses an algorithm called "Delegation Hierarchy
Algoroithm".
1) LOADING
2) LINKING
3) INITIALIZATION
LOADING :
---------
In order to load the required .class file, JVM makes a request to class loader sub system. The class
loader sub system follows delegation hierarchy algorithm to load the required .class files from different
areas.
To load the required .class file we have 3 different kinds of class loaders.
It has the highest priority becuase Bootstrap class loader is the super class for Platform class loader.
It is the sub class of Bootstrap class loader and super class of Application class loader so it has more
priority than Application class loader.
[If we want to compile more than one java file at a time then the command is : javac *.java]
It has the lowest priority because it is the sub class Platform class loader.
Bootstrap class loader will load the .class file from lib folder([Link]) and then by pass the request back to
extension class loader, Extension class loader will load the .class file from ext folder(*.jar) and by pass the
request back to Application class loader, It will load the .class file from environment variable into JVM
memory.
Note :-
------
If all the class loaders are failed to load the .class file into JVM memory then we will get a Runtime
exception i.e [Link].
Note : Always Super class will be loaded before sub class loading.
[A child cannot exist without parent]
==================================================================
What is Method Chaning in java ?
--------------------------------
It is a technique through we call multiple methods in a single
statement.
In this method chaining, always for calling next method we depend upon last method return type.
The final return type of the method depends upon last method call as shown in the program.
[Link]
--------------------------
package [Link].method_chaining;
[Link]
-------------------------
package [Link].method_chaining;
}
---------------------------------------------------------------
20-11-2024
---------
Role of [Link] class in class loading :
----------------------------------------------------
There is a predefined class called Class available in [Link] pacakge.
In JVM memory whenever we load a class then it is loaded in special memory called Method Area and
retutn type is [Link] class object.
package [Link].method_area;
class Employee{}
class Student{}
class Sample{}
cls = [Link];
[Link]([Link]());
cls = [Link];
[Link]([Link]());
}
----------------------------------------------------------------------
WAP that describes Application class loader is responsible to
load the user defined .class file
[Link] class has provided a predefined non static method called getClassLoader(), the return
type of this method
is ClassLoader class.[Factory Method]
This method will provide the class loader name which is responsible to load the .class file into JVM
Memory.
[Link]
-------------------------------
package [Link].method_area;
class Customer
{
WAP to describe that Platform class loader is the super class for
application class loader.
getClassLoader() method return type is ClassLoader so further we can call any method of ClassLoader
class, ClassLoader class
has provided a method called getParent() whose return type is again ClassLoader only.
[Link]
-----------------------------
package [Link].method_area;
class Foo
{
}
public class PlatformClassLoaderDemo
{
public static void main(String[] args)
{
[Link]("Super class of application class loader is :");
[Link]([Link]().getParent());
}
------------------------------------------------------------------------
//Program to show Bootstarp class loader
package [Link].method_area;
class Foo
{
}
public class PlatformClassLoaderDemo
{
public static void main(String[] args)
{
[Link]("Super class of platform class loader is :");
[Link]([Link]().getParent().getParent());
Note :- Here we will get the output as null because it is built in class loader for JVM which is used for
internal purpose (loading only predefined .class file) so implementation is not provided hence we are
getting null.
-----------------------------------------------------------------------
Linking Phase :
---------------
verify :-
-------
It ensures the correctness of the .class files, If any suspicious activity is there in the .class file then It will
stop the execution immediately by throwing a runtime error i.e [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.
prepare :
---------
[Static variable memory allocation + static variable initialization with default value even the variable is
final]
It will allocate the memory for all the static data members, here all the static data member will get the
default values so if we have static int x = 100; then for variable x memory will be allocated (4 bytes) and
now it will initialize with default value i.e 0, even the variable is final.
Here, t is a static reference variable so for t variable (reference variable) memory will be allocated as per
JVM implementation i.e for 32 bit JVM (4 bytes of Memory) and for 64 bit (8 bytes of memory) and
initialized with null.
Resolve :
---------
All the symbolic references (like #7) will be converted into direct references OR actual reference.
Note :- By using above command we can read the internal details of .class file.
-----------------------------------------------------------------------
Initialization :
-----------------
Here class initialization will take place. All the static data member will get their actual/original value and
we can also use static block for static data member initialization.
Here, In this class initialization phase static variable and static block is having same priority so it will
executed according to the order.(Top to bottom)
-----------------------------------------------------------------------
21-11-2024
-----------
Static Block in java :
-----------------------
It is a special block in java which is automatically executed at the time of loading the .class file.
Example :
static
{
Static blocks are executed only once because in java we can load the .class files only once.
If we have more than one static block in a class then it will be executed according to the order [Top to
bottom]
The main purpose of static block to initialize the static data member of the class so it is also known as
static initializer.
In java, a class is not loaded automatically, it is loaded based on the user request so static block will not
be executed everytime, It depends upon whether class is loaded or not.
static blocks are executed before the main or any static method.
A static blank final field must be initialized inside the static block only.
static
{
A = 100;
}
If we don’t declare static variable before static block body execution then we can perform write
operation(Initialization is possible due to prepare phase) but read operation is not possible directly
otherwise we will get an error Illegal forward reference, It is possible with class name bacause now
compiler knows that variable is coming from class area OR Method area.
-----------------------------------------------------------------------
//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 ");
}
}
Here [Link] file is not loaded into JVM Memory so static block of Foo class will not be executed.
--------------------------------------------------------------
class Test
{
static int x;
static
{
x = 100;
[Link]("x value is :"+x);
}
static
{
x = 200;
[Link]("x value is :"+x);
}
static
{
x = 300;
[Link]("x value is :"+x);
}
}
public class StaticBlockDemo1
{
public static void main(String[] args)
{
[Link]("Main Method");
[Link](Test.x);
}
}
Note : If a class contains more than 1 static block then it will be executed from top to bottom.
--------------------------------------------------------------
class Foo
{
static int x;
static
{
[Link]("x value is :"+x);
}
}
static
{
m1();
a = 100;
[Link]("User Value :"+a);
}
}
public class StaticBlockDemo3
{
public static void main(String[] args)
{
[Link]("a value is :"+Demo.a);
}
}
A static black final field must be initailized inside static block only and it also contains default value.
------------------------------------------------------------------
class A //AD BC EF
{
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();
}
}
------------------------------------------------------------------
22-11-2024
-----------
//illegal forward reference
class Demo
{
static
{
i = 100; //valid
}
static int i;
}
public class StaticBlockDemo5
{
public static void main(String[] args)
{
[Link](Demo.i);
}
}
------------------------------------------------------------------
class Demo
{
static
{
i = 100;
//[Link](i); //Invalid
[Link](Demo.i); //Valid
}
static int i;
}
Note : All the initializer must be executed normally so we can’t write return statement OR any transfer
statement.
------------------------------------------------------------------
public class StaticBlockDemo8
{
final static int x; //Blank static final field
static
{
m1();
x = 15;
}
public static void m1()
{
[Link]("Default value of x is :"+x);
}
static
{
[Link]("static block");
}
{
[Link]("Non static block");
}
Test()
{
[Link]("No Argument Constructor");
}
Note : First non static block, constructor then only static block will be executed.
==================================================================
Variable Memory Allocation and Initialization :
-------------------------------------------------
1) static field OR Class variable :
-----------------------------------
Memory allocation done at prepare phase of class loading and initialized with default value even variable
is final.
It will be initialized with Original value (If provided by user at the time of declaration) at class initialization
phase.
When JVM will shutdown then during the shutdown phase class will be un-loaded from JVM memory so
static data members are destroyed. They have long life.
When object is eligible for GC then object is destroyed and all the non static data memebers are also
destroyed with corresponding object. It has less life in comparison to static data members becuase they
belongs to object.
3) Local Variable
------------------
Memory allocation done at stack area (Stack Frame) and developer is responsible to initialize the variable
before use. Once metod execution is over, It will be deleted from stack Frame henec it has shortest life.
4) Parameter variable
----------------------
Memory allocation done at stack area (Stack Frame) and end user is responsible to pass the value at
runtime. Once metod execution is over, It will be deleted from stack Frame henec it has shortest life.
It was possible to write a java program without main method till JDK 1.6V. From JDK 1.7v onwards, at the
time of loading the .class file JVM will verify the presence of main method in the .class file. If main method
is not available then it will generate a runtime error that "main method not found in so so class".
------------------------------------------------------------------
How many ways we can load the .class file into JVM memory :
-----------------------------------------------------------
There are so many ways to load the .class file into JVM memory but the following are the common
examples :
javac [Link]
java Test
Here we are making a request to class loader sub system to load [Link] file into JVM memory
2) By using Constructor (new keyword at the time of creating object).
4) By using inheritance
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]("Main Method");
new Demo();
//[Link](Demo.x);
}
}
------------------------------------------------------------------
//Program that describes whenever we try to load sub class, first of all super class will be loaded. [before
parent, child can’t exist]
class Alpha
{
static
{
[Link]("Static Block of super class Alpha!!");
}
}
class Beta extends Alpha
{
static
{
[Link]("Static Block of Sub class Beta!!");
}
}
class InheritanceLoading
{
public static void main(String[] args)
{
new Beta();
}
}
------------------------------------------------------------------
Loading the .class file by using Reflection API :
-------------------------------------------------
[Link] class has provided a predefined static factory method called forName(String className),
It is mainly used to load the given .class file at runtime, The return type of this method is [Link]
class Demo
{
static
{
[Link]("static block");
}
}
public class Main
{
public static void main(String [] args) throws ClassNotFoundException
{
[Link]("Demo");
}
}
-------------------------------------------------------------------
loading .class file by using [Link](String className) at runtime using Eclipse IDE :
package [Link].static_block;
class Ravi
{
static
{
[Link]("Static Block of Ravi class");
}
}
Note : In eclipse IDE a class is represented by (FQN) Fully Qualified Name (Package Name + class
name)
-------------------------------------------------------------------
** What is the difference between [Link] and
[Link]
[Link] :-
-----------------------------------------
It occurs when we try to load the required .class file at RUNTIME by using [Link](String
className) statement or loadClass() static of ClassLoader class and if the required .class file is not
available at runtime then we will get an exception i.e [Link]
Note :- It does not have any concern at compilation time, at run time, JVM will simply verify whether the
required .class file is available or not available.
package [Link].static_block;
class Ravi
{
static
{
[Link]("Static Block of Ravi class");
}
}
Note : In the above program we will get get [Link] because Ravi class is not
identified by Application class loader, In Eclise IDE Fully Qualified Name is reqd.
-------------------------------------------------------------------
[Link] :
--------------------------------
It occurs when the class was present at the time of COMPILATION but at runtime the required .class file
is not available(manualy deleted by user ) Or it is not available in the current directory (Misplaced) then
we will get a runtime error i.e [Link].
class Hello
{
public void greet()
{
[Link]("Hello Batch 39");
}
}
public class NoClassDefFoundErrorDemo
{
public static void main(String[] args)
{
Hello h = new Hello();
[Link]();
}
}
Note : 1) After compilation delete [Link] file from the current folder and execute the program, we will
get [Link]
All the static members (static variable, static block, static method, static nested inner class) are
loaded/executed at the time of loading the .class file into JVM Memory.
At class loading phase object is not created because object is created in the 2nd phase i.e Runtime data
area so at the TIME OF EXECUTION OF STATIC METHOD AT CLASS LOADING PAHSE, NON
STATIC VARIABLE WILL NOT BE AVAILABLE henec we can’t access non static variable from static
context[static block, static method and static nested inner class]
[Link]
----------
public class Test
{
int x = 100;
class Test
{
private int x;
public Test(int x)
{
this.x = x;
}
===================================================================
Accessing variable of Sub class and Super class by using static method.
package [Link];
class Super
{
protected int x = 100;
}
class Sub extends Super
{
protected int x = 200; //Variable Hiding
===================================================================
25-11-2024
----------
Runtime Data Areas :
---------------------
It is also known as Memory Area.
Once a class is loaded then based on variable type method type it is divided into different memory areas
which are as follows :
1) Method Area
2) HEAP Area
3) Stack Area
4) PC Register
5) Native Method Stack
Method Area :
-------------
Whenever a class is loaded then the class is dumpped inside method area and returns [Link]
class.
It provides all the information regarding the class like name of the class, name of the package, static and
non static fields available in the class, methods available in the class and so on.
We have only one method area per JVM that means for a single JVM we have only one Method area.
This Method Area OR Class Area is sharable by all the objects.
--------------------------------------------------------------
Program to Show From Method Area we can get complete information of the class. (Reflection API)
2 files :
---------
[Link]
-----------
package [Link].class_info;
import [Link];
[Link]
--------------------------
package [Link].class_info;
import [Link];
import [Link];
count = 0;
Field[] fields = [Link]();
javac [Link]
java ClassInformationDemo FQN of the class
Note :- getDeclaredMethods() is a predefined non static method available in [Link] class , the
return type of this method is Method array where Method is a predefined class available in
[Link] sub package.
getDeclaredFields() is a predefined non static method available in [Link] class , the return type
of this method is Field array where Field is a predefined class available in [Link] sub package.
Field and Method both the classes are providing getName() method to get the name of the field and
Method.
=====================================================================
HEAP AREA :
-----------
Whenever we create an object in java then the properties and behavior of the object are strored in a
special memory area called HEAP AREA.
Whenever we call a method in java then internally one stack Frame will be created to hold method related
information.
Everytime we create a thread in java then JVM will create a separate Runtime Stack.[Multithreading]
=====================================================================
HEAP and STACK Diagram for [Link]
------------------------------------
class Alpha
{
int val;
ar[0] = am1;
[Link](ar[0].val);
[Link](ar[1].val);
}
return fa;
}
}
---------------------------------------------------------------------
26-11-2024
----------
PC Register :
-------------
It stands for Program counter Register.
In order to hold the current executing instruction of running thread we have separate PC register for each
and every thread.
----------------------------------------------------------------
Native Method Stack :
----------------------
Native method means, the java methods which are written by using native languages like C and C++. In
order to write native method we need native method library support.
Native method stack will hold the native method information in a separate stack.
---------------------------------------------------------------------
Execution Engine : [Interpreter + JIT Compiler]
Interpreter
------------
In java, JVM contains an interpreter which executes the program line by line. Interpreter is slow in nature
because at the time of execution if we make a mistake at line number 9 then it will throw the execption at
line number 9 and after solving the execption again it will start the execution from line number 1 so it is
slow in execution that is the reason to boost up the execution java software people has provided JIT
compiler.
JIT Compiler :
--------------
It stands for just in time compiler. The main purpose of JIT compiler to boost up the execution so the
execution of the program will be completed as soon as possible.
JIT compiler holds the repeated instruction like method signature, variables, native method code and
make it available to JVM at the time of execution so the overall execution becomes very fast.
=====================================================================
HAS-A Relation :
----------------
If we use any class (Engine class) as a property to another class (Car class) then it is called HAS-A
relation.
class Engine
{
}
class Car
{
private Engine engine; //HAS-A relation
}
Association :
---------------
Association is a connection between two separate classes that can be built up through their Objects.
The association builds a relationship between the classes and describes how much a class knows about
another class.
This relationship can be unidirectional or bi-directional. In Java, the association can have one-to-one,
one-to-many, many-to-one and many-to-many relationships.
Example:-
One to One: A person can have only one PAN card
One to many: A Bank can have many Employees
Many to one: Many employees can work in single department
Many to Many: A Bank can have multiple customers and a customer can have multiple bank accounts.
3 files :
---------
[Link]
-------------
package [Link];
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentMarks=" +
studentMarks
+ "]";
}
[Link]
-------------
package [Link];
import [Link];
if(id == [Link]())
{
[Link](obj);
}
else
{
[Link]("Sorry! No such student with given id");
}
[Link]();
[Link]
----------------------
package [Link];
}
---------------------------------------------------------------------
Composition (Strong reference) :
--------------------------------
Composition in Java is a way to design classes such that one class contains an object of another class. It
is a way of establishing a "HAS-A" relationship between classes.
Composition represents a strong relationship between the containing class and the contained [Link] the
containing object (Car object) is destroyed, all the contained objects (Engine object) are also destroyed.
A car has an engine. Composition makes strong relationship between the objects. It means that if we
destroy the owner object, its members will be also destroyed with it. For example, if the Car is destroyed
the engine will also be destroyed as well.
Program Guidelines :
--------------------
One object can’t exist without another object
We will not create two separate objects
3 files :
-----------
[Link]
-----------
package [Link];
@Override
public String toString() {
return "Engine [engineType=" + engineType + ", horsePower=" + horsePower + "]";
}
[Link]
---------
package [Link];
@Override
public String toString()
{
return "Car [carName=" + carName + ", carModel=" + carModel + ", engine=" + engine + "]";
}
[Link]
--------------------
package [Link];
}
---------------------------------------------------------------------
Aggregation (Weak Referance) :
------------------------------
Aggregation in Java is another form of association between classes that represents a "HAS-A"
relationship, but with a weaker bond compared to composition.
In aggregation, one class contains an object of another class, but the contained object can exist
independently of the container. If the container object is destroyed, the contained object can still exist.
[Link]
-------------
package [Link];
@Override
public String toString() {
return "College [collegeName=" + collegeName + ", collgeLocation=" + collgeLocation + "]";
}
[Link]
--------------
package [Link];
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" + studentName + ", collge=" + collge + "]";
}
[Link]
----------------------
package [Link];
[Link](s1);
[Link](s2);
[Link](s3);
Note :- IS-A relation is tightly coupled relation so if we modify the content of super class, sub class
content will also modify but in HAS-A realtion we are accessing the properties of another class so we are
not allowed to modify the content, we can access the content or Properties.
=====================================================================
27-11-2024
----------
Description of [Link]() :
-------------------------------------
public class System
{
public final static [Link] out = null; //HAS-A Relation
}
[Link]();
Internally [Link]() creates HAS-A relation because System class contains a predefined class
called [Link] as shown in the above example.
package [Link].s_o_p;
class Test
{
static final String str = "Hyderabad";
}
}
---------------------------------------------------------------------
***Polymorphism :
-----------------
Poly means "many" and morphism means "forms".
In our real life a person or a human being can perform so many task, in the same way in our programming
languages a method or a constructor can perform so many task.
Eg:-
In static polymorphism, compiler has very good idea that which method is invoked depending upon
METHOD PARAMETER.
Here the binding of the method is done at compilation time so, it is known as early binding.
2) Dynamic Polymorphism
-----------------------
The polymorphism which exist at runtime is called Dynamic polymorphim Or Runtime Polymorphism.
*Here compiler does not have any idea about method calling, at runtime JVM will decide which method
will be invoked depending upon CLASS TYPE OBJECT.
Here method binding is done at runtime so, it is also called Late Binding.
====================================================================
Method Overloading :
--------------------
Writing two or more methods in the same class or even in the super and sub class in such a way that the
method name must be same but the argument must be different.
While Overloading a method we can change the return type of the method.
If parameters are same but only method return type is different then it is not an overloaded method.
Method overloading is possible in the same class as well as super and sub class.
While overloading the method the argument must be different otherwise there will be ambiguity problem.
Method Overloading allows us to write two methods with same name but differ in:
1. Number of parameters
2. Data type of parameters
3. Sequence of data type of parameters(int -long and long int)
IQ :
----
Can we overload the main method/static method ?
Yes, we can overload the main method OR static method but the execution of the program will start from
main method which accept String [] array as a parameter.
Note :- The advantage of method overloading is same method name we can reuse for different
functionality for refinement of the method.
Example :
----------
public void makePayment(Cash c)
{
}
public void makePayment(UPI c)
{
}
public void makePayment(CreditCard c)
{
}
-------------------------------------------------------------------
28-11-2024
----------
Program on Constructor Overloading :
------------------------------------
package [Link];
class Calculate
{
public Calculate()
{
this(10,20);
}
public Calculate(int x, int y)
{
this(100,200,300);
[Link]("Sum of two integer is :"+(x+y));
}
public Calculate(int x, int y, int z)
{
[Link]("Sum of three integer is :"+(x+y+z));
}
}
}
-------------------------------------------------------------------
Program on Method Overloading :
--------------------------------
package [Link];
class Addition
{
public int add(int x, int y)
{
return 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.
package [Link];
class Test
{
public void input(int ...x)
{
[Link]("Var args executed");
}
}
package [Link];
class AddParameter
{
public void acceptAndAddParameter(int ...values)
{
int sum = 0;
for(int value : values)
{
sum = sum + value;
}
[Link]("Sum of parameter is :"+sum);
}
}
------------------------------------------------------------------
//We can hetrogeneous types of data
package [Link];
class Hetro
{
public void acceptHetro(Object ...x)
{
for(Object y : x)
{
[Link](y);
}
}
}
}
------------------------------------------------------------------
//Var args must be only one and last argument.
package [Link];
class Demo
{
// All commented codes are invalid
/*
* public void accept(float ...x, int ...y) { }
*
* public void accept(int ...x, int y) { }
*
* public void accept(int...x, int ...y) {}
*/
for (int z : y)
{
[Link](z);
}
}
}
If we remove these 8 primitive data types then only java can become pure object oriented language.
On these primitive data types, we can’t assign null or we can’t invoke a method.
These primitive data types are unable to move in the network, only objects are moving in the network.
We can’t perform serialization and object cloning on primitive data [Link] is only possible with objects.
To avoid the above said problems, From JDK 1.5v, java software people has provided the following two
concepts :
a) Autoboxing
b) Unboxing
Autoboxing
--------------
When we convert the primitive data types into corresponding wrapper object then it is called Autoboxing
as shown below.
}
-------------------------------------------------------------------
String is also an immutable class as shown in the program.
package [Link];
}
------------------------------------------------------------------
//[Link](int);
public class AutoBoxing1
{
public static void main(String[] args)
{
int a = 12;
Integer x = [Link](a); //Upto 1.4 version
[Link](x);
int y = 15;
Integer i = y; //From 1.5 onwards compiler takes care
[Link](i);
}
}
------------------------------------------------------------------
public class AutoBoxing2
{
public static void main(String args[])
{
byte b = 12;
Byte b1 = [Link](b);
[Link]("Byte Object :"+b1);
short s = 17;
Short s1 = [Link](s);
[Link]("Short Object :"+s1);
int i = 90;
Integer i1 = [Link](i);
[Link]("Integer Object :"+i1);
long g = 12;
Long h = [Link](g);
[Link]("Long Object :"+h);
float f1 = 2.4f;
Float f2 = [Link](f1);
[Link]("Float Object :"+f2);
double k = 90.90;
Double l = [Link](k);
[Link]("Double Object :"+l);
char ch = ’A’;
Character ch1 = [Link](ch);
[Link]("Character Object :"+ch1);
boolean x = true;
Boolean x1 = [Link](x);
[Link]("Boolean Object :"+x1);
}
}
In the above program we have used 1.4 approach so we are converting primitive to wrapper object
manually.
--------------------------------------------------------------
Overloaded valueOf() method :
-----------------------------
We have 3 overloaded valueOf() method :
----------------------------------------
1) public static Integer valueOf(int x) : It will convert the given int value into Integer Object.
[Link](Character.MAX_RADIX); //36
MAX_RADIX is a final and static variable of Character class.
-----------------------------------------------------------------
//[Link](String str)
//[Link](String str, int radix/base)
public class AutoBoxing3
{
public static void main(String[] args)
{
Integer a = [Link](15);
Integer b = [Link]("25");
[Link](a);
[Link](b);
[Link](c);
}
}
-------------------------------------------------------------------
public class AutoBoxing4
{
public static void main(String[] args)
{
Integer i1 = new Integer(100);
Integer i2 = new Integer(100);
[Link](i1==i2);
Integer a1 = [Link](15);
Integer a2 = [Link](15);
[Link](a1==a2);
}
}
Short - short
Integer - int
Long - long
Float - float
Double - double
Chracter - char
Boolean - boolean
-----------------------------------------------------------------
We have total 8 Wrapper classes.
Among all these 8, 6 Wrapper classes (Byte, Short, Integer, Long, Float and Double) are the sub class of
[Link] class which represent numbers (either decimal OR non decimal)
so all the following six wrapper classes (Which are sub class of Number class) are providing the following
common methods.
Integer a = 128;
Integer b = 128;
[Link](a==b);
[Link]([Link](b));
Integer p = 130;
Integer q = 130;
[Link]([Link](q));
}
}
2) Here when we write the statement Integer i = 128 then it is out of the range of byte (-128 to 127)
hence == opertor will provide false if we compare two Integer object.
Unlike primitive types we can’t convert one wrapper type object to another wrapper object.
Example :
package [Link];
Long a = 12L;
Double d = 90D;
Double d1 = 90.78;
Float f = 12F;
}
}
---------------------------------------------------------------
Ambiguity issue while overloading a method :
---------------------------------------------
When we overload a method then compiler is selecting appropriate method among the available methods
based on the following types.
In case of ambiguity where compiler can select more than one method then compiler will provide the
priority in the following
rules :
Compiler gives the priority to select appropriate method by using the following sequence :
Widening ---> Autoboxing ----> Var args
While selecting the appropriate method in ambiguity issue compiler provides priority to nearest data
type or nearest class i.e sub class
------------------------------------------------------------------
class Test
{
public void accept(double d)
{
[Link]("double");
}
public void accept(float d)
{
[Link]("float");
}
}
public class AmbiguityIssue {
}
}
Note : Here float will be executed becuase float is the most specific type.
------------------------------------------------------------------
class Test
{
public void accept(int d)
{
[Link]("int");
}
public void accept(char d)
{
[Link]("char");
}
}
public class AmbiguityIssue {
public static void main(String[] args)
{
Test t = new Test();
[Link](6);
}
}
Here we will get compilation error because there is no relation between char and short based on the
specific type rule.
--------------------------------------------------------------
class Test
{
public void accept(short ...d)
{
[Link]("short");
}
public void accept(byte ...d)
{
[Link]("byte");
}
}
public class AmbiguityIssue {
Here long will be executed because long is the most specific type.
--------------------------------------------------------------
class Test
{
public void accept(byte d)
{
[Link]("byte");
}
public void accept(short s)
{
[Link]("short");
}
}
public class AmbiguityIssue {
}
}
Here Object will be executed
--------------------------------------------------------------
class Test
{
public void accept(Object s)
{
[Link]("Object");
}
public void accept(String s)
{
[Link]("String");
}
}
public class AmbiguityIssue {
}
}
Here String will be executed
--------------------------------------------------------------
class Test
{
public void accept(Object s)
{
[Link]("Object");
}
public void accept(String s)
{
[Link]("String");
}
public void accept(Integer i)
{
[Link]("Integer");
}
}
public class AmbiguityIssue {
}
}
Here We will get compilation error
---------------------------------------------------------------
class Alpha
{
}
class Beta extends Alpha
{
}
class Test
{
public void accept(Alpha s)
{
[Link]("Alpha");
}
public void accept(Beta i)
{
[Link]("Beta");
}
}
public class AmbiguityIssue {
}
}
}
}
}
}
Here Autoboxing will be executed.
--------------------------------------------------------------
class Test
{
public void accept(Number n)
{
[Link]("Number");
}
public void accept(Double d)
{
[Link]("Double");
}
}
public class AmbiguityIssue {
}
}
Here Number will be executed.
-------------------------------------------------------------------
02-12-2024
----------
***Method Overriding :
----------------------
Writing two or more non static methods in super and sub class in such a way that method name along
with method parameter (Method Signature) must be same as well as return type must be compaitable is
called Method Overriding.
Generally we can’t change the return type of the method while overriding a method (compatibility issue)
but from JDK 1.5v there is a concept called Co-variant (In same direction) through which we can change
the return type of the method.
Example :
---------
class Super
{
public void m1()
{
}
}
class Sub extends Super
{
public void m1() //Overridden Method
{
}
}
Method overriding is mainly used to replacing the implementation of super class method by sub class
method body.
Downcasting :
-------------
By default we can’t assign super class object to sub class reference variable.
Even if we type cast Animal to Lion type then compiler will allow but at runtime JVM will not convert
Animal object (Generic type) into Lion object (Specific type) and it will throw an exception
[Link]
Downcasting is a technique to assign sub class object (Only reference is super type) to sub class
reference variable as shown below.
class Bird
{
public void fly()
{
[Link]("Generic Bird is flying");
}
}
class Parrot extends Bird
{
public void fly()
{
[Link]("Parrot Bird is flying");
}
}
}
--------------------------------------------------------------
package [Link];
class Animal
{
public void eat()
{
[Link]("Generic Animal is eating");
}
}
class Dog extends Animal
{
public void eat()
{
[Link]("Dog Animal is eating");
}
}
class Puppy extends Dog
{
}
Here compiler will search the eat method in Animal class where as JVM will start executing from Puppy
class, Dog class, Animal class, Object class.
--------------------------------------------------------------
@Override Annotation :
--------------------------
In Java we have a concept called Annotation, introduced from JDK 1.5 onwards. All the annotations must
be start with @ symbol.
@Override annotation is metadata (Giving information that method is overridden) and it is optional but it is
always a good practice to write @Override annotation before the Overridden method so compiler as well
as user will get the confirmation that the method is overridden method and it is available in the super
class.
If we use @Override annotation before the name of the overridden method in the sub class and if the
method is not available in the super class then it will generate a compilation error so it is different from
comments because comment will not generate any kind of compilation error if method is not an
overridden method, so this is how it is different from comment.
package [Link];
class Shape
{
public void draw()
{
[Link]("Generic Draw");
}
}
class Rectangle extends Shape
{
@Override
public void draw()
{
[Link]("Drawing Rectangle");
}
}
}
--------------------------------------------------------------
Variable Hiding concept in upcasting :
---------------------------------------
class Super
{
int x = 100;
}
class Sub exetnds Super
{
int x = 200; //Variable Hiding
}
Only non static methods are overridden in java but not the variables[variables are not overridden in java]
because behavior will change but not the property(variable).
Note : In upcasting variable will be always executed besed on the current reference class variable.
package [Link];
class RBI
{
protected String ifscCode = "RBIHYD09675";
@Override
public String loan()
{
return "Providing loan @ 9.2% ROI";
}
}
[Link]([Link]+" : "+[Link]());
}
}
--------------------------------------------------------------
Can we override private method ?
--------------------------------
No, We can’t override private method because private methods are not visible (not available) to the sub
class hence we can’t override.
We can’t use @Override annotation on private method of sub class because it is not overridden method,
actually it is re-declared by sub class developer.
package [Link];
class Super
{
private void m1()
{
[Link]("Private Method of super class");
}
}
class Sub extends Super
{
protected void m1() //Re-declaration of Method
{
[Link]("Method has re-declared");
}
}
Note :- private method of super class is not available or not inherited in the sub class so if the sub class
declare the method with same signature then it is not overridden method, actually it is re-declared in the
sub class.
--------------------------------------------------------------
04-12-2024
----------
Role of access modifier while overriding a method :
---------------------------------------------------
While overriding the method from super class, the access modifier of sub class method must be greater
or equal in comparison to access modifier of super class method otherwise we will get compilation error.
In terms of accessibility, public is greater than protected, protected is greater than default (public >
protected > default)
[default < protected < public]
**So the conclusion is we can’t reduce the visibility of the method while overriding a method.
Note :- private method is not availble (visible) in sub class so it is not the part of method overriding.
class Super
{
public void m1()
{
}
}
class Sub extends Super
{
@Override
protected void m1() //error [super class method AM
is public ]
{
}
}
public class OverridingDemo6
{
public static void main(String[] args)
{
Super s1 = new Sub();
s1.m1();
}
}
--------------------------------------------------------------
Co-variant in java :
--------------------
In general we cann’t change the return type of method while overriding a method. if we try to change it will
generate compilation error because in method overriding, return type of both the methods must be
compaitable as shown in the program below.
class Super
{
public void m1()
{
}
}
class Sub extends Super
{
@Override
public int m1() //error [int is not compaitable with
void]
{
return 0;
}
}
public class OverridingDemo7
{
public static void main(String[] args)
{
Super s1 = new Sub();
s1.m1();
}
}
Note : error, return type int is not compaitable with void.
-------------------------------------------------------------
But from JDK 1.5 onwards we can change the return type of the method in only one case that the return
type of both the METHODS(SUPER AND SUB CLASS METHODS) MUST BE IN INHERITANCE
RELATIONSHIP (IS-A relationship so it is compatible) called Co-Variant as shown in the program below.
Note :- Co-variant will not work with primitive data type, it will work only with classes.
class Alpha
{
}
class Beta extends Alpha
{
}
class Super
{
public Alpha m1()
{
[Link]("Super class Method");
return new Alpha();
}
}
class Sub extends Super
{
@Override
public Beta m1()
{
[Link]("Sub class Method");
return new Beta();
}
}
public class OverridingDemo8
{
public static void main(String[] args)
{
Super s1 = new Sub();
s1.m1();
}
}
Note : Here we need to verify one concept, can we assign Beta class Object to Alpha class, if yes then it
is compitable.
--------------------------------------------------------------
class Super
{
public Super m1()
{
[Link]("Super class Method");
return this;
}
}
class Sub extends Super
{
@Override
public Sub m1()
{
[Link]("Sub class Method");
return this;
}
}
public class OverridingDemo9
{
public static void main(String[] args)
{
Super s1 = new Sub();
s1.m1();
}
}
--------------------------------------------------------------
package [Link];
class A
{
public Object m1()
{
[Link]("Super class m1 method");
return this;
}
}
class B extends A
{
@Override
public System m1()
{
[Link]("Sub class m1 method");
return null;
}
}
public class OverridingDemo10 {
While working with co-variant (In the same direction), sub class method return type object, if we can
assign to super class method return then only it is compatible and it is co-variant
--------------------------------------------------------------
IQ :
-----
-------------------------------------------------------------
package [Link].polymorphic_behavior;
class Vehicle
{
public int getHorsePower()
{
return 1000;
}
}
class Car extends Vehicle
{
public int getHorsePower()
{
return 1200;
}
public class IQ {
}
-------------------------------------------------------------
Progrm that describes Polymorphic behaviour of sub classes :
-----------------------------------------------------------
Case 1 :
--------
package [Link].polymorphic_behavior;
class Animal
{
public void roam()
{
[Link]("Generic Animal is roaming");
}
}
class Lion extends Animal
{
public void roam()
{
[Link]("Lion Animal is roaming");
}
}
class Dog extends Animal
{
public void roam()
{
[Link]("Dog Animal is roaming");
}
}
public class PolymorphicDemo1
{
public static void main(String[] args)
{
Animal a = null;
a = new Lion();
animalRoam(a);
a = new Dog();
animalRoam(a);
}
}
--------------------------------------------------------------
Case 2 :
---------
How to call specific method of sub class :
-------------------------------------------
package [Link].polymorphic_behavior;
class Animal
{
public void roam()
{
[Link]("Generic Animal is roaming");
}
}
class Lion extends Animal
{
public void roam()
{
[Link]("Lion Animal is roaming");
}
a = new Dog();
animalRoam(a);
}
In the above program when we pass Dog object then we will get Runtime Exception
[Link] becuase Dog can’t be converted into Lion.
--------------------------------------------------------------
instanceof Operator :
---------------------
It is an operator as well as keyword.
It is relational operator which provides true/false.
It is used to verify whether a reference variable is pointing to a particular type of object or not ?
We must have IS-A relation between the reference variable and class or interface type.
Programs :
-----------
package [Link].instance_of;
class Test
{
}
}
------------------------------------------------------------
package [Link].instance_of;
class Alpha
{
}
class Beta extends Alpha
{
}
class Gamma extends Beta
{
}
}
------------------------------------------------------------
package [Link].instance_of;
Integer i = 90;
}
-----------------------------------------------------------
package [Link].instance_of;
class Bird
{
}
class Parrot extends Bird{}
acceptBirdType(s);
}
}
-------------------------------------------------------------
Dynamic Polymorphism with the help of instanceof Operator.
----------------------------------------------------------
package [Link];
class Payment
{
public double makePayment(double amount)
{
return amount;
}
}
p = new CreditCard();
acceptPayment(p);
}
-------------------------------------------------------------
**What is Method Hiding in java ?
OR
Can we override static method ?
OR
Can we override main method ?
Case 1 :
--------
A public static method of super class by default available to sub class so, from sub class we can call
super class static method with the help of Class name as well as object reference as shown in the below
program
class Parent
{
public static void show()
{
[Link]("Show method of Parent class");
}
}
class Child extends Parent
{
}
public class MethodHidingDemo1
{
public static void main(String[] args)
{
[Link]();
class Super
{
public static void m1() //class
{
}
}
class Sub extends Super
{
public void m1() //object
{
}
}
public class MethodHidingDemo2
{
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
---------------------------------------------------------------
Case 3 :
--------
We can’t override any non static method with static method, If we try then it will generate an error,
Overriding method is static.
class Super
{
public void m1() //Object
{
}
}
class Sub extends Super
{
public static void m1() //class
{
}
}
public class MethodHidingDemo3
{
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
So, the conclusion is we cannot overide static with non static method as well as non-static with static
method because static method belongs to class and non-static method belongs to object.
---------------------------------------------------------------
Case 4 :
-------
Program that describes method hiding concept as well as sub class method can’t hide super class
method because return type is not compaitable.
class Super
{
public static void m1() //class
{
}
}
class Sub extends Super
{
public static int m1() //class
{
return 0;
}
}
public class MethodHidingDemo2
{
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
Note : sub class method can’t hide super class method becuase return type is not compaitable
--------------------------------------------------------------
case 5 :
---------
We can’t override static method because It belong to class but not object, If we write static method in the
sub class with same signature and compaitable return type then It is Method Hiding but not Method
Overriding here compiler will search the method of super class and JVM will also execute the method of
super class because method is not overridden.[Single copy and belongs to class area and common for all
the objects]
class Base
{
public static void m1()
{
[Link]("Static Method of Base class");
}
}
class Derived extends Base
{
}
--------------------------------------------------------------
06-12-2024
----------
*What is the limitation of ’new’ keyword ?
OR
What is the difference between new keyword and newInstance() method?
OR
How to create the Object for the classes which are coming dynamically from the database or from some
file at runtime.
The limitation with new keyword is, It demands the class name at the begning or at the time of compilation
so new keyword is not suitable to create the object for the classes which are coming from database or
files at runtime dynamically.
In order to create the object for the classes which are coming at runtime from database or files, we should
use newInstance() method available in [Link] class.
newInstance() method creates the object internally by using new keyword only and the class must contain
either default OR no
argument constructor.
Methods :
----------
public Object newInstance() : Predefined non static method of
[Link]. It is used to
create the object for dynmacilly
loaded classes.
public native [Link] getClass() :Predefined non static method of Object class. The return type of
this method is [Link] so further we can call any method of [Link] class object
getClass().getName();
---------------------------------------------------------------
[Link]
----------------------
class Student
{
}
class Employee
{
}
public class ObjectAtRuntime
{
public static void main(String[] args) throws Exception
{
Object obj = [Link](args[0]).newInstance();
[Link]("Object created for :"+[Link]().getName());
}
}
---------------------------------------------------------------
class Student
{
public void greet()
{
[Link]("Welcome Student");
}
}
class Sample
{
public void greet()
{
[Link]("Hello Batch 39!!!!");
}
}
public class ObjectAtRuntime1
{
public static void main(String[] args) throws Exception
{
Object obj = [Link](args[0]).newInstance();
We should declare a class as a final if the composition of the class (logic of the class) is very important
and we don’t want to share the feature of the class to some other developer to modify the original
behavior of the existing class, In that situation we should declare a class as a final.
Declaring a class as a final does not mean that the variables and methods declared inside the class will
also become as a final, only the class behavior is final that means we can modify the variables value as
well as we can create the object for the final classes.
Note :- In java String and All wrapper classes are declared as final class.
--------------------------------------------------------------
final class A
{
private int x = 100;
Note : class A is final so we can’t inherit hence we will get compilation error.
---------------------------------------------------------------
final class Test
{
private int data = 100;
}
}
Note : for final class we can create object as well as we can modify the data.
--------------------------------------------------------------
Whenever we declare a constructor as private then we should declare the class with final modifier. If
constructor is private then we can’t create a sub class because super class constructor is not visible from
sub class constructor.
}
}
---------------------------------------------------------------
07-12-2024
----------
Sealed class in Java :
-----------------------
It is a new feature introduced from java 15v (preview version) and become the integral part of java from
17v.
It is one kind of restriction that describes which classes and interfaces can extend or implement from
Sealed class Or interface.
It is similar to final keyword with less restriction because here we can permit the classes to extend from
the original Sealed class.
The class which is inheriting from the sealed class must be final, sealed or non-sealed.
2) non-sealed : Can be extended by any sub class, if a user wants to give permission to its sub classes.
3) permits : We can provide permission to the sub classes, which are inheriting through Sealed class OR
sealed interface
4) final : we can declare permitted sub class as final so, it cannot be extended further.
-----------------------------------------------------------------
package [Link].sealed_ex;
}
------------------------------------------------------------------
package [Link].sealed_ex;
}
------------------------------------------------------------------
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;
class Alpha
{
private final void accept()
{
[Link]("Alpha class accept method");
}
}
class Beta extends Alpha
{
protected void accept()
{
[Link]("Beta class accept method");
}
}
public class FinalMethodEx1
{
public static void main(String [] args)
{
new Beta().accept();
}
}
Note : Here Program will compile and execute because private method of super class is not available to
sub class.
-------------------------------------------------------------
3) To declare a variable/Field as a final :
--------------------------------------------
In older langugaes like C and C++ we use "const" keyword to declare a constant variable but in java,
const is a reserved word for future use so instead of const we should use "final" keyword.
If we declare a variable as a final then we can’t perform re-assignment (i.e nothing but re-initialization) of
that variable.
In java It is always a better practise to declare a final variable by uppercase letter according to the naming
convention.
class A
{
final int A = 10;
public void setData()
{
A = 10;
[Link]("A value is :"+A);
}
}
class FinalVarEx
{
public static void main(String[] args)
{
final A a1 = new A();
[Link]();
a1 = new A();
[Link]();
}
}
-------------------------------------------------------------
Abstraction : [Hiding the complexcity]
---------------------------------------
Showing the essential details without showing the background details is called abstraction.
An abstract method is a common method which is used to provide easiness to the programmer because
the programmer faces complexcity to remember the method name.
An abstract method observation is very simple because every abstract method contains abstract keyword,
abstract method does not contain any method body and at the end there must be a terminator i.e ;
(semicolon)
In java, whenever action is common but implementations are different then we should use abstract
method, Generally we declare abstract method in the super class and its implementation must be
provided in the sub classes.
if a class contains at least one method as an abstract method then we should compulsory declare that
class as an abstract class.
Once a class is declared as an abstract class we can’t create an object for that class.
*All the abstract methods declared in the super class must be overridden in the sub classes otherwise the
sub class will become as an abstract class hence object can’t be created for the sub class as well.
In an abstract class we can write all abstract method or all concrete method or combination of both the
method.
It is used to acheive partial abstraction that means by using abstract classes we can acheive partial
abstraction(0-100%).
*An abstract class may or may not have abstract method but an abstract method must have abstract
class.
Note :- We can’t declare an abstract method as final, private and static (illegal combination of modifiers)
-------------------------------------------------------------
abstract class Shape
{
public abstract void draw();
}
}
class Circle extends Shape
{
@Override
public void draw()
{
[Link]("Drawing Circle");
}
}
}
-------------------------------------------------------------
09-12-2024
----------
package [Link].abstract_demo;
public Bike()
{
[Link]("Bike Constructor");
}
public void getBikeDeatils()
{
[Link]("It has two wheels");
}
}
-------------------------------------------------------------
IQ :
----
What is the advantage of taking instance variable OR writing constructor inside abstract class ?
As we know we can’t create an object for abstract class but still we can take object properties (Instance
variable) and
constructor, To call the abstract class constructor for initialization of instance variable we should use sub
class object (Using super keyword)
[Note : Even at the time of working with inheritance concept, to initialize the super class instance variable
through super class constructor, super class object is not required, by creating the object of sub class, we
can initialize super class properties(Instance variable)]
-------------------------------------------------------------
//Program that describes how to initialize super class properties :
package [Link].abstract_demo_ex;
@Override
public void draw()
{
[Link]("Drawing "+shapeType);
}
}
class Circle extends Shape
{
public Circle(String shapeType)
{
super(shapeType);
}
@Override
public void draw()
{
[Link]("Drawing "+shapeType);
}
}
public class AbstractDemo3 {
}
-------------------------------------------------------------
//Program that describes we should compulsory override all
the abstract methods of super class in sub classes.
package [Link].abstract_demo_ex;
}
public class AbstractDemo4
{
public static void main(String[] args)
{
Gamma g = new Gamma();
[Link](); [Link]();
}
-------------------------------------------------------------
WAP to force the sub class developer to implement super class
abstract method by using Array concept.
package [Link].abstract_demo_ex;
@Override
public void checkup()
{
[Link](name+ " Lion is going for Checkup");
}
}
class Elephant extends Animal
{
protected String name;
@Override
public void checkup()
{
[Link](name+ " Elephant is going for Checkup");
}
}
@Override
public void checkup()
{
[Link](name+ " Horse is going for Checkup");
}
}
visitZooForCheckup(lions);
[Link]("..................");
visitZooForCheckup(elephants);
[Link]("..................");
visitZooForCheckup(horses);
}
}
-------------------------------------------------------------
10-12-2024
----------
Anonymous inner class with abstract class and Concrete class.
--------------------------------------------------------------
What is Anonymous inner class ?
--------------------------------
If we define a class inside a method body without any name then it is called Anonymous inner class.
The main purpose of anonymous inner class to extend a class OR to implement an interface that means
creating a sub type.
An anonymous inner class object will be created by using new keyword at the time of defining the
anonymous inner class.
class Super
{
public void show()
{
[Link]("Super class show method");
}
}
public class AnonymousInnerDemo1
{
public static void main(String[] args)
{
//Anonymous inner class
Super sub = new Super()
{
@Override
public void show()
{
[Link]("Sub class show method");
}
};
[Link]();
}
--------------------------------------------------------------
Program on Anonymous inner class using abstract class :
-------------------------------------------------------
package [Link].anonymous_inner_demo;
};
}
--------------------------------------------------------------
interface :
-----------
interface upto java 1.7
------------------------
An interface is a keyword in java which is similar to a class which defines working functionality of a class.
Upto JDK 1.7 an interface contains only abstract methods that means there is a guarantee that inside an
interfcae we don’t have concrete or general or instance methods.
From java 8 onwards we have a facility to write default and static methods.
By using interface we can achieve 100% abstraction concept because it contains only abstract methods.
In order to implement the member of an interface, java software people has provided implements
keyword.
All the methods declared inside an interface is by default public and abstract so at the time of overriding
we should apply public access modifier to sub class method.
All the variables declared inside an interface is by default public, static and final.
We should override all the abstract methods of interface to the sub classes otherwise the sub class will
become as an abstract class hence object can’t be created.
Note :- inside an interface we can’t declare any blocks (instance, static), instance variables (No
properties) as well as we can’t write constructor inside an interface.
--------------------------------------------------------------
package [Link].interface_demo;
}
}
}
--------------------------------------------------------------
package [Link].interface_demo;
interface Bank
{
void deposit(double amount);
void withdraw(double amount);
}
class Customer implements Bank
{
double balance;
public Customer(double balance)
{
super();
[Link] = balance;
}
@Override
public void deposit(double amount)
{
if(amount<=0)
{
[Link]("deposit is not possible");
}
else
{
[Link] = [Link] + amount;
[Link]("After deposit amount is :"+[Link]);
}
}
@Override
public void withdraw(double amount)
{
if(amount > [Link])
{
[Link]("Insufficient Balance");
}
else
{
[Link] = [Link] - amount;
[Link]("Balance after withdraw is :"+[Link]);
}
}
}
}
--------------------------------------------------------------
11-12-2024
-----------
Program on loose coupling :
----------------------------
Loose Coupling :- If the degree of dependency from one class object to another class is very low then it is
called loose coupling. [interface is reqd]
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.
[Link]
---------
package [Link].loose_coupling;
[Link]
------------
package [Link].loose_coupling;
@Override
public void prepare()
{
[Link]("Preparing Coffee");
}
[Link]
--------------
package [Link].loose_coupling;
@Override
public void prepare()
{
[Link]("Preparing Horlicks");
[Link]
----------------
package [Link].loose_coupling;
[Link]
-------------------
package [Link].loose_coupling;
--------------------------------------------------------------
Method retutn type as a interface :
-----------------------------------
It is always better to take method return type as interface so we can return any implementer class object
as shown in the example below
------------------------------------------------------------
Compile time constant :
-----------------------
A compile time constant is a constant that is evaluated and replaced with its value at compile time rather
than runtime.
It must be declared with static and final modifier as well as initialized with constant expression. (Must not
be initialized by method call)
At compile time constant value will be converted by compiler at the time of compilation itself so, at runtime
JVM can see the value but not the class name so class will not be loaded as shown in the program.
[Link]
-------------------------
class Alpha
{
static
{
[Link]("Static block of Alpha class");
}
--------------------------------------------------------------
The following program explains that compiler will convert the final, static variable value at the time of
compilation itself
(so compile time OR early binding)
2 files :
----------
[Link]
----------
public class Beta
{
public static final int D = 1200;
}
[Link]
----------
public class Main
{
public static void main(String[] args)
{
[Link](Beta.D); //1000
}
}
Instruction :
--------------
1) Compile both the program and execute [Link]
interface Hello
{
public static final int X = 100;
}
}
--------------------------------------------------------------
Multiple Inheritance by using interface :
-----------------------------------------
In a class we have a constructor so, it is providing ambiguity issue but inside an interface we don’t have
constructor so multiple inheritance is possible using interface.
The sub class constructor’s super keyword will directly move to Object class constructor.(11-DEC)
package [Link];
interface Alpha
{
void m1();
}
interface Beta
{
void m1();
}
class Implementer implements Alpha, Beta
{
@Override
public void m1()
{
[Link]("MI is possible");
}
}
}
--------------------------------------------------------------
12-12-2024
----------
Extending interface :
---------------------
One interface can extends another interface, it cannot implement because interface cannot provide
implementation for the abstract method.
package [Link].exetnding_interface;
interface Alpha
{
void m1();
}
interface Beta extends Alpha
{
void m2();
}
class MyClass implements Beta
{
@Override
public void m1()
{
[Link]("M1 method Overridden");
}
@Override
public void m2()
{
[Link]("M2 method Overridden");
}
}
public class ExtendingInterfaceDemo {
}
--------------------------------------------------------------
java 8 features :
------------------
intreface from JDK 1.8V [Java 8 = 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.
We need to provide implementation for all the abstract methods available inside an interface whether it is
required or not?
To avoid this maintenance problem java software people introduced default method inside an interface.
---------------------------------------------------------------
What is default method :
-------------------------
We can write default method (method with body) inside an interface with default keyword from Java 8v.
This default method provides "default implementation" so the implementer class can override to provide
specific implementation in the class.
Unlike abstract method, default method does not provide any kind of boundation to override this default
method in the sub class.
4 files :
---------
[Link](I)
---------------
package [Link].java_new_features;
[Link]
---------
package [Link].java_new_features;
@Override
public void horn()
{
[Link]("Car has horn");
}
@Override
public void digitalMeter() //java 8
{
[Link]("Digital Meter Facility is Available in the Car");
}
}
[Link]
----------
package [Link].java_new_features;
@Override
public void run()
{
[Link]("Bike is running");
}
@Override
public void horn()
{
[Link]("Bike has horn");
}
}
package [Link].java_new_features;
Note :- abstract method is a common method which is used to provide easiness to the programmer so, by
looking the abstract method we will get confirmation that this is common behavior for all the sub classes
and it must be implemnted in all the sub classes.
package [Link].java_new_features;
interface A
{
default void m1()
{
[Link]("Default Method of interface A");
}
}
class B
{
public void m1()
{
[Link]("Concrete Method of Class B");
}
}
}
---------------------------------------------------------------
Multiple Inheritance by using default method :
----------------------------------------------
Multiple inheritance is possible in java by using default method inside an interface, here we need to use
super keyword to differenciate the super interface methods.
Before java 1.8, we have abstract method inside an interface but now we can write method body(default
method) so, to execute the default method inside an interface we need to take super keyword with
interface name([Link].m1()).
package [Link].java_new_features;
interface Alpha
{
default void m1()
{
[Link]("m1 method of Alpha interface");
}
}
interface Beta
{
default void m1()
{
[Link]("m1 method of Beta interface");
}
}
@Override
public void m1() //Overriding is compulsory, otherwise
{ we will get compilation error
[Link].m1();
[Link].m1();
[Link]("MI is possible");
}
}
public class MultipleInheritance
{
public static void main(String[] args)
{
MI m = new MI();
m.m1();
}
Note : Here both the interfaces are having same method name m1() so, overridng is compulsory in the
implementer class otherwise we will get compilation error due to ambiguity issue.
---------------------------------------------------------------
13-12-2024
----------
What is static method inside an interface?
------------------------------------------
We can define static method inside an interface from java 1.8 onwards.
static method is only available inside the interface, It is not available to the implementer classes.
It is used to provide common functionality which we can apply/invoke from any BLC/ELC class.
return num*num;
}
[Link]
----------
package [Link].static_method;
}
--------------------------------------------------------------
Program that describe that static method of an interface is only available to interface only that means we
can access the static method of an interface by using only one way i.e interface name.
interface Alpha
{
static void m1()
{
[Link]("Interface static method");
}
}
class Beta implements Alpha
{
}
public class StaticMethodOfInterface
{
public static void main(String[] args)
{
Alpha.m1();
//Beta.m1(); [Invalid]
package [Link];
package [Link].interface_demo;
class A
{
public static void m1()
{
[Link]("Static method A");
}
}
class B extends A
{
}
public class Demo
{
public static void main(String [] args)
{
A.m1();
B.m1(); //valid
new B().m1(); //valid
}
}
--------------------------------------------------------------
Introdction to Functional Programming :
---------------------------------------
In OOP, We always concentrate on objects but in Function Programming which is introduced from JDK
1.8V, Here we will
concentrate on functions.
It may contain ’n’ number of static and default methods but it must contain exactly one abstract method.
Example :
---------
@FunctionalInterface
public interface Printable
{
}
--------------------------------------------------------------
Functional interface by using Anonymous inner class :
------------------------------------------------------
package [Link].interface_demo;
@FunctionalInterface
interface Payment
{
void makePayment();
}
public class AnonymousWithFunctionalInterface {
[Link](); [Link]();
}
---------------------------------------------------------------
What is Lambda Expression in java ?
------------------------------------
It is a new feature introduced in java from JDK 1.8 onwards.
It is an anonymous function i.e function without any name.
In java it is used to enable functional programming.
It is used to concise our code as well as we can remove boilerplate code.
It can be used with functional interface only.
If the body of the Lambda Expression contains only one statement then curly braces are optional.
We can also remove the variables type while defining the Lambda Expression parameter.
If the lambda expression method contains only one parameter then we can remove () symbol also.
In lambda expression return keyword is optional but if we use return keyword then {} are compulsory.
Lamda target can’t be class or abstract class, it will work with functional interface only.
---------------------------------------------------------------
abstract class Drawable
{
abstract void draw();
}
public class LambdaTarget
{
public static void main(String[] args)
{
Drawable d = ()-> [Link]("Drawing");
[Link]();
}
}
Note : The above program will generate compilation error, Lambda Target must be Functional interface.
-------------------------------------------------------------
Program on Lambda Expression :
------------------------------
package [Link];
interface Vehicle
{
void run();
}
}
-------------------------------------------------------------
package [Link].basic_concepts;
import [Link];
@FunctionalInterface
interface Calculate
{
double doSum(double x, double y);
}
-------------------------------------------------------------
package [Link];
interface Length
{
int getLength(String str);
}
[Link]([Link]("India"));
}
--------------------------------------------------------------
package [Link].basic_concepts;
import [Link];
@FunctionalInterface
interface Verifier
{
boolean verify(Integer num);
}
}
-------------------------------------------------------------
/* If the input number is 0 or negative return -1
* If the input number is even return square of the number
* If the input number is even return cube of the number
* */
package [Link].basic_concepts;
import [Link];
@FunctionalInterface
interface Calculator
{
Double getSquareAndCube(Integer num);
}
[Link]([Link](no));
[Link]();
}
===============================================================
What is type parameter<T> in java ?
------------------------------------
It is a technique through which we can make our application indepenedent of data type. It is represented
by <T>
In java we can pass Wrapper classes as well as User-defined classes (reference classe) to this type
parameter.
package [Link].basic_concepts;
import [Link];
class Accept<T>
{
private T data;
public T getData()
{
return data;
}
}
class Product
{
private int productId;
@Override
public String toString()
{
return "Product [productId=" + productId + "]";
}
}
-----------------------------------------------------------
17-12-2024
-----------
Note :-
-------
All these predefined functional interfaces are provided as a part of [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.
import [Link];
import [Link];
}
----------------------------------------------------------
package [Link].functional_interface;
import [Link];
import [Link];
}
-----------------------------------------------------------
package [Link].functional_interface;
import [Link];
import [Link];
if(isEligible)
{
[Link]("You are eligible for Voting");
}
else
{
[Link]("You are not eligible for Voting");
}
[Link]();
}
}
----------------------------------------------------------
package [Link].functional_interface;
import [Link];
import [Link];
[Link]();
}
-----------------------------------------------------------
Consumer<T>
-----------
Consumer<T> functional interface :
-----------------------------------------
It is a predefined functional interface available in [Link] sub package.
It contains an abstract method accept() which takes T type parameter and returns nothing (void). It is
used to accept the parameter value or consume the value.
@FunctionalInterface
public interface Consumer<T>
{
void accept(T x);
}
----------------------------------------------------------
package [Link].functional_interface;
import [Link];
class Customer
{
private int customerId;
@Override
public String toString()
{
return "Customer [customerId=" + customerId + "]";
}
}
-----------------------------------------------------------
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 package.
It provides an abstract method apply that accepts one argument(T) and produces a result(R).
Note :- The type of T(input) and the type of R(Result) both will be decided by the user.
@FunctionalInterface
public interface Function<T,R>
{
public abstract R apply(T x);
}
-----------------------------------------------------------
package [Link].functional_interface;
import [Link];
import [Link];
}
-----------------------------------------------------------
package [Link].functional_interface;
import [Link];
import [Link];
}
----------------------------------------------------------
package [Link].functional_interface;
import [Link];
import [Link];
}
------------------------------------------------------------
18-12-2024
-----------
Supplier<T> prdefined functional 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/return a
value of type T.
@FunctionalInterface
public interface Supplier<T>
{
T get();
}
------------------------------------------------------------
//Programs on Supplier :
------------------------
package [Link];
import [Link];
}
-----------------------------------------------------------
package [Link];
import [Link];
class Employee
{
private Integer employeeId;
private String employeeName;
private Double employeeSalary;
@Override
public String toString()
{
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ",
employeeSalary="
+ employeeSalary + "]";
}
[Link](obj);
}
}
-----------------------------------------------------------
package [Link];
import [Link];
import [Link];
class Product
{
private Integer productId;
private String productName;
private Double productPrice;
@Override
public String toString() {
return "Product [productId=" + productId + ", productName=" + productName + ", productPrice=" +
productPrice
+ "]";
}
}
}
}
------------------------------------------------------------
Creating our own Functional interface with various Parameter
------------------------------------------------------------
We can create our own userdefined functional interaface
with various parameters as shown below :
package [Link].custom_fun_interface;
@FunctionalInterface
interface TriFunction<T,U,V,R>
{
public abstract R myApply(T a, U b, V c);
}
public class CustomFunctionalInterface
{
public static void main(String[] args)
{
TriFunction<Integer,Integer, Integer, String> fn1
= (a , b, c)-> ""+a+b+c;
}
------------------------------------------------------------
BiPredicate<T,U> functional interface :
-----------------------------------
It is a predefined functional interface available in [Link] sub package.
The BiPredicate interface has method named test, which takes two parameters and returns a boolean
value, basically this BiPredicate is same with the Predicate, instead, it takes 2 arguments for the metod
test.
@FunctionalInterface
public interface BiPredicate<T, U>
{
boolean test(T t, U u);
}
Type Parameters:
[Link]([Link](2, 3));
[Link]([Link](5, 7));
}
}
-----------------------------------------------------------
BiConsumer<T, U> functional interface :
---------------------------------------
It is a predefined functional interface available in [Link] sub package.
It is a functional interface in Java that represents an operation that accepts two input arguments and
returns no result.
It takes a method named accept, which takes two parameters and performs an action without returning
any result.
@FunctionalInterface
public interface BiConsumer<T, U>
{
void accept(T t, U u);
}
------------------------------------------------------------
import [Link];
[Link](number, text);
// Values after the update (note that the original values are unchanged)
[Link]("Original values: " + number + ", " + text);
}
}
-------------------------------------------------------------
BiFunction<T, U, R> Functional interface :
---------------------------------
It is a predefined functional interface available in [Link] sub package.
It is a functional interface in Java that represents a function that accepts two arguments and produces a
result R.
The BiFunction interface has a method named apply that takes two arguments and returns a result.
@FunctionalInterface
public interface BiFunction<T, U, R>
{
R apply(T t, U u);
}
-------------------------------------------------------------
import [Link];
}
}
--------------------------------------------------------------
UnaryOperator<T> :
------------------
It is a predefined functional interface available in [Link] sub package.
It is a functional interface in Java that represents an operation on a single operand that produces a result
of the same type as its operand. This is a specialization of Function for the case where the operand and
result are of the same type.
It has a single type parameter, T, which represents both the operand type and the result type.
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T,R>
{
public abstract T apply(T x);
}
--------------------------------------------------------------
import [Link].*;
public class Lambda15
{
public static void main(String[] args)
{
UnaryOperator<Integer> square = x -> x*x;
[Link]([Link](5));
It is a functional interface in Java that represents an operation upon two operands of the same type,
producing a result of the same type as the operands.
This is a specialization of BiFunction for the case where the operands and the result are all of the same
type.
It has two parameters of same type, T, which represents both the operand types and the result type.
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,U,R>
{
public abstract T apply(T x, T y);
}
--------------------------------------------------------------
import [Link].*;
public class Lambda16
{
public static void main(String[] args)
{
BinaryOperator<Integer> add = (a, b) -> a + b;
[Link]([Link](3, 5));
}
}
--------------------------------------------------------------
19-12-2024
-----------
Can an interface extend a class ?
---------------------------------
An interface can’t extend a class, It can extend only interface.
Every public method of Object class is implicitly re-declared inside every interface as an abstract method
to support upcasting if interface does not extend any super interface.
}
public class InterfaceMemberDemo1 {
}
---------------------------------------------------------------
package [Link].interface_member;
interface Printable
{
}
class Print implements Printable
{
@Override
public String toString() {
return "Print []";
}
}
public class InterfaceMemberDemo2
{
public static void main(String[] args)
{
Printable p = new Print();
[Link]([Link]());
[Link]([Link]());
}
}
--------------------------------------------------------------
package [Link].interface_member;
@FunctionalInterface
abstract interface Moveable
{
void move();
public String toString();
public int hashCode();
public boolean equals(Object obj);
}
public class InterfaceMemberDemo3 {
}
---------------------------------------------------------------
package [Link].interface_member;
interface Alpha
{
Note : From the above program, It is clear that we can’t override Object class public method as a default
method inside interface.
---------------------------------------------------------------
Interface from JAVA 9V
----------------------
We can write private static and private non static (not public)
methods inside an interface from java 9 version.
1) Code Reusability
--------------------
If two or more than two default methods want to share a common code (Helper Method code) then we
can write these common code in private methods so it will enhance code reusability.
Note : By default interface is not Fully abstract but we can make it full abstract from java 9V by writing the
logic inside private method.
Note : from default method we can call private static as well as private non static methods but from public
static method of interface we can call only private static method.
--------------------------------------------------------------
package [Link].interface_member;
interface Acceptable
{
int MAX_VALUE = 500; //JDK 1.0
---------------------------------------------------------------
The following Program explains how to use Helper method (private Method) to validate different data
package [Link].method_overloading;
import [Link];
class Payment
{
// Payment using cash
public void makePayment(double amount)
{
if (validateAmount(amount))
{
[Link]("Processing payment via Cash...");
[Link]("Amount Paid RS :" + amount);
[Link]("Payment Successful!");
}
}
//Helper Method
private String maskCardNumber(String cardNumber)
{
return "****-****-****-" + [Link](12);
}
switch(choice)
{
case 1:
[Link]("Enter the amount you want to pay through cash :");
double amount = [Link]();
[Link](amount);
break;
case 2:
[Link]("Enter your name :");
String name = [Link]();
name = [Link]();
[Link]("Enter your 16 digit Credit Card Number :");
String creditCard = [Link]();
case 3 :
[Link]("Enter your 16 digit Debit Card Number :");
String debitCard = [Link]();
debitCard = [Link]();
[Link]("Enter your Payment Amount :");
amount = [Link]();
[Link](debitCard, amount);
break;
}
[Link]();
}
}
--------------------------------------------------------------
What is a Marker interface ?
-----------------------------
If an interface does not contain any field or method, Basically It is an empty interface then it is called
Marker interface OR Tag interface.
Example :
a) [Link]
b) [Link]
c) [Link]
**The main purpose of marker interface to provide additional information to the JVM reagarding the
Object like Object is Serializable, Cloneable OR Randomly Accessible.
---------------------------------------------------------------
---
****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 (no instance variable).
2) An abstract class can have state (properties) of an object but interface can’t have state of an object.
3) An abstract class can contain constructor but inside an interface we can’t define constructor.
4) An abstract class can contain instance and static blocks but inside an interface we can’t define any
blocks.
5) Abstract class can’t refer Lambda expression but using Functional interface we can refer Lambda
Expression.
6) By using abstract class multiple inheritance is not possible but by using interface we can achieve
multiple inheritance.
------------------OOPs Completed..............................
1) Exception Handling
2) Multithreading
3) Collections Framework (22 Session)
Due to an exception, the execution of the program will be disturbed first and then terminated
permanently.
---------------------------------------------------------------
Different Crieteria of Exception :
----------------------------------
The following are the different criteria for exception :
1) [Link]
Whenever we divide a number by zero(an int value) then we will get a RuntimeException i.e
[Link].
int x = 10;
int y = 0;
int z = x/y; //[Link].
[Link](z);
2) [Link]
If we try to access the index of the array where element is not available then we will get
[Link]
3) [Link]
While retrieving the character from the String, if we pass
any negative index then we will get [Link]
4) [Link]
While defining an array, the size of the Array must be
positive integer value otherwise we will get [Link]
5) [Link]
If any refrence variable is pointing to null literal then we
can’t invoke any non static method on this reference variable which is pointing to null otherwise we will
get
NullPointerException.
OR
--
Scanner sc = new Scanner([Link]);
[Link]("Enter your Name :");
String name = [Link]();
6) [Link]
----------------------------------
If we try to convert a String value into primitive OR Wrapper type but if the number is not available in
numeric
format then we will get [Link]
7) [Link]
While reading the data through Scanner class if the input
is not is a proper format then we will get [Link]
[Link](roll);
-------------------------------------------------------------
Exception Hierarchy :
----------------------
Diagram (20-DEC-24)
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.
-------------------------------------------------------
23-12-2024
-----------
Exception format :
------------------
In java, If we want to print any exception object by using print() statement then the java software people
has provided
the following format :
package [Link];
}
-----------------------------------------------------------
WAP to show that [Link] is the super class for all the exceptions (Checked + Unchecked)
package [Link];
import [Link];
e1 = new ArrayIndexOutOfBoundsException();
[Link](e1);
e1 = new NullPointerException();
[Link](e1);
e1 = new NumberFormatException();
[Link](e1);
e1 = new IOException();
[Link](e1);
}
}
------------------------------------------------------------
WAP that describes that whenever an exception is encounter in the program then program will be
terminated in the middle.
package [Link];
import [Link];
Note : In the above program, If we enter the value of y as 0 then our program will be terminated
abnormally, JVM has
default exception handler, which will terminate the program in the middle (abnormal termination) and
provide the execption message with line number.
-------------------------------------------------------------
In order to work with exception, java software people has provided the following keywords :
1) try block
2) catch block
3) finally block [Java 7 try with resourses]
4) throw
5) throws
-----------------------------------------------------------
Key points to remember :
--------------------------------
-> With try block we can write either catch block or finally block or both.
-> In between try and catch we can’t write any kind of statement.
-> try block will trace our program line by line.
-> If we have any exception inside the try block,With the help of JVM, try block will automatically create
the appropriate Exception object and then throw the Exception Object to the nearest catch block.
-> In the try block whenever we get an exception the control will directly jump to the nearest catch block
so the remaining code of try block will not be executed.
-> catch block is responsible to handle the exception.
-> catch block will only execute if there is an exception inside try block.
------------------------------------------------------------
try block :
-----------
Whenever our statement is error suspecting statement OR Risky statement then we should write that
statement inside the try block.
try block must be followed either by catch block or finally block or both.
*try block is responsible to trace our code line by line, if any execption encounter then with the help of
JVM, TRY BLOCK WILL CREATE APPROPRIATE EXECPTION OBJECT, AND THROW THIS
EXCEPTION OBJECT to the nearest catch block.
After the execption in the try block, the remaining code of try block will not be executed because control
will directly transfer to the catch block.
In between try and catch block we cannot write any kind of statement.
catch block :
--------------
The main purpose of catch block to handle the exception which is thrown by try block.
catch block will only executed if there is an exception in the try block.
-------------------------------------------------------------
package [Link];
import [Link];
try
{
[Link]("Enter the value of x :");
int x = [Link]();
}
catch(Exception e)
{
[Link]("Inside Catch Block");
[Link](e);
}
[Link]("Main method ended....");
[Link]();
}
}
In the above program if we put the value of y as 0 but still program will be executed normally because we
have used try-catch so it is a
normal termination even we have an exception in the program.
-------------------------------------------------------------
24-12-2024
-----------
public class Main
{
public static void main(String[] args)
{
try
{
//[Link](10/0);
//OR
From the above program it is clear that try block implicitly creating the exception object with the help of
JVM and throwing the execption object to the nearest catch block.
------------------------------------------------------------------
The main purpose of Exception handling to provide user-friendly message to our end user as shown in
the program.
package [Link];
import [Link];
Exception handlinag = No Abnormal Termination + User-friendly message on wrong input given by the
client.
=================================================================
Throwable class Method to print Exception :
--------------------------------------------
Throwable class has provided the following three methods :
2) public void printStackTrace() :- It will provide the complete details regarding exception like exception
class name, exception error message, exception class location, exception method name and exception
line number.
3) public String toString() :- It will convert the exception Object into String representation.
------------------------------------------------------------------
package [Link];
}
-----------------------------------------------------------------
Working with Specific Exception :
---------------------------------
While working with exception, in the corresponding catch block we can take Exception (super class)
which can handle any type of Exception.
On the other hand we can also take specific type of exception (ArithmetiException,
InputMismatchException and so on) which will handle only one type i.e specific type of exception.
package [Link];
import [Link];
import [Link];
try
{
[Link]("Enter your Roll :");
int roll = [Link]();
[Link]("Your Roll is :"+roll);
}
catch(InputMismatchException e)
{
[Link]();
}
[Link]();
[Link]("Main ended");
}
}
------------------------------------------------------------------
While dividing a number with 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, static variable
support to deal with Infinity and Undefined.
On the other hand while dividing a number with with floating point literal in the both cases i.e Infinity
(10/0.0) and Undefined (0/0.0) we have final, static variable support so the program will not be terminated
in the middle which are as follows
10/0.0 = POSITIVE_INFINITY
-10/0.0 = NEGATIVE_INFINITY
0/0.0 = NaN
[Link] and [Link] classes are provided the support for these final and static variable,
the same OR same type of variables are not available in Integeral Literal classes.
-----------------------------------------------------------------
package [Link];
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 index is out of limit!!!");
}
try
{
String str = null;
[Link]([Link]());
}
catch(NullPointerException e)
{
[Link]("ref variable is pointing to null");
}
Note : Here we are getting all the execptions messages through catch blocks at a time so it is not a better
approach from client point of view, We should always provide only one error message to our client.
---------------------------------------------------------------
* Single try with multiple catch block :
-----------------------------------------
According to industry standard we should write try with multiple catch blocks so we can provide proper
information for each and every exception to the end user.
While working with multiple catch block always the super class catch block must be last catch block.
From java 1.7v this multiple exceptions we can write in a single catch block by using | symbol.
If try block is having more than one exception then always try block will entertain only first exception
because control will transfer to the nearest catch block.
package [Link];
public class MultyCatch
{
public static void main(String[] args)
{
[Link]("Main Started...");
try
{
int c = 10/2;
[Link]("c value is :"+c);
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...");
}
}
------------------------------------------------------------------
package [Link];
}
------------------------------------------------------------------
27-12-2024
-----------
finally block [100% Guaranteed for Exceution]
---------------------------------------------
finally is a block which is meant for Resource handling purposes.
According to Software Engineering, the resources are memory creation, buffer creation, opening of a
database, working with files, working with network resourses and so on.
Whenever the control will enter inside the try block always the finally block would be executed.
We should write all the closing statements inside the finally block because irrespective of exception finally
block will be executed every time.
If we use the combination of try and finally then only the resources will be handled but not the execption,
on the other hand if we use try-catch and finally then execption and resourses both will be handled.
-----------------------------------------------------------------
package [Link];
try
{
[Link](10/0);
}
finally
{
[Link]("Finally Block");
}
Note :- In the above program finally block will be executed, even we have an exception in the try block but
here only the resourses will be handled but not the exception.
---------------------------------------------------------------
package [Link];
}
catch(NegativeArraySizeException e)
{
[Link]("Array Size is in negative value...");
}
finally
{
[Link]("Resources will be handled here!!");
}
[Link]("Main method ended!!!");
}
}
In the above program exception and resourses both are handled because we have a combination of
try-catch and finally.
Note :- In the try block if we write [Link](0) and if this line is executed then finally block will not be
executed.
-----------------------------------------------------------------
Limitation of finally Block :
------------------------------
The following are the limitation of finally block :
1) In order to close the resourses, user is responsible to write finally block manually.
3) In order to close the resourses inside the finally block, we need to declare the resourses outside of try
block.
package [Link];
import [Link];
import [Link];
}
}
-----------------------------------------------------------------
** try with resourses :
-----------------------
To avoid all the limitation of finally block, Java software people introduced a separate concept i.e try with
resources from java 7 onwards.
Case 1:
-------
try(resource1 ; resource2) //Only the resources will be handled
{
}
Case 2 :
----------
//Resources and Exception both will be handled
try(resource1 ; resource2)
{
}
catch(Exception e)
{
}
Case 3 :
----------
try with resourses enhancement from java 9v
try(r1; r2)
{
}
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 AutoCloseable interface.
Whenever we pass any resourse class object as part of try with resources as a parameter then that class
must implements either Closeable or AutoCloseable interface so, try with resourses will automatically call
the respective class
close() method even an exception is encountered in the try block.
This ResourceClass must implements either Closeable or AutoCloseable interface so, try block will
automatically call the close() method as well as try block will get the guarantee of close() method support
in the respective class.
The following program explains how try block is invoking the close() method available in
DatabaseResource class and FileResourse class.
3 files :
----------
[Link]
----------------------
package [Link].try_with_resourses;
[Link]
------------------
package [Link].try_with_resourses;
import [Link];
import [Link];
[Link]
----------
package [Link].try_with_resourses;
try(dr;fr)
{
[Link](10/0);
}
catch(ArithmeticException e)
{
[Link]("Divide by zero problem");
}
[Link]("Main method Completed!!");
}
------------------------------------------------------------------
//Program to close Scanner class automatically using try with resourses
package [Link].try_with_resourses;
import [Link];
import [Link];
Note :- Scanner class internally implementing Closeable interface so it is providing auto closing facility
from java 1.7, as a user we need to pass the reference of Scanner class inside try with resources try()
Whenver we write try with resourses then automatically compiler will generate finally block internally to
close the resourses automatically.
-----------------------------------------------------------------
28-12-2024
-----------
Nested try block :
------------------
If we write a try block inside another try block then it is called Nested try block.
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];
package [Link];
import [Link];
import [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");
}
}
finally
{
try
{
throw new ArrayIndexOutOfBoundsException("Array is out of bounds");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array is out of Bounds");
}
}
}
We can also write return statement inside the finally block only, if the finally block is present. After this
return statement we cannot write any kind of statement. (Unrechable)
Always finally block return statement having more priority then try-catch return statement.
-----------------------------------------------------------------
package [Link];
public class ReturnExample
{
public static void main(String[] args)
{
[Link](methodReturningValue());
}
// [Link]("Unreachable code");
}
}
----------------------------------------------------------------
package [Link];
@SuppressWarnings("finally")
public static int m1()
{
try
{
[Link]("Inside try");
return 100;
}
catch(Exception e)
{
[Link]("Inside Catch");
return 200;
}
finally
{
[Link]("Inside finally");
return 300;
}
If we initialize inside the try block only then from catch block we cannot access local variable value, Here
initialization is compulsory inside catch block.
package [Link];
}
-----------------------------------------------------------------
30-12-2024
-----------
**Difference between Checked Exception and Unchecked Exception :
----------------------------------------------------------------
Checked Exception :
----------------------
A checked exception is a common exception that must be throws or handled by the application code
where it is thrown, Here compiler takes very much care and wanted the clarity regarding the exception by
saying that, by using this code you may face some problem at runtime and you did not report me how
would you handle this situation at runtime are called Checked exception, so provide either try-catch or
declare the method as throws.
Except RuntimeException, all the checked exceptions are directly sub class of [Link] OR
Throwable.
Eg:
---
FileNotFoundException, IOException, InterruptedException,ClassNotFoundException, SQLException,
CloneNotSupportedException, EOFException and so on
Unchecked Exception :-
--------------------------
An unchecked exception is rare and any exception that does not need to be throw by throws keyword or
handled by the application code where it is thrown, here compiler does not take any care are called
unchecked exception.
Unchecked exceptions are directly entertain by JVM because they are rarely occurred in java.
Eg:
---
ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, NumberFormatException,
ClassCastException, ArrayStoreException and so on.
-----------------------------------------------------------------
Some Bullet points regarding Checked and Unchecked :
-----------------------------------------------------
Checked Exception :
------------------
1) Common Exception
2) Compiler takes care (Will not compile the code)
3) Handling is compulsory (try-catch OR throws)
4) Directly the sub class of [Link] OR Throwable
Unchecked Exception :
----------------------
1) Rare Exception
2) Comiler will not take any care
3) Handling is not Compulsory
4) Sub class of RuntimeException
-------------------------------------------------------------------
*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.
throws :
--------
throws keyword describes that the method might throw an Exception, It also might not. It is used only at
the end of a
method declaration to indicate what exceptions it supports OR what type of Exception it might throw
which will be handled by JVM (not recommended) or caller method.
Note :- It is always better to use try catch so we can provide appropriate user defined messages to our
client.
--------------------------------------------------------------------
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.[30-DEC]
---------------------------------------------------------------------Exception Propagation program :
--------------------------------
package [Link].custom_exception;
[Link]("Sample");
}
}
---------------------------------------------------------------------
** What is the difference between throw and throws :
------------------------------------------------------
throw [THROWING THE EXCEPTION OBJCET EXPLICITLY.]
------------------------------------------------------
We should use throw keyword to throw the exception object explicitly, In case of try block, try block is
responsible to create the exception object with JVM as well as throw the exception object to the nearest
catch block
but if a developer wants to throw exception object explicitly then we use throw keyword.
after using throw keyword the control will transfer to the nearest catch block so after throw keyword
statement, the remaining statements are un-reachable.
throws :-
---------
throws keyword describes that the method might throw an Exception, It also might not. It is used only at
the end of a
method declaration to indicate what exceptions it supports OR what type of Exception it might throw.
It is used to skip from the current situation so now the execption will be propagated to the caller method
OR JVM for
handling purpose.
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.
---------------------------------------------------------------------
How to develop User-defined Exceptions :
-----------------------------------------
As a developer we can develop user-defined checked and user-defined unchecked exception.
If we want to develop checked exception then our user-defined class must extends from
[Link], on the other hand if we want to develop un-checked exception then our user-defined
class must extends from [Link].
In the user-defined exception class, we should write No argument constructor(in case if we don’t want to
pass any error message) and we should write parameterized constructor with String errorMessage as a
parameter (in case if we want to pass any error message) with super keyword.
In order to throw the exception object explicitly we should use throw keyword as well as our user-defined
class object must be of Throwable type.
package [Link].custom_exception;
import [Link];
@SuppressWarnings("serial")
class InvalidAgeException extends Exception
{
public InvalidAgeException()
{
}
}
else
{
[Link]("You are allowed for Movie");
}
}
--------------------------------------------------------------------
01-01-2025
----------
WAP to develop user-defined un-checked Exception :
---------------------------------------------------
package [Link];
import [Link];
@SuppressWarnings("serial")
class GreaterMarksException extends RuntimeException
{
public GreaterMarksException()
{
}
Example :-
try
{
}
catch(ArithmeticException e) //Valid
{
[Link]();
}
----------------------------------------------------------------------
b) If the try block does not throw any exception then in the corresponding catch block we can write
Exception OR 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];
import [Link];
}
catch(Exception e) //Exception and Throwable both are allowed
{
[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 but overridden method can throw Unchecked Exception.
package [Link].method_related_rule;
import [Link];
import [Link];
class Super
{
public void show()
{
[Link]("Super class method not throwing checked Exception");
}
}
class Sub extends Super
{
@Override
public void show() throws ClassNotFoundException //error
{
[Link]("Sub class method should not throw checked Exception");
}
}
}
---------------------------------------------------------------------
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 FileNotFoundException
{
[Link]("Super class method ");
}
}
class Derived extends Base
{
public void show() throws IOException //error
{
[Link]("Sub class method ");
}
}
}
----------------------------------------------------------------------
e) Just like return keyword we can’t use throw keyword inside static and non static block to throw an
exception because all initializers must be executed normally.
We can use throw keyword in the protection of try-catch so the code will be executed normally.
{
try
{
throw new ArithmeticException();
}
catch (ArithmeticException e)
{
[Link]("Normal Termination");
}
}
}
----------------------------------------------------------------------
public class ArrayStoreException {
[Link]([Link](obj));
}
--------------------------------------------------------------
public boolean equals(Object obj) :
-----------------------------------
There is predefined non static method called equals(Object obj) which is available in [Link]
class.
It is used to compare two objects based on the memory reference or memory address so we can say the
object class equals() method behavior is similar to == operator because internally, It uses == operator
only as shown in the program.
package [Link];
[Link](e1==e2); //false
[Link]([Link](e2)); //false [== operator]
In the above program equals(Object obj) methdo will return false because internally object class
equals(Object obj) method uses == operator.
We can override this equals(Object obj) method in the Employee class for content comparison. Eclipse
IDE provides auto generate facility to override hashCode() and equals(Object obj).
package [Link];
import [Link];
[Link]([Link](e2)); //true
Note : In the above program we will get the output as true because the overridden equals(Object obj)
method will compare the content of the both the objects. It is auto generated method i.e equals() and
hashCode() method
There is contract between equals() and hashCode() method is, we should always overridde both the
methods together.
--------------------------------------------------------------
Record class in java [java 17 features]
-----------------------------------------
public abstract class Record extends Object.
record Student(){} //final class Student extends Record [Compiler generated code]
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 (final
data) from one application to another application.
It is also known as DTO (Data transfer object) OR POJO (Plain Old Java Object) 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 and static block inside the record.
We cannot define instance variable and instance block inside the record.
We cann’t extend or inherit records because by default every record is implicilty final and It is extending
from [Link] class, which is an abstract class.
We don’t have setter facility in record because by default components are final.
3 files :
---------
[Link](C)
------------------
package [Link];
import [Link];
@Override
public String toString() {
return "ProductClass [productId=" + productId + ", productName=" + productName + "]";
}
@Override
public int hashCode() {
return [Link](productId, productName);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
ProductClass other = (ProductClass) obj;
return [Link](productId, [Link]) && [Link](productName,
[Link]);
}
}
[Link](R)
----------------------
package [Link];
[Link]
---------------
package [Link];
[Link]("....................................");
ProductRecord r1 = new ProductRecord(999, "Laptop");
[Link](r1);
ProductRecord r2 = new ProductRecord(999, "Laptop");
[Link]([Link](r2));
[Link]([Link]());
}
}
==============================================================
03-01-2025
-----------
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
In multitasking multiple tasks can concurrently work with CPU so, our task will be completed as soon as
possible.
[Diagram : 03-JAN]
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.
It is well known for independent execution. The main purpose of multithreading to boost the execution
sequence.
A thread can run with another thread concurrently within the same process so our task will be completed
as soon as possible.
In java whenever we define main method then JVM internally creates a thread called main thread under
main group.
Program that describes that main is a Thread :
-----------------------------------------------
Whenever we define main method then JVM will create main thread internally under main group, the
purpose of this main thread to execute the entire main method code.
In java there is a predefined class called Thread available in [Link] package, this class contains a
predefined static factory method currentThread() which will provide currently executing Thread Object.
Thread class has provided predefined method getName() to get the name of the Thread.
Note : The main pupose of main thread to execute the entire main method.
--------------------------------------------------------------
How to create user-defined thread ?
-----------------------------------
In order to create user-defined thread we can use the following two packages :
1) It will make a request to the O.S to assign a new thread for concurrent execution.
package [Link];
In the above program, we have two threads, main thread which is responsible to execute main method
and Thread-0 thread which is responsible to execute run() method. [04-JAN-25]
In entire Multithreading start() is the only method which is responsible to create a new thread.
------------------------------------------------------------------
public final boolean isAlive() :-
-----------------------------
It is a predefined non static 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/started 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].is_alive;
[Link]();
[Link]("Is child thread started after start():"+[Link]());
[Link](); //[Link]
}
}
-------------------------------------------------------------------
package [Link];
[Link]();
[Link]();
[Link](10/0);
Note :- Here main thread is interrupted due to AE but still child thread will be executed because child
threads are executing with separate Stack
-------------------------------------------------------------------
05-01-2025
-----------
WAP to show that when we work with multiple threads then processor will frequently move from one
thread to another thread.
package [Link];
}
}
}
}
In the above program, Processor is frequently moving from main thread to child thread.
------------------------------------------------------------------
How to set and get the name of the Thread :
--------------------------------------------------
Whenever we create a userdefined 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().
[Link]();
[Link]();
We are not providing the user-defined names so by default the name of thread would be Thread-0,
Thread-1.
------------------------------------------------------------------
package [Link];
class Demo extends Thread
{
@Override
public void run()
{
String name = [Link]().getName();
[Link]("Running Thread name is :"+name);
}
}
public class ThreadName1
{
public static void main(String[] args)
{
Thread t = [Link]();
[Link]("Parent");
[Link]("Child1");
[Link]("Child2");
[Link]();
[Link]();
}
}
Note : Here we are providing the user-defined name i.e child1 and child2 for both the user-defined
thread.
-------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
[Link]();
}
catch(InputMismatchException e)
{
[Link]("Invalid Input");
}
}
------------------------------------------------------------------
[Link](long millisecond) :
-------------------------------
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 in millisecond as parameter
to sleep() method.
It is throwing a checked Exception i.e InterruptedException because there may be chance that this
sleeping thread may be interrupted by a thread so provide either try-catch or declare the method as
throws.
-------------------------------------------------------------------
package [Link];
}
public class SleepDemo
{
public static void main(String[] args)
{
Sleep s1 = new Sleep();
[Link]();
}
}
Note : Here child thread is not interrupted, so catch block will not be executed.
------------------------------------------------------------------
package [Link];
@Override
public void run()
{
[Link]("Child Thread id is :"+[Link]().getId());
for(int i=1; i<=5; i++)
{
[Link]("i value is :"+i); //11 22 33 44 55
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]("Thread has Interrupted");
}
}
}
}
public class SleepDemo1
{
public static void main(String[] args)
{
[Link]("Main Thread id is :"+[Link]().getId()); //1
[Link]();
[Link]();
}
}
-----------------------------------------------------------------
Assignment :
------------
[Link](long mills, int nanos);
06-01-2025
----------
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 state 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.
------------------------------------------------------------------
Anonymous inner class by using Thread class :
---------------------------------------------
Case 1:
-------
Creating Anonymous inner class object using Thread class with ref.
package [Link];
}
------------------------------------------------------------------
Case 2 :
----------
Creating Anonymous inner class object using Thread class without ref.
package [Link];
}
--------------------------------------------------------------07-01-2025
----------
join() method of Thread class :
-------------------------------
The main purpose of join() method to put the current thread into waiting state 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 a non static method so we can call this method with the help of Thread object reference.
-------------------------------------------------------------
package [Link];
[Link]("J1");
[Link]("J2");
[Link]("J3");
[Link]();
[Link]();
[Link]("Main Thread wake up");
[Link]();
[Link]();
}
--------------------------------------------------------------
package [Link];
class Alpha extends Thread
{
@Override
public void run()
{
Thread t = [Link]();
String name = [Link](); //Alpha_Thread is current thread
}
}
}
}
[Link]("Beta Thread Ended");
}
}
--------------------------------------------------------------
package [Link];
Thread t = [Link]();
join(long millis)
join(long millis, long nanos)
--------------------------------------------------------------
Assigning target by Runnable interface :[Loose Coupling]
----------------------------------------------------------
By using Runnable interface we can assign different targets to our thread but thread will be created by
using start() method
of Thread class.
package [Link];
}
--------------------------------------------------------------
08-01-2025
----------
Thread class Constructor :
--------------------------
We have total 10 constructors in the Thread class, The following are commonly used constructor in the
Thread class
}
--------------------------------------------------------------
Case 2 :
--------
By using Lambda :
-----------------
package [Link].runnable_ex;
};
}
--------------------------------------------------------------
Case 3 :
--------
package [Link].runnable_ex;
});
[Link]();
}
-------------------------------------------------------------
Case 4 :
---------
package [Link].runnable_ex;
}
--------------------------------------------------------------
Limitation of 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
may 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. [08-JAN-25]
-------------------------------------------------------------
package [Link].runnable_ex;
@Override
public void run()
{
String name = null;
}
}
[Link]();
[Link]();
}
}
Most of the time, both the Threads will get the ticket.
--------------------------------------------------------------
package [Link].runnable_ex;
class Customer
{
private double availableBalance = 20000;
private double withdrawAmount;
}
else
{
name = [Link]().getName();
[Link]("Sorry!!!"+name+" you have insufficient balance ");
}
}
[Link]();
[Link]();
}
-------------------------------------------------------------
09-01-2025
-----------
***Synchronization :
-------------------
In order to solve the problem of multithreading java software people has introduced synchronization
concept.
It is a technique through which we can control multiple threads but accepting only one thread at a time for
Single object.
Actually this lock is available with each individual object provided by Object class.
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 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 synchronization
mechanism.
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++)
{
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
[Link](num+" X "+i+" = "+(num*i));
}
String name = [Link]().getName();
[Link](name+" thread is completed!!");
}
}
[Link](); [Link]();
}
--------------------------------------------------------------
//Program on Block Level Synchronization :
-------------------------------------------
package [Link];
class ThreadName
{
public void printThreadName()
{
String name = [Link]().getName();
[Link]("Running Thread name is :"+name);
synchronized(this)
{
[Link]("Synchronized block started by thread :"+name);
for(int i = 1; i<=10; i++)
{
[Link]("i value is :"+i+" by "+name);
}
[Link]("Synchronized block ended by thread :"+name);
}
}
[Link](); [Link]();
}
------------------------------------------------------------
10-01-2025
----------
Limitation/Drawback of 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 (object1), 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 thread can enter inside the
synchronized area so the conclusion is, synchronization mechanism does not work with multiple Objects.
[09-JAN-25]
------------------------------------------------------------
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](".......................");
}
}
Here we are getting exprected output because two locks are available from two differenet object. It is
clear that synchronization logic will not work with multiple objects.
The thread will take the lock from class but not object because we can call the static method with the help
of class name.
Unlike Object, we cann’t create multiple classes in the same package.
synchronized([Link])
{
}
------------------------------------------------------------
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 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 numbers 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 user-defined 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 :-
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];
package [Link];
ote : By default every thread even main thread is having default priority i.e 5.
-----------------------------------------------------------
package [Link];
package [Link];
}
}
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]("Last");
[Link]("First");
[Link](); [Link]();
}
Most of time the thread having highest priority will complete its task but we can’t say that it will always
complete its task first that means Thread schedular dominates over the priority of the Thread.
------------------------------------------------------------
Lab Task :
----------
Problem Statement:
You are tasked with creating an education institute course enrollment system using Java. The system
should provide courses and offers to students, allowing them to view available courses, ongoing offers,
and enroll in their preferred courses.
Classes:
class Course:
Attributes:
Methods:
-> Course(int id, String name, double fee): Constructor to initialize the course attributes.
class Offer:
Attributes:
-> offerText (String): Description of the special offer provided by the education institute.
Methods:
class EducationInstitute:
Attributes:
Methods:
-> enrollStudentInCourse(int courseId, String studentName): Simulates the enrollment process and prints
a message when a student -> enrolls in a course.
class Student:
Attributes:
-> institute (EducationInstitute): Reference to the education institute where the student interacts.
Methods:
-> Student(String name, EducationInstitute institute): Constructor to initialize the student with their name
and the education institute reference.
-> enrollInCourse(int courseId): Enrolls the student in the specified course using the education institute’s
enrollment process.
class Main :
The EducationInstituteApp class is the main program that simulates concurrent student interactions using
threads. It creates an education institute, initializes students, and allows them to view course details,
ongoing offers, and enroll in courses concurrently without disturbing the execution flow of each thread.
-> Implement the above classes and their methods following the given specifications.
-> Create an instance of EducationInstitute, and initialize courses and offers with hardcoded data for
simplicity.
-> Create two students: "John" and "Alice". Allow them to view available courses, check ongoing offers,
and enroll in their preferred courses concurrently using threads.
-> Use the Thread class to simulate concurrent student interactions. Ensure that the system provides a
responsive user experience for multiple students.
-> Test your program with multiple executions and verify that students can view course details, offers, and
enroll without conflicts.
-> Feel free to enhance the program with additional features or error handling to further improve its
functionality.
[Note : Include appropriate comments and use meaningful variable names to make your code more
readable and understandable.]
Sample Output :
Available Courses:
Ongoing Offers:
Limited time offer: Enroll in any two courses and get one course free!
Available Courses:
Ongoing Offers:
Limited time offer: Enroll in any two courses and get one course free!
@Override
public String toString() {
return "Course [courseId=" + courseId + ", courseName=" + courseName + ", courseFee=" + courseFee
+ "]";
}
package [Link].educational_institute;
package [Link].educational_institute;
package [Link].educational_institute;
package [Link].educational_institute;
}
};
}
};
[Link]();
[Link]();
[Link](".....................");
[Link]();
[Link]();
}
}
-------------------------------------------------------------
[Link]() :[Prevent from over-utilisation a CPU]
-------------------------------------------------------
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 higher priority than currently executing Thread.
Here The running Thread will directly move from Running state to Runnable state.
The Thread schedular may accept OR 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.[That is the reason yield() method is
not throwing InterruptedExecption]
If the thread which is in runnable state is having low priority than the current executing thread in Running
state, then currently executing thread will continue its execution.
*It is mainly used to avoid the over-utilisation a CPU by the current Thread.
-------------------------------------------------------------
package [Link];
if([Link]("Child1"))
{
[Link](); //give a chance to child2
}
}
}
}
[Link](); [Link]();
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.
It will put a thread into temporarly waiting state and it will release the Object lock, It will remain in the wait
state till another thread provides a notification message on the same object, After getting the lock (not
notification message), It will wake up and it will complete its remaining task.
public native final void notify() :-
-------------------------------------
It will wake up the single thread that is waiting on the same [Link] will not release the lock , once
synchronized area is completed then only lock will be released.
Once a waiting thread(wait()) will get the notification from the another thraed using notify()/notifyAll()
method then the waiting thread will move from Blocked state to Runnable state(Ready to run state) but it
will continue its execution after getting the lock.
*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.
The following program explains we should use these methods from synchronized area only otherwise we
will get [Link].
package [Link];
}
--------------------------------------------------------------
package [Link];
@Override
public void run()
{
for(int i=1; i<=100; i++)
{
val = val + i;
}
}
[Link](1);
[Link]([Link]());
package [Link];
@Override
public void run()
{
//child thread will wait for Object lock
synchronized(this)
{
[Link]("Loop Started");
for(int i=1; i<=10; i++)
{
val = val + i;
}
[Link]("Sending notification to main thread");
notify();
}
}
synchronized(d1)
{
//Suspended
[Link]("Waiting for child thread to complete");
[Link]("Lock is released");
[Link]();
[Link]("Main Thread wake up");
[Link]([Link]());
}
Note : Here we have co-ordination between main thread and child thread so we will get predicatable
output.
-------------------------------------------------------------
21-01-2025
-----------
//Program on ITC where son can withdraw the amount and father
can deposit the amount.
package [Link];
class Customer
{
private double balance = 10000;
[Link]();
[Link]();
}
}
------------------------------------------------------------
//Program to show how to cancel and book the ticket on the same TicketSystem object
package [Link];
class TicketSystem
{
private int availableTickets = 5; //availableTickets = 5
}
}
class Resource
{
private boolean flag = false;
while (!flag)
{
try
{
[Link]([Link]().getName() + " is waiting...");
[Link]([Link]().getName()+" is Waiting for Notification");
wait();
}
catch (InterruptedException e)
{
[Link]();
}
}
[Link]([Link]().getName() + " thread completed!!");
}
[Link]();
[Link]();
[Link]();
Thread setter = new Thread(() -> [Link](), "Setter_Thread");
try
{
[Link](2000);
}
catch (InterruptedException e)
{
[Link]();
}
[Link]();
}
}
-------------------------------------------------------------
22-01-2025
-----------
ThreadGroup :
------------
It is a predefined class available in [Link] Package.
By using ThreadGroup class we can put ’n’ number of threads into a single group to perform some
common/different operation.
By using ThreadGroup class constructor, we can assign the name of group under which all the thread will
be executed.
pubic int activeCount() : How many threads are alive and running under that particular group.
Thread class has provided constructor to put the thread into particular group.
By using ThreadGroup class, multiple threads will be executed under single group.
------------------------------------------------------------------
package [Link];
}
}
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
//[Link](5000);
}
}
------------------------------------------------------------------
package [Link];
}
}
}
------------------------------------------------------------------
package [Link];
JVM can’t terminate the program till any of the non-daemon (user) thread is active, once all the user
thread will be completed then JVM will automatically 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) which is a non static
method Thread class.
[Link](true);
[Link]();
[Link]();
[Link]("Main Thread Ended...");
}
}
--------------------------------------------------------------
public void interrupt() Method of Thread class :
--------------------------------------------------
It is a predefined non static 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.
Methods :
---------
1) public void interrupt () :- Used to interrupt the Thread but the thread must be in sleeping or waiting
mode.
try
{
[Link](1000);
}
catch (Exception e)
{
[Link]("Thread is Interrupted ");
[Link]();
}
}
}
}
public class InterruptThread
{
public static void main(String[] args)
{
Interrupt it = new Interrupt();
[Link]([Link]()); //NEW
[Link]();
//[Link](); //main thread is interrupting the child thread
}
}
--------------------------------------------------------------
23-01-2025
-----------
class Interrupt extends Thread
{
@Override
public void run()
{
try
{
[Link]().interrupt(); //self interruption
}
catch (InterruptedException e)
{
[Link]("Thread is Interrupted :"+e);
}
[Link]("Child thread completed...");
}
}
public class InterruptThread1
{
public static void main(String[] args)
{
Interrupt it = new Interrupt();
[Link]();
}
}
[Link]();
}
}
Note : If main thread will not interrupt the child thread then child thread will not come out from infinite
while loop hance
the lock will not be released.
--------------------------------------------------------------
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. (23-JAN-25)
Note : Here this situation is known as Deadlock situation because both the threads are waiting for infinite
state.
---------------------------------------------------------------
New Thread life cycle :
-----------------------
New thread life cycle which is available from java 5V. Java
software people has provided an enum called State (State is an
enum which is defined inside Thread class)
A thread is well known for independent execution, During the life cycle of a thread it passes through
different states which are as follows :
NEW :
-----
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 :
-----------
Whenever we call start() method on thread object, A thread moves to Runnable state i.e Ready to run
state. Here the thread is considered "alive," but it doesn t immediately start execution unless the CPU
scheduler assigns it time.
BLOCKED :
---------
If a thread is waiting for object lock OR monitor to enter inside synchronized area OR re-enter inside
synchronized area then it is in blocked state.
WAITING :
---------
A thread in the waiting state is waiting for another thread to
perform a particular action but WITHOUT ANY TIMEOUT time. A thread that has called wait() method on
an object is waiting for another thread to call notify() or notifyAll() on the same object OR A thread that
has called join() method is waiting for a specified thread to terminate.
TIMED_WAITING :
---------------
A thread in the timed_waiting state, if we call any method which put the thread into temporarly
timed_waiting state but WITH POSITIVE TIMEOUT period like sleep(lons ms), join(long ms), wait(long
ms) then the Thread is considered as Timed_Waiting state.
TERMINATED :
-------------
The thread has successuflly completed it’s execution in the separate stack memory.
---------------------------------------------------------------
24-01-2025
----------
Volatile Keyword in java :
--------------------------
While working in a multithreaded environment multiple threads can perform read and write operation with
common variable (chances of Data inconsistency so use synchronized OR AtomicInteger) concurrently.
In order to store the value temporarly, Every thread is having local cache memory (PC Register) but if we
declare a variable with volatile modifier then variable’s value is not stored in a thread’s local cache; it is
always read from the main memory.
So the conclusion is, a volatile variable value is always read from and written directly to the main memory,
which ensures that changes made by one thread are visible to all other threads immediately.
package [Link];
class SharedData
{
private volatile boolean flag = false;
}
[Link]("Reader thread got the updated value");
});
[Link]();
[Link]();
}
Note : In the above program, remove the volatile keyword and verify the output.
----------------------------------------------------------------
Methods of Object class :
-------------------------
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.
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] otherwise cloning
opertion is not possible and JVM will throw an exception at runtime
[Link]
We can say an object is a Cloneable object if the corresponding class implements Cloneable interface.
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 follows deep copy concept so hashcode will be different as well as if we
modify one object content then another object content will not be modified.
clone() method of Object class has protected access modifier so we need to override clone() method in
sub class.
@Override
public String toString()
{
}
public class CloneMethodDemo
{
public static void main(String[] args) throws CloneNotSupportedException
{
Employee e1 = new Employee(111,"Scott");
[Link](e1);
[Link](e2);
[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.
package [Link];
p1 = null;
[Link](3000);
[Link](p1);
}
----------------------------------------------------------------
25-01-2025
-----------
** What is the difference final, finally and finalize() method :
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 is automatically called by JVM 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().
-----------------------------------------------------------------
Collections Framework : (40-45% IQ)
-----------------------------------
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.
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.
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 retainAll(Collection c) :- It is used to retain all the elements from existing element.
(Common Element)
d) public boolean removeAll(Collection c) :- It is used to delete all the elements from the existing
collection.
e) public boolean remove(Object element) :- It is used to delete an element from the collection based on
the object.
f) public int size() :- It is used to find out the size of the Collection [Total number of elements available]
g) public void clear() :- It is used to clear all the elements at once from the Collection.
All the above methods of Collection interface will be applicable to all the sub interfaces like List, Set and
Queue.
-------------------------------------------------------------
List interface Hierarchy :
---------------------------
Available in Paint Digram [28-JAN-25]
List interface :
----------------
List interface is a sub interface of Collection in [Link] package available from JDK 1.2V
List interface, Internally uses array concept so all the elements will be stored based on the index.
We can perform automatic sorting by using [Link](List list) because sort() method accept List as
a parameter.
----------------------------------------------------------------
Behaviour of List interface Specific classes :
-----------------------------------------------
* It stores the elements on the basis of index because internally it is using array concept.
* It can accept duplicate, homogeneous and hetrogeneous elements.
* It stores everything in the form of Object.
* When we accept the collection classes without generic concept then compiler generates a warning
message because It is unsafe object.
* By using generic (<>) we can eliminate compilation warning and still we can take homogeneous as well
as hetrogeneous.(<Object>)
* In list interface few classes are dynamically Growable like Vector and ArrayList. [28-JAN]
----------------------------------------------------------------
Methods of List interface :
--------------------------
1) public boolean isEmpty() :- Verify whether List is empty or not
2) public void clear() :- Will clear all the elements, Basically List will become empty.
3) public int size() :- To get the size of the Collections(Total number of elements are available in the
collection)
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
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.
---------------------------------------------------------------
29-01-2025
----------
How many ways we can fetch the Collection Object :
--------------------------------------------------
There are 9 ways to fetch the Collection Object which are as
follows :
Note : Among all these 9 ways Enumeration, Iterator, ListIterator and SplIterator are the cursors so It can
move from one direction to another direction.
Enumeration :
----------------
It is a predefined interface available in [Link] package from JDK 1.0 onwards(Legacy interface).
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 legacy Collection class. Internally it
uses anonymous inner class object.
2) public Object nextElement() :- It will return collection object so return type is Object and move the
cursor to the next line.
It is used to fetch/retrieve the elements from the Collection in forward direction only because it is also a
cursor.
Example :
-----------
Iterator itr = [Link]();
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 and move the cursor to the element object.
--------------------------------------------------------------
ListIterator<E> interface :
-------------------------
It is a predefined interface available in [Link] package and it is the sub interface of Iterator available
from JDK 1.2v.
It is used to retrieve the Collection object in both the direction i.e in forward direction as well as in
backward direction. Here the inner class name is LstItr class extends from Itr class.
Example :
-----------
ListIterator lit = [Link]();
2) public Object next() :- It will return the next position collection object.
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.
--------------------------------------------------------------
SplIterator :
-------------
SplIterator interface :
-----------------------
It is a predefined interface available in [Link] package from java 1.8 version.
It is a cursor through which we can fetch the elements from the Collection [Collection, array, Stream]
It is the combination of hasNext() and next() method.
forEach(Consumer<T> cons)
-------------------------
From java 1.8 onwards every collection class provides a method forEach() method, this method takes
Consumer functional interface as a parameter.
import [Link];
import [Link];
[Link](cons);
}
-------------------------------------------------------------
Case 2 :
---------
package [Link].for_each_method_internals;
import [Link];
import [Link];
public class ForEachMethodInternalDemo2
{
//Lambda
Consumer<String> cons = fruit -> [Link]([Link]());
[Link](cons);
}
--------------------------------------------------------------
Case 3 :
---------
package [Link].for_each_method_internals;
import [Link];
import [Link];
--------------------------------------------------------------
WAP that describes how to retrieve the Objects by using above 9 ways :
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
while([Link]())
{
[Link]([Link]());
}
while([Link]())
{
[Link]([Link]());
}
while([Link]())
{
[Link]([Link]());
}
}
}
--------------------------------------------------------------
30-01-2025
----------
Working with List interface Specific classes :
-----------------------------------------------
As we know, in List interface we have 4 implemented classes which are as follows :
1) Vector<E>
2) Stack<E>
3) ArrayList<E>
4) LinkedList<E>
------------------------------------------------------------- Vector<E>
----------
Vector<E> :
-----------
public class Vector<E> extends AbstractList<E> implements List<E>, Serializable, Clonable,
RandomAccess
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 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.
Constructors in Vector :
-------------------------
We have 4 types of Constructor in Vector
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.
--------------------------------------------------------------
package [Link];
import [Link];
import [Link];
[Link](listOfCity);
}
-------------------------------------------------------------
//Vector Program on capacity
package [Link];
import [Link].*;
[Link](101);
[Link]("After adding 101th elements capacity is :" + [Link]());
}
}
-------------------------------------------------------------
package [Link];
//Array To Collection
import [Link].*;
public class VectorDemo2
{
public static void main(String args[])
{
Vector<Integer> v = new Vector<>();
int x[]={22,20,10,40,15,58};
[Link](".....................");
[Link](v);
[Link](y -> [Link](y));
//Vector to Array
Object[] array = [Link]();
[Link]("Vector to array");
[Link]([Link](array));
}
}
--------------------------------------------------------------
package [Link];
import [Link];
[Link]([Link]::println);
}
}
-------------------------------------------------------------
31-01-2025
-----------
What is Fail Fast Iterator in Collection ?
------------------------------------------
While retrieving the object from the collection by using Itearor interface or for each loop, if at any point of
time the original structure is going to modify after the creation of Itearator then we will get
[Link].
package [Link];
import [Link];
import [Link];
@Override
public void run()
{
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
[Link]("Ameerpet");
}
}
while([Link]())
{
[Link]([Link]());
[Link](500);
}
In the above program we will get [Link] because Iterator is Fail Fast
iterator hence while iterating the element if the structure will be modified then exception will be
generated.
-----------------------------------------------------------------------
In order to resolve the issue, Java software people has provided
a new concept in a new package i.e [Link] sub package which is introduced from JDK 1.5V.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
public void run()
{
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
[Link]("Ameerpet");
}
}
public class FailFastIterator {
while([Link]())
{
[Link]([Link]());
[Link](500);
}
[Link](".................");
}
------------------------------------------------------------------
03-02-2025
---------
Program that describes ArrayList is better than Vector in performance wise :
----------------------------------------------------------------------
As we know ArrayList methods are not synchronized so multiple threads can access the method of
ArrayList, on the other hand most of the methods are synchronized in Vector class.
[Link] class has provided a predefined static method called currentTimeMillis() through which
we can get the current system time in millisecond.
package [Link];
import [Link];
import [Link];
startTime = [Link]();
endTime = [Link]();
}
}
Note : Performance wise ArrayList is better than Vector becoz ArrayList methods are not synchronized.
---------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
[Link](listOfCity);
[Link]([Link]::println);
[Link](".............");
[Link]("Original Data...");
[Link](listOfNumbers);
[Link]("Ascending Order...");
[Link](listOfNumbers);
[Link](listOfNumbers);
[Link]("Descending Order...");
//sort(List list, Comparator<T> comp);
[Link](listOfNumbers, [Link]());
[Link](listOfNumbers);
2) public Object[] toArray() : It is used to convert the Collection object into Object array.
----------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
int choice;
do
{
[Link]("To Do List Menu:");
[Link]("1. Add Task");
[Link]("2. View Tasks");
[Link]("3. Mark Task as Completed");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link]();
switch (choice)
{
case 1:
// Add Task
[Link]("Enter task description: ");
String task = [Link]();
[Link](task);
[Link]("Task added successfully!\n");
break;
case 2:
// View Tasks
[Link]("To Do List:");
for (int i = 0; i < [Link](); i++)
{
[Link]((i + 1) + ". " + [Link](i));
}
[Link]();
break;
case 3:
// Mark Task as Completed
[Link]("Enter task number to mark as completed: ");
int taskNumber = [Link](); //1
if (taskNumber >= 1 && taskNumber <= [Link]())
{
String completedTask = [Link](taskNumber - 1);
[Link]("Task marked as completed: " + completedTask + "\n");
}
else {
[Link]("Invalid task number!\n");
}
break;
case 4:
[Link]("Exiting ToDo List application. Goodbye!");
break;
default:
[Link]("Invalid choice. Please enter a valid option.\n");
}
}
while (choice != 4);
[Link]();
}
}
--------------------------------------------------------------------
public Iterator asIterator() : It is a default method provided inside
Enumeration interface from java 9V. It will return Iteartor interface Object so we can
apply Iterator interface method.
package [Link];
import [Link];
import [Link];
import [Link];
}
---------------------------------------------------------------
Stack<E> :
------------
public class Stack<E> extends Vector<E>
It is a predefined class available in [Link] package. It is the sub class of Vector class introduced from
JDK 1.0 so, It is also a legacy 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 exception called [Link], if Stack is empty and we want to fetch the
element.
public E pop() :- To remove and return the element from the top of the Stack.
public E peek() :- Will fetch the element from top of the Stack without removing.
public boolean empty() :- Verifies whether the stack is empty or not (return type is boolean)
public int search(Object o) :- It will search a particular element in the Stack and it returns OffSet position
(int value). If the element is not present in the Stack it will return -1
----------------------------------------------------------------------
//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);
}
}
---------------------------------------------------------------------
//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));
------------------------------------------------------------------
04-02-2025
----------
ArrayList<E>
------------
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 from java 1.2v.
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 [Almost 50% increment]
*All the methods declared inside an ArrayList is not synchronized so multiple thread can access the
method of ArrayList so performance wise it is good.
*It is highly suitable for fetching or retriving operation when duplicates are allowed and Thread-safety is
not required.
Constructor of ArrayList :
----------------------------
In ArrayList we have 3 types of Constructor:
Constructor of ArrayList :
package [Link];
import [Link];
import [Link];
}
------------------------------------------------------------------
package [Link];
import [Link];
[Link](100);
[Link](200);
[Link](300);
[Link](400);
int sum = 0;
for (int number : numbers)
{
sum += number;
}
[Link]("Sum of numbers: " + sum);
}
}
-----------------------------------------------------------------
package [Link];
import [Link];
import [Link];
[Link]([Link]::println);
}
}
------------------------------------------------------------------
package [Link];
[Link](".................................");
[Link](al4);
In this fixed lengh array we can’t add/remove any new element but we can replace the existing element
using new element.
[Link]
----------------------
package [Link];
import [Link];
import [Link];
We can’t perform any add or remove or replace operation otherwise we will get
[Link].
package [Link];
import [Link];
}
------------------------------------------------------------------
//Program to fetch the elements in forward and backward
//direction using ListIterator interface
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link](listOfName);
}
}
--------------------------------------------------------------
Serialization and Deserialization on ArrayList object :
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
//Serialization
var fout = new FileOutputStream("D:\\new\\[Link]");
var oos = new ObjectOutputStream(fout);
try(oos; fout)
{
[Link](listOfIceCream);
[Link]("Object Data stored Successfully!!!");
}
catch(Exception e)
{
[Link]();
}
//De-Serialization
try(ois; fin)
{
@SuppressWarnings("unchecked")
ArrayList<String> list = (ArrayList<String>) [Link]();
[Link]([Link]::println);
}
catch(Exception e)
{
[Link]();
}
}
}
Note : In the above program, String and ArrayList both the classes implements from [Link].
------------------------------------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
try(fos; oos)
{
[Link](listOfEmployees);
[Link]("Object data stored successfully");
}
catch(Exception e)
{
[Link]();
}
//De-Serialization
try(fin; ois)
{
@SuppressWarnings("unchecked")
ArrayList<Employee> empList = (ArrayList<Employee>) [Link]();
[Link]([Link]::println);
}
catch(Exception e)
{
[Link]();
}
}
--------------------------------------------------------------
[Link](List<E> list, Comparator<T> comp):
---------------------------------------------------
Collections class has provided static method called reverseOrder()
to reverse the Collection data, the return type of this method is Comparator<T> interface.
package [Link];
import [Link];
import [Link];
[Link]("Hyderabad");
[Link]("Delhi");
[Link]("Banglore");
[Link]("Chennai");
[Link](cities);
[Link]("After sorting (Ascending): " + cities);
[Link](cities, [Link]());
[Link]("After sorting (Descending): " + cities);
}
}
-----------------------------------------------------------------
package [Link];
import [Link];
import [Link];
class Department
{
private String departmentName;
private List<Professor> professors;
}
}
------------------------------------------------------------------
How to copy the data from the Original List :
---------------------------------------------
We can copy the content from original list by using the following two ways :
package [Link];
import [Link];
@SuppressWarnings("unchecked")
ArrayList<String> duplicate =(ArrayList<String>) [Link]();
[Link](duplicate);
ArrayList<String> copy = new ArrayList<>(original);
[Link](copy);
}
}
-----------------------------------------------------------------
public List subList(int fromIndex, int toIndex) :
--------------------------------------------------
It is used to fetch/retrieve the part of the List based on the given index. The return type of this method is
List, Here fromIndex is inclusive and toIndex is exclusive.
package [Link];
import [Link];
import [Link];
[Link]("........................");
[Link]("........................");
}
}
-----------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
}
----------------------------------------------------------------------
public void trimToSize() :
---------------------------
Used to reduce the capacity.
The minCapacaity parameter will specify that ArrayList will definetly hold the number of elements
specified in the parameter of ensureCapacity() method.
package [Link];
import [Link];
import [Link];
[Link](".........................");
[Link](100);
}
-----------------------------------------------------------------------
Time Complexity of ArrayList :
-------------------------------
The time complexity of ArrayList to insert OR delete an element from the middle would be O(n) [Big O of
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 OR begning of the List.
On the other hand time complexity of ArrayList to retrieve an element from the List would be O(1)
because by using get(int index) method we can retrieve the element randomly from the list. ArrayList
class implements RandomAccess marker interface which provides the facility to fetch the elements
Randomly.
[05-FEB]
------------------------------------------------------------------
In order to insert and delete the element in middle of the list frequently, we introduced LinkedList class.
LinkedList<E>
--------------
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 from JDK 1.2v.
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.6 onwards LinkedList class has been enhanced to support basic queue operation by
implementing Deque<E> interface.
It inserts the elements by using Doubly linked List so insertion and deleteion is very easy.
ArrayList is using Dynamic array data structure but LinkedList class is using LinkedList (Doubly
LinkedList) data structure.
At the time of searching an element, It will start searching from Head node OR tail node OR closer one
based on the index.
Constructor:
-------------
It has 2 constructors
3) Object getFirst()
4) Object getLast()
5) Object removeFirst()
6) Object removeLast()
The time complexcity for insertion and deletion is O(1) The time complexcity for seraching O(n)
because it serach the elemnts using node reference.
====================================================================
package [Link].linked_list;
import [Link];
import [Link];
import [Link];
public class LinkedListDemo
{
public static void main(String args[])
{
LinkedList<Object> list=new LinkedList<>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link](null);
[Link](42);
//Iterator interface
}
}
--------------------------------------------------------------------
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](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);
}
}
Note : From the above program, It is clear that insertion and deletion in the LinkedList is very efficient due
to doubly LinkedList data structure.
-------------------------------------------------------------------
package [Link].linked_list;
[Link]("Ravi"); // Rahul
[Link]("Rahul");
[Link]("Anand");
[Link]([Link]());
[Link]([Link]());
[Link]();
[Link]();
[Link](list); //[Rahul]
}
}
-------------------------------------------------------------------
package [Link].linked_list;
//ListIterator methods (add(), set(), remove())
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);
}
}
import [Link];
import [Link];
import [Link];
if(remove)
{
[Link]("Element "+elemenetToDelete+ " is deleted Successfully" );
}
else
{
[Link]("Element "+elemenetToDelete+" not available is the LinkedList");
}
}
break;
case 3:
[Link]("Elements in the linked list.");
[Link]([Link]::println);
break;
case 4:
[Link]("Exiting the program.");
[Link]();
[Link](0);
default:
[Link]("Invalid choice. Please try again.");
}
}
}
}
--------------------------------------------------------------------
package [Link].linked_list;
import [Link];
import [Link];
import [Link];
}
--------------------------------------------------------------------
package [Link].linked_list;
import [Link];
import [Link];
import [Link];
}
-------------------------------------------------------------------
import [Link];
import [Link];
[Link]("Pallavi");
[Link]("Sweta");
Set interface never accept duplicate elements, Here internally equals(Object obj) method is working from
the respective class.
Set interface does not maintain any order (because internally It does not use Array concept, Actually It
uses hashing algorithm)
Set interface supports all the methods of Collection interface, few more methods were added from java
9v.
-------------------------------------------------------------
Set interface Hierarchy :
(07-FEB-25)
-------------------------------------------------------------
What is hashing algorithm ?
-------------------------------
Hashing algorithm is a technique through which we can search, insert and delete an element in more
efficient way in comparison to our classical indexing approach.
Hashing algorithm, internally uses Hashtable data structute, Hashtable data structure internally uses
Bucket data structure.
Here elements are inserted by using hashing algorithm so the time complaxity to insert, delete and search
an element would be O(1).
It is more efficient than our classical array approach which works on the basis of index.
------------------------------------------------------------
08-02-2025
----------
HashSet<E> [UNORDERED, UNSORTED, 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 and introduced from JDK 1.2V.
*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 has constant performance in all the operations like insert, delete and search.
[Link](num-> [Link](num));
}
}
-------------------------------------------------------------
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];
import [Link];
import [Link];
[Link]([Link](arr));
if([Link](15))
{
[Link]("15 is available");
}
else
{
[Link]("It is not available");
}
}
----------------------------------------------------------------
//add, delete, display and exit
import [Link];
import [Link];
while (true)
{
[Link]("Options:");
[Link]("1. Add element");
[Link]("2. Delete element");
[Link]("3. Display HashSet");
[Link]("4. Exit");
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:");
[Link]([Link]::println);
break;
case 4:
[Link]("Exiting the program.");
[Link]();
[Link](0);
default:
[Link]("Invalid choice. Please try again.");
}
[Link]();
}
}
}
--------------------------------------------------------------
package [Link];
import [Link];
[Link](".............");
String size is 1 but StringBuffer size will be 2 because hashCode() and equals(Object obj) methods are
not overridden
in StringBuffer class.
----------------------------------------------------------------
LinkedHashSet<E> [It maintains order]
---------------------------------------
public class LinkedHashSet extends HashSet implements Set, Clonable, Serializable
It is a predefined class in [Link] package under Set interface and introduced from java 1.4v.
It is an orderd version of HashSet that maintains a doubly linked list across all the elements.
When we iterate the elements through HashSet the order will be unpredictable, while when we iterate the
elements through LinkedHashSet then the order will be same as they were inserted in the collection.
[Link](10);
[Link](5);
[Link](15);
[Link](20);
[Link](5);
[Link]();
[Link]("After clearing, LinkedHashSet elements: " + linkedHashSet);
}
}
---------------------------------------------------------------
SortedSet interface :
---------------------
As we know [Link](List list) method accept list as a parameter so, we can’t perform sorting
operation by using sort() method on HashSet and LinkedHashSet.
In order to provide automatic sorting facility, Set interface has provided one more interface i.e SortedSet
interface available from JDK 1.2.
SortedSet interface provided default natural sorting order, default natural sorting order means, if it is
number then ascending order but if it is String then alphabetical OR dictionary order.
In order to sort the element either in default natural sorting order or user-defined sorting order we are
using Comparable or Comparator interfaces.
--------------------------------------------------------------
10-02-2025
-----------
Comparable<T> and Comparator<T> interfaces :
--------------------------------------------
1) Comparable<T> and Comparator<T> both are functional interfaces.
//Program on Comparable :
-------------------------
package [Link];
package [Link];
import [Link];
import [Link];
[Link](listOfCustomers);
[Link]("Data After sorting based on the ID :");
[Link]([Link]::println);
}
-----------------------------------------------------------------
package [Link].updated_array_25;
import [Link];
record Employee(Integer id, String name) implements Comparable<Employee>
{
@Override
public int compareTo(Employee e2)
{
return [Link] - [Link];
}
[Link](employees);
}
}
------------------------------------------------------------------
Limitation of Comparable interface :
------------------------------------
We have 3 limitations with Comparable<T>
-----------------------------------------
1) We need to modify the BLC class OR Original source code to provide current object support(this
keyword), If the BLC class OR
source code is provided by any 3rd party developer and we are unable to modify the source code then
Comparable will not work.
//Program on Comparator<T>
---------------------------
package [Link];
package [Link];
import [Link];
import [Link];
}
-----------------------------------------------------------------
How to sort the Integer object in descending order by using Comparator :
package [Link];
import [Link];
import [Link];
public class IntegerDesc {
[Link](al,(i1,i2)-> [Link](i1));
[Link](al);
}
---------------------------------------------------------------
List intreface sort() method :
-------------------------------
List interface has provided sort(Comparator<t> cmp) method introduced from JDK 1.8 which accepts
Comapartor as a parameter.
package [Link];
import [Link];
[Link]((i1,i2)-> [Link](i2));
[Link](listOfNumber);
[Link]((s1,s2)-> [Link](s1));
[Link](listOfCity);
}
}
-----------------------------------------------------------------
11-02-2025
----------
TreeSet<E>
-----------
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Clonable, Serializable
It is a predefined class available in [Link] package under Set interface available from JDK 1.2v.
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 according to user choice, It
uses Comparable/Comparator interface.
It does not accept non comparable type of Objects if we try to insert it will throw a runtime exception i.e
[Link]
--------------------------------------------------------------
//program that describes by default 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);
Note :- descendingIterator() is a predefined method of TreeSet class which will traverse in the descending
order and return type of this method is Iterator interface available from JDK 1.6
package [Link];
import [Link];
import [Link];
}
---------------------------------------------------------------
How to sort TreeSet by using Comparator :
package [Link];
import [Link];
[Link](ts1);
}
}
---------------------------------------------------------------
import [Link].*;
public class TreeSetDemo5
{
public static void main(String[] args)
{
Set<String> t = new TreeSet<>((s1,s2)-> [Link](s1));
[Link]("6");
[Link]("5");
[Link]("4");
[Link]("2");
[Link]("9");
Iterator<String> iterator = [Link]();
[Link](x -> [Link](x));
}
}
--------------------------------------------------------------
import [Link].*;
import [Link];
for(Student st : ts1)
{
[Link](st);
}
TreeSet<Student> ts2 = new TreeSet<>((s1,s2) -> [Link]([Link](), [Link]()));
[Link](new Student(333, 25000D));
[Link](new Student(222, 2200D));
[Link](new Student(111, 20000D));
for(Student st : ts2)
{
[Link](st);
}
}
}
--------------------------------------------------------------
Methods of SortedSet interface :
--------------------------------------
public E first() :- Will fetch first 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);
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<E>
---------------
It is used to navigate among the elements, Unlike SortedSet which provides range of values. Here we can
navigate among the values as shown below.
import [Link].*;
}
}
--------------------------------------------------------------
12-02-2025
-----------
Map<K,V> 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. {key = value}
Map interface works with key and value pair introduced from 1.2V.
Here key and value both are objects.
Each key and value pair is creating one Entry.(Entry is nothing but the combination of key and value pair)
In Map interface whenever we have a duplicate key then the old key value will be replaced by new
key(duplicate key) value.
Map interface has defined forEach(BiConsumer cons) method to work with group of [Link] does not
extends Iterable interface.
1) Object put(Object key, Object value) :- To insert one entry in the Map collection. It will return the value
of old Object key, if the key is already available(Duplicate key), If key is not available (new key) then it will
return null.
2) Object putIfAbsent(Object key, Object value) :- It will insert an entry, if and only if, key is not available ,
if the key is already available then it will not insert the Entry to the Map Collection
3) Object get(Object key) :- It will return corresponding value of the key, if the key is not present then it
will return null.
4) Object getOrDefault(Object key, Object defaultValue) :- To avoid null value this method has been
introduced from JDK 1.8V, here we can pass some defaultValue to avoid the null value.
3) public Set<[Link]> entrySet() : It will retrieve key and value both in a single object.
a) getKey()
b) getValue()
--------------------------------------------------------------
**** 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 only equals(Object obj) method is invoked to compare
those keys by using state(data). [content comparison]
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 by new key value.
If equals(Object obj) method returns false, this new key is unique, new entry (key-value) will be inserted
in the same Bucket by using Singly LinkedList
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 SAME 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 Hashtable 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.
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.
--------------------------------------------------------------
14-02-2025
----------
** 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.
Note : IF TWO OBJECTS ARE HAVING SAME HASH CODE THEN IT MAY BE SAME OR DIFFERENT
BUT IF EQUALS(OBJECT OBJ) METHOD RETURNS TRUE THEN BOTH OBJECTS MUST RETURN
SAME HASHCODE.
package [Link];
import [Link];
[Link]("....................");
}
-------------------------------------------------------------
What will happen if we don’t follow the contract ?
Case 1 :
--------
If we override only equals(Object obj)
---------------------------------------
If we override only equals(Object obj) method for content comparison
then same object (duplicate object) will have different hashcode (due to Object class hashCode()) hence
same object (content wise) will move into two different buckets [Duplication].
Case 2 :
--------
If we override only hashCode() method
--------------------------------------
If we overrdie only hashCode() method then two objects which are having same hashcode (due to
overriding) will go to same bucket but == operator and equals(Object obj) method of Object class, both
will return false hence duplicate object will be inserted into same bucket by using Singly LinkedList.
So, the conclusion is, compulsory we need to override both the methods for removing duplicate
elements.
package [Link];
import [Link];
import [Link];
class Customer
{
private Integer customerId;
private String customerName;
@Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" + customerName + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
Customer other = (Customer) obj;
return [Link](customerId, [Link]) && [Link](customerName,
[Link]);
}
[Link]([Link]()+" : "+[Link]());
[Link]([Link](c2));
[Link]("..............................");
HashMap<Customer,String> map = new HashMap<>();
[Link](c1, "A");
[Link](c2, "B");
[Link]([Link]()); //1
[Link](map); //{c1 = B}
All the Wrapper classes and String class are immutable as well as
hashCode() and equals(Object obj) methods are overridden in these classes so perfectly suitable to
becoming HashMap key.
--------------------------------------------------------------
package [Link];
import [Link];
record Manager(Integer id, String managerName)
{
[Link]([Link]());
so final conclusion is, In our user-defined class which we want to use as a HashMap key must be
immutable and hashCode() and equals(Object obj) method must be overridden.
Instead of BLC class we can also use simply record because record is implicitly final and hashCode() and
equals(Object obj) methods are overridden.
---------------------------------------------------------------
package [Link];
import [Link];
int hashCode = 0;
return hashCode;
}
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter your String :");
String str = [Link]();
[Link]("..................");
[Link]();
}
}
--------------------------------------------------------------
HashMap<K,V> :- [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 available from JDK 1.2v.
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 accepts only one null key(because duplicate keys are not allowed) but multiple null values are allowed.
For eliminating duplicate keys in hashMap object we should compulsory follow the contract between
hashcode and equals(Object obj) OR Use record
import [Link];
import [Link];
import [Link];
[Link](1, "Vanilla");
[Link](2, "Butterscotch");
[Link](3, "Chocolate");
[Link](4, "Cotton Candy");
[Link](1);
[Link]("HashMap after removing key 1: " + map);
[Link]();
[Link]("HashMap after clearing: " + map); //{}
}
}
--------------------------------------------------------------
package [Link];
import [Link];
[Link](101, "Scott");
[Link](102, "Smith");
[Link](103, "Martin");
[Link](104, "Aryan");
if (studentName != null)
{
[Link]("Student with ID " + searchId + " is " + studentName);
}
else
{
[Link]("Student with ID " + searchId + " not found.");
}
[Link]([Link](103, "Rahul"));
[Link]("Updated Records: " + studentRecords);
[Link](104);
[Link]("Records after removal: " + studentRecords);
[Link]();
[Link]("All records cleared: " + studentRecords);
}
}
---------------------------------------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
[Link](1, "OCPJP");
[Link](2, "is");
[Link](3, "best");
[Link](4, "Exam");
[Link](newmap1);
[Link](1, "Ravi");
[Link](2, "Rahul");
[Link](3, "Rajen");
}
}
--------------------------------------------------------------
17-02-2025
-----------
package [Link];
import [Link];
import [Link];
// Borrow a book
String bookToBorrow = "Advanced Java";
if ([Link](bookToCheck))
{
String availability = [Link](bookToCheck) ? "available" : "borrowed";
[Link](bookToCheck + " Book is " + availability + ".");
}
else
{
[Link](bookToCheck + " is not in the library.");
}
//Display the final library status
}
}
--------------------------------------------------------------
LinkedHashMap<K,V>
-------------------
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 available from 1.4.
It maintains insertion order. It contains a doubly linked with the elements or nodes so It will iterate more
slowly in comparison to HashMap.
If We want to fetch the elements in the same order as they were inserted in the Map then we should go
with LinkedHashMap.
It is not synchronized.
--------------------------------------------------------------
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].*;
[Link]((k,v)->[Link](k+" : "+v));
}
}
It is predefined class available in [Link] package under Map interface from JDK 1.0.
Like Vector, Hashtable is also form the birth of java so called legacy class.
*The major difference between HashMap and Hashtable is, HashMap methods are not 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 then JVM will throw an exception i.e
NullPointerException.
//[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<K,V> :
------------------
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 as well as Object is
also 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 and corresponding object 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 does not implements Cloneable and Serailizable because It is mainly used for inventory system where
we need to manage the data and we can insert and delete object data frequently in the inventory.
Creates an empty WeakHashMap object with default capacity is 16 and load fator 0.75
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.
package [Link];
import [Link];
[Link](map);
p1 = null;
[Link](3000);
[Link](map); //{}
}
------------------------------------------------------------
18-02-2025
-----------
How to generate OR find out System hashcode value :
---------------------------------------------------
System class has provided a predefined native and static method called identityHashCode(Object obj), It
is used to
generate System hashcode.
It accepts Object as a parameter and return type of this method is int.
If we don’t override hashCode() method in the corresponding class then System generated Hashcode and
Object class hashcode would be same.
package [Link];
class Foo
{
}
public class SystemHashCode {
[Link]([Link](str1));
[Link]([Link](str2));
[Link](".........................");
Foo f1 = new Foo();
Foo f2 = new Foo();
[Link]([Link](f1));
[Link]([Link](f2));
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 compare the keys by using 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)
package [Link];
import [Link];
import [Link];
[Link]("........................");
}
-----------------------------------------------------------------
SortedMap<K,V>
--------------
It is a predefined interface available in [Link] package under Map interface available from JDK 1.2V.
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.
It is a predefined class avaialble in [Link] package under Map interface available for 1.2V.
It is a sorted map that means it will sort the elements by natural sorting order based on the key or by
using Comparator interface as a constructor parameter.
TreeMap implements NavigableMap and NavigableMap extends SortedMap. SortedMap extends Map
interface.
}
-------------------------------------------------------------
import [Link].*;
public class TreeMapDemo
{
public static void main(String[] args)
{
TreeMap<Object,String> 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]("six", "Xyz");
//[Link](null, "abc");
[Link](t);
}
}
Note : put() method, internally uses compareTo() method of Integer class to sort the key object in
ascending order.
------------------------------------------------------------
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);
}
static void displayMap(TreeMap map)
{
Collection c = [Link](); //Set<[Link]>
Iterator i = [Link]();
[Link](x -> [Link](x));
}
}
------------------------------------------------------------
//firstKey() lastKey() headMap() tailMap() subMap() SortedMap
// first() last() headSet() tailSet() subSet() SortedSet
import [Link].*;
public class TreeMapDemo2
{
public static void main(String[] argv)
{
Map<String,String> map = new TreeMap<String,String>();
[Link]("key2", "value2");
[Link]("key3", "value3");
[Link]("key1", "value1");
[Link](map); //
import [Link];
}
public class TreeMapDemo3
{
public static void main(String[] args)
{
TreeMap<Product,String> tm1 = new TreeMap<>((p1, p2)-> [Link]().compareTo([Link]()));
[Link](new Product(333, "Laptop"), "Hyderabad");
[Link](new Product(444, "Mobile"), "Pune");
[Link](new Product(111, "HeadPhone"), "Indore");
[Link](new Product(222, "Camera"), "Mumbai");
}
-------------------------------------------------------------
package [Link].tree_map;
import [Link];
import [Link];
import [Link];
//TreeMap(SortedMap<K,V>)
TreeMap<String, Integer> map2 = new TreeMap<>(map1);
[Link](map2);
[Link]("......................");
//HashMap to TreeMap
HashMap<Integer, String> hm1 = new HashMap<>();
[Link](89, "Ravi");
[Link](71, "Scott");
[Link](17, "Smith");
[Link](13, "Martin");
}
------------------------------------------------------------
Methods of SortedMap interface :
--------------------------------
1) firstKey() //first key
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() return type 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");
}
}
-----------------------------------------------------------
Assignment for NavigableMap Methods :
-------------------------------------
1) ceilingEntry(K key)
2) ceilingKey(K key)
3) floorEntry(K key)
4) floorKey(K key)
5) higherEntry(K key)
6) higherKey(K key)
7) lowerEntry(K key)
8) lowerKey(K key)
-------------------------------------------------------------
19-02-2025
-----------
Properties :
------------
public class Properties extends Hashtable<K,V>
It is used to maintain the persistent data in the key-value form. It takes both key and value as a String
format.
It is used to load properties file in our java application directly at runtime without compilation/deploymnet.
Constructors :
--------------
Commonly we are using this constructor :
Methods :
----------
1) public void load(InputStream stream): Reads a property list (key and value pair) from the input byte
stream.
2) public void load(Reader reader):Reads a property list (key and value pair) from the Character
Oriented stream.
3) Object setProperty(String key, String value) : It Calls the Hashtable method put internally.
4) public String getProperty(String key) :Searches for the property with the specified key in this property
list.
Program :
----------
Create a [Link] file as shown below :
--------------------------------------------
[Link]
--------------
driver = [Link]
userName = scott
password = tiger
[Link]
--------------------
import [Link].*;
import [Link].*;
If we make changes in the properties file then directly (without compilation) we can take the the value in
our java file so after any modification in the properties file we need not to re-compile/re-deploy our java
program.
-----------------------------------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
try(writer)
{
[Link]("book", "Java");
[Link]("author", "James");
[Link]("price", "1200");
}
catch(Exception e)
{
[Link]();
}
try(reader)
{
[Link](reader);
[Link]("Book Name is "+[Link]("book"));
[Link]("Author Name is "+[Link]("author"));
[Link]("Price Name is "+[Link]("price"));
}
catch(Exception e)
{
[Link]();
}
}
}
------------------------------------------------------------
Queue interface :-
-------------------
1) It is sub interface of Collection(I) available from JDK 1.5V hence it support all the methods of Collection
interface.
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)In order to support Basis Queue operation, LinkedList class implements Deque and Deque interface
exetnds Queue
interface.
PriorityQueue<E>
-----------------
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
It stores the elements using balanced binary heap tree, meaning the smallest element is at the head of
the queue.
The elements of the priority queue are ordered according to their natural ordering (binary heap tree), or by
using Comparator provided at queue construction time, depending on which constructor is used.
It provides natural sorting order so we can’t take non-comparable objects(hetrogeneous types of Object)
Constructor :
--------------
1) PriorityQueue pq1 = new PriorityQueue();
Will create PriorityQueue object with default capacity is 11, Elements will be inserted based on binary
heap tree.
Methods :-
----------
public boolean offer(E e) /public boolean add(E e) :- Used to add an element in the Queue
public E poll() :- It is used to fetch the elements from head of the queue, after fetching it will delete the
element.
public E peek() :- It is also used to fetch the elements from head of the queue, Unlike poll it will only fetch
but not delete the element.
public boolean remove(Object element) :- It is used to remove an element. The return type is boolean.
------------------------------------------------------------ import [Link];
//[Link](null); // Inavlid
//[Link](23); //Invalid
[Link](pq);
}
}
----------------------------------------------------------
import [Link];
public class PriorityQueueDemo1
{
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 PriorityQueueDemo2
{
public static void main(String[] argv)
{
PriorityQueue<String> pq = new PriorityQueue<>();
[Link]("2");
[Link]("4");
[Link]("6");
[Link]([Link]() + " "); //2 2 3 4 4
[Link]("1");
[Link]("9");
[Link]("3"); // 6 9
[Link]("1");
[Link]([Link]() + " ");
if ([Link]("2"))
{
[Link]([Link]() + " ");
}
[Link]([Link]() + " " + [Link]()+" "+[Link]());
}
}
------------------------------------------------------------
package [Link];
import [Link];
import [Link];
while (![Link]())
{
[Link]("Executing: " + [Link]());
}
}
}
=============================================================
Generics :
----------
What is the need of Generics ?
-------------------------------
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.
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 to provide casting as shown below.
import [Link].*;
class Test
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
[Link](12);
[Link](15);
[Link](18);
[Link](22);
[Link](24);
Note : Even we are accepting only Integer type of Object but still type casting is required.
-------------------------------------------------------------
import [Link].*;
class Test1
{
public static void main(String[] args)
{
ArrayList al = new ArrayList(); //raw type
[Link]("Ravi");
[Link]("Ajay");
[Link]("Vijay");
}
}
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);
}
}
}
Even after type casting there is no guarantee that the things which are coming from ArrayList Object is
String only because we can add anything in the Collection as a result [Link]
-------------------------------------------------------------
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 guarantee of both the end i.e putting inside and getting
outside.
Example:-
ArrayList<String > al = new ArrayList<>();
Now here we have a guarantee 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 of Generics :
------------------------
1) Type Safe Object (No Compilation warning)
2) No need of type casting
3) Strict compile time checking. (*Type Erasure)
------------------------------------------------------------
import [Link].*;
public class Test3
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<>(); //Generic type
[Link]("Ravi");
[Link]("Ajay");
[Link]("Vijay");
package [Link];
import [Link];
import [Link];
return listOfDogs;
}
}
Note :- In the above program the compiler will stop us from returning anything which is not compaitable
List<Dog> and there is a guarantee 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());
[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);
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 generics 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
import [Link].*;
public class TypeErasure
{
public static void main(String[] args)
{
}
import [Link].*;
abstract class Animal
{
public abstract void checkup();
}
checkAnimals(dogs);
checkAnimals(cats);
checkAnimals(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();
}
}
}
So from the above program it is clear that polymorphism does not work in the same way for generics as it
does with arrays.
Example :
------------------------------------------------------------
21-02-2025
---------
import [Link].*;
public class Test10
{
public static void main(String [] args)
{
/* ArrayList<Object> al = new ArrayList<String>(); [Compile time ]
ArrayList al = new ArrayList(); [Runtime, Type Erasure]
[Link]("Ravi");*/
Note :- Program will generate [Link] because we are trying to insert 90 (integer
value) into String array.
In Array we have an Exception called ArrayStoreException (Which protect us to assign some illegal value
in the array) but the same Exception or such type of exception, is not available with Generics (due to
Type Erasure) that is the reason in generics, compiler does not allow upcasting concept.
(It is a strict compile time protection)
------------------------------------------------------------
Wildcard character <?>
-----------------------
Different Cases :
-----------------
Case 1 :
---------
<Dog> : Only we can take <Dog> object
Now to provide some kind of restriction, java software people has provided two more concepts
1) Upper Bound
2) Lower Bound
Upper Bound :
-------------
<? extends Animal> : This is upper bound here we can replace
wild-card (?) with any class which
extends Animal but here there is a chance
of wrong collection in the future because
in future Animal can have more sub classes
so, we can’t add any element in the Collection.
Lower Bound :
--------------
<? super Dog> : This is called lower bound, Here we can replace wild card (?) with with any
class which is super of Dog i.e Animal, Object. Here compiler knows
that the only classes which are super of Dog are
allowed so adding element in the collection is allowed.
package [Link].wild_card;
import [Link];
class Animal
{
}
----------------------------------------------------------------
import [Link].*;
class Parent
{
}
class Child extends Parent
{
}
[Link]("Success");
}
}
---------------------------------------------------------------
Working in some places :
-------------------------
var<?> lp = new ArrayList<Parent>();
[Link](new Parent());
[Link]("Wild card....");
----------------------------------------------------------------
//program on wild-card chracter
import [Link].*;
class Parent
{
}
class Child extends Parent
{
}
public class Test12
{
public static void main(String [] args)
{
ArrayList<?> lp = new ArrayList<Parent>();
[Link]("Wild card....");
}
}
-----------------------------------------------------------------import [Link].*;
public class Test13
{
public static void main(String[] args)
{
List<? extends Number> list1 = new ArrayList<Long>();
[Link]("yes");
}
}
class Alpha
{
}
class Beta extends Alpha
{
}
class Gamma extends Beta
{
}
--------------------------------------------------------------
class MyClass<T>
{
T obj;
public MyClass(T obj) //Student obj
{
[Link]=obj;
}
T getObj()
{
return [Link];
}
}
public class Test14
{
public static void main(String[] args)
{
Integer i=12;
MyClass<Integer> mi = new MyClass<>(i);
[Link]("Integer object stored :"+[Link]());
Float f=12.34f;
MyClass<Float> mf = new MyClass<>(f);
[Link]("Float object stored :"+[Link]());
Double d=99.34;
MyClass<Double> md = new MyClass<>(d);
[Link]("Double object stored :"+[Link]());
}
---------------------------------------------------------------
package [Link];
class Basket<E>
{
private E element;
public E getElement()
{
return element;
}
}
class Fruit {
@Override
public String toString() {
return "Orange []";
}
}
}
----------------------------------------------------------------
//Generic Method
public class Test16
{
public static void main(String[] args)
{
Integer []intArr = {10,20,30,40,50};
printArray(intArr);
[Link](".............");
}
===============================================================