Understanding Java Language Basics
Understanding Java Language Basics
-------------
A language is a communication media.
1) Syntax (Rules)
2) Semantics (Structure OR Meaning)
He is a boy. (Valid)
He is a box. (Invalid)
Note :-
Syntax of the programming language is taken care by compiler.
compiler generates errors if a user does not follow the syntax of the programming
language.
In these languages we can hold different kind of value during the execution of the
program.
Ex:- Visual Basic, Javascript, Python
----------------------------------------------------------------
Flavors Of JAVA language :
------------------------------
1) JSE (Java Standard Edition) ->J2SE -> Core Java
2) JEE (Java Enterprise Edition) -> J2EE -> Advanced Java
-------------------------------------------------------------------
What is the difference between stand-alone programs and web-related
programs?
Standalone Application
--------------------------
If the creation(development), compilation and execution of the program, everthing
is done in a single system then it is called stand-alone program.
Eg:- C, C++, Java, C# and so on.
2) Easy understanding :- Once we divide the bigger task into number of smaller
tasks then it is easy to understand the entire code.
4) Easy Debugging :- Debugging means finding the errors, With function It is easy
to find out the errors because each module is independent with another module.
------------------------------------------------------------------
31-Aug-23
---------
Eg:-
-----------------------------------------------------------------------------------
---
Why functions are called method in java?
----------------------------------------------
In C++ there is a facility to write a function inside the class as well as outside
of the class by using :: (Scope resolution Operator), But in java all the functions
must be declared inside the class only.
That is the reason C and C++ programs are not suitable for website development.
Note :- We have different JVM for different Operating System that means JVM is
platform dependent technology where as Java is platform Independent technology.
-------------------------------------------------------------------
What is the difference between bit code and bytecode?
-----------------------------------------------------
Bit code is directly understood by Operating System but on the other hand byte code
is understood by JVM, JVM is going to convert this byte code into machine
understandable format.
-------------------------------------------------------------------
Comments in JAVA :-
------------------------
Comments are used to increase the readability of the program. It is ignored by the
compiler.
In java we have 3 types of comments
/**
Name of the Project : Online Shopping
Date created :- 12-12-2021
Last Modified - 16-01-2022
Author :- Ravishankar
Modules : - 10 Modules
*/
------------------------------------------------------------------
Note :-
1) In java whenever we write a program we need at least a main method which takes
String array as an argument.
2) In java the execution of the program always starts and ends with main method.
public :-
--------
public is an access modifier in java. The main method must be declared as public
otherwise JVM cannot execute our main method or in other words JVM can't enter
inside the main method for execution of the program.
If main method is not declared as public then program will compile but it will not
be executed by JVM.
Note :- From java compiler point of view there is no rule to declare our methods as
public.
-----------------------------------------------------------------
static :-
--------
In java our main method is static so JVM need not to create an object to call the
main method.
We can directly call the static methods, if it is defined in the same class on the
other hand if is defined in another class then we can call with the help of class
name.
If we don't declare the main method as static method then our program will compile
but it will not be executed by JVM.
-----------------------------------------------------------------
void :-
-------
It is a keyword. It means no return type. Whenever we define any method in java and
if we don't want to return any kind of value from that particular method then we
should write void before the name of the method.
Eg:
Note :- In the main method if we don't write void or any other kind of return type
then it will generate a compilation error.
In java whenever we define a method then compulsory we should define return type of
method.(Syntax rule)
-----------------------------------------------------------------
main() :-
----------
It is a user defined function/method because a user is responsible to define some
logic inside the main method.
main() method is very important method because every program execution will start
from main() method only, as well as the execution of the program ends with main()
method only.
Internally JVM is calling this main method with the help of class name.
-----------------------------------------------------------------
Command Line Argument (Introduction):-
-------------------------------------
Whenever we pass an argument/parameter to the main method then it is called Command
Line Argument.
The argument inside the main method is String because String is a alpha-numeric
collection of character so, It can accept numbers,decimals, characters, combination
of number and character.
That is the reason java software people has provided String as a parameter inside
the main method.(More Wider scope to accept the value)
-----------------------------------------------------------------
04-Sep-23
---------
String [] args :-
------------------
Here String is a predefined class available in [Link] package(Header files in C
and C++) and args is an array variable of type String.
Note :- args is an array variable, we can take square bracket before the variable
as well as after the variable.
--------------------------------------------------------------------
[Link]() :-
-------------------------
It is an output statement in java, By using [Link]() statement we can
print anything on the console.
-> By using Eclipse IDE , In a single window we can develop, compile and execute
our programs
-> Eclipse IDE provides an environment to execute our program with very less time.
Once the time will be reduced then automatically the cost of the project will be
reduced.
What is a package :
------------------
-> A package is nothing but folder in widows.
-> The main purpose of package to arrange our programs so fast searching will
become easy.
The following command will create a folder having same name with package :
Program :
---------
package [Link];
The advantage of command line argument is "Single time compilation and number of
times execution".
------------------------------------------------------------------
//Write a program to pass some value at runtime using Command Line Argument
Note :- In the above program both the values are appended to each other and here
'+' operator behaves like String concatenation operator
----------------------------------------------------------------------
How to convert a String value into integer :
--------------------------------------------
If we want to convert any String value into integer then java software people has
provided a predefined class called Integer available in [Link] package, this
class contains a predefined static method parseInt(String x) through which we can
convert any String value into integer.
This parseInt(String str) method throws an exception
[Link]
[Link]("Sum is :"+(i+j));
}
}
thisIsExampleOfMethod()
Example:
----------
read()
readLine()
toUpperCase()
charAt()
rollNumber;
employeeName;
customerNumber;
customerBill;
MAX_VALUE;
MIN_VALUE;
Each character must be capital and in between every word _ symbol should be there.
-----------------------------------------------------------------------
Token :
--------
A token is the smallest unit of the program that is identified by the compiler.
Every Java statements and expressions are created using tokens.
1) Keywords
2) Identifiers
3) Literals
4) Punctuators
5) Operators
Keyword :-
----------
A keyword is a predefined word whose meaning is already defined by the compiler.
A keyword we can't use as a name of the variable, name of the class or name of the
method.
true, false and null look like keywords but actually they are literals.
Identifiers :
--------------
A name in java program by default considered as identifiers.
Ex:-
class Fan
{
int coil ;
void start()
{
}
}
Here Fan(Name of the class), coil (Name of the variable) and start(Name of the
function) are identifiers.
-----------------------------------------------------------------------------------
-
Rules for defining an identifier :
------------------------------------
1) Can consist of uppercase(A-Z), lowercase(a-z), digits(0-9), $ sign, and
underscore (_)
2) Begins with letter, $, and _
3) It is case sensitive
4) Cannot be a keyword
5) No limitation of length
-----------------------------------------------------------------------------------
-
Literals :-
-----------
Assigning some constant value to variable is called Literal.
Java supports 5 types of Literals :
Decimal Literal :-
-------------------
The base of decimal literal is 10. we can accept any digit from 0-9
Octal Literal :-
----------------
The base is 8. Here we can accept digits from 0-7 only. In java if any integral
literal prefeix with '0' (Zero) then it becomes octal lietral.
Example:-
Hexadecimal Literal :-
-------------------------
The base is 16. Here we can accept digits from 0-15 (0-9 and A-F). In java if any
integral literal prefix with 0X or 0x (zero with capital X OR zero with small x)
then it becomes hexadecimal literal.
Example :-
Binary Literal :-
-----------------
It is introduced from jdk 1.7 onwards. The base or radix is 2. Here we can accept
digits 0 and 1 only. In java if any integral Literal prefix with 0B or 0b (zero
capital B or 0 small b) then it becomes binary literal.
Example :-
Note :-
------
Being a user we can represent integral literal in decimal, octal, hexadecimal and
binary form but JVM always produces the result in decimal only.
-----------------------------------------------------------------------
07-Sep-23
----------
//Octal literal
public class Test1
{
public static void main(String[] args)
{
int one=01;
int six=06;
int seven=07;
int eight=010;
int nine=011;
[Link]("Octal 01 = "+one);
[Link]("Octal 06 = "+six);
[Link]("Octal 07 = "+seven);
[Link]("Octal 010 = "+eight);
[Link]("Octal 011 = "+nine);
}
}
----------------------------------------------------------------------
//Hexadecimal
public class Test2
{
public static void main(String[] args)
{
int i = 0x10; //16
int j = 0Xadd; //2781
[Link](i);
[Link](j);
}
}
----------------------------------------------------------------------
//Binary Literal
public class Test3
{
public static void main(String[] args)
{
int i = 0b101;
int j = 0B111;
[Link](i); //5
[Link](j); //7
}
}
---------------------------------------------------------------------
By default every integral literal is of type int only but we can specify explicitly
as long type by suffixing with l (small l) OR L (Capital L).
There is no direct way to specify byte and short literals explicitly. If we assign
any integral literal to byte variable and if the value is within the range (-128 to
127) then it is automatically treated as byte literals.
If we assign integral literals to short and if the value is within the range (-
32768 to 32767) then automatically it is treated as short literals.
-----------------------------------------------------------------------
/* By default every integral literal is of type int only*/
public class Test4
{
public static void main(String[] args)
{
byte b = 128; //error becoz 128 is int value
[Link](b);
long l = 29L;
[Link]("l value = "+l);
}
}
---------------------------------------------------------------------
08-Sep-23
---------
Java is pure object oriented language or not ?
----------------------------------------------
No, Java is not a pure Object-Oriented language. In fact any language which accepts
the primary data type like int, float, char is not a pure object oriented language
hence java is also not a pure object oriented language.
If we remove all 8 primitive data types from java then Java will become pure object
oriented language.
In java we have a concept called Wrapper classes through which we can convert the
primary data types into corrosponding Wrapper Object.
Boolean b = true;
[Link](b);
Double d = 90.90;
[Link](d);
}
}
---------------------------------------------------------------------
How to know the minimum and maximum value as well as size of integral literal data
types:
-----------------------------------------------------------------------------------
-
Thses classes (Wrapper classes) are providing the static and final variables
through which we can find out the minimum, maximum value as well as size of the
data types
Example:- I want to find out the range and size of Byte class
Byte.MIN_VALUE = -128
Byte.MAX_VALUE = 127
Here MIN_VALUE, MAX_VALUE and SIZE these are static and final variables available
in these classes(Byte, Short, Integer and Long).
---------------------------------------------------------------------
//Program to find out the range and size of Integeral Data type
public class Test9
{
public static void main(String[] args)
{
[Link]("\n Byte range:");
[Link](" min: " + Byte.MIN_VALUE);
[Link](" max: " + Byte.MAX_VALUE);
[Link](" size :"+[Link]);
}
}
---------------------------------------------------------------------
Underscore Facility in integeral literal :
--------------------------------------------
From java 7v onwards, now we can provide _ symbol while writing the
integral literal just to enhance the readability of the number.
//decimal to Octal
[Link]([Link](15));
//decimal to Hexadecimal
[Link]([Link](2781));
}
}
---------------------------------------------------------------------
// Converting from decimal to another number system
public class Test12
{
public static void main(String[] argv)
{
//decimal to Binary
[Link]([Link](47));
//decimal to Octal
[Link]([Link](15));
//decimal to Hexadecimal
[Link]([Link](2781));
}
}
-------------------------------------------------------------------
//var keyword from java 10v
public class Test13
{
public static void main(String[] args)
{
var x = 12; //From java 10v
x = 15;
[Link]("x value is :"+x);
}
}
---------------------------------------------------------------------
Floating point Literals :
---------------------------
1) The literals which contains decimal point or fraction are called Floating Point
Literal.
float f1 = 23.90f;
float f2 = 23.90F;
4) As we know by default every floating point literal is of type double but still
we have two flavors given by the java compiler to represent double value explicitly
just to enhance the readability of the code.
a) double d1 = 1.1d;
b) double d2 = 1.1D;
5) *While working with Integral literal we had four flavors i.e decimal, octal,
hexadecimal and binary.
But while working with floating point literal only decimal form is allowed.
6) *Any integral literal we can assign on floating point literal but floating point
literal we can't assign on integral literal.
}
}
---------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
double d = 15.15;
double e = 15.15d;
double f = 15.15D;
[Link](d+" : "+e+" : "+f);
}
}
----------------------------------------------------------------------
public class Test3
{
public static void main(String[] args)
{
double x = 0129.89;
double y = 0167;
[Link](x+","+y+","+z);
}
}
-----------------------------------------------------------------------
class Test4
{
public static void main(String[] args)
{
double x = 0X29;
double y = 0X9.15;
[Link](x+","+y);
}
}
-----------------------------------------------------------------------
public class Test5
{
public static void main(String[] args)
{
double d1 = 15e-3;
[Link]("d1 value is :"+d1);
double d2 = 15e3;
[Link]("d2 value is :"+d2);
}
}
----------------------------------------------------------------------
public class Test6
{
public static void main(String[] args)
{
double a = 0791; //error
double b = 0791.0;
double c = 0777;
double d = 0Xdead;
2) In char literal we have one data type i.e char data type which accepts 2 bytes
(16 bits) of memory.
c) Char literals we can also assign to integral data types to get the UNICODE
value of that particular character.
d) Char literals we can also represent in UNICODE format where it must contain
4 digit hexadecimal number.
}
}
----------------------------------------------------------------------
class Test2
{
public static void main(String[] args)
{
int ch = 'A';
[Link]("ch value is :"+ch);
}
}
---------------------------------------------------------------------
//The UNICODE value for ? character is 63
public class Test3
{
public static void main(String[] args)
{
char ch1 = 63;
[Link]("ch1 value is :"+ch1);
char ch3 = 1;
[Link]("ch3 value is :"+ch3);
}
}
---------------------------------------------------------------------
public class Test4
{
public static void main(String[] args)
{
char ch1 = 65535;
[Link]("ch1 value is :"+ch1);
Note :- Here we will get the output as ? because the equivalent language translator
for these particular characters are not available in my system.
----------------------------------------------------------------------
//Addition of two character in the form of Integer
public class Test5
{
public static void main(String txt[ ])
{
int x = 'A';
int y = 'B';
[Link](x+y);
[Link]('A' + 'A');
}
}
--------------------------------------------------------------------
//Range of UNICODE Value (65535)
class Test6
{
public static void main(String[] args)
{
char ch1 = 65535;
[Link]("ch value is :"+ch1);
Example:-
boolean isValid = true;
boolean isEmpty = false;
boolean d = "true"; //here true is String literal not boolean, not possible
boolean e = "false";//here false is String literal not boolean, not possible
---------------------------------------------------------------------
public class Test1
{
public static void main(String[] args)
{
boolean isValid = true;
boolean isEmpty = false;
[Link](isValid);
[Link](isEmpty);
}
}
--------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
boolean c = 0; //error
boolean d = 1; //error
[Link](c);
[Link](d);
}
}
---------------------------------------------------------------------
public class Test3
{
public static void main(String[] args)
{
boolean x = "true"; //error
boolean y = "false"; //error
[Link](x);
[Link](y);
}
}
---------------------------------------------------------------------
String Literal :-
----------------
A string literal in Java is basically a sequence of characters. These characters
can be anything like alphabets, numbers or symbols which are enclosed with double
quotes. So we can say String is alpha-numeric collection of character.
String x = "Ravi";
---------------------------------------------------------------------
//Three Ways to create the String Object
public class StringTest1
{
public static void main(String[] args)
{
String s1 = "Hello World"; //Literal
[Link](s1);
}
}
---------------------------------------------------------------------
//String is collection of alpha-numeric character
public class StringTest2
{
public static void main(String[] args)
{
String x="B-61 Hyderabad";
[Link](x);
String y = "123";
[Link](y);
String z = "67.90";
[Link](z);
String p = "A";
[Link](p);
}
}
----------------------------------------------------------------------
//IQ
class StringTest3
{
public static void main(String args[])
{
String s = 15+29+"Ravi"+40+40;
[Link](s);
}
}
----------------------------------------------------------------------
Punctuators :
---------------
It is also called separators.
It is used to inform the compiler how things are grouped in the code.
() {} [] ; , . @
-----------------------------------------------------------------------------------
-
Operators :
-------------
It is a symbol which describes that how a calculation will be performed on
operands.
Types Of Operators :
------------------------
1) Arithmetic Operator (Binary Operator)
2) Unary Operators
3) Assignment Operator
4) Relational Operator
5) Logical Operators
6) Boolean Operators
7) Bitwise Operators
8) Ternary Operator
9) Member Operator
}
}
----------------------------------------------------------------------
How to read the value from the user/keyboard (Accepting the data from client)
-----------------------------------------------------------------------------------
--------
In order to read the data from the client or keyboard, java software people has
provided a predefined class called Scanner available in [Link] package.
[Link] :- It is used to take input from the user.(Attaching the keyboard with
System resource)
}
}
----------------------------------------------------------------------
//BUFFER PROBLEM
import [Link].*;
public class ReadName
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
}
}
---------------------------------------------------------------------
//Arithmetic Operator (+, -, *, / , %)
//Reverse of a 3 digit number
import [Link].*;
class Test3
{
public static void main(String[] args)
{
[Link]("Enter a three digit number :");
Scanner sc = new Scanner([Link]);
--------------------------------------------------------------
12-Sep-23
----------
Unary Operator :
--------------------
The operator which works upon single operand is called Unary Operator. Here in java
we have 3 types of unary opertor.
//Unary Operators
//Unary post increment Operator
class Test9
{
public static void main(String[] args)
{
int x = 15;
[Link](++x + x++);
[Link](x);
[Link]("..................");
int y = 15;
[Link](++y + ++y);
[Link](y);
}
}
--------------------------------------------------------------
Note :- Increment and decrement operator we can apply with any data type except
boolean.
---------------------------------------------------------------
//Unary Operators
//Unary post increment Operator
class Test10
{
public static void main(String[] args)
{
char ch ='A';
ch++;
[Link](ch);
}
}
---------------------------------------------------------------
//Unary Operators
//Unary post increment Operator
class Test11
{
public static void main(String[] args)
{
double d = 15.15;
d++;
[Link](d);
}
---------------------------------------------------------------
//Unary Operators
//Unary Pre decrement Operator
class Test12
{
public static void main(String[] args)
{
int x = 15;
int y = --x; //First decrement then assignment
[Link](x+":"+y);
}
}
--------------------------------------------------------------
//Unary Operators
//Unary Post decrement Operator
class Test13
{
public static void main(String[] args)
{
int x = 15;
int y = x--;
[Link](x+":"+y);
}
}
---------------------------------------------------------------
Interview Question
----------------------
Whenever we work with Arithmetic Operator or Unary minus operator, the minimum data
type required is int, So after calculation of expression it is promoted to int
type.
//IQ
class Test14
{
public static void main(String args[])
{
byte i = 1;
byte j = 1;
byte k = i + j; //error
[Link](k);
}
}
-------------------------------------------------------------
class Test15
{
public static void main(String args[])
{
/*byte b = 6;
b = b + 7; //error
[Link](b); */
byte b = 6;
b += 7;//short hand operator b += 7 is equal to (b = b + 7)
[Link](b);
}
}
Note :- In the above program it generates error while working with Arithmetic
Operator but when we change the operator from
Arithmetic to short hand operator then the expression result we can assign on byte
data type.
--------------------------------------------------------------
class Test16
{
public static void main(String args[])
{
byte b = 1;
byte b1 = -b; //error
[Link](b1);
}
}
---------------------------------------------------------------
What is a local variable :
----------------------------
If a variable is declared inside a method body(not as a method parameter) then it
is called Local / Stack/ Temporary / Automatic variable.
Ex:-
A local variable must be initialized before use otherwise we wiil get compilation
error.
Program
---------
public class Test17
{
public static void main(String [] args)
{
int x ; //must be initialized before use
[Link](x);
//ELC
class IQ
{
public static void main(String[] args)
{
[Link]([Link]()); //[Link]()
}
}
-----------------------------------------------------------------------
What is BLC class in java ?
---------------------------
BLC stands for Business Logic class. The class which does not contain main method
and it is only meant for writing logic is called BLC class.
--------------------------------------------------------------------
13-Sep-23
----------
Relational Operator :-
------------------------
These operators are used to compare the values. The return type is boolean. We have
total 6 Ralational Operators.
6) != (Not equal to )
else if(num>0)
[Link](num+" is positive");
else
[Link](num+" is negative");
int big=0;
Note :- In the above program to find out the biggest number among three number we
need to take the help of nested if condition but the code becomes complex, to
reduce the length of the code Logical Operator came into the picture.
--------------------------------------------------------------
Logical Operator :-
--------------------
It is used to combine or join the multiple conditions into a single statement.
&& :- All the conditions must be true. if the first expression is false it will
not check right side expressions.
Note :- The && and || operator only works with boolean operand so the following
code will not compile.
if(5 && 6)
{
}
---------------------------------------------------------------
//*Program on Logical Operator (AND, OR, Not Operator)
//Biggest number among 3 numbers
class Test23
{
public static void main(String args[])
{
[Link] sc = new [Link]([Link]);
[Link]("Enter the value of a :");
int a = [Link]();
[Link]("Enter the value of b :");
int b = [Link]();
[Link]("Enter the value of c :");
int c = [Link]();
It is also known as non short circuit. There are two non short circuit logical
operators.
& boolean AND operator (All condions must be true but if first expression is
false still it will check all right side expressions)
| boolean OR operator (At least one condition must be true but if the first
condition is true still it will check all right side expression )
--------------------------------------------------------------
//* Boolean Operators
/*
& boolean AND operator
| boolean OR operator
*/
//Works with boolean values
class Test26
{
public static void main(String[] args)
{
int z = 5;
if(++z > 5 || ++z > 6) //Logical OR
{
z++;
}
[Link](z); //7
[Link]("................");
z = 5;
if(++z > 5 | ++z > 6) //Boolean OR
{
z++;
}
[Link](z); //8
}
}
--------------------------------------------------------------
class Test27
{
public static void main(String[] args)
{
int z = 5;
if(++z > 6 & ++z> 6)
{
z++;
}
[Link](z);
}
}
---------------------------------------------------------------
Bitwise Operator :-
---------------------
In order to work with binary bits java software people has provided Bitwise
operator. It also contains 3 operators
& (Bitwise AND) :- Returns true if both the inputs are true.
^ (Bitwise X-OR) :- Returns true if both the arguments are opposite to each other.
//Bitwise Operator
class Test28
{
public static void main(String[] args)
{
[Link](true & true); //true
[Link](false | true); //true
[Link](true ^ true); //true
}
}
---------------------------------------------------------------
14-Sep-23
---------
Ternary Operator OR Conditional Operator :
--------------------------------------------------
The ternary operator (? :) consists of three operands. It is used to evaluate
boolean expressions. The operator decides which value will be assigned to the
[Link] is used to reduced the size of if-else condition.
//Ternary Operator OR Conditional Operator
public class Test30
{
public static void main(String args[])
{
int a = 60;
int b = 59;
int max = 0;
}
}
--------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
char a = 'A';
int i = 65 ;
[Link](false ? i : a); //Type casting
[Link](true ? a : 65);
}
}
---------------------------------------------------------------
Member access Operator Or Dot Operator :
--------------------------------------------------
It is used to access the member of the class so whenever we want to invoke the
member of the class (fields + methods) then we should use dot(.) operator.
We can directly call any static method and static variable from the main method
with the help of class name , here object is not required as shown in the program
below.
If static variable or static method is present in the same class where main method
is available then we can directly call but if the static variable and static method
is available in another class then to call those static members of the class, class
name is required.
class Welcome
{
static int x = 100;
This Operator is used to create Object. If the member of the class (field + method)
is static, object is not required. we can directly call with the help of class
name.
On the other hand if the member of the class (variables + method) is not declared
as static then it is called non-static member Or instance member , to call the non-
static member object is required.
class Welcome
{
int x = 100; //non-static variable
}
-------------------------------------------------------------
instanceof operator :-
3) It is also a keyword.
4) In between the object reference and class name , we must have some kind of
relation (assignment relation) otherwise we will get compilation error.
Integer i = 45;
if(i instanceof Number)
{
[Link]("Holding the Integer object");
}
else
{
[Link]("Not holding the Integer object");
}
}
}
--------------------------------------------------------------
Types of variables in java
---------------------------
-> Based on the data type we can define the variable into two
categories
Note :- Any variable if we declare with the help of class then it is called
reference variable.
Example :
---------
//Primitive Example
public class Test
{
int a = 100; //Instance variable
static int b = 200; //class variable
---------------------------------------------------------------------
Reference variable Example :
----------------------------
import [Link].*;
class Student
{
public void show()
{
[Link]("Batch 24 student");
}
}
switch case :-
----------------
In switch case dpending upon the parameter the appropriate case would be executed
otherwise default would be executed.
In this approch we need not to check each and every case, if the appropriate case
is available then directly it would be executed.
break keyword is optional here but we can use as per requirement. It will move the
control outside of the body of the switch.
----------------------------------------------------------------
import [Link].*;
public class SwitchDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Please Enter a Character :");
//Method Chaining
switch(choice)
{
case 100:
[Link]("Police Services");
break;
case 101:
[Link]("Fire Services");
break;
case 102:
[Link]("Ambulance Services");
break;
case 139:
[Link]("Railway Enquiry");
break;
case 181:
[Link]("Women's Helpline ");
break;
default:
[Link]("Your choice is wrong");
}
}
}
-----------------------------------------------------------------------
import [Link].*;
public class SwitchDemo2
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the name of the season :");
String season = [Link]().toLowerCase();
switch(season)
{
case "summer" :
[Link]("It is summer Season!!");
break;
case "rainy" :
[Link]("It is Rainy Season!!");
break;
}
}
}
-----------------------------------------------------------------------
1) do-while loop
2) while loop
3) for loop
4) for-each loop
do-while loop :-
------------------
It will repeat the statment but in this loop first of all statement will be printed
and then only the condition will verify so it is also called exit control loop.
do
{
statement;
}
while();
----------------------------------------------------------------------
//program on do-while loop
public class Test3
{
public static void main(String [] args)
{
do
{
int x = 1; //error x is block level variable
[Link](x+"\t");
x++;
}
while (x<=10);
}
}
----------------------------------------------------------------------
//Program on do-while loop to print 1-10
public class Test4
{
public static void main(String[] args)
{
int x = 1; //Local variable
do
{
[Link](x+"\n");
x++;
}
while (x<=10);
}
}
-----------------------------------------------------------------------
here basic drawback with do-while loop is, first of all it will print the value and
then only it will check the condition.
while loop :-
-------------
In while loop first of all we will verify the condition, if the condition is true
then only the control will enter inside the body of the loop hence it is known as
entry control loop.
while(condition)
{
statement;
}
----------------------------------------------------------------------
//program on while loop
public class Test5
{
public static void main(String[] args)
{
int x = -1;
while(x>=-10)
{
[Link](x);
x--;
}
}
}
-----------------------------------------------------------------------
//Program on for loop
public class Test6
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
[Link]("i value is :"+i);
}
}
}
-----------------------------------------------------------------------
//Program to accept user input to initialize our loop
import [Link];
public class Test7
{
public static void main(String [] args)
{
[Link]("Please enter a number from where you want to start
the loop : ");
Scanner sc = new Scanner([Link]);
int i = [Link]();
do
{
[Link](i+"\t"); // \t for tab space
i = i + 1;
}
while (i<=100);
}
}
----------------------------------------------------------------------
//WAP in java to print all even number from 1 -100
}
}
----------------------------------------------------------------------
//WAP to print sum of first 100 natural number (1+2+3+4+.......100)
public class Test9
{
public static void main(String[] args)
{
int sum = 0;
[Link](x);
for(int y : x)
[Link](y);
}
}
Note :
-------
1) In the above program each value of x is assigning to y variable.
//break
class Test12
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
if(i==5)
break;
[Link]("i value is :"+i);
}
}
}
----------------------------------------------------------------
//continue (Will skip the current execution sequence)
class Test13
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
if(i==5)
continue;
[Link]("i value is :"+i);
}
}
}
----------------------------------------------------------------------
Working with static Method and return type :
----------------------------------------
/*
* Finding the area of circle
* if radius is 0 or negative then
* return -1 otherwise return area of circle
*
*/
//BLC
public class Circle
{
public static String getAreaOfCircle(int radius)
{
if(radius <=0)
return "-1";
else
{
final double PI = 3.14;
double area = PI * radius * radius;
return ""+area;
}
}
}
[Link](ELC)
----------------------
package [Link].method_return;
import [Link];
import [Link];
}
}
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;
}
--------------------------------------------------------------------
Program to print the table
---------------------------
2 files
-------
[Link]
-----------
package [Link].pack9;
//BLC
public class Table
{
public static void printTable(int num) //5
{
for(int i=1; i<=10; i++)
{
[Link](num + " X "+i+" = "+(num*i));
}
}
}
[Link]
---------
package [Link].pack9;
import [Link];
//ELC
public class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the number whose table you want to print : ");
[Link]([Link]());
[Link]();
}
}
---------------------------------------------------------------------
16-Sep-23
----------
Object Oriented Programming(OOPs) :
-----------------------------------
An Object is a physical entity which is existing in the real world.
Writing Java program on those Real World Object is known as Object Oriented
Programming.
Features of OOPs
--------------------
We have 6 features
1) Class
2) Object
3) Abstraction
4) Encapsulation
5) Inheritance
6) Polymorphism
----------------------------------------------------------------
What is a class ?
------------------
A class is a model/blueprint/template/prototype for creating an object.
A class is userdefined data type which contains data members and member function.
Example :
---------
public classs Student
{
Student Data (Student Variables or Student properties)
+
Student behavior (Function / Method of the student)
}
Object :
---------
An object is a physical entity.
Example :
-----------
Mouse, Laptop, key, pen and so on.
[Link](".....................");
}
----------------------------------------------------------------------
Default constructor added by the compiler
--------------------------------------------------
In java whenever we write a class and If user does not write any type of
constructor then automatically compiler will add default constructor to the class.
class Test
{
//Here in this class we don't have constructor
}
javac [Link] (At the time of compilation automatically compiler will add
default constructor)
class Test
{
Test() //default constructor added by the compiler
{
}
}
-------------------------------------------------------------------------
----------------------------------------------------------------
Why compiler adds default constructor to our class :
---------------------------------------------------
If the compiler does not add default constructor to our class then object creation
is not possible in java. At the time of object creation by using new keyword we
depend upon the constructor.
Every Java class contains at least one constructor, implicitly added by compiler OR
explicitly written by user.
The following program explains how to re-initialize our object property (instance
variable) with method support.
[Link]
-------------
package [Link];
if we separate our classes with BLC and ELC approach then reusability of our BLC
classes would be possible from same package and even from different package.
This package contains 3 files [All these classes are in the same package]
---------------------------------------------------------------------
[Link]
------------
package [Link].blc_elc;
//BLC
public class Player
{
int playerId;
String playerName;
double playerPrice;
[Link]
----------
package [Link].blc_elc;
//ELC
public class Main
{
public static void main(String[] args)
{
Player rohit = new Player();
[Link](45, "Rohit Sharma", 12000.00);
[Link]();
[Link]
----------
package [Link].blc_elc;
In order to re-use this Player class (BLC) class, we have another class called
Dhoni available in another package
[Link]
-----------
package [Link].re_use;
import [Link].blc_elc.Player;
----------------------------------------------------------------------
instance variable :
--------------------
A non-static variable which is declared inside the class but outside of a method is
called instance variable.
[Instance variable is having strong association with object , we can't think about
instance variable without object]
Parameter variable :
-----------------------
If a variable is declared inside the method parameter (not inside the method body)
then the variables are called as parameter variables.
As far as its scope is concerned, parameters variables we can access within the
same method body but not outside of the method.
----------------------------------------------------------------------
21-Sep-23
----------
this keyword (Diagram):
-----------------------
Whenever our instance variable name and parameter variable name both are same then
at the time of variable initialization our runtime environment gets
confused that which one is an instance variable which one is parameter variable.
this keyword always refers to the current object and we know that instance
variables are the part of object but not the parameter variable.
this keyword we can't use from a static context because it is a non- static member.
2 files :
---------
[Link]
-------------
package [Link].this_keyword;
//BLC
public class Customer
{
int custId;
String custName;
//
public void setCustomerData(int custId, String custName)
{
[Link] = custId;
[Link] = custName;
//[Link]();
}
[Link]
-----------------
package [Link].this_keyword;
//ELC
public class CustomerDemo {
}
-----------------------------------------------------------------------
Role of instance variable while creating the Object :
-----------------------------------------------------
Whenever we create an object in java, a separate copy of all the instance variables
will be created with each and every object as shown in the program below.
package [Link].this_keyword;
++t1.x; --t2.x;
[Link](t1.x);
[Link](t2.x);
}
}
-----------------------------------------------------------------------
Working with static variable :
----------------------------------
In static variable only one copy will be created and this single copy will be
sharable by all the objects as shown in the program below.
package [Link].this_keyword;
++d1.x; ++d2.x;
[Link](d1.x);
[Link](d2.x);
}
Note :
Whenever the value of the variable is different with respect to objects then we
should declare the variable as instance variable.
On the other hand if the value of the variable is common for all the objects then
we should declare the variable as a static variable, if we declare static variable
as an instance variable then multiple copies will be created for holding same
value, so there is a westage of memory.
Note :- static variable will save the memory so the overall execution of the
program will become faster.
2 files :-
---------
[Link]
------------
package [Link].instance_static;
//BLC
public class Student
{
int rollNumber;
String studentName;
String studentAddress;
static String collegeName = "NIT";
static String courseName = "Java";
[Link]
-----------------
package [Link].instance_static;
import [Link];
//ELC
public class StudentDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Student Roll Number :");
int roll = [Link]();
Whenever we override this toString() method in our class then we need not to write
any kind of display() method to display our data(instance variable).
2 files :-
[Link]
------------
package [Link].to_string;
//BLC
public class Manager
{
double managerSalary;
String managerName;
@Override
public String toString()
{
return "Manager [managerSalary=" + managerSalary + ", managerName=" +
managerName + "]";
}
[Link]
----------------
package [Link].to_string;
//ELC
public class ManagerDemo
{
public static void main(String[] args)
{
Manager m1 = new Manager();
[Link](40000.00, "VK");
[Link](m1); //passing object reference inside the s.o.p
//statement which will automatically call
//toString() method
}
}
-----------------------------------------------------------------------
How to generate toString() method :
-----------------------------------
Right click on the program -> source -> generate toString()
-> select all -> generate
-----------------------------------------------------------------------
Lab Program :
-------------
2 files
--------
[Link]
-------------
package [Link].lab_prog;
else
managerGrade = 'D';
}
@Override
public String toString() {
return "Manager [managerId=" + managerId + ", managerName=" +
managerName + ", managerSalary=" + managerSalary
+ ", managerGrade=" + managerGrade + "]";
}
[Link]
----------------
package [Link].lab_prog;
}
}
------------------------------------------------------------------------23-Sep-23
---------
Data hiding :
---------------
Data hiding means our data (variables) must be hidden from outer world that means
no one can access our data directly from outside of the class.
To achieve data hiding concept we should declare our class properties or data
members or variables with private access modifier.
We should not provide access of data directly but we can access our data via
methods. Once we are accessing our data through methods then we can PERFORM
VALIDATION ON DATA WHICH ARE COMING FROM OUTER WORLD.
Note :- Data members must be declared as private where as member functions (Method)
must be declared as public.
2 Files :
---------
[Link]
--------------
package [Link].data_hiding;
[Link]
------------------------
package [Link].data_hiding;
In real world a user always interacts with the functionality of the product but not
the data or internal details so for a user method/function is essential details
where as data is non-essential details.
So being a developer we should always hide the data from the user(by declaring them
private) where as on the other hand we should always decalre member function/Method
as public so a user can easily interact with the product.
Example :
-----------
class Fan
{
private int coil;
private int wings;
Note :- Here User will interact with the functionality of the fan i.e switchOn and
switchOff but will not interact with data(coil, wings) directly.
Note :- In java we can achieve abstarction by using abstract class and interface
concept.
In other words we can say "Grouping the related things together is called
Encapsulation".
It provides us security because we can't access the data directly, data must be
accessible via methods.
We can achieve encapsulation in our program by using following
Note :
-----
If we declare all the instance variables with private access modifier then it is
called tightly encapsulated class
On the other hand if some variables are declared with private access modifier and
other variables are not declared with private access modifier then it is called
loosly encapsulated class
2 Files :
---------
[Link]
-------------
package [Link];
[Link]
----------------
package [Link];
}
------------------------------------------------------------------------
25-Sep-23
---------
Constructor :
--------------
Why we write a constructor in a program
OR
what is the benefit of writing constructor in our program :-
-----------------------------------------------------------
If we don't write a constructor in our program then variable initialization and
variable re-initialization both are done in two different lines.
If the name of the class and name of the method both are same then it is called
constructor or in other words constructor is a special method whose name is same as
class name.
Every java class has a constructor either explicitly written by the user or
implicitly added by the compiler.
A constructor never containing any return type including void also, if we try to
put the return type then it will become normal method.
A constructor is called and executed once per object that means if we create an
object then automatically the constructor will be called and executed,
again if we create another object for second time then again the constructor will
be called and executed.
3) Parameterized Constructor
----------------------------------------------------------------------
2) No argument constructor :-
----------------------------------
The constructor written by the user in the class without any parameter then it
is called No argument constructor or parameter less constructor or zero argument
constructor.
By using no argument constructor all the objects will be initialized with same
values so it is not recommended approach because we will not be able to customized
each individual object with different value, to avoid this parameterized
constructor came into picture.
[Diagram is available 26-SEp-23]
Ex:-
public class Test
{
int x, y;
[Link]
------------
package [Link].no_arg_cons;
@Override
public String toString()
{
return "Person [personId=" + personId + ", personName=" + personName +
", personBill=" + personBill + "]";
}
[Link]
--------------------------
package [Link].no_arg_cons;
[Link]("............");
Note :- In the above program we are creating two different objects but
they are containing same data.
----------------------------------------------------------------------
3) Parameterized Constructor :
------------------------------
----------------------------------------------------------------------
3) Parameterized Constructor :
------------------------------
If one or more argument is passed to the constructor then it is called
parameterized constructor.
2 files :
---------
[Link]
--------
package [Link].parameterized_constructor;
@Override
public String toString() {
return "Dog [dogName=" + dogName + ", dogAge=" + dogAge + ",
dogHeight=" + dogHeight + "]";
}
}
[Link]
------------------------------
package [Link].parameterized_constructor;
[Link]("................");
}
-----------------------------------------------------------------------
How many ways to initialize our object properties
--------------------------------------------------------
There are 5 ways to initialize our object properties (instance variables)
class Exapmle
{
int x = 10;
int y = 20;
}
It is also not a recommended approach because here the length of the code
will increase as well as the understanability of the code will decrease.
3) BY USING METHODS
class Example
{
int x;
int y;
public void input()
{
x = 100;
y = 200;
}
}
class Example
{
int x;
int y;
public void input(int x, int y)
{
this.x = x;
this.y = y;
}
}
SO CONCLUSIUON IS
a) Constructors are used to initialize the object properties
b)
Setters are used to modify the object properties
c)
Methods are used for calculation or printing the data
d)
To print object properties we have toString() method
e)
If Properties are private then to read properties value in
another class we should use getter.
---------------------------------------------------------------------
27-Sep-23
---------
HAS-A Relation :
----------------
Whenever we are using class variable (ref. variable) as a property to another class
then it is called HAS-A relation.
@Override
public String toString()
{
return "College [collegeName=" + collegeName + ", collegeAddress=" +
collegeAddress + "]";
}
[Link](BLC)
------------------
package [Link].has_a_reln;
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentAddress=" + studentAddress
+ ", clg=" + clg + "]";
}
[Link]
-------------------------
package [Link].has_a_reln;
---------------------------------------------------------------------
Another program on HAS-A Relation :
------------------------------------
Program on HAS-A relation :
---------------------------
3 Files :
---------
[Link](BLC)
-----------------
package [Link].has_a_reln;
@Override
public String toString() {
return "Order [OrderId=" + OrderId + ", itemName=" + itemName + ",
itemPrice=" + itemPrice + ", itemQuantity="
+ itemQuantity + "]";
}
[Link](BLC)
-----------------
package [Link].has_a_reln;
@Override
public String toString() {
return "Customer [custId=" + custId + ", customerName=" + customerName
+ ", shippingAddress=" + shippingAddress
+ ", totalBill=" + totalBill + ", mobileNumber=" +
mobileNumber + ", order=" + order + "]";
}
[Link](ELC)
----------------
package [Link].has_a_reln;
3 files :
---------
[Link](BLC)
------------------
package [Link].passing_object_ref;
@Override
public String toString() {
return "Employee [employeeNumber=" + employeeNumber + ", employeeName="
+ employeeName + "]";
}
[Link](BLC)
-----------------
package [Link].passing_object_ref;
@Override
public String toString() {
return "Manager [managerId=" + managerId + ", managerName=" +
managerName + "]";
}
[Link](ELC)
---------------------------------------
package [Link].passing_object_ref;
}
}
---------------------------------------------------------------------
28-Sep-23
---------
Program on Passing Object Reference to the Constructor :
--------------------------------------------------------
package [Link].passing_object_ref_to_cons;
public Player(Player p) // p = p1
{
this.name1 = p.name2;
this.name2 = p.name1;
}
@Override
public String toString() {
return "Player [name1=" + name1 + ", name2=" + name2 + "]";
}
}
package [Link].passing_object_ref_to_cons;
[Link]("..............");
Player p2 = new Player(p1);
[Link](p2);
}
}
---------------------------------------------------------------------
Copy Constructor Program :
--------------------------
[Link](BLC)
--------------
package [Link].copy_constr;
@Override
public String toString() {
return "Milk [milkPrice=" + milkPrice + "]";
}
[Link](BLC)
---------------
package [Link].copy_constr;
@Override
public String toString() {
return "Baby [babyName=" + babyName + ", babyAge=" + babyAge + ",
milk=" + milk + ", milkType=" + milkType
+ "]";
}
[Link](ELC)
-------------------------
package [Link].copy_constr;
}
--------------------------------------------------------------------
Method return type as a class :
--------------------------------
We can take return type of the method as a class. As a return type of method we can
take all primitive data type (byte, Short, int and so on) class name, interface
name;
public class Test
{
public Test m1()
{
return 5;
}
}
---------------------------------------------------------------------
The following program explains how to tale return type of a method as class
2 files :
---------
[Link]
--------------
package [Link].class_as_a_return_type;
import [Link];
import [Link];
return e1;
}
@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" +
employeeName + ", employeeSalary="
+ employeeSalary + ", hireDate=" + hireDate + "]";
}
[Link]
--------------------------
package [Link].class_as_a_return_type;
import [Link];
}
}
------------------------------------------------------------------------
29-Sep-23
---------
LAB Program :
---------------
A BLC class called Customer is given to you.
The task is to find the Applicable Credit card Type and create CardType object
based on the Credit Points of a customer.
Attributes :
customerName : String,private
creditPoints: int, private
Constructor :
parameterizedConstructor: for both cusotmerName & creditPoints in that order.
Methods :
Name of the method : getCreditPoints
Return Type : int
Modifier : public
Task : This method must return creditPoints
Create another class called CardType. Define the following for the class
Attributes :
customer : Customer, private
cardType : String, private
Constructor :
parameterizedConstructor: for customer and cardType attributes in that order
Methods :
Name of the method : toString Override this.
Return type : String
Modifier : public
Task : Return the string in the following format.
The Customer 'Rajeev' Is Eligible For 'Gold' Card.
Create One more class by name CardsOnOffer and define the following for the class.
Method :
Name Of the method : getOfferedCard
Return type : CardType
Modifiers: public,static
Arguments: Customer object
Create an ELC class CreditCard which contains Main method to test the working of
the above.
Program :
---------
4 files are there :
--------------------
[Link](BLC)
------------------
package [Link].lab_credit_card_program;
@Override
public String toString()
{
return ""+[Link];
}
[Link](BLC)
-------------------
package [Link].lab_credit_card_program;
@Override
public String toString()
{
return "The Customer '"+[Link]+"' Is Eligible For
'"+[Link]+"' Card";
}
[Link](BLC)
-----------------------
package [Link].lab_credit_card_program;
[Link](ELC)
---------------------
package [Link].lab_credit_card_program;
import [Link];
[Link](offeredCard);
}
}
-------------------------------------------------------------------------
Lab Program :
-------------
The payroll system of an organization involves calculating the gross salary of each
type of employee and the tax applicable to each.
Create the following entity classes as described below.
Class Employee
Fields: id: int, name : String, basicSalary : double, HRAPer : double, DAPer :
double
Class Manager
Fields: id: int, name : String, basicSalary : double, HRAPer : double,DAPer :
double, projectAllowance: double
Public Method: calculateGrossSalary() - returns a double
Calculate the gross salary as : basicSalary +HRAPer +DAPer + projectAllowance
Class Trainer
Fields: id: int, name : String, basicSalary : double, HRAPer : double,DAPer :
double, batchCount: int, perkPerBatch: double
Public Method: calculateGrossSalary() - returns a double
Calculate the gross salary as : basicSalary +HRAPer +DAPer +(batchCount *
perkPerBatch)
Class Sourcing
Fields: id: int, name : String, basicSalary : double, HRAPer : double,DAPer :
double, enrollmentTarget: int, enrollmentReached: int, perkPerEnrollment: double
Public Method: calculateGrossSalary() - returns a double
Class TaxUtil
Fields: None
Public Methods:
calculateTax(Employee) - returns a double
calculateTax(Manager) - returns a double
calculateTax(Trainer) - returns a double
calculateTax(Sourcing) - returns a double
Tax Calculation Logic: If gross salary is greater than 30000 tax is 20% else, tax
is 5%
A ClassObject class is given to you with the main Method. Use this class to test
your solution.
---------------------------------------------------------------
This Lab program contains 6 files :
------------------------------------
[Link]
-------------
package [Link].lab_prog_tax_util;
public Employee(int id, String name, double basicSalary, double hRAPer, double
dAPer) {
super();
[Link] = id;
[Link] = name;
[Link] = basicSalary;
HRAPer = hRAPer;
DAPer = dAPer;
}
[Link]
-------------
package [Link].lab_prog_tax_util;
public Manager(int id, String name, double basicSalary, double hRAPer, double
dAPer, double projectAllowance) {
super();
[Link] = id;
[Link] = name;
[Link] = basicSalary;
HRAPer = hRAPer;
DAPer = dAPer;
[Link] = projectAllowance;
}
[Link]
-------------
package [Link].lab_prog_tax_util;
return grossSalary;
}
}
[Link]
--------------
package [Link].lab_prog_tax_util;
[Link]
-------------
package [Link].lab_prog_tax_util;
[Link]
----------------
package [Link].lab_prog_tax_util;
-------------------------------------------------------------------------
instance block in java
------------------------
It is a new feature introduced in java. The main purpose of instance block to
initialize the instance variable of the class before the constructor, that is the
reason it is also known as instance initializer.
An instance block we can write inside the class even inside the method or
constructor.
An instance block will be executed automatically at the time of creating the object
BEFORE THE CONSTRUCTOR BODY EXECUTION.
Instance block will execute once per object that means whenever we create an
object, instance block will be executed.
If we have multiple instance blocks in a class then they would be executed in the
same order as they were written in the class(order wise)
Example :-
//Instance Block
}
------------------------------------------------------------------------
//WAP which displays instance block is executed before the Constructor
body
2 files :
--------
package [Link].instance_block;
//instance block
{
[Link]("Instance Block");
}
[Link]
-------------------
package [Link].instance_block;
}
}
Note :- From the above program it is clear that instance block will be executed as
per object.
------------------------------------------------------------------------
WAP in Java that describes instance blocks are executed from top to bottom.
2 files :-
-----------
[Link]
----------
package [Link].instance_block;
public Test()
{
[Link](x);
}
{
x = 100;
[Link](x);
}
{
x = 200;
[Link](x);
}
{
x = 300;
[Link](x);
}
[Link]
-------------------
package [Link].instance_block;
But in Java a user is not responsible to de-allocate the memory that means memory
allocation is the responsibility of user but memory de-allocation is automatically
done by Garbage Collector.
Garbage collection is the process of looking at heap memory, identifying which
objects are in use and which are not, and deleting the unused objects (The object
which does not contain any references).
Note :- GC uses an algorithm mark and sweep to make an un-used objects eligible for
Garbage Collection.[Diagram 30-SEP-23]
-----------------------------------------------------------------------
How many ways we can make an object eligible for garbage Collector :
--------------------------------------------------------------------
There are 3 ways to make an Object eligible for Garbage Collector :
----------------------------------------------------------------
1) Assigning a null literal to reference variable
e3 = new Employee();
----------------------------------------------------------------------
HEAP and STACK diagram for [Link]
-----------------------------------------
[Link] (Single file)
---------------------------
class Customer
{
private String name;
private int id;
m1(c);
[Link]([Link]());
}
[Link](9);
[Link]([Link]());
}
}
// 9 5
----------------------------------------------------------------------------
HEAP and STACK diagram for [Link]
-----------------------------------------
public class Sample
{
private Integer i1 = 900;
Sample s3 = modify(s2);
s1=null;
[Link](s2.i1);
}
public static Sample modify(Sample s)
{
s.i1=9;
s = new Sample();
s.i1= 20;
[Link](s.i1);
s=null;
return s;
}
}
//20 9
----------------------------------------------------------------------------
HEAP and STACK diagram for [Link]
-----------------------------------------
public class Test
{
Test t;
int val;
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
//300 200 400 200
----------------------------------------------------------------------
03-Oct-23
---------
HEAP and STACK diagram for [Link]
--------------------------------------
public class Employee
{
int id=100;
public static void main(String[] args)
{
int val=200;
update(e1);
[Link]([Link]);
[Link]=500;
switchEmployees(e2,e1);
//GC [2 objects 2000x and 4000x are eligible for Garbage Collector]
[Link]([Link]);
[Link]([Link]);
}
class Vehicle
{
private Engine engine; \\HAS-A relation
}
class Car extends Vechile
{
//Car IS-A Vehicle so it is creating IS-A relation
}
--------------------------------------------------------------------
04-Oct-23
---------
It is one of the most imporatnt feature of OOPs which provides "CODE REUSABILITY".
Using inheritance mechanism the relationship between the classes is parent and
child. According to C++ the parent class is called Base class and the child class
is called Derived class, According to Java the parent class is called super class
and the child class is called sub class.
By using inheritance all the feature of super class is by default available to the
sub class so the sub class need not to start the process from begning onwards.
Inheritance provides IS-A relation between the classes. IS-A relation is tightly
coupled relation (Blood Relation) so if we modify the super class content then
automatically sub class content will also modify.
Types of Inheritance :
----------------------
There are 5 types of Inheritance in java :-
[Link]
---------
package [Link];
[Link]
---------
package [Link];
}
------------------------------------------------------------------------
WAP in java to implement Single level inheritance :
----------------------------------------------------
Writing multiple classes in a single file (Not recommended)
1 file :
---------
[Link]
---------------------------
package [Link].single_lev;
class Emp
{
protected int employeeNumber;
protected String employeeName;
protected double employeeSalary;
}
class Pemp extends Emp
{
protected String department;
protected String designation;
public void setPemp(String department, String designation)
{
[Link] = department;
[Link] = designation;
}
@Override
public String toString()
{
return "Pemp [department=" + department + ", designation=" +
designation + ", employeeNumber=" + employeeNumber
+ ", employeeName=" + employeeName + ", employeeSalary=" +
employeeSalary + "]";
}
}
class GrandFather
{
public void land()
{
[Link]("1600 SQFT land");
}
}
class Father extends GrandFather
{
public void house()
{
[Link]("3 BHK house");
}
}
class Employee
{
protected double salary;
}
@Override
public String toString()
{
return "Developer [salary=" + salary + "]";
}
@Override
public String toString() {
return "Designer [salary=" + salary + "]";
}
}
-------------------------------------------------------------------------
05-Oct-23
---------
super keyword :
---------------
It is a keyword in java which is used to access the member of super class.
Note :- We should use super keyword when the super class member name and sub
class member name both are same as welll as We can't use super keyword from static
context.
3 files :
----------
[Link]
------------
package [Link].super_var;
[Link]
--------
package [Link].super_var;
public Son()
{
[Link]("Son balance is :"+balance);
[Link]("Father balance is :"+[Link]);
}
}
[Link]
-------------
package [Link].super_var;
class A
{
public void show()
{
[Link]("Show method of super class...");
}
}
class B extends A
{
public void show()
{
[Link]("Show method of Sub class...");
[Link]();
}
}
}
}
--------------------------------------------------------------------
06-Oct-23
---------
*3) To call the super class constructor : (Constructor Chaining)
-------------------------------------------------------------------
Whenever we write a class in java and we don't write any kind of constructor to the
class then the java compiler will automatically add one default constructor to the
class.
THE FIRST LINE OF ANY CONSTRUCTOR IS RESERVERD EITHER FOR super() or this()
keyword.
In the first line of any constructor if we don't specify either super() or this()
then the compiler will automatically add super() to the first line of constructor.
Now the purpose of this super() [added by java compiler], to call the default
constructor or No-Argument constructor of the super class.
In order to call the constructor of super class as well as same class, we have
total 4 cases.
CASE 1 :
--------
super() :- To call the no-argument constructor or default constructor of the super
class. It is automatically added by the compiler.
class A
{
public A()
{
[Link]("No Argument constructor of Super class");
}
}
class B extends A
{
public B()
{
[Link]("No Argument constructor of Sub class");
}
}
Note :- From the above program it is clear that, super() is added by compiler to
the first line of constructor so, the control will reach to Object class first to
maintain the hierarchy.
----------------------------------------------------------------------
CASE 2 :-
----------
super("NIT") :- To call the parameterized constructor of super class
package [Link].super_this;
class Parent
{
public Parent(String str)
{
[Link]("My Institute Name is :"+str);
}
}
class Super
{
public Super()
{
[Link]("No-Args constructor of Super class");
}
}
----------------------------------------------------------------------
CASE 4 :-
----------
this("Ravi") :- It is used to invoked parameterized constructor of
current class.
class Base
{
public Base()
{
this(100,200);
[Link]("No argument constructor of Base class");
}
}
----------------------------------------------------------------------
[Link][Single File Approach]
package [Link].super_this;
class Employee
{
private int empId;
private String empName;
public Employee()
{
this(222,"Rahul");
[Link] = 111;
[Link] = "Raj";
}
[Link](id);
[Link](name);
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + "]";
}
}
----------------------------------------------------------------------
Program on super keyword, to call parameterized constructor of super class
by using Single level Inheritance
--------------------------------------------------------------------------
package [Link].super_ex;
import [Link];
class Shape
{
protected int x;
public Shape(int x)
{
this.x = x;
[Link]("x value is :"+x);
}
}
}
--------------------------------------------------------------------------
Program on super keyword, to call parameterized constructor of super class
by using Hierarchical Inheritance
--------------------------------------------------------------------------
package [Link].super_hierarchical;
class Shape
{
protected int x;
public Shape(int x)
{
this.x = x;
[Link]("x value is :"+x);
}
}
class Rectangle extends Shape
{
protected int breadth;
public Rectangle(int length, int breadth)
{
super(length);
[Link] = breadth;
}
}
--------------------------------------------------------------------------
Program on super keyword using Hierarchical Inheritance :
----------------------------------------------------------
4 files :
----------
[Link]
-------------
package [Link].super_hierarchical;
@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" +
employeeName + ", employeeRole="
+ employeeRole + "]";
}
[Link]
------------
package [Link].super_hierarchical;
@Override
public String toString() {
return [Link]()+"Manager [managerSalary=" + managerSalary +
"]";
}
}
[Link]
--------
package [Link].super_hierarchical;
@Override
public String toString() {
return [Link]()+"HR [hrSalary=" + hrSalary + "]";
}
}
[Link]
------------------
package [Link].super_hierarchical;
}
-------------------------------------------------------------------------
07-Oct-23
---------
*Why java does not support multiple inheritance ?
-------------------------------------------------
Whenever a sub class wants to inherit the properties of two or more super classes
and both the super class contains same method name then it leads ambiguity problem
for the sub class to invoke the method of super classes as shown in our example
(diagram 07-OCT-23)
In our example two super classes i.e class A and class B contain doSum(int x, int
y) method and there is a sub class called C which try to extends two super classes
i.e A and B.
For sub class C, it is difficult to call doSum(int x , int y) method because there
would be an ambiguity problem.
That is the reason java does not support multiple inheritance using classes also
known as "Diamond Problem" in java, but same(multiple inheritance) we can achieve
by using interface concept later.
In java multiple inheritance is possible using interfaces but not by using the
classes.
--------------------------------------------------------------------------
IQ
--
class A
{
public A(double d)
{
[Link](d);
}
}
class Test extends A
{
public static void main(String[] args)
{
A a1 = new A(5);
}
}
--------------------------------------------------------------------------
10-Oct-23
----------
Access modifiers in java :
-----------------------------
An access modifiers describes the accessibility scope of the classes as well as the
member of the classes.
private :-
---------
It is an access modifier and it is the most restrictive access modifier because the
member declared as private can't be accessible from outside of the class.
In Java we can't declare an outer class as a private or protected. Generally we
should declare the data member(variables) as private.
In java outer class can be declared as public, abstract and final only.
default :-
----------
It is an access modifier which is less restrictive than private. It is such kind of
access modifier whose physical existance is not avaialble that means when we don't
specify any kind of access modifier before the class name, variable name or method
name then by default it would be default.
As far as its accessibility is concerned, default members are accessible within the
same folder(package) only.
protected :
------------
It is an access modifier which is less restrictive than default because the member
declared as protected can be accessible from the outside of the package (folder)
too but by using inheritance concept.
import [Link];
public :-
-------
It is an access modifier which does not contain any kind of restriction that is the
reason the member declared as public can be accessible from everywhere without any
restriction.
According to Object Oriented rule we should declare the classes and methods as
public where as variables must be declared as private or protected according to the
requirement.
--------------------------------------------------------------------------
Data types in java : [diagram 10-OCT-23]
----------------------------------------
Type casting in Java :
-----------------------
Type casting is nothing but converting one data type to another data type.
In java, type casting can be divided into two types
byte -> short -> char -> int -> long -> float -> double
Eg:- byte b = 12;
short s = b;
-----------------------------------------------------------------------------------
---------
//program on Implicit type casting
package [Link];
}
-------------------------------------------------------------------------
While performing the explicit type casting there may be chance of loss of data if
the value for smaller data type will be beyond the range.
double -> float -> long ->int -> char -> short -> byte
Eg:-
short s = 23;
byte b = s; //not possible short is bigger, byte is smaller
int x = (int) l;
}
-----------------------------------------------------------------------------------
----------
package [Link];
float f2 = 234.78f;
float f3 = 1567.67F;
}
--------------------------------------------------------------------------
HAS-A relation between the classes :
------------------------------------------
In order to acheive HAS-A relation concept we should use Association.
The association builds a relationship between the classes and describes how much a
class knows about another class.
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.
Note : In this Program a trainer wants to view the profile of the Student.
3 files :
---------
[Link]
------------
package [Link].association_demo;
[Link]
------------
package [Link].association_demo;
import [Link];
if(id == [Link]())
{
[Link](s);
}
else
{
[Link]("Sorry!!! Student record is not available");
}
}
}
[Link]
----------
package [Link].association_demo;
[Link](1);
[Link]("Pooja");
[Link](9812345678L);
}
}
--------------------------------------------------------------------------
Composition :
-------------
Composition relation is a restricted form of Aggregation in which two classes (or
entities) are highly dependent on each other; the composed object cannot exist
without the other entity. The composition can be described as a part-of
relationship.
A car has an engine. Composition makes strong relationship between the objects. It
means that if we destroy the owner object, its members will be also destroyed with
it. For example, if the Car is destroyed the engine will also be destroyed as well.
-------------------------------------------------------------------------
[Link]
------------
package [Link];
//Composition(Strong reference type)
//Constructor
public Engine(String engineType, int horsePower)
{
super();
[Link] = engineType;
[Link] = horsePower;
}
//Getter Methods
@Override
public String toString() {
return "Engine [engineType=" + engineType + ", horsePower=" +
horsePower + "]";
}
}
[Link]
---------
package [Link];
[Link]
---------
package [Link];
}
-----------------------------------------------------------------------
11-Oct-23
----------
Aggregation (Weak Reference) :
-----------------------------------
Aggregation is a relation between two classes which can be built through entity
reference, It is a weak reference type that means one object entity does not
depend upon another object entity.
For example, customers can have orders but the reverse is not possible, hence
unidirectional in nature.
Example :-
------------
3 files :
---------
[Link]
-------------
package [Link].aggregation_demo;
@Override
public String toString() {
return "Company [companyName=" + companyName + ", companyLocation=" +
companyLocation + "]";
}
[Link]
-------------
package [Link].aggregation_demo;
@Override
public String toString() {
return "Employee [emoloyeeNumber=" + emoloyeeNumber + ", employeeName="
+ employeeName + ", employeeSalary="
+ employeeSalary + ", company=" + company + "]";
}
[Link]
----------
package [Link].aggregation_demo;
}
}
---------------------------------------------------------------------
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.
Example:-
In static polymorphism, compiler has very good idea that which method is going to
invoke(call) depending upon the type of parameter we have passed in the method.
----------------------------------------------------------------------
Dynamic Polymorphism :
----------------------------
The polymorphism which exist at runtime is called dynamic polymorphism.
In dynamic polymorphism, compiler does not have any idea about method calling, at
runtime JVM will decide that which method is invoked depending upon the class type.
Example :
------------
public static void main(String [] args) //JVM will serach this method
{
}
public static void main(String x)
{
}
public static void main(int y)
{
}
While Overloading a method we can change the return type of the method.
Method overloading is possible in the same class as well as super and sub class.
While overloading the method the argument must be different otherwise there will be
ambiguity problem.
Example :-
[Link]
--------------
package [Link].constructor_overloading;
[Link]
---------
package [Link].constructor_overloading;
[Link]
--------------
package [Link].constructor_overloading1;
[Link]
---------
package [Link].constructor_overloading1;
}
-----------------------------------------------------------------------
Program on Method overloading that describes we can change the return type of the
method while Overloading a method.
[Link]
----------
package [Link].method_overload;
[Link]
---------
package [Link].method_overload;
}
}
-----------------------------------------------------------------------
Var-Args :
------------
It was introduced from JDK 1.5 onwards.
var-args must be only one and last argument.(var args must be the last argument)
2 Files
[Link]
---------
package [Link].var_args;
[Link]
---------
package [Link].var_args;
}
-----------------------------------------------------------------------
Program to add parameters values of a method at the time of calling
2 Files
[Link]
---------
package [Link].var_args1;
for(int y : x)
{
sum = sum+ y;
}
[Link]("Sum of parameters are :"+sum);
}
}
[Link]
---------
package [Link].var_args1;
}
-----------------------------------------------------------------------
Program that describes var args must be only one and last argument.
2 Files
[Link]
----------
package [Link].var_args2;
/*
* public void accept(float ...x, int ...y) //invalid {
*
* }
*
*
* public void accept(int ...x, int y) //Invalid {
*
* }
*/
[Link]
----------
package [Link].var_args3;
[Link]
---------
package [Link].var_args3;
}
-----------------------------------------------------------------------
13-Oct-23
---------
Ambiguity issues while overloading a method ?
----------------------------------------------
Points to remember :
--------------------
1) While Overloading if we get ambiguity issues compiler will provide more priority
to the nearest data type.
[Link]
---------
package [Link].ambigity_issues;
class Test
{
public void access(byte b)
{
[Link]("byte is executed :"+b);
}
public void access(short b)
{
[Link]("short is executed :"+b);
}
}
public class Main1 {
[Link]((byte)29);
[Link]((short)22);
}
}
-----------------------------------------------------------------------
[Link]
----------
package [Link].ambigity_issues;
class A
{
public void access(String x)
{
[Link]("String is invoked :"+x);
}
}
}
-----------------------------------------------------------------------
package [Link].ambigity_issues;
class B
{
public void access(Integer x)
{
[Link]("Autoboxing is invoked :"+x);
}
}
----------------------------------------------------------------------
package [Link].ambigity_issues;
class D
{
public void access(Integer x)
{
[Link]("Autoboxing is invoked :"+x);
}
}
----------------------------------------------------------------------
package [Link].ambigity_issues;
class E
{
public void access(int x)
{
[Link]("int is invoked :"+x);
}
}
public class Main6 {
}
}
------------------------------------------------------------------------
16-Oct-23
---------
Method Overriding :
-------------------
Writing two or more methods in the super and sub class in such a way that method
signature(method name along with method parameter) of both the methods must be same
in the super and sub classes.
While working with method overriding generally we can't change the return type of
the method but from JDK 1.5 onwards we can change the return type of the method in
only one case that is known as Co-Variant.
Downcasting :
---------------
By default downcasting is not possible, Here we are trying to assign super class
object to sub class reference variable but the same we can achieve by using
explicit type casting. It is known as downcasting
class Animal
{
public void eat()
{
[Link]("I cannot say");
}
}
class Animal
{
public void eat()
{
[Link]("I cannot say");
}
}
}
-----------------------------------------------------------------------
17-Oct-23
---------
Program on Method Overriding by using Dynamic Method Dispatch:
--------------------------------------------------------------
class RBI
{
public void loan()
{
[Link]("Bank Should provide loan!!!");
}
}
class SBI extends RBI
{
public void loan()
{
[Link]("SBI provides loan @ 9.2%");
}
}
class BOB extends RBI
{
public void loan()
{
[Link]("BOB provides loan @ 10.4%");
}
}
If we use @Override annotation before the name of the method in the sub class and
if the method is not available in the super class then it will generate a
compilation error so it is different from comment because comment will not generate
any kind of compilation error if method is not an overridden method, so this is how
it is different from comment.
------------------------------------------------------------------------
class Shape
{
public void draw()
{
[Link]("No idea about shape");
}
}
class Rectangle extends Shape
{
@Override
public void draw()
{
[Link]("Drawing Rectangle");
}
}
class Square extends Shape
{
@Override
public void draw()
{
[Link]("Drawing Square");
}
}
public is greater than protected, protected is greater than default (public >
protected > default)
[default < protected < public]
Note :- private access modifier is not availble (visible) in sub class so it is not
the part of method overriding.
[Link]
-------------------
class Super
{
public void show()
{
[Link]("Super class show method");
}
}
class Sub extends Super
{
@Override
protected void show() //error
{
[Link]("Sub class show method");
}
}
public class AccessModifier
{
public static void main(String[] args)
{
Super s = new Sub();
[Link]();
}
}
-----------------------------------------------------------------------
Co-variant concept in method overriding :
------------------------------------------------
In general we cann't change the return type of method while overriding a method. if
we try to change it will generate compilation error as shown in the program below.
class Super
{
public void show()
{
[Link]("Super class show method ...");
}
}
class Sub extends Super
{
@Override
public int show() //error[int is not compatible with void]
{
[Link]("Sub class show method ");
return 0;
}
}
public class IncompatibleOverride
{
public static void main(String [] args)
{
Super s = new Sub();
[Link]();
}
}
But from JDK 1.5 onwards we can change the return type of the method in only
one case that the return type of both the METHODS(SUPER AND SUB CLASS METHODS) MUST
BE IN INHERITANCE RELATIONSHIP called Co-Variant as shown in the program below.
----------------------------------------------------------------------
class Animal
{
}
class Dog extends Animal
{
}
class Bird
{
public Animal fly()
{
[Link]("Bird is flying");
return new Dog();
}
}
class Parrot extends Bird
{
@Override
public Dog fly()
{
[Link]("Parrot is flying");
return new Dog();
}
}
class Super
{
public Object display()
{
[Link]("Super class display method!!!");
return new Object();
}
}
class Sub extends Super
{
@Override
public String display()
{
[Link]("Sub class display method!!!");
return null;
}
}
class CoVariant1
{
public static void main(String[] args)
{
Super s = new Sub();
[Link]();
}
}
-----------------------------------------------------------------------
18-10-2023
----------
*Can we override main method?
OR
Can we override static method
OR
What is method hiding in java?
4) We can't override main method but we can overload the main method, Here JVM will
always search the main method which contains String array as a parameter.
Defination
----------
We can't override static method because it is not the part of the object it is
executed at the time of loading the .class file into JVM memory.
If a sub class defines a static method with the same signature with the static
method in the super class, the method in the sub class is hidden by the method in
the super class.
We can declare a static method with the same signature in the sub class as declared
in the super class which looks like we can override static methods but in java
static methods of super class are hidden from sub class which is known as Method
Hiding.
class Super
{
public static void display()
{
[Link]("Display Method of Super class");
}
}
class Sub extends Super
{
//Method Hiding
public static void display()
{
[Link]("Display Method of Sub class");
}
}
public class MethodHiding
{
public static void main(String[] args)
{
Super s = new Sub();
[Link]();
}
}
-------------------------------------------------------------------
Method Chaining :
-----------------
It provides a facility to call n number of methods in a single statement.
While calling the method, we always depend upon previous method return type and the
last invoked method will be final return type of the statement(18-OCT-23)
We should declare a class as a final if the composition of the class (logic of the
class) is very important and we don't want to share the feature of the class to
some other developer to modify the original behavior of the existing class, In that
situation only we should declare a class as a final.
Declaring a class as a final does not mean that the variables and methods declared
inside the class will also become as a final only the class behavior is final that
means we can modify the variables value as well as we can create the object for the
final classes.
Note :- In java String and all wrapper classes declared as final class.
------------------------------------------------------------------
//Program that describes we can inherit final class
final class A
{
private int x = 100;
public void setData()
{
x = 120;
[Link](x);
}
}
class B extends A //error
{
}
public class FinalClassEx
{
public static void main(String[] args)
{
B b1 = new B();
[Link]();
}
}
------------------------------------------------------------------
final class Test
{
private int data = 100;
Note :- It is clear that we can create the object for final class as well as we can
modify the data of final class.
------------------------------------------------------------------
2) To declare a method as a final (Overriding is not possible)
-----------------------------------------------------------------
Whenever we declare a method as a final then we can't override that method in the
sub class otherwise there will be a compilation error.
We should declare a method as a final if the body of the method i.e the
implementation of the method is very important and we don't want to override or
change the super class method body by sub class method body then we should declare
the super class method as final method.
-----------------------------------------------------------------
class A
{
protected int a = 10;
protected int b = 20;
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.
Example:- final int DATA = 10; (Now we can not perform re-assignment )
------------------------------------------------------------------
class A
{
final int A = 10;
public void setData()
{
A = 10; //error re-assignment is not possible
[Link]("A value is :"+A);
}
}
class FinalVarEx
{
public static void main(String[] args)
{
A a1 = new A();
[Link]();
}
}
------------------------------------------------------------------
class FinalVarEx1
{
public static void main(String[] args)
{
final int A = 12;
byte b = A;
[Link](b);
}
}
------------------------------------------------------------------
Blank final variable :
-----------------------
Note :- From the above program it is clear that Blank final variable cannot be
initialized by default constructor.
------------------------------------------------------------------
class Demo
{
final int A; // blank final variable
class Test
{
Note :- Object is the super class for this Test class. by default this Object class
is super class so explicitly we need not to mention.
Since, Object is the super class of all the classes in java that means we can
override the method of Object class as well as we can use the methods of Object
class anywhere in java because every class is sub class of Object class.
The Object class provides some common behavior to each sub class Object like we can
compare two objects (equals(Object obj)), we can create clone (duplicate) objects
(clone()), we can print object properties(instance variable) by using toString(),
providing a unique number to each and every object(hashCode()) and so on.
------------------------------------------------------------------
public native int hashCode() :
------------------------------
It is a predefined method of Object class.
Every Object contains a unique number generated by JVM at the time of Object
creation is called hashCode.
we can find out the hashCode value of an Object by using hashCode() method of
Object class, return type of this method is int.
Program :
---------
[Link]
------------------
package [Link];
class Test
{
}
[Link]([Link]());
[Link]([Link]());
}
}
[Link]
------------------
package [Link];
class Student
{
private int studentId;
private String studentName;
This method returns the runtime class of the object, the return type of this method
is [Link].
This method will provide the class keyword + fully qualified name
[fully qualified name = Package Name + class name]
This getClass() method return type is [Link] so further we can apply any
other method of [Link] class to this method.
-------------------------------------------------------------------
[Link]
-------------------
package [Link];
class Employee
{
}
}
-------------------------------------------------------------------
package [Link];
class Customer
{
}
Double d1 = 89.67;
name = [Link]().getName();
[Link]("CLASS NAME IS :"+name);
}
}
------------------------------------------------------------------
21-10-2023
-----------
public String toString() :
----------------------------
It is a predefined method of Object class.
Please note internally the toString() method is calling the hashCode() and
getClass() method of Object class.
class Foo
{
}
public class ToStringDemo1
{
public static void main(String[] args)
{
Foo f1 = new Foo();
[Link]([Link]()); //toString();
}
class Demo
{
@Override
public String toString()
{
[Link]();
return "Overridden toString() method";
}
}
}
-----------------------------------------------------------------
public boolean equals(Object obj) :
----------------------------------
-----------------------------------------------------------------
package [Link];
class Customer
{
private int customerId;
private String customerName;
[Link](c1==c2);
[Link]([Link](c2));
}
}
Note :- Here in both the cases we will get the output as a false because ==
operator always verify the memory address or momory reference on the other hand
equals(Object obj) method of Object class, internally uses == operator only so
equals() method will provide false.
-----------------------------------------------------------------
//Overriding the equals(Object obj) method for comparing the content of two
objects.
package [Link];
class Student
{
private int studentId;
private String studentName;
In the above program we have overridden equals(Object obj) method from Object class
for content comparison.
String class has an overridden method called equals(Object obj) method for
comparing the String content, return type of this method is boolean.
----------------------------------------------------------------
//Same as above program
package [Link];
class Player
{
int playerId;
String playerName;
class Student
{
private int studentId;
private String studentName;
@Override
public boolean equals(Object obj) //obj = e2
{
if(obj instanceof Student)
{
Student s2 = (Student) obj;
if([Link] == [Link] &&
[Link]([Link]))
{
return true;
}
else
{
return false;
}
}
else
{
[Link]("Sorry! Comparison is not possible");
return false;
}
}
class Employee
{
private int empId;
private String empName;
Example :
enum Direction
{
EAST, WEST, NORTH, SOUTH //public + static + final
}
All the enum constants are public, static and final. We should write enum constants
inside the enum and every constant must be separated by comma.
An enum we can write outside of the class, inside of the class or even inside of
the method.
An enum defined inside a class can be declare private, protected, public and
static.
Enum keyword has provided the method values() through which we can fetch all the
enum constants.
In order to fetch the enum constant position we can use ordinal method of Enum
class. The return type of this method is int.
We can also write constructor inside an enum but it should not be declared as
public.
[Link]([Link]);
}
}
-----------------------------------------------------------------
enum Month
{
JANUARY,FEBRUARY,MARCH
}
public class Test2
{
enum Color { RED,BLUE,BLACK }
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
Note :- From the above Program it is clear that we can define an enum inside a
class, outside of a class and inside a method as well.
----------------------------------------------------------------
//Comapring the constant of an enum
public class Test3
{
enum Color { RED,BLUE }
if(c1 == c2)
{
[Link]("==");
}
if([Link](c2))
{
[Link]("equals");
}
}
}
------------------------------------------------------------------
public class Test4
{
private enum Season //private, public, protected, static
{
SPRING, SUMMER, WINTER, RAINY;
}
class Test5
{
public static void main(String[] args)
{
[Link]([Link]);
}
}
Note :- The above program will generate the error because by default every enum
extends [Link] class. Which is an abstract class.
------------------------------------------------------------------
//All enums are by default final so can't inherit
enum Color
{
RED, BLUE, PINK;
}
class Test6 extends Color
{
public static void main(String[] args)
{
[Link]([Link]);
}
}
class Test7
{
enum Season
{
SPRING, SUMMER, WINTER, FALL, RAINY
}
for(Season y : x)
[Link](y);
}
}
-----------------------------------------------------------------
//ordinal() to find out the order position
class Test8
{
static enum Season
{
SPRING, SUMMER, WINTER, FALL, RAINY
}
for(Season x : s1)
[Link](x+" order is :"+[Link]());
}
}
------------------------------------------------------------------
//We can take main () inside an enum
enum Test9
{
TEST1, TEST2, TEST3; //Semicolon is compulsory
enum Test10
{
public static void main(String[] args)
{
[Link]("Enum main method");
}
Season()
{
[Link]("Constructor is executed....");
}
}
class Test11
{
public static void main(String[] args)
{
[Link]([Link]);
[Link]([Link]);
}
}
Note :- All enum constants are by default Object of type enum so when JVM will
load enum to the memory all objects will be automatically loaded so for every enum
Object respective constructor will be executed.
------------------------------------------------------------------
//Writing constructor with message
enum Season
{
SPRING("Pleasant"), SUMMER("UnPleasent"), RAINY("Rain"), WINTER;
String msg;
Season(String msg)
{
[Link] = msg;
}
Season()
{
[Link] = "Cold";
}
for(Season x : s1)
[Link](x+" is :"+[Link]());
}
}
-----------------------------------------------------------------
enum MyType
{
ONE
{
@Override
public String toString()
{
return "this is one";
}
},
TWO
{
@Override
public String toString()
{
return "this is two";
}
}
}
public class Test13
{
public static void main(String[] args)
{
[Link]([Link]);
[Link]([Link]);
}
}
------------------------------------------------------------------
public class Test14
{
enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
switch(day)
{
case SUNDAY:
[Link]("Sunday");
break;
case MONDAY:
[Link]("Monday");
break;
default:
[Link]("other day");
}
}
}
-----------------------------------------------------------------
26-10-2023
-----------
Inner classes in java :
------------------------
In java it is possible to define a class (inner class) inside another class (outer
class). It is also called Nested class.
A nested class or an inner class is a class that exists within another class. In
other words, the inner class is a part of a class, just as variables and methods
are members of a class
It can be declared with access modifiers like private, default, protected, public,
abstract and final.
An inner class can also access the private member of outer class.
Note :- The .class file of an inner class will be represented by $ symbol at the
time of compilation.
class Inner
{
public void displayValue()
{
[Link]("Value of a is " + a);
}
}
}
public class Test1
{
public static void main(String... args)
{
//Outer mo = new Outer(); //Outer class Object is created
//[Link] inner = [Link] Inner(); //Inner class object is created
class MyInner
{
private int y = 15;
public void seeOuter()
{
[Link]("Outer x is "+x);
}
}
}
public class Test2
{
public static void main(String args[])
{
MyOuter m = new MyOuter();
[Link]();
}
}
-----------------------------------------------------------------
class MyOuter
{
private int x = 15;
class MyInner
{
public void seeOuter()
{
[Link]("Outer x is "+x);
}
}
}
public class Test3
{
public static void main(String args[])
{
//Creating inner class object in a single line
[Link] m = new MyOuter().new MyInner();
[Link]();
}
}
-----------------------------------------------------------------
class MyOuter
{
static int x = 7;
class MyInner
{
public static void seeOuter() //[Link]();
{
[Link]("Outer x is "+x);
}
}
}
new OuterClass().display();
}
}
-----------------------------------------------------------------
27-10-2023
----------
2) Method local inner class :
-------------------------------
If a class is declared inside the method then it is called method local inner
class.
We cann't apply any access modifier on method local inner class but they can be
marked as abstract and final.
A local inner class we can't access outside of the method that means the scope of
method local inner class within the same method only.
-----------------------------------------------------------------
//program on method local inner class
class MyOuter3
{
private String x = "Outer class private data";
}
public class Test11
{
public static void main(String args[])
{
MyOuter3 m = new MyOuter3();
[Link]();
}
}
----------------------------------------------------------------
//local inner class we can't access outside of the method
class MyOuter3
{
private String x = "Outer class Data";
}
public class Test12
{
public static void main(String args[])
{
MyOuter3 m = new MyOuter3();
[Link]();
}
}
Note :- Method local inner class object must be created inside the method only.
-----------------------------------------------------------------
3) Static Nested Inner class :
---------------------------------
A static inner class which is declared with static keyword inside an outer class is
called static Nested inner class.
It cann't access non-static variables and methods i.e (instance members) of outer
class.
For static nested inner class, Outer class object is not required.
If a static nested inner class contains static method then object is not required
for inner class. On the other hand if the static inner class contains instance
method then we need to create an object for static nested inner class.
-----------------------------------------------------------------
//static nested inner class
class BigOuter
{
static class Nest //static nested inner class
{
void go() //Instance method of static inner class
{
[Link]("Hello welcome to static nested class");
}
}
}
class Test13
{
public static void main(String args[])
{
[Link] n = new [Link]();
[Link]();
}
}
-----------------------------------------------------------------
class Outer
{
static int x=15;
}
}
}
class Test15
{
public static void main(String args[])
{
[Link]();
}
}
-----------------------------------------------------------------
class Outer
{
int x=15; //error (not possible because try to access instance variable)
static class Inner
{
void msg()
{
[Link]("x value is "+x);
}
}
}
class Test16
{
public static void main(String args[])
{
[Link] obj=new [Link]();
[Link]();
}
}
-----------------------------------------------------------------
4) Anonymous inner class :
------------------------------
It is an inner class without a name and for this kind of inner class only single
Object is created. (Singleton class)
*A normal class can implement any number of interfaces but an anonymous inner class
can implement only one interface at a time.
A normal class can extend one class and implement any number of interfaces at the
same time but an anonymous inner class can extend one class or can implement one
interface at a time.
-----------------------------------------------------------------
package [Link];
class Vehicle
{
public void run()
{
[Link]("Vehicle is running");
}
}
public class Anonymous {
};
};
[Link](); [Link]();
}
-----------------------------------------------------------------
28-10-2023
-----------
Abstract class and abstract methods :
-------------------------------------
Abstract class and abstract methods :
-------------------------------------------
A class that does not provide complete implementation (partial implementation) is
defined as an abstract class.
In java whenever action is common but implementations are different then we should
use abstract method, Generally we declare abstract method in the super class and
its implementation must be provided in the sub class.
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.
*An abstract class may or may not have abstract method but an abstract method must
have abstract class.
public Car()
{
[Link]("Car class Constructor!!!");
}
Note :- In the above program Car class constructor will be executed by super
keyword of Honda class using default constructor.
Abstract class constrcutor will be executed with the help of sub class object.
-----------------------------------------------------------------
31-10-2023
----------
Program that describes, all the abstract method defined in the super class must be
overridden in the sub class
[Link]
---------------------
package [Link].abstract_demo;
abstract class A
{
public abstract void show();
public abstract void demo();
}
abstract class B extends A
{
@Override
public void show() // + demo();
{
[Link]("Show method implemented in class B");
}
}
class C extends B
{
@Override
public void demo()
{
[Link]("Demo method implemented in class C");
}
}
}
------------------------------------------------------------------
//Program to describe common abstract method must be overridden
in the sub classes.
package [Link].abstract_demo;
@Override
public void area()
{
double area = [Link] * [Link];
[Link]("Area of Rectangle is :"+area);
}
}
class Circle extends Shape
{
private final double PI = 3.14;
private int radius;
@Override
public void area()
{
double area = PI * radius * radius;
[Link]("Area of Circle is :"+area);
}
}
[Link]
-----------------
package [Link].abstract_demo;
@Override
public void run()
{
[Link]([Link] + " Car is running!!");
}
@Override
public String toString() {
return "Car [carName=" + carName + ", vehicleNumber=" + vehicleNumber +
"]";
}
}
};
};
}
----------------------------------------------------------------
interface :
-----------
interface (Upto 1.7) :-
------------------------
An interface is a keyword in java which is similar to a class.
Upto JDK 1.7 an interfcae contains only abstract method that means there is a
gurantee that inside an interfcae we don't have concrete or general or instance
methods.
From java 8 onwards we have a facility to write default and static methods.
By using interface we can acheive 100% abstraction concept because it contains only
abstract methods.
In order to implement the member of an interface, java software people has provided
implements keyword.
All the methods declared inside an interface is by default public and abstract so
at the time of overriding we should apply public access modifier to sub class
method.
All the variables declared inside an interface is by default public, static and
final.
We should override all the abstract methods of interface to the sub class otherwise
the sub class will become as an abstract class hence object can't be created.
Note :- inside an interface we can't declare any blocks (instance, static) as well
as we can't write constructor inside an interface.
----------------------------------------------------------------
3 files :
---------
[Link](I)
-----------------
package [Link];
[Link](C)
-----------
package [Link];
[Link](C)
------------
package [Link];
}
---------------------------------------------------------------
3 files :
[Link](I)
---------------
package [Link].interface_demo;
[Link](C)
-----------------
package [Link].interface_demo;
@Override
public void doSum(int x, int y)
{
int sum = x + y;
[Link]("Addition is :"+sum);
}
@Override
public void doSub(int x, int y)
{
int sub = x - y;
[Link]("Subtraction is :"+sub);
}
@Override
public void doMul(int x, int y)
{
int mul = x * y;
[Link]("Multiplication is :"+mul);
}
[Link](C)
-----------------
package [Link].interface_demo;
}
---------------------------------------------------------------
H.W
interface Bank
{
void deposit(int amount);
void withdraw(int amount);
}
----------------------------------------------------------------
Program on loose coupling :
---------------------------
IQ
--
How to achieve loose coupling using interfaces :
------------------------------------------------
Loose Coupling :- If the degree of dependency from one class object to another
class is very low then it is called loose coupling.
[Link]
-----------
package [Link].loose_coupling;
[Link]
-----------
package [Link].loose_coupling;
[Link]
--------------
package [Link].loose_coupling;
[Link]
---------------
package [Link].loose_coupling;
package [Link].loose_coupling;
[Link](new Coffee());
[Link](new Horlicks());
}
------------------------------------------------------------------
Note :- We can also take return type of the method as an interface so that method
can return the object of all the sub classes which are implementing from that
particular interface.
package [Link].interface_demo;
interface A
{
void m1();
}
interface B
{
void m1();
}
class Implementer implements B,A
{
@Override
public void m1()
{
[Link]("Multiple Inheritance using interface..");
}
}
public class MultipleInheritance
{
public static void main(String[] args)
{
Implementer i = new Implementer();
i.m1();
}
}
------------------------------------------------------------------
package [Link].interface_demo;
interface C
{
void doSum(int x, int y);
}
interface D extends C
{
void doSub(int x, int y);
}
class Calculate implements D
{
@Override
public void doSum(int x, int y)
{
int sum = x+y;
[Link]("Sum is :"+sum);
@Override
public void doSub(int x, int y)
{
int sub = x-y;
[Link]("Sub is :"+sub);
}
}
public class ExtendingInterface
{
public static void main(String[] args)
{
Calculate c = new Calculate();
[Link](12, 12);
[Link](100, 50);
}
}
------------------------------------------------------------------
Extending one interface to another interface :
-----------------------------------------------
One interface can extends another interface but one interface can't implement
another interface.
The following program explains how one interface can extends another interface
package [Link].interface_demo;
interface C
{
void doSum(int x, int y);
}
interface D extends C
{
void doSub(int x, int y);
}
class Calculate implements D
{
@Override
public void doSum(int x, int y)
{
int sum = x+y;
[Link]("Sum is :"+sum);
@Override
public void doSub(int x, int y)
{
int sub = x-y;
[Link]("Sub is :"+sub);
}
}
public class ExtendingInterface
{
public static void main(String[] args)
{
Calculate c = new Calculate();
[Link](12, 12);
[Link](100, 50);
}
}
------------------------------------------------------------------
Overriding interface method by using anonymous inner class :
-----------------------------------------------------------
By using anonymous inner class without using an external class, inside the ELC
class only we can take an anonymous class to override the super class
method/abstract class method/ interface method.
package [Link].interface_demo;
interface Student
{
void writeExam();
}
};
};
[Link]();
[Link]();
}
}
-----------------------------------------------------------------
java 8 features : (March 2014)
-----------------------------
Limitation of abstract method :
OR
Maintenance problem with interface in an Industry upto JDK 1.7
--------------------------------------------------------------
The major maintenance problem with interface is, if we add any new abstract method
at the later stage of development inside an existing interface then all the
implementer classes have to override that abstract method otherwise the
implementer class will become as an abstract class so it is one kind of boundation
as shown in the program below.
-----------------------------------------------------------------
4 Files :
---------
[Link](I)
---------------
package [Link].java_8;
[Link](C)
------------
package [Link].java_8;
@Override
public void horn()
{
[Link]("Car has horn");
}
@Override
public void digitalMeter() //From java 1.8 onwards
{
[Link]("Car has Digital Meter Facility");
}
}
[Link](C)
------------
package [Link].java_8;
@Override
public void horn()
{
[Link]("Bike has horn");
}
}
[Link](C)
------------
package [Link].java_8;
Note :-
--------
Here in the Vehicle interface we have added dafault method digitalMeter() so now
for Car class as well as Bike class, there is no boundation to override this
default method.
If an implementer class is really required it then that class can override it.
-----------------------------------------------------------------
03-11-2023
----------
interface from JDK 1.8 onwards :
------------------------------------
Upto JDK 1.7 we can use only abstract methods inside an interface, as we know all
the abastrct methods must be overridden in the sub class otherwise the sub class
will become as an abstract class.
This facility of abstract methods leads to maintenance problem because if we add
any new abstract method inside an existing interface then that method has to
override by all the sub classes or the classes which are implementing from that
particular interface.
To avoid this boundation problem java software people has introduced default and
static method inside an interface so from JDK 1.8 onwards we can define the body of
the method inside an interface by declaring those method as default method and
static method or both.
-------------------------------------------------------------------
What is default Method inside an interface?
------------------------------------------------
default method is just like concrete method which contains method body and we can
write inside an interface from java 8 onwards.
*By using default method there is no boundation to override the default method in
the sub class, if we really required it then we can override to provide my own
implementation.
interface HotDrink
{
void prepare();
@Override
public void expressPrepare() //public is compulsory here
{
[Link]("Preparing premium Tea");
}
}
class Coffee implements HotDrink
{
@Override
public void prepare()
{
[Link]("Preparing Coffee");
}
@Override
public void expressPrepare() //public is compulsory here
{
[Link]("Preparing Filter Coffee");
}
}
public class DefaultMethod
{
public static void main(String[] args)
{
HotDrink hk;
hk = new Tea(); [Link](); [Link]();
hk = new Coffee(); [Link](); [Link]();
}
}
------------------------------------------------------------------
The following program explains that default methods are having low priority than
normal methods (Concrete Method). class is having more power than interface.
interface I
{
default void demo()
{
[Link]("Demo Method in interface I1");
}
}
class A
{
public void demo()
{
[Link]("Demo Method in class A");
}
}
Note :- MI is possible by using default method of interface but here we need to use
super keyword.
------------------------------------------------------------------
static method is only available inside the interface where it is defined that means
we cannot invoke static method from the implementer classes.
It is used to provide common functionality which we can apply/invoke from any ELC
class.
------------------------------------------------------------------
package [Link].static_demo;
interface Calculate
{
public static int doSum(int x, int y)
{
return (x+y);
}
public static int doSub(int x, int y)
{
return (x-y);
}
}
}
------------------------------------------------------------------
interface Callable
{
public static void access()
{
[Link]("static method available inside interface");
}
}
public class StaticDemo2 implements Callable
{
public static void main(String[] args)
{
[Link]();
[Link](); //error
Note :- In the above program we will get compilation error because static method is
available to Callable interface only so, implementer class cannot invoke static
method access.
------------------------------------------------------------------
What is Functional interface ?
-------------------------------
@FunctionalInterface Annotation :
---------------------------------------
If an interface contains only one abstract method then we can say that interface is
Functional Interface.
Functional Interface may contain default method and static method but it must
contain only one abstract method.
@FunctionalInterface
interface Printable
{
void print1();//SAM [Single Abstract Method]
Lamda target can't be class or abstract class, it will work with functional
interface only.
------------------------------------------------------------------
package [Link];
@FunctionalInterface
interface Drawable
{
void draw();
}
@FunctionalInterface
interface Calculate
{
void doSum(int x, int y);
}
public class Lambda2
{
public static void main(String[] args)
{
Calculate c = (p,q)-> [Link]("Sum is :"+(p+q));
[Link](10, 20);
}
}
------------------------------------------------------------------
package [Link];
interface Length
{
int getLength(String str);
}
}
--------------------------------------------------------------------------------
06-11-2023
----------
Programs on Lambda :
--------------------
@FunctionalInterface
interface Moveable
{
void move(); //SAM (Single Abstract Method)
}
public class Lambda1
{
public static void main(String[] args)
{
Moveable car = () -> [Link]("Moving With Car......");
[Link]();
@FunctionalInterface
interface Length
{
int getLength(String str);
}
[Link]("Square is :"+[Link](4));
}
}
------------------------------------------------------------------------
Working with predefined functional interfaces provided by java software people :
------------------------------------------------------------------------
Java software prople has provided a predefined functional interaface called
Runnable available in [Link] package, it contains only one abstract method i.e
run() so, it is a functional interface.
@FunctionalInterface
public interface Runnable
{
public abstract void run();
}
------------------------------------------------------------------------
Implementation of predefined Runnable interafce using Lambda :
--------------------------------------------------------------
public class Test
{
public static void main(String []a)
{
Runnable r1 = ()-> [Link]("Run method implemnted!!!");
[Link]();
}
}
------------------------------------------------------------------------
Working with predifined fuctional interfaces which are taking type parameter :
------------------------------------------------------------------------
Type Parameter in Java :
---------------------------
Java software people take this concept from C++ to make our variables are
independent of data type which is known as Type Parameter<T>.
Type parameter will accept Wrapper type OR User-defined class type, it will not
accept primitive type.
class Accept<T> //T can accept any type Wrapper + User-Defined (No primitive)
{
private T var; //var = new Student();
public T getVar()
{
return var;
}
}
class Student
{
@Override
public String toString()
{
return "Student -> With Type Parameter";
}
}
In the above program we can accept only Wrapper type and User-defined class type as
a parameter we cannot accept primitive type as a parameter.
------------------------------------------------------------------------
07-11-2023
----------
Working with predefined functional interfaces :
------------------------------------------------------
In order to help the java programmer to write concise java code in day to day
programming java software people has provided the following predefined functional
interfaces
1) Predicate<T>
2) Consumer<T>
3) Function<T,R>
4) Supplier<T>
Note :-
-------
All these predefined functional interfaces are provided as a part of
[Link] sub package.
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.
package [Link].predicate_interface;
import [Link];
import [Link];
}
-----------------------------------------------------------------------
Write a program to verify whether a name starts with 'A' or not ?
---------------------------------------------------------------
package [Link].predicate_interface;
import [Link];
import [Link];
if(test)
{
[Link](name +" starts with A");
}
else
{
[Link](name +" does not start with A");
}
}
}
----------------------------------------------------------------------
WAP to verify whether a person is eligible 4 voting or not ?
------------------------------------------------------------
package [Link].predicate_interface;
import [Link];
}
}
----------------------------------------------------------------------
WAP to verify my name is Ravi or not ?
--------------------------------------
package [Link].predicate_interface;
import [Link];
import [Link];
}
---------------------------------------------------------------------
//Leap Year or Not ?
package [Link].predicate_interface;
import [Link];
}
-----------------------------------------------------------------------
Consumer<T> functional interface :
-----------------------------------------
It is a predefined functional interface available in [Link] sub
package.
@FunctionalInterface
public interface Consumer<T>
{
void accept(T x);
}
------------------------------------------------------------------------
//Program on Consumer to accept multiple values :
import [Link].*;
public class ConsumerDemo1
{
public static void main(String [] args)
{
Consumer<Integer> printInt = x -> [Link](x);
[Link](15);
class Student
{
@Override
public String toString()
{
return "Consumer Student Object";
}
}
-------------------------------------------------------------------------
Function<T,R> functional interface :
-----------------------------------------
Type Parameters:
T - the type of the input to the function.
R - the type of the result of the function.
Note :- The type of T(input) and the type of R(Result) both will be decided by the
user.
@FunctionalInterface
public interface Function<T,R>
{
R apply(T x);
}
-------------------------------------------------------------------------
//Square of the number
package [Link].function_interface;
import [Link];
import [Link];
}
-------------------------------------------------------------------------
//Length of the name + Name starst with particular String or not
package [Link].function_interface;
import [Link];
}
------------------------------------------------------------------------
08-11-2023
----------
Supplier<T> interface :
---------------------------
It is a predefined functional interface available in [Link] sub
package. It provides an abstract method get() which does not take any argument but
produces/supply a value of type T.
@FunctionalInterface
public interface Supplier<T>
{
T get();
}
--------------------------------------------------------------------------
//Here Supplier get() method is returning Player object
package [Link].supplier_interface;
import [Link];
class Player
{
int pid;
String pname;
public Player(int pid, String pname) {
super();
[Link] = pid;
[Link] = pname;
}
@Override
public String toString() {
return "Player [pid=" + pid + ", pname=" + pname + "]";
}
[Link]([Link]());
}
------------------------------------------------------------------------
//Here Supplier get() method is returning String object
package [Link].supplier_demo;
import [Link];
}
------------------------------------------------------------------------
//Here Supplier get() method is returning Employee object
2 files :
---------
[Link]
-------------
package [Link].supplier_demo;
@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" +
employeeName + ", employeeSalary="
+ employeeSalary + "]";
}
[Link]
-----------------
package [Link].supplier_demo;
import [Link];
}
-------------------------------------------------------------------
Can a functional interface contains the method of Object class?
---------------------------------------------------------------
Yes, Functional interface may contain the method of Object class. The main reason
to re-declare Object class method inside functional ineterface to follow the
contract.
package [Link].functional_interface;
@FunctionalInterface
public interface Callable
{
public abstract void call();
From the avove interface, It is clear that inside a Functional interface we can re-
declare the method of Object class.
--------------------------------------------------------------
Can we override Object class methods inside a functional interface as a default
method?
No, We cannot override Object class method as a default method inside a functional
interface, we can only re-declare as showm in interface below.
package [Link].functional_concept;
@FunctionalInterface
public interface Printable
{
void print();
--------------------------------------------------------------
Can we write private method inside an inetrafce?
Yes, From java 9 onwards we can also write private static and private non-static
methods inside an interface.
interface CustomInterface
{
public abstract void method1(); //abstract method
@Override
public void method1() {
[Link]("abstract method");
}
It describes run-time type information about objects, so the JVM have additional
information about the object. [like object is clonable OR object is serializable]
Example :
----------
public interface Drawable //Marker interface
{
}
Note :-In java we have Clonable and Serializable are predefined marker interface.
--------------------------------------------------------------------
*What is difference between abstract class and interface ?
------------------------------------------------------------------
The following are the differences between abstract class and interface.
1) An abstract class can contain instance variables but interface variables are by
default public , static and final.
2) An abstract class can have state (properties) of an object but interface can't
have state of an object.
4) An abstract class can contain instance and static blocks but inside an interface
we can't define any blocks.
5) Abstract class can't refer Lambda expression but using Functional interface we
can refer Lambda Expression.
6) We can write concrete method inside an abstract class but inside an interface we
can't write concrete public method, only abstract , default, static and private
methods are allowed.
----------------------------OOPS ENDED--------------------------------
09-11-2023
-----------
Class loader sub system with JVM Architecture :
------------------------------------------------------
The three main components of JVM
3) Execution engine
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.
Note :-
------
If all the class loaders are failed to load the .class file into JVM memory then we
will get a Runtime exception i.e [Link].
----------------------------------------------------------------------
10-11-2023
-----------
//Write a program in java which shows that our userdefined .class file will be
loaded by Application class loader
package [Link].jvm_architecture;
class Customer{}
class Employee{}
cls = [Link];
[Link]([Link]());
}
----------------------------------------------------------------------
Linking :
---------
verify :-
-------
It ensures the correctness of the .class files, If any suspicious activity is there
in the .class file then It will stop the execution immediately by throwing an
exception i.e [Link].
---------------------------------------------------------------------
prepare:
---------
It will allocate the memory for all the static data members, here all the static
data member will get the default values so if we have static int x = 100;
then for variable x memory will be allocated and now it will initialize with
default value i.e 0.
----------------------------------------------------------------------
Resolve :-
-----------
All the symbolic references will be converted to direct references or actual
reference.
static block :-
---------------
It is a very special block in java which will be executed automatically at the time
of loading the .class file into JVM memory by class loader sub system.
Example:-
static
{
The main purpose of static block to initialize the static data member of the class.
static block will be executed only once because class loading is possible only once
in java.
If we have multiple static blocks are present in a class then It will be executed
according to order (Top to bottom).
We can't access static field before it is declared otherwise we will get illegal
forward reference error but we can initialize in the static block before
declaration.
{
[Link]("Instance block..");
}
static
{
[Link]("Static block...");
}
}
public class StaticBlockDemo
{
public static void main(String [] args)
{
[Link]("Main Method Executed ");
}
}
Note :- In the above program [Link] file is not loaded into JVM memory so the
static block of [Link] file will not be executed.
---------------------------------------------------------------------
class Test
{
static int x;
static
{
x = 100;
[Link]("x value is :"+x);
}
static
{
x = 200;
[Link]("x value is :"+x);
}
static
{
x = 300;
[Link]("x value is :"+x);
}
static
{
x = 400;
[Link]("x value is :"+x);
}
}
public class StaticBlockDemo1
{
public static void main(String[] args)
{
[Link](Test.x);
}
}
Note -: From the above program it is clear that static blocks are executed
according to order i.e top to bottom
--------------------------------------------------------------------
class Foo
{
static int x;
static
{
[Link]("x value is :"+x);
}
}
Note :- The program says that static variables are also initialized with default
value.
---------------------------------------------------------------------
class Demo
{
// static blank final variable
static final int a;
static
{
a = 10; //Initialization is compulsory becuae final blank static
}
}
public class StaticBlockDemo3
{
public static void main(String[] args)
{
[Link]("a value is :"+Demo.a);
}
}
{
[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();
}
}
a) Always the super class wil be loaded first then only sub class will be loaded
into JVM Memory.
b) The first two line of any constructor is reserved for super() and
non-static block i.e instance block.
----------------------------------------------------------------------
//illegal forward reference
class Demo
{
static
{
i = 10; //valid
//i = i + 19; //error
//[Link](i); //error
}
static int i;
}
static int i;
}
public class StaticBlockDemo6
{
From JDK 1.7 onwards now we can't execute java program without main method because
JVM checks the presence of the main method before initializing the class.
Eg:-
class WithoutMain
{
static
{
[Link]("Hello world");
[Link](0);
}
}
The above program was possible to execute upto JDK 1.6.
----------------------------------------------------------------------
How many ways we can load the .class file into JVM memory :
-----------------------------------------------------------
There are so many ways we can load our .class file into JVM memory, Here we have
few example
class Test
{
}
class Test
{
}
class ELC
{
public static void main(String [] args)
{
new Test(); [Making a request to JVM to load the [Link] file]
}
}
4) By using Inheritance :
class Alpha
{
}
class Beta extends Alpha
{
}
class ELC
{
public static void main(String [] args)
{
new Beta(); [Before [Link], first of all [Link] file will
be loaded and then [Link] file will be loaded]
}
}
[Link](String className);
----------------------------------------------------------------------
1) By using Java tools
javac [Link]
java Test [Load the [Link] file into JVM memoy]
class Demo
{
static int x = 10;
static
{
[Link]("Static Block of Demo class Executed!!! :"+x);
}
}
public class ClassLoading
{
public static void main(String[] args)
{
[Link](Demo.x);
}
}
---------------------------------------------------------------------
13-11-2023
-----------
4) By using Inheritance :
-------------------------
By using Inheritance concept, whenever we want to load sub class .class file then
first of all super class .class file will be loaded and then only syb class .class
file will be loaded.
class A
{
static
{
[Link]("Static Block of super class A!!");
}
}
class B extends A
{
static
{
[Link]("Static Block of Sub class B!!");
}
}
class InheritanceLoading
{
public static void main(String[] args)
{
new B();
}
}
----------------------------------------------------------------------
By Using Reflection API :
--------------------------
In [Link] package, there is a predefined class called Class. This class called
Class contains one predefined static method forName(String className) which is used
to LOAD THE SPECIFIED .CLASS INTO JVM MEMORY DYNAMICALLY. [In eclipse, class name
must be Fully Qualified Name]
[Link]
--------------------
package [Link].dynamic_class_loading;
}
---------------------------------------------------------------------
* What is the difference [Link] and
[Link].
[Link] :
----------------------------------
In Java whenever we try to load the .class file dynamically at runtime by using
[Link]() or loadClass() method of ClassLoader class and if the
required .class file is not availavle at RUNTIME then it will generate an execption
i.e [Link]
Program :
----------
class Foo
{
static
{
[Link]("static block gets executed...");
}
}
public class ClassNotFoundExceptionDemo
{
public static void main(String[] args) throws ClassNotFoundException
{
[Link]("Player");
}
}
[Link] :
--------------------------------
In this approach the class name is available at the time of compilation but after
compilation the .class file ([Link]) will be deleted by user manually or It
was re-located from one package to another package then at the time of execution
the required .class file is not available hence we will get
[Link].
Plaese notice, class was present at the time of compilation but at runtime the
required .class file is not available.
class Message
{
public void greet()
{
[Link]("Hello Everyone I hope you are fine..");
}
}
public class NoClassDefFoundErrorDemo
{
public static void main(String[] args)
{
Message m = new Message();
[Link]();
}
}
"new" keyword is suitable for creating the object for the classes which are
available at compilation time or at the time of writing the source code (.java
file) but on the other hand it is not suitable for
the classes are coming from database or some file at runtime dynamically.
In order to create the object for the classes which are coming from the database or
file at runtime we need to use newInstance() method available in [Link].
class Customer
{
}
class ObjectAtRuntime
{
public static void main(String [] args) throws Exception
{
Object obj = [Link](args[0]).newInstance();
[Link]([Link]().getName());
}
}
javac [Link]
java ObjectAtRuntime Customer
/* getclass() is the method of Object class and its return type is Class, so we can
apply any method of class called Class, getName() is the method of Class class.
*/
----------------------------------------------------------------------
class Customer
{
public void greet()
{
[Link]("Hello Batch 24");
}
}
class ObjectAtRuntime1
{
public static void main(String [] args) throws Exception
{
Object obj = [Link](args[0]).newInstance();
Customer c1 = (Customer) obj;
[Link]();
}
}
javac [Link]
java ObjectAtRuntime Customer
----------------------------------------------------------------------
14-11-2023
-----------
Runtime Data Areas :
--------------------
Once the .class file is loaded successfully in the JVM memory then the content of
the class is divided into different memory areas which are as follows :
a) Method Area
b) HEAP Area
c) Stack Area
d) PC Register
e) Native Method Stack
a) Method Area :
-------------------
In this area all class level information is available. Actually the .class file is
dumpped here hence we have all kinds of information related to class is available
like name of the class, name of the immediate super class, package name, method
name , variable name, static variable, all method available in that particular
class and so on.
This method area returns type [Link] class , this [Link] class
object can hold any .class file
(Class c = [Link])
Note :- Method and Field both are predefined classes available [Link]
package. Both contain getName() method to get the name of the method and name of
the field.
import [Link];
[Link]
----------------------
package [Link].method_area;
import [Link];
import [Link];
int fieldCount = 0;
for(Field field : fields)
{
[Link]([Link]());
fieldCount++;
}
[Link]("Total Fields are :"+fieldCount);
}
}
----------------------------------------------------------------------
Why static method does not act on instance variable ?
-----------------------------------------------------
All the static data member like static variable, static block, static nested inner
class and static method are executed at the time of loading .class file into JVM
memory, At the time of execution of these static data member, object is not
available and we known instance variables are the part of the object so, we cannot
act on instance variable using static area.
[Link]
----------
public class Demo
{
int x = 100;
public Test(int x)
{
this.x = x;
}
}
public class StaticTest
{
public static void main(String[] args)
{
Test t1 = new Test(10);
[Link]();
}
}
From the above two programs it is clear that we cannot access instance variables
from static area even object is already created.
----------------------------------------------------------------------
HEAP Area :
-----------
In java whenever we create the Object, all object related data like instance
variable and instance methods are strored in HEAP Area.
This is the 2nd layer architecture of JVM so from this area we can access the
static memeber of the class but vice versa is not possible.
But in Java a user is not responsible to de-allocate the memory that means memory
allocation is the responsibility of user but memory de-allocation is automatically
done by Garbage Collector.
Note :- GC uses an algorithm mark and sweep to make an un-used objects eligible for
Garbage Collection.
The garbage Collector thread is visiting our program at regular interval to delete
the unused objects but as a programmer we can call garbge collector explicitly to
visit our program by using the following code.
e3 = new Employee();
class Customer
{
private String name;
private int id;
[Link]([Link]());
}
[Link](9);
[Link]([Link]());
}
}
//9 5
----------------------------------------------------------------
public class Sample
{
private Integer i1 = 900;
Sample s3 = modify(s2);
s1=null;
[Link](s2.i1);
}
public static Sample modify(Sample s)
{
s.i1=9;
s = new Sample();
s.i1= 20;
[Link](s.i1);
s=null;
return s;
}
}
//20 9
-----------------------------------------------------------------------
25-11-2023
----------
HEAP and STACK diagram for [Link]
-----------------------------------------
public class Employee
{
int id=100;
public static void main(String[] args)
{
int val = 200;
[Link]=val;
update(e1);
[Link]([Link]);
[Link]=500;
switchEmployees(e2,e1);
[Link]([Link]);
[Link]([Link]);
}
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
//300 200 400 200
--------------------------------------------------------------------------
HEAP and STACK Diagram for [Link]
------------------------------------
class Alpha
{
int val;
static int sval = 200;
static Beta b = new Beta();
Alpha(int val)
{
[Link] = val;
}
}
ar[0] = am1;
[Link](ar[0].val);
[Link](ar[1].val);
}
//15 15
--------------------------------------------------------------------------
Runtime Data Areas :
--------------------
a) Method Area
b) Heap Area
c) Stack Area
d) PC register
e) Native Method Stack
PC Register :
-------------
It stands for Program counter Register.
Native method stack will hold the native method information in a separate stack.
--------------------------------------------------------------------------
Execution Engine :
------------------
Interpreter
------------
In java, JVM is an interpreter which executes the program line by line. JVM
(Interpreter) is slow in nature because at the time of execution if we make a
mistake at line number 9 then it will throw the execption at line number 9 and
after solving the execption again it will start the execution from line number 1 so
it is slow in execution that is the reason to boost up the execution java software
people has provided JIT compiler.
JIT Compiler :
--------------
It stands for just in time compiler. The main purpose of JIT compiler to boost up
the execution so the execution of the program will be completed as soon as
possible.
JIT compiler holds the repeated instruction like method signature, variables and
make it available to JVM at the time of execution so the overall execution becomes
very fast.
--------------------------------------------------------------------------
27-11-2023
----------
Exception Handling :
--------------------
What is an execption ?
----------------------
An execption is a runtime error.
An execption is an abnormal situation or un-expected situation in a noraml
execution flow.
Exception Hierarchy :
--------------------
This Exception hierarchy is available in the diagram (Exception_Hierarchy.png)
int x = 10;
int y = 0;
int z = x /y; [Dividing a number by zero (int value) then we will get
[Link]]
2) [Link]
int []arr = {10,20,30};
[Link](arr[3]); [Accessing the index which is out of the
bound]
3) [Link]
String str = null;
[Link]([Link]()); [calling any method on null literal]
4) [Link]
String str = "Ravi";
int no = [Link](str);
-----------------------------------------------------------------------
Note :- As a developer we are responsibe to handle the Exception. System admin is
responsibe to handle the error because we cannot recover from error.
-----------------------------------------------------------------------
Exception is the super class of all the execptions whether it is a predefined
exception or user-defined exception in Java.
-----------------------------------------------------------------------
WAP that describes that Exception is the super class of all the exceptions we have
in java :
package [Link];
package [Link];
import [Link];
Note :- In the above program if the value of y will be 0 then our program will halt
in the middle, it is called abnormal termination so, JVM is having default
exception handler, which will terminate the program and provide the appropriate
message.
------------------------------------------------------------------------
In order to work with Exception, Object Oriented Programming has provided the
following keywords :
1) try
2) catch
3) finally (try with resources [java 1.7])
4) throw
5) throws
-----------------------------------------------------------------------
28-11-2023
-----------
try block :
-----------
Whenever our statement is error suspecting statement OR Risky statement
then we should write that statement inside the try block.
try block must be followed either by catch block or finally block or both.
*try block is responsible to trace our code line by line, if any execption
encounter then TRY BLOCK WILL CREATE APPROPRIATE EXECPTION OBJECT, AND THROW THIS
EXCEPTION OBJECT to the nearest catch block.
After the execption in the try block, the remaining code of try block will not be
executed because control will directly transfer to the catch block.
In between try and catch block we cannot write any kind of statement.
catch block :
--------------
The main purpose of catch block to handle the exception which is thrown by try
block.
catch block will only executed if there is an exception in the try block.
import [Link];
[Link]("Result is :"+result);
[Link]("End of try block");
}
catch(Exception e)
{
[Link]("Inside catch Block");
[Link](e);
}
[Link]();
[Link]("Main method ended....");
}
}
In the above program, even exception encounter but program will be terminated
normally.
-----------------------------------------------------------------------
package [Link];
}
catch(Exception e)
{
[Link]("Inside catch");
[Link](e);
}
}
}
-----------------------------------------------------------------------
Program that describes we should provide user-friendly message to our client
package [Link];
import [Link];
int z = x/y;
[Link]("z value is :"+z);
}
catch(Exception e)
{
[Link]("Please don't put zero");
}
[Link]("Thank you 4 visiting!!");
[Link]();
}
}
-------------------------------------------------------------------------
29-11-2023
----------
Methods of Throwable class :
----------------------------
The Throwable class has provided the following methods to work with Exception.
[Link]
---------------------
package [Link];
}
[Link]("Main method ended...");
}
-------------------------------------------------------------------------
Working with Specific Exception :
---------------------------------
While working with exception, in the corresponding catch block we can take
Exception (super class) which can handle any type of Exception.
On the other hand we can also take specific type of exception (ArithmetiException,
NullPointerException and so on) which will handle only one type i.e specific type
of exception.
package [Link];
import [Link];
import [Link];
try
{
[Link]("Enter your Roll :");
int roll = [Link]();
[Link]("Your roll Number is :"+roll);
}
catch(InputMismatchException e)
{
[Link]("Input is not in a proper format!!");
[Link]();
}
[Link]();
[Link]("Main ended");
}
}
-------------------------------------------------------------------------
Working with Infinity and Not a number(NaN) :
---------------------------------------------
10/0 -> Infinity ([Link])
10/0.0 -> Infinity
While working Integral literal in both the cases i.e Infinity (10/0) and
Undefined (0/0) we will get [Link] because java software
people has not provided any final variable support to deal with
Infinity and Undefined.
On the other hand while working with floating point literal in the both cases i.e
Infinity (10/0.0) and Undefined (0/0.0) we have final variable
support so the program will not be terminated in the middle which are as follows
10/0.0 = POSITIVE_INFINITY
-10/0.0 = NEGATIVE_INFINITY
0/0.0 = Nan
[Link]
---------------------------
package [Link];
[Link](10/0.0);
[Link](-10/0.0);
[Link](0/0.0);
[Link](0/0);
[Link](10/0);
package [Link];
public class MultipleTryCatch
{
public static void main(String[] args)
{
[Link]("Main method started!!!!");
try
{
int arr[] = {10,20,30};
[Link](arr[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array is out of limit!!!");
}
try
{
String str = null;
[Link]([Link]());
}
catch(NullPointerException e)
{
[Link]("ref variable is pointing to null");
}
While working with multiple catch block always the super class catch block must be
last catch block.
From java 1.7 this multiple catch block we can also represent by using | symobl.
package [Link];
public class MultyCatch
{
public static void main(String[] args)
{
[Link]("Main Started...");
try
{
int a=10,b=3,c;
c=a/b;
}
catch(ArrayIndexOutOfBoundsException e1)
{
[Link]("Array is out of limit...");
}
catch(ArithmeticException e1)
{
[Link]("Divide By zero problem...");
}
catch(Exception e1)
{
[Link]("General");
}
[Link]("Main Ended...");
}
}
-----------------------------------------------------------------------
01-12-2023
----------
Multiple catch block using single try with Java 7 using | symbol.
package [Link];
}
-----------------------------------------------------------------------
finally block :
---------------
finally is a block which is meant for Resource handling purposes.
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.
try
{
[Link](10/0);
}
finally
{
[Link]("Finally Block");
}
package [Link];
import [Link];
import [Link];
}
catch(InputMismatchException e)
{
[Link]("Input is not matching");
}
finally
{
[Link]();
[Link]("Finally Ended");
}
[Link]("Main Ended");
}
}
-----------------------------------------------------------------------
02-12-2023
-----------
try with resources :
--------------------
To avoid all the limitation of finally block, Java software people introduced a
separate concept i.e try with resources from java 1.7 onwards.
Case 1:
-------
try(resource1 ; resource2) //Only the resources will be handled
{
}
Case 2 :
----------
try(resource1 ; resource2) //Resources and Exception both will be
{ //handled
}
catch(Exception e)
{
}
There is a predefined interface available in [Link] package called AutoCloseable
which contains predefined abstract method i.e close()
which throws Exception.
Whenever we pass any resourse class as part of try with resources then that class
must implements either Closeable or AutoCloseable interface so, try with resourses
will automatically call the respective class
close() method even an exception is encountered in the try block.
The following program explains how try block is invoking the close() method
available in DatabaseResource class and FileResource class.
[Link]
-----------------
package [Link].try_resource;
import [Link];
import [Link];
[Link]
---------------------
package [Link].try_resource;
}
-----------------------------------------------------------------------
Program on try-with Resources :
-------------------------------
package [Link].try_resource;
import [Link];
import [Link];
try(sc)
{
[Link]("Enter your Age :");
int age = [Link]();
[Link]("Your Age is :"+age);
}
catch(InputMismatchException e)
{
[Link]();
}
[Link]("Main Method Ended!!!");
}
}
Here in the above program we need to close Scanner class manually, it
will be taken care by try with resources.
----------------------------------------------------------------------
Exception propagation :-
--------------------------
Whenever we call a method and if the the callee method contains any kind of
exception and if callee method doesn't contain any kind of exception handling
mechanism (try-catch) then JVM will propagate the exception to caller method for
handling purpose. This is called Exception Propagation.
If the caller method also does not contain any exception handling mechanism then
JVM will terminate the method from the stack frame hence the remaining part of the
method(m1 method) will not be executed even if we handle the exception in another
caller method like main.
If any of the the caller method does not contain any exception handling mechanism
then exception will be handled by JVM, JVM has default exception handler which will
provide the exception message and terminates the program abnormally.
package [Link].try_resource;
}
catch(Exception e) //Outer Catch
{
}
The execution of inner try block depends upon outer try block that means if we have
an exception in the Outer try block then inner try block will not be executed.
package [Link];
}
catch(NumberFormatException e)
{
[Link]("Number is not in a proper format");
}
}
catch(NullPointerException e)
{
[Link]("Null pointer Problem");
}
}
}
----------------------------------------------------------------------
Writing try-catch inside catch block :
---------------------------------------
We can write try-catch inside catch block but this try-catch block will be exceuted
if the catch block will be executed.
package [Link];
import [Link];
import [Link];
}
catch(InputMismatchException e)
{
[Link]("Provide Valid input!!");
try
{
[Link](10/0);
}
catch(ArithmeticException e1)
{
[Link]("Divide by zero problem");
}
}
}
}
---------------------------------------------------------------------
05-12-2023
----------
try-catch with return statement
-------------------------------
If we write try-catch block inside a method and that method is returning some value
then we should write return statement in both the places i.e inside the try block
as well as inside the catch block.
We can also write return statement inside the finally block only, if the finally
block is present. After this finally block we cannot write any kind of statement.
(Unrechable)
package [Link];
public class ReturnExample
{
public static void main(String[] args)
{
[Link](methodReturningValue());
}
@SuppressWarnings("finally")
public static int methodReturningValue()
{
try
{
[Link]("Try block");
return 10/0;
}
catch (Exception e)
{
[Link]("catch block");
return 10/0;
}
finally
{
[Link]("Finally block");
}
}
-----------------------------------------------------------------------
Initialization of a variable in try and catch :
-----------------------------------------------
A local variable must be initialized inside try block as well as catch block OR at
the time of declaration otherwise we will get compilation error if we want to use
the local variable.
package [Link];
[Link]("Main completed!!!");
}
}
-----------------------------------------------------------------------
* Difference between Checked Exception and Unchecked Exception :
----------------------------------------------------------------
Checked Exception :
----------------------
In java some exceptions are very common exceptions are called Checked excption here
compiler takes very much care and wanted the clarity regarding the exception by
saying that by using this code you may face some problem at runtime and you did not
report me how would you handle this situation at runtime are called Checked
exception, so provide either try-catch or declare the method as throws.
Eg:
---
FileNotFoundException, IOException, InterruptedException,ClassNotFoundException,
SQLException and so on
Unchecked Exception :-
--------------------------
The exceptions which are rarely occurred in java and for these kinds of exception
compiler does not take very much care are called unchecked exception.
Unchecked exceptions are directly entertain by JVM because they are rarely occurred
in java.
Eg:
---
ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
NumberFormatException, ClassCastException, ArrayStoreException and so on.
-------------------------------------------------------------------------
06-12-2023
-----------
Checked Exception :
------------------
1) Common Exception
2) Compiler takes care (Will not compile the code)
3) Handling is compulsory (try-catch OR throws)
4) Directly the sub class of [Link]
Unchecked Exception :
----------------------
1) Rare Exception
2) Comiler will not take any care
3) Handling is not Compulsory
4) Sub class of RuntimeException
When we should declare the method as throws and when we should write
--------------------------------------------------------------------
try-catch
---------
When to provide try-catch or declare the method as throws :-
---------------------------------------------------------------------
We should provide try-catch if we want to handle the exception by own as well as if
we want to provide user-defined messages to the client but on the other hand we
should declare the method as throws when we are not interested to handle the
exception and try to send it to the JVM for handling purpose.
Note :- It is always better to use try catch so we can provide appropriate user
defined messages to our client.
-------------------------------------------------------------------------
Why compiler takes very much care regarding the checked Exception ?
---------------------------------------------------------------------
As we know Checked Exceptions are very common exception so in case of checked
exception "handling is compulsory" because checked Exception depends upon other
resources as shown below.
throws :-
---------
In case of checked Exception if a user is not interested to handle the exception
and wants to throw the exception to JVM, wants to skip from the current situation
then we should declare the method as throws.
It is mainly used to work with Checked Exception.
-------------------------------------------------------------------------
Types of exception in java :
-------------------------------
Exception can be divided into two types :
Predefined Exception :-
-------------------------
The Exceptions which are already defined by Java software people for some specific
purposes are called predefined Exception or Built-in exception.
Ex :
----
IOException, ArithmeticException and so on
Userdefined Exception :-
---------------------------
The exceptions which are defined by user according to their own use and requirement
are called User-defined Exception.
Ex:-
----
InvalidAgeException, GreaterMarksException
------------------------------------------------------------------------
Steps to create userdefined exception :
------------------------------------------
In order to create user defined exception we should follow the following steps.
import [Link];
@SuppressWarnings("serial")
class InvalidAgeException extends Exception //Checked Exception
{
public InvalidAgeException()
{
}
import [Link];
@SuppressWarnings("serial")
class GreaterMarksException extends RuntimeException
{
public GreaterMarksException()
{
}
[Link]("Main Completed");
}
}
------------------------------------------------------------------------
07-12-2023
----------
Some important rules to follow :
---------------------------------
a) If the try block does not throw any checked exception then in the corresponding
catch block we can't handle checked [Link] will generate compilation error
i.e "exception never thrown from the corresponding try statement"
Example :-
try
{
//try block is not throwing any checked Exception
}
catch(IOException e) //Error
{
}
-----------------------------------------------------------------------
package [Link].method_related_rule;
import [Link];
public class CatchingCheckedWithoutThrow
{
public static void main(String[] args)
{
try
{
throw new IOException();
}
catch(IOException e)
{
[Link]();
}
}
------------------------------------------------------------------------
b) If the try block does not throw any exception then in the corresponding catch
block we can write Exception, Throwable because both are the super classes for all
types of Exception whether it is checked or unchecked.
package [Link].method_related_rule;
import [Link];
import [Link];
}
------------------------------------------------------------------------
c) At the time of method overriding if the super class method does
not reporting or throwing checked exception then the overridden method of sub
class not allowed to throw checked exception. otherwise it will generate
compilation error.(Sub class method can throws un-checked Exception)
package [Link].method_related_rule;
class Super
{
public void show()
{
[Link]("Super class method not throwing checked
Exception");
}
}
class Sub extends Super
{
@Override
public void show() //throws [Link]
{
[Link]("Sub class method should not throw checked
Exception");
}
}
}
------------------------------------------------------------------------
d) If the super class method declare with throws keyword to throw a checked
exception, then at the time of method overriding sub class method may or may not
use throws keyword.
If the Overridden method is also using throws
keyword to throw checked exception then it must be either same exception class or
sub class, it should not be super class as well as we can't add more exceptions in
the overridden method.
package [Link].method_related_rule;
import [Link];
import [Link];
class Base
{
public void show() throws IOException
{
[Link]("Super class method ");
}
}
class Derived extends Base
{
//throws is applicable but must be equal or sub class
public void show() throws FileNotFoundException
{
[Link]("Sub class method ");
}
}
}
------------------------------------------------------------------------
package [Link].method_related_rule;
class Parent
{
public void m1() throws InterruptedException
{
[Link]("Parent class m1 method");
}
}
Note :- In the above program we are calling super class method which is throwing a
checked Exception but the caller method does not have any protection so compilation
error hence provide either try-catch or declare the method as throws.
----------------------------------------------------------------------
package [Link].method_related_rule;
import [Link];
class Parent1
{
public void m1() throws IOException
{
[Link]("Parent class m1 method");
}
}
}
}
Here we are calling the super class method by declaring the method as
throws.
------------------------------------------------------------------------
package [Link].method_related_rule;
import [Link];
class Parent2
{
public void m1() throws InterruptedException
{
[Link]("Parent class m1 method");
}
}
}
}
So the Conclusion is, if we are calling any method and that method is throwing any
checked exception then the caller method must have either try-catch or throws
(Protection is reqd).
------------------------------------------------------------------------
Input Output in java :
-----------------------
In order to work with input and output concept, java software people has provided a
separate package called [Link] package.
By using this [Link] package we can read the data from the user, creating file,
reading/writing the data from the file and so on.
How to take the input from the user using [Link] package :
------------------------------------------------------------
Scanner class is available from java 1.5 onwards but before 1.5, In order to read
the data we were using the following two classes which are available in [Link]
package.
1) DataInputStream (Deprecated)
2) BufferedReader
BufferedRedaer :
----------------
It provides more faster technique because it internally stores the data in a buffer
and it is always recomended to read the data from the buffer.
import [Link];
}
}
-----------------------------------------------------------------------
Program to read age from the keyboard :
package [Link].input_data;
import [Link];
import [Link];
import [Link];
}
-----------------------------------------------------------------------
Program to read the salary from the keyboard :
----------------------------------------------
package [Link].input_data;
import [Link];
import [Link];
import [Link];
}
catch(IOException e)
{
[Link]();
}
}
-----------------------------------------------------------------------
Program to read the character (gender) from the keyboard :
-----------------------------------------------------------
package [Link].input_data;
import [Link];
import [Link];
import [Link];
}
catch(IOException e)
{
[Link]();
}
}
-----------------------------------------------------------------------
Program to read the Employee Data :
-----------------------------------
package [Link].input_data;
import [Link];
import [Link];
Files are stored in the secondary storage devices so, we can use/read the data
stored in the file anytime according to our requirement.
In order to work with File system java software people has provided number of
predefined classes like File, FileInputStream, FileOutputStream and so on. All
these classes are available in [Link] package. We can read and write the data in
the form of Stream.
-----------------------------------------------------------------
Streams in java :
--------------------
A Stream is nothing but flow of data or flow of characters to both the end.
Stream is divided into two categories
Now byte oriented or binary Stream can be categorized as "input stream" and "output
stream". input streams are used to read or receive the data where as output streams
are used to write or send the data.
Again Character oriented Stream is divided into Reader and Writer. Reader is used
to read() the data from the file where as Writer is used to write the data to the
file.
InputStream is the super class for all kind of input operation where as
OutputStream is the super class for all kind of output Operation for byte oriented
stream.
Where as Reader is the super class for all kind reading operation where as Writer
is the super class for all kind of writing operation in character oriented Stream.
---------------------------------------------------------------------
11-12-2023
----------
File :-
-----
It is a predefined class in [Link] package through which we can create file and
directory. By using this class we can verify whether the file is existing or not.
The above statement will not create any file, It actually create the file object
and perform one of the following two task.
a) If [Link] does not exist, It will not create it
b) if [Link] does exist, the new file object will be refer to the referenec
variable f
Now if the file does not exist and to create the file we should use createNewFile()
method as shown below.
File class has also provided a method called exists() through which we can verify
the corresponding file is available or not. The return type of this method is
boolean.
Note :- The return type of both the methods i.e exists() and createNewFile() are
boolean.
File class has also a predefined method called getName(), to get the name of the
file.
---------------------------------------------------------------
//Create a file and verify file is existing or not?
import [Link].*;
public class File0
{
public static void main(String[] args)
{
try
{
File f = new File("C:\\new\\[Link]");
if([Link]())
{
[Link]("File is existing");
}
else
{
[Link]("File is not existing");
}
if ([Link]())
{
[Link]("File created: " +
[Link]());
}
else
{
[Link]("File is already existing....");
}
}
catch (IOException e)
{
[Link](e);
}
}
}
Whenever we want to write the data into the file using FileOutputStream class then
data must be available into the form of byte because It is byte-oriented class.
Note :- String class has provided a method called getBytes() through which we can
read the String data in byte format and the return type of this method is byte[].
(byte array)
Eg:-
String x = "India is Great";
byte b [] = [Link]();
Note :- try with resources are used to automatically close our resources.
-----------------------------------------------------------------------
//Creating and writing the data to the file
import [Link].*;
public class File1
{
public static void main(String args[]) throws IOException
{
var fout = new FileOutputStream("C:\\new\\[Link]");
try(fout)
{
String s = "Hyderabad is a nice city";
byte b[] = [Link]();
[Link](b);
[Link]("Success....");
}
catch(Exception e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
In binary Stream, whenever we want to write the data, the data must be available in
byte format, If we want to print the data
on the console(Monitor) the data must be converted into char.
---------------------------------------------------------------
FileInputStream :-
-----------------
It is a predefined class available in [Link] package. It is used to read the file
data/content. If we want to print the file data in console then data must be
available in char format.
try(fin)
{
int i = 0;
while(true)
{
i = [Link]();
if(i==-1)
break;
[Link]((char)i);
}
}
catch(Exception e)
{
[Link](e);
}
[Link]();
}
}
----------------------------------------------------------------------
//wap in java to read the data from one file and to write the data to another file.
import [Link].*;
class File3
{
public static void main(String s[]) throws IOException
{
//Outside of try (Java 9 enhancement in try with resource)
try(fin; fout)
{
while(true)
{
int i = [Link]();
if(i==-1) break;
[Link]((char)i);
[Link]((byte)i);
}
}
catch(IOException e)
{
[Link]();
}
}
}
---------------------------------------------------------------------
Limitation of FileInputStream class :
-------------------------------------
As we know FileInputStream class is used to read the content from the file but it
can read the data from a single file only that means if we want to read the data
from two files at the same time then we should use a separate Stream called
SequenceInputStream.
SequenceInputStream :
-------------------------
It is a predefined class available in [Link] package. This class is used to read
the data from two files at the same time.
//Proram to read the data from two files at the same time
import [Link].*;
public class File4
{
public static void main(String args[]) throws IOException
{
var f1 = new FileInputStream("[Link]");
var f2 = new FileInputStream("[Link]");
try(f1; f2; s)
{
int i;
while(true)
{
i = [Link]();
if(i==-1)
break;
[Link]((char)i);
}
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
//Reading the data from two files and writing the data to a single file
import [Link].*;
public class File5
{
public static void main(String x[]) throws IOException
{
var f1 = new FileInputStream("[Link]");
var f2 = new FileInputStream("[Link]");
int i;
try(f1; f2; fout; s)
{
while(true)
{
i = [Link]();
if(i==-1)
break;
[Link]((char)i);
[Link]((byte)i);
}
}
catch(IOException e)
{
[Link]();
}
[Link]("File Created Successfully");
}
}
---------------------------------------------------------------------
12-12-2023
----------
Limitation of FileOutputStream :-
-----------------------------------
It is used to write the data to a single file only. It is not suitable if we want
to write the data more then one file at a time. In order to write the data more
than one file we should use a seperate Stream called ByteArrayOutputStream.
ByteArrayOutputStream :-
---------------------------
It is a predefined class available in [Link] package. By using this class we can
write the data to multiple files. ByteArrayOutputStream class provides a method
called writeTo(), through which we can write the data to multiple files.
[Link](f1);
[Link](f2);
[Link](f3);
Whenever we use the class FileOutputStream the data will be available on the Stream
but not in the buffer so there may be chance of miss memory management, It is
always preferable that the data should be available in the buffer.
By using this BufferedOutputStrean now the data is in the buffer so the execution
will become more faster.
----------------------------------------------------------------------
//Program to put the data in the buffer for fast execution
import [Link].*;
class File8
{
public static void main(String args[]) throws IOException
{
var fout = new FileOutputStream("C:\\new\\[Link]");
try(fout ; bout)
{
String s = "Hyderabad is a nice city";
byte b[] = [Link]();
[Link](b);
[Link]("success...");
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
BufferedInputStream :-
-------------------------
It is a predefined class available in [Link] package. Whenever we use
FileInputStream to read the data/content from the file the data will be available
on the Stream but not in the buffer so there may be a chance of miss memory
management so we should take the data into the buffer by using BufferedInputStream
class so overall the execution will become faster.
//BufferedInputStream
import [Link].*;
public class File9
{
public static void main(String args[]) throws IOException
{
var fin = new FileInputStream("[Link]");
var bin = new BufferedInputStream(fin);
try(fin ; bin)
{
int i;
while((i = [Link]()) != -1)
{
[Link]((char)i);
}
}
catch(IOException e)
{
[Link]();
}
[Link]();
}
}
-----------------------------------------------------------------------
Writing and Reading the primitive data to the files :-
----------------------------------------------------------
It is possible to write the primitive data(byte,short,int, long, float, double,
char and boolean) to the file.
In order to write primitive data to the file we should use a predefined class
available in [Link] package called DataOutputStream.
If we want to read the primitive data from the file we can use a predefined class
available in [Link] package called DataInputStream, this class provides various
methods like readByte(), readShort(), readInt() and so on.
Note :- For writing String into a file we have writeBytes() and to read the String
data from the file we have readLine() method.
try(fout ; dout)
{
[Link](true);
[Link]('A');
[Link](Byte.MAX_VALUE);
[Link](Short.MAX_VALUE);
[Link](Integer.MAX_VALUE);
[Link](Long.MAX_VALUE);
[Link](Float.MAX_VALUE);
[Link]([Link]);//PI is a final static variable
[Link]("Hello India...");
[Link]();//For reuse purpose
}
catch(IOException e)
{
[Link]();
}
[Link](f +"\n"+c+"\n"+b+"\n"+s+"\n"+i+"\n"+l+"\n"+ft+"\
n"+d+"\n"+x);
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
* Serialization and De-Serialization :
--------------------------------------
---------------------------------------
It is a technique through which we can store the object data in a file. Storing the
object data into a file is called Serialization on the other hand Reading the
object data from a file is called De-serialization.
import [Link];
import [Link];
@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" +
employeeName + ", employeeSalary="
+ employeeSalary + "]";
}
[Link]
------------------------
package [Link].ser_der;
import [Link];
import [Link];
import [Link];
import [Link];
public class StoreEmployeeObject {
[Link]
---------------------------
package [Link].ser_der;
import [Link];
import [Link];
import [Link];
try(fin ; ois)
{
Employee emp = null;
while((emp = (Employee)[Link]())!=null)
{
[Link](emp);
}
}
catch(Exception e)
{
[Link]("End of File reached :"+e);
}
}
}
-----------------------------------------------------------------------
13-12-2023
----------
transient keyword :
------------------
If we don't want to perform serialization operation on a prticular field then we
should declare that field with transient keyword so we will get the default value
for that particular field.
class Product
{
private transient int productId; -> 0
private transient String productId; -> null
}
3 files :
---------
[Link]
----------
package [Link].ser_der_demo;
import [Link];
import [Link];
import [Link];
import [Link];
@Override
public String toString() {
return "Bank [bankIfscCode=" + bankIfscCode + ", bankName=" + bankName
+ ", branchLocation=" + branchLocation
+ "]";
}
[Link]
------------------------
package [Link].ser_der_demo;
import [Link];
import [Link];
import [Link];
import [Link];
}
catch([Link] e)
{
[Link]("Serialization is not possible :"+e);
}
catch(Exception e)
{
[Link]("general Exception");
}
[Link]
--------------------------
package [Link].ser_der_demo;
import [Link];
import [Link];
import [Link];
import [Link];
try(fin ; ois)
{
Bank obj;
}
catch(EOFException e)
{
[Link]("File ended :"+e);
}
catch(Exception e)
{
[Link]("general Exception");
}
}
try(fw; bw)
{
[Link]("It is in Asia");
[Link]("Success....");
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
//FileWriter
import [Link].*;
class File12
{
public static void main(String args[]) throws IOException
{
var fw = new FileWriter("C:\\new\\[Link]");
var bw = new BufferedWriter(fw);
try(fw;bw)
{
char c[ ] = {'H','E','L','L','O', ' ',' ','W','O','R','L','D'};
[Link](c);
[Link]("Success....");
}
catch(Exception e)
{
[Link]();
}
}
}
---------------------------------------------------------------------
FileReader class :
--------------------
It is a predefined class available in [Link] package, It is a character oriented
Stream. The main purpose of this class to read the data in the character format
directly from the file.
---------------------------------------------------------------
//FileReader
import [Link].*;
public class File13
{
public static void main(String args[]) throws IOException
{
var fr = new FileReader(args[0]); //Command Line Arg
var br = new BufferedReader(fr);
try(fr ; br)
{
while(true)
{
int i = [Link]();
if(i == -1)
break;
[Link]((char)i);
}
}
catch(IOException e)
{
[Link]();
}
}
}
----------------------------------------------------------------------
import [Link].*;
public class File14
{
public static void main(String[] args) throws IOException
{
var fr = new FileReader("C:\\new\\[Link]");
var fw = new FileWriter("C:\\new\\[Link]");
try(fr;fw)
{
int i;
while((i=[Link]())!= -1)
{
[Link](i);
}
}
catch(Exception e)
{
}
}
}
Note :- Here we are trying to write the image file using FileWriter class which is
not possible because image internally contains binary data and FileWriter is used
to write character Stream.
---------------------------------------------------------------------
PrintWriter :
--------------
It is a predefined class available in [Link] package. The main purpose of this
class to write the primitive data into text format.
Methods :
-----------
printf() :- It is a predefined method of PrintWriter class which takes two
parameter
a) Specification of the data so we can print the data according to
specification(Formatted String)
b) Parameter to print the actual data.
//PrintWriter
import [Link].*;
public class File15
{
public static void main(String[] args) throws IOException
{
PrintWriter writeData = new PrintWriter("C:\\new\\[Link]");
try(writeData)
{
int roll = 15;
//Writing primitive data into text format
[Link]("My roll number is : %d ", roll);
}
catch(Exception e)
{
[Link]();
}
}
}
--------------------------------------------------------------------
import [Link];
import [Link];
import [Link];
try(fileWriter;bufferedWriter)
{
String x = "Ravi";
Strings literals are created in a very special memory of HEAP called String
Constant Pool(SCP) and it is not eligible for garbage collection.
If the String is pre-existing (already available) in the String Constant pool then
JVM will not create any new String object, the same old existing String object
would be refer by new reference variable as shown in the diagram(14-DEC)
package [Link];
str1 = null;
[Link](); //Calling GC explicitly
From the above program it is clear that String objects are not eligible for GC.
-----------------------------------------------------------------------
15-12-2023
----------
Working with String class methods :
-----------------------------------
//Three Ways to create the String Object
public class Test
{
public static void main(String[] args)
{
String s1 = "Hello World"; //Literal
[Link](s1);
String y = "123@$5";
[Link](y);
String z = "67.90";
[Link](z);
String p = "A";
[Link](p);
}
}
-----------------------------------------------------------------------
Working with methods of String :-
--------------------------------------
String class has provided number of predefined methods to work with String which
are as follows :-
We need to pass the index position as a parameter to the method and based on the
index position it will extract the character. The return type of this method is
char.
ch1 = [Link](4);
[Link](ch1); //o
ch1 = [Link](9);
[Link](ch1); //e
}
}
----------------------------------------------------------------------
public String concat(String str) :-
--------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to concat or append two Strings. This can be also done by using
concatenation operator '+'.
This method takes String as a parameter and the return type of this method is
String.
String s4 = "Tata";
String s5 = "Nagar";
String s6 = s4+s5;
[Link]("String after concatenation :"+s6);
String s7 = "Naresh";
[Link]([Link](" Technology"));
}
}
----------------------------------------------------------------------
public boolean equals(Object obj) :-
--------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to verify whether two Strings are equal or not based on the content.
If both the Strings are equal it will return true otherwise it will return [Link]
is case sensitive method.
if([Link]("Ravi"))
{
[Link]("Welcome Ravi");
}
else
{
[Link]("Sorry! wrong username /Password");
}
}
}
-----------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
}
-----------------------------------------------------------------------
public boolean equalsIgnoreCase(String str) :-
--------------------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to Compare two Strings based on the content by ignoring the case.
This method takes String as a parameter and return type of this method is boolean.
It comapres two Strings by ignoring the case so it is not a case sensitive method.
Hence for this method 'A' and 'a' both are same.
equals(object obj) method of String class compares two strings based on the content
because it is an overriden method where as == operator compares two Strings based
on the reference i.e memory address.
//IQ
public class Test8
{
public static void main(String[] args)
{
String s1="India";
String s2="India";
String s3=new String("India");
[Link](s1==s2); //true
[Link](s1==s3); //false
[Link]([Link](s2)); //true
[Link]([Link](s3)); //true
}
}
Note :- String class has overridden equals(Object obj) method from Object class
because Object class equals(Object obj) method meant for memory address comparison
but this overridden String class equals(Object obj) meant for content comparison.
Note :-
-------
Length and Size always start from 1 where as index of the character String always
starts from 0.
By using this method we can replace a single character or a complete String from
the given String.
String y="Manager";
[Link]([Link]("Man","Dam"));
}
}
-----------------------------------------------------------------------
public int compareTo(String s) :-
-------------------------------------
It is a predefined method available in the String class. The main purpose of this
method two compare two String based on character by character, comparison of two
Strings chracter by chracter based on the UNICODE values are called Lexicographical
comparison or dictionary comparison or alphabetical comparison(String case).
if s1==s2 -> 0
[Link]([Link](s2)); //0
[Link]([Link](s3)); //1 [Sachin with Ratan]
[Link]([Link](s1)); //-1 [Ratan With Sachin]
String s4 = "Apple";
String s5 = "apple";
[Link]([Link](s5)); // -32 [65 to 97]
[Link]([Link](s4)); // 32 [97 to 65]
String s6 = "Ravi";
String s7 = "Raj";
[Link]([Link](s7)); //+-ve [j to v]
}
}
-----------------------------------------------------------------------
public String substring(int startIndex) :-
In this method the startIndex starts from 0 whereas endIndex starts from 1.
If end index will be less than start index then we will get an exception i.e
StringIndexOutOfBoundsException
substring(5,2);
If start index and end index both are equal, nothing will print
Nither start index nor end index will accept (-ve) value otherwise
StringIndexOutOfBoundsException.
[Link]([Link](3)); //ERABAD
[Link]([Link](3,3));
//[Link]
//[Link]([Link](6,3));
//[Link]
[Link]([Link](6, -3));
}
}
-----------------------------------------------------------------------
public boolean isEmpty() :-
------------------------------
It is a predefined method available in the String class. The main purpose of this
method to check whether a String is empty or not. This method returns true if the
String is empty that means length is 0, otherwise it will return false.
The return type of this method is boolean.
----------------------------------------------------------------
//public boolean isEmpty()
[Link]([Link]());
[Link]([Link]());
}
}
----------------------------------------------------------------------
public String intern() :
---------------------------
It is a predefined method available in the String class. The main purpose of this
method to return canonical representation for the string object that means String
interning ensures that all strings having the same contents use the same memory
location.
s1 = [Link]();
s2 = [Link]();
[Link](s1 == s2);
String s3 = "Hyd";
String s4 = new String("Hyd");
[Link](s3 == s4);
s4 = [Link]();
[Link](s3 == s4);
}
}
Note :- Java automatically interns the string literals but we can manually use the
intern() method on String object created by new keyword so all the Strings which
are having same content will get the same String and return the same memory
address(Canonical representation for the String ).
From the above program it is clear that, All that String having same content will
represent the same memory address so the hashcode value will be same.
public class EnumTest {
}
--------------------------------------------------------------------
//IQ
public class Test15
{
public static void main(String args[])
{
String x = "india";
[Link]("it's length is :"+[Link]); //error
With array variable we have length property where as with String ref variable we
have length() method.
----------------------------------------------------------------------
startsWith() is used to verify that the given String is Starting with prefix String
or not, if yes it will return true otherwise it will return false.
endsWith() is used to verify that the given String is ending with suffix String or
not, if yes it will return true otherwise it will return false.
It will serach the index position of the first occurrance of the specified String
as a parameter.
It will serach the index position of the last occurrance of the String.
It will not remove any white space in the between the String. The return type of
this method is String.
--------------------------------------------------------------
//program on trim()
public class Test21
{
public static void main(String args[])
{
String s1=" Tata ";
[Link](s1+"Nagar"); // Tata Nagar
}
}
----------------------------------------------------------------------
public String [] split (String delimiter) :
-----------------------------------------------
It is a predefined method available in the String class. The main purpose of this
method to split or break the given String based on specified delimiter(Criteria).
The return type of this method is String array because It returns the collection of
String tokens or multiple Strings.
import [Link].*;
public class STDemo
{
public static void main(String [] args)
{
String str ="Hyderabad is a lovely place";
StringTokenizer st = new StringTokenizer(str,"a");
while([Link]())
{
String token = [Link]();
[Link](token);
}
}
}
----------------------------------------------------------------------
public char[] toCharArray() :-
--------------------------------
It is a predefined method available in the String class. The main purpose of this
method to convert the given string into a sequence of characters. The returned
array length is equal to the length of the string.
This method does not take any parameter and return type is character array.
---------------------------------------------------------------
//public char[] toCharArray()
public class Test23
{
public static void main(String args[])
{
String str = "Java technology";
char ch [] = [Link]();
for(char c : ch)
{
[Link](c+" ");
}
[Link]();
}
}
---------------------------------------------------------------------
package [Link];
byte [] b = [Link]();
for(byte a : b)
{
[Link](a);
}
}
}
---------------------------------------------------------------------
StringBuffer :-
----------------
While working with String class the drawback is memory consumption is very high
because it is immutable so whenever we want to perform some operation on the
existing String Object, a new String object will be created.
StringBuilder :-
-----------------
It is a predefined class available in [Link] packge. It is also mutable class.
The only difference between StringBuffer and StringBuilder is, almost all the
methods of StringBuffer are synchronized where as all the methods of StringBuilder
are non-synchronized hence performance wise StringBuilder is more better than
StringBuffer.
StringBuffer and StringBuilder both are sharing the same API hence methods name,
paramater and return type are same.
---------------------------------------------------------------------
** What is difference between String, StringBuffer and StringBuilder.
}
}
----------------------------------------------------------------------
//public StringBuffer insert(int position, String str)
//Based on the index position we can insert the String
public class Test27
{
public static void main(String args[])
{
StringBuffer sb1=new StringBuffer("Hello");
[Link](1,"JSE");
[Link](sb1); //HJSEello
---------------------------------------------------------------------
//Program to demonstrate the performance of StringBuffer and StringBuilder classes.
package [Link];
startTime = [Link]();
endTime = [Link]();
[Link]("Total time taken by StringBuilder class is :"+
(endTime-startTime)+ " ms");
}
int count = 0;
char[] arr = [Link](); //{'r','a'....}
if (containsVowel)
{
[Link]("The string contains a vowel.");
}
else
{
[Link]("The string does not contain a vowel.");
}
}
}
----------------------------------------------------------------------
//How to sort a String data
import [Link];
public class Test6
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String :");
String str = [Link](); //mango
int count = 0;
import [Link].*;
public class Test8
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String :");
String str = [Link]();
if (containsDigits)
{
[Link]("The string contains digits.");
}
else
{
[Link]("The string does not contain digits.");
}
}
}
---------------------------------------------------------------------
//program to count capital and small letter from the given String
//public static boolean isUpperCase(char ch)
//public static boolean isLowerCase(char ch)
import [Link];
public class Test9
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link](); //RaVi
if ([Link](ch))
{
upperCase++;
}
else if ([Link](ch))
{
lowerCase++;
}
}
[Link]("Uppercase letters: " + upperCase);
[Link]("Lowercase letters: " + lowerCase);
}
}
----------------------------------------------------------------------
//Program to count the consonants and vowels in the given String
import [Link];
public class Test10
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
if (isPalindrome)
{
[Link](str + " is a palindrome.");
}
else
{
[Link](str + " is not a palindrome.");
}
}
}
---------------------------------------------------------------------
01-02-2024
-----------
Multithreading
--------------
Uniprocessing :-
----------------
In uniprocessing, only one process can occupy the memory So the
major drawbacks are
1) Memory is westage
2) Resources are westage
3) Cpu is idle
---------------------------------------------------------------------
Thread :
--------
A thread is the basic unit of CPU which can run concurrently with another thread at
the same time within the same process.
A thread can run with another thread at the same time so our task will be completed
as soon as possible.
Every time we create a thread in java, the thread will be executed in a different
Stack memory.
---------------------------------------------------------------------
In java whenever we define a main method then JVM internally creates a thread
called main thread.
It is a factory method.
--------------------------------------------------------------------
[Link]
----------------
package [Link];
The purpose of main thread to execute the entire main method so at the time of
execution of main method a user can create our own userdefined thread.
In order to create the userdefined Thread we can use one of the following two
ways :-
Note :- For every individual thread, JVM creates a separate runtime stack.
package [Link];
In the above program main thread and Thread-0 threads are created both threads are
executing their own Stack Memory as shown in the diagram
(01-FEB-24)
---------------------------------------------------------------------
public boolean isAlive() :
--------------------------
It is a predefined method of Thread class through which we can find out whether a
thread has started or not ?
package [Link];
[Link]();
[Link]("Thread started :"+[Link]());
[Link](); //[Link]
}
}
----------------------------------------------------------------------
//Exception while executing the thread
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 thread is executing with separate Stack.
----------------------------------------------------------------------
Loop program by using Multithreading :
--------------------------------------
package [Link];
int x =1;
do
{
[Link]("Hello");
x++;
}
while(x<=10);
}
}
---------------------------------------------------------------------
How to set and get the name of the Thread :
--------------------------------------------------
Whenever we create a Thread in java then by default JVM assigns the name of thread
is Thread-0, Thread-1, Thread-2 and so on.
If a user wants to assign some user defined name of the Thread, then Thread class
has provided a predefined method called setName(String name) to set the name of the
Thread.
On the other hand we want to get the name of the Thread then Thread class has
provided a predefined method called getName().
[Link]();
[Link]();
[Link]([Link]().getName()+" thread is
running.....");
}
}
Note :- In the above program we have not assigned userdefined name to Thread so by
default the name of the Thread woud be Thread-0 and Thread-1
----------------------------------------------------------------------
package [Link];
class Demo extends Thread
{
@Override
public void run()
{
[Link]([Link]().getName()+" thread is
running.....");
}
}
public class ThreadName1
{
public static void main(String[] args)
{
Thread t = [Link]();
[Link]("Parent");//changing the main thread name
[Link]("Child1");
[Link]("Child2");
[Link]();
[Link]();
[Link]([Link]().getName()+" thread is
running!!!!");
}
}
----------------------------------------------------------------------
[Link](long milisecond) :
-------------------------------
If we want to put a thread into temporarly waiting state then we should use sleep()
method.
The waiting time of the Thread depends upon the time specified by the user as
parameter to sleep() method.
}
public class SleepDemo
{
public static void main(String[] args)
{
[Link]("Main Thread started...");
Sleep s = new Sleep();
[Link]();
[Link]();
[Link](1000);
}
catch(Exception e)
{
[Link]("thread has interrupted");
}
[Link]("Child1");
[Link]("Child2");
[Link]();
[Link]();
}
}
----------------------------------------------------------------------
package [Link];
[Link](1000);
}
catch(Exception e)
{
[Link]("thread has interrupted");
}
[Link]("Child1");
[Link]("Child2");
[Link]();
[Link]();
}
}
----------------------------------------------------------------
Thread Life cycle :
-------------------
Thread life cycle in java :
-----------------------------
As we know a thread is well known for Independent execution and it contains a life
cycle which internally contains 5 states (Phases). During the life cycle of a
thread, It can pass from thses 5 states. At a time a thread can reside to only one
state of the given 5 states.
3) RUNNING state
5) EXIT/Dead state
New State :-
-------------
Whenever we create a thread instance(Thread Object) a thread comes to new state OR
born state. New state does not mean that the Thread has started yet only the object
or instance of Thread has been created.
Runnable state :-
-------------------
Whenever we call start() method on thread object, A thread moves to Runnable state
i.e Ready to run state. Here Thread schedular is responsible to select/pick a
particular Thread from Runnable state and sending that particular thread to Running
state for execution.
Running state :-
-----------------
If a thread is in Running state that means the thread is executing its own run()
method.
From Running state a thread can move to waiting state either by an order of thread
schedular or user has written some method(wait(), join() or sleep()) to put the
thread into temporarly waiting state.
From Running state the Thread may also move to Runnable state directly, if user has
written [Link]() method explicitly.
Waiting state :-
------------------
A thread is in waiting state means it is waiting for it's time period to complete.
Once the time period will be completed then it will re-enter inside the Runnable
state to complete its remaining task.
Dead or Exit :
----------------
Once a thread has successfully completed its run method then the thread will move
to dead state. Please remember once a thread is dead we can't restart a thread in
java.
IQ :- If we write [Link](1000) then exactly after 1 sec the Thread will re-
start?
Ans :- No, We can't say that the Thread will directly move from waiting state to
Running state.
The Thread will definetly wait for 1 sec in the waiting mode and then again it will
re-enter into Runnable state which is control by Thread Schedular so we can't say
that the Thread will re-start just after 1 sec.
-----------------------------------------------------------------------
package [Link];
Note :- From JDK 1.5 we have State enum which defines both the states i.e Runnable
and Running into single state i.e RUNNABLE.
----------------------------------------------------------------------
join() method of Thread class :
------------------------------------
The main purpose of join() method to put the one thread into waiting mode until the
other thread finish its execution.
Here the currently executing thread stops its execution and the thread goes into
the waiting state. The current thread remains in the wait state until the thread on
which the join() method is invoked has achieved its dead state.
It is an instance method so we can call this method with the help of Thread object
reference.
package [Link];
[Link]();
[Link]();
[Link]();
}
}
----------------------------------------------------------------------
package [Link];
}
[Link](); //Deadlock
Here in the above program the main thread is waiting for main thread
only so it is a deadloack state.
-----------------------------------------------------------------------
package [Link];
}
}
}
------------------------------------------------------------------
Anonymous class Approach :
---------------------------
Creating Anonymous inner class for Thread class with reference :
[Link]
----------------------------------
package [Link];
}
----------------------------------------------------------------------
Creating Anonymous innner Thread class without reference :
----------------------------------------------------------
package [Link];
}.start();
}
-----------------------------------------------------------------------
Anonymous inner class uisng Runnable approach :
-----------------------------------------------
package [Link];
}
----------------------------------------------------------------------
//Lambda Expression
package [Link];
}
----------------------------------------------------------------------
package [Link];
}
-----------------------------------------------------------------------
* In between extends Thread and implements Runnable, which one is better and why?
1) When we use extends Thread, all the methods and properties of Thread class is
available to sub class so it is heavy weight but this is not the case while
implementing Runnable interface.
2) As we know Java does not support multiple inheritance using classes so in the
extends Thread approach we can't extend another class but if we use implments
Runnable interface still we have chance to extend another class and we can also
implement one or more interfaces.
----------------------------------------------------------------
Thread class Constructor (Total 9 constructors):
-------------------------------------------------
The following are the commonly used constructor available in Thread class :
1) Thread()
2) Thread(String name)
3) Thread(Runnable target)
4) Thread(Runnable target, String name)
5) Thread(ThreadGroup threadGroup, Runnable target, String name)
----------------------------------------------------------------
06-02-2024
----------
Problem with multithreading :-
----------------------------------
Multithreading is very good to complete our task as soon as possible but in some
situation, It provides some wrong data or wrong result.
In Data Race or Race condition, all the threads try to access the resource at the
same time so the result will be corrupted.
---------------------------------------------------------------
package [Link].multithreading_limitation;
@Override
public void run()
{
String name = null;
}
else
{
name = [Link]().getName();
[Link]("Sorry !!"+name+" seats are not available");
}
[Link](); [Link]();
package [Link];
@Override
public void run()
{
for(int i=1; i<=10; i++)
{
[Link](str+ " : "+i);
try
{
[Link](100);
}
catch (Exception e)
{
[Link](e);
}
}
}
}
public class Theatre
{
public static void main(String [] args)
{
MyThread obj1 = new MyThread("sell the Ticket");
MyThread obj2 = new MyThread("Allocate the Seat");
[Link]();
[Link]();
}
}
---------------------------------------------------------------
Assignment :
------------
Two thread are trying to withdraw the amount from same account. Use multithreading
with Lambda to implement this logic.
----------------------------------------------------------------
Synchronization :
----------------
In order to solve the problem of multithreading java software people has introduced
synchronization concept.
It is a technique through which we can control multiple threads but accepting only
one thread at all the time.
Synchronization allows only one thread to enter inside the synchronized area for a
single object.
The thread who acquires the lock from the Object will enter inside the synchronized
area, it will complete its task without any disturbance because at a time there
will be only one thread is allowed inside the synchronized area(for single Object).
This is known as Thread-safety in java.
The thread which is inside the synchronized area, after completion of its task
while going back will release the lock so the other threads (which are waiting
outside for the lock) will get a chance to enter inside the synchronized area by
again taking the lock from the Object and submitting it to the synchronized
keyword.
Note :- Synchronization logic can be done by senior programmers in the real time
industry because due to poor synchronization there may be chance of getting
deadlock.
----------------------------------------------------------------
Program on Method level synchronization :
------------------------------------------
package [Link];
class Table
{
public synchronized void printTable(int num)
{
for(int i=1; i<=10; i++)
{
[Link](num+" X "+i+" = "+(num*i));
try
{
[Link](500);
}
catch(InterruptedException e)
{
[Link]();
}
}
[Link](".................");
}
}
public class MethodLevelSynchronization
{
public static void main(String[] args)
{
Table obj = new Table(); //lock is created
[Link](); [Link]();
}
class ThreadName
{
public void printThreadName()
{
//This area is accessible by all the threads (c1 c2)
String name = [Link]().getName();
[Link]("Thread inside the method is :"+name);
But there may be chance that with t1 Thread, t3 or t4 thread can enter inside the
synchronized area at the same time, simillarly it is also possible that with t2
thread, t3 or t4 can enter inside the synchronized area so the conclusion is
synchronization mechanism does not work with multiple Objects.(Diagram 07-FEB-24)
[Link]
package [Link];
class PrintTable
{
public synchronized void printTable(int n)
{
for(int i=1; i<=10; i++)
{
[Link](n+" X "+i+" = "+(n*i));
try
{
[Link](500);
}
catch(Exception e)
{
}
}
[Link](".......................");
}
}
Now with static synchronization lock will be available at class level but not
Object level.
To call the static synchronized method, object is not required so we can call the
static method with the help of class name.
Unlike objects we can't create multiple classes for the same application.
package [Link];
class MyTable
{
public static synchronized void printTable(int n) //static synchronization
{
for(int i=1; i<=10; i++)
{
try
{
[Link](100);
}
catch(InterruptedException e)
{
[Link]("Thread is Interrupted...");
}
[Link](n+" X "+i+" = "+(n*i));
}
[Link]("------------------------");
}
}
public class StaticSynchronization
{
public static void main(String[] args)
{
Thread t1 = new Thread()
{
@Override
public void run()
{
[Link](5);
}
};
}
};
Thread t3 = new Thread(r3);
[Link]();
[Link](); [Link]();
}
}
----------------------------------------------------------------
08-02-2024
----------
*Inter Thread Communication (ITC) :
----------------------------------
It is a mechanism to communicate two synchronized threads within the context to
achieve a particular task.
In ITC we put a thread into wait mode by using wait() method and other thread will
complete its corresponding task, after completion of the task it will call notify()
method so the waiting thread will get a notification to complete its remaining
task.
*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.
}
}
public class ITCProblem
{
public static void main(String[] args)
{
Test t = new Test();
Thread t1 = new Thread(t);
[Link]();
try
{
[Link](500);
}
catch (Exception e)
{
}
[Link]([Link]);
}
}
-----------------------------------------------------------------
//Communication between main thread and child thread using ITC
@Override
public void run()
{
//Child Thread is waiting here for the lock
synchronized(this)
{
for(int i=1; i<=100; i++)
{
x = x + i;
}
[Link]("Sending notification");
notify(); //will give notification to waiting thread
}
}
}
public class InterThreadComm
{
public static void main(String [] args)
{
SecondThread b = new SecondThread();
[Link]();
try
{
wait(); //waiting and releasing the lock
}
catch(Exception e){}
}
balance = balance - amount;
[Link]("withdraw completed..."+balance+" is remaining
balance");
}
[Link]();
}
}
-----------------------------------------------------------------
Thread Priority :
------------------
Thread Priority :
------------------
It is possible in java to assign priority to a Thread.
Thread class has provided two predefined methods setPriority(int newPriority) and
getPriority() to set and get the priority of the thread respectively.
In java we can set the priority of the Thread in number from 1- 10 only where 1 is
the minimum priority and 10 is the maximum priority.
The userdefined thread created as a part of main thread will acquire the same
priority of main Thread.
Thread class has also provided 3 final static variables which are as follows :-
Thread.MIN_PRIORITY :- 01
Thread.NORM_PRIORITY : 05
Thread.MAX_PRIORITY :- 10
Note :- We can't set the priority of the Thread beyond the limit(1-10) so if we set
the priority beyond the limit (1 to 10) then it will generate an exception
[Link].
-----------------------------------------------------------------
package [Link];
}
Any thread which is created as a part of main thread will get the
priority of main thread.
-----------------------------------------------------------------
package [Link];
Note :- If we change the priority of main thread then the thread crearted as a part
of main thread will get same priority of main thread
-----------------------------------------------------------------
package [Link];
int count = 0;
for(int i=1; i<=1000000; i++)
{
count++;
}
[Link](Thread.MIN_PRIORITY);//1
[Link](Thread.MAX_PRIORITY);//10
[Link]("Last");
[Link]("First");
[Link]();
[Link]();
}
}
-----------------------------------------------------------------
[Link]() :
----------------
It is a static method of Thread class .
The Thread schedular can ignore this notification message given by currently
executing Thread.
Here there is no guarantee that after using yield() method the running Thread will
move to Runnable state and from Runnable state the thread can move to Running
state.
If the thread which is in runnable state is having low priority then the same
running thread will continue its execution.
if([Link]("Child1"))
{
[Link](); //Give a chance to Child2 Thread
}
}
}
}
public class ThreadYieldMethod
{
public static void main(String[] args)
{
Test obj = new Test();
[Link](); [Link]();
}
}
-----------------------------------------------------------------
09-02-2024
----------
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.
}
catch (InterruptedException e)
{
[Link]("Thread is Interrupted :"+e);
}
[Link]("Child thread completed...");
}
}
public class InterruptThread1
{
public static void main(String[] args)
{
[Link]("Main thread is started");
Interrupt it = new Interrupt();
[Link]();
[Link]("Main thread is ended");
}
}
----------------------------------------------------------------
public class InterruptThread2
{
public static void main(String[] args)
{
Thread thread = new Thread(new MyRunnable());
[Link]();
try
{
[Link](2000); //main thread is waiting for 2 sec
}
catch (InterruptedException e)
{
[Link]();
}
[Link]();
}
}
Note :- Here main thread is in sleeping mode for 5 sec, after wake up main thread
is interrupting child thread so child thread will come out from infinite loop and
if any resource is attached with child thread that will be released because child
thread execution completed.
finally block is there to close the resource.
-----------------------------------------------------------------
Thread Group :-
--------------
There is a predefined class called ThreadGroup available in [Link] package.
[Link]();
[Link]();
[Link]();
[Link]();
This situation happens when multiple threads demands same resource without
releasing its own attached resource so as a result we get Deadlock situation and
our execution of the program will go to an infinite state as shown in the diagram.
(09-FEB-24)
The main purpose of of Daemon thread to provide services to the user thread.
JVM can't terminate the program till any of the non-daemon (user) thread is active,
once all the user thread will be completed than JVM will terminate all Daemon
threads, which are running in the background to support user threads.
The example of Daemon thread is Garbage Collection thread, which is running in the
background for memory management.
[Link](true);
[Link]();
[Link]();
Shallow Copy :
-----------------
In shallow copy, we create a new reference variable which will point to same old
existing object so if we make any changes through any of the reference variable
then original object content will be modified.
class Student
{
int id;
String name;
@Override
public String toString()
{
return "Id is :" + id + "\nName is :" + name ;
}
}
public class ShallowCopy
{
public static void main(String[] args)
{
Student s1 = new Student();
[Link] = 111;
[Link] = "Ravi";
[Link](s1);
[Link](s1);
[Link](s2);
[Link]([Link]());
[Link]([Link]());
}
In Shallow copy, one object will be created and it is refered by multiple referenec
variable so, hashcode will be same.
------------------------------------------------------------------
Deep Copy :
--------------
In deep copy, We create a copy of object in a different memory location. This is
called a Deep copy.
Here objects are created in two different memory locations so if we modify the
content of one object it will not reflect another object.
package [Link].clone_method;
class Employee
{
int id;
String name;
@Override
public String toString()
{
return "Employee [id=" + id + ", name=" + name + "]";
}
}
[Link] = 222;
[Link] = "shankar";
[Link](e1 +" : "+e2);
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].
clone() method of Object class follow deep copy concept so hashcode will be
different.
package [Link].clone_method;
@Override
protected Object clone() throws CloneNotSupportedException
{
return [Link]();
}
@Override
public String toString()
{
return "Customer [id=" + id + ", name=" + name + "]";
}
}
[Link](c1);
[Link](c2);
[Link]([Link]());
[Link]([Link]());
}
-----------------------------------------------------------------
protected void finalize() throws Throwable :
---------------------------------------------
It is a predefined method of Object class.
Garbage Collector automatically call this method just before an object is eligible
for garbage collection to perform clean-up activity.
Here clean-up activity means closing the resources associated with that object like
file connection, database connection, network connection and so on we can say
resource de-allocation.
package [Link].finalize_method;
@Override
public String toString()
{
return "Id is :"+id+"\nName is :"+name;
}
@Override
protected void finalize()
{
[Link]("JVM call this finalize method...");
}
s1 = null;
[Link](); //Explicitly calling Garbage Collector
[Link](3000);
[Link](s1);
}
}
-----------------------------------------------------------------
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.
f) public int size() :- It is used to find out the size of the Collection.
g) public void clear() :- It is used to clear all the elements at once from the
Collection.
----------------------------------------------------------------------
20-12-2023
----------
List interface :
----------------
a) It is the sub interface of Collection interface
4) public void add(int index, Object o) :- Insert the element based on the index
position.
6) public Object get(int index) :- To retrieve the 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.
----------------------------------------------------------------------
Behaviour of List interface Specific classes :
-----------------------------------------------
1) It will store the elements based on the index.
2) It can accept hetrogeneous types of elements.
3) It will accept duplicate elements.
4) With generics concept we can eliminate the compilation warning and
still we can take hetrogeneous types of elements. (<>)
5) IT IS DYNAMICALLY GROWABLE.
6) It can accept null values.
7) It stores everything in the form of Object.
----------------------------------------------------------------------
21-12-2023
-----------
How many ways we can fetch Collection Object from Collections Framework.
There are 7 ways to fetch the Collection Object from Collections Framework :
We can use Enumeration interface to fetch or retrieve the Objects one by one from
the Collection because it is 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.
It is used to retrieve the Collection object in both the direction i.e in forward
direction as well as in backward direction.
2) public Object next() :- It will return the next position collection object.
Note :- Apart from these 4 methods we have add(), set() and remove() method in
ListIterartor interface.
-----------------------------------------------------------------------
By using forEach() method :
--------------------------------
From java 1.8 onwards every collection class provides a method forEach() method,
this method takes Consumer functional interface as a parameter
as shown in the follwing program.
The following program explains how forEach(Consumer cons) method works internally.
package [Link].fetching_collection_object;
import [Link];
import [Link];
}
------------------------------------------------------------------------
//7 ways to fetch the Collection Object Data
package [Link].fetching_collection_object;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
for(String fruit : v)
{
[Link](fruit);
}
while([Link]())
{
[Link]([Link]());
}
ListIterator<String> lt = [Link]();
while([Link]())
{
[Link]([Link]());
}
[Link]("IN BACKWARD DIRECTION");
while([Link]())
{
[Link]([Link]());
}
[Link]([Link]::println);
}
}
-----------------------------------------------------------------------
ArrayList :
-----------
public class ArrayList<E> extends AbstractList<E> implements List<E>,
Serializable, Clonable, RandomAccess
*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 :
----------------------------
We have 3 types of Constructor in ArrayList
package [Link];
import [Link].*;
public class ArrayListDemo
{
public static void main(String... a)
{
ArrayList<String> arl = new ArrayList<>();//Generic type
[Link]("Apple");
[Link]("Orange");
[Link]("Grapes");
[Link]("Mango");
[Link]("Guava");
[Link]("Mango");
[Link](arl);
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
+ "]";
}
}
[Link](".............");
//By using forEach method
[Link](p-> [Link](p));
}
----------------------------------------------------------------------
package [Link];
[Link](al2);
[Link](".................................");
[Link](al4);
package [Link];
import [Link].*;
public class ArrayListDemo3
{
public static void main(String args[])
{
//Arrays class is having static method asList()
List<String> list =
[Link]("Ravi","Rahul","Sweta","Ananya","Bina");
[Link](list);
[Link](list);
ListIterator<String> itr=[Link]();
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
public String toString() {
return "Prod [productId=" + productId + ", productName=" + productName
+ ", productPrice=" + productPrice + "]";
}
}
//Serialization
var fos = new FileOutputStream("C:\\new\\[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//De-Serialization
var fin = new FileInputStream("C:\\new\\[Link]");
ObjectInputStream ois = new ObjectInputStream(fin);
}
catch(Exception e)
{
[Link]();
}
}
}
-----------------------------------------------------------------------
//Serialization and De-serialization on ArrayList Object
package [Link];
import [Link].*;
import [Link].*;
public class ArrayListDemo4
{
public static void main(String [] args) throws IOException
{
ArrayList<String> al=new ArrayList<>();
[Link]("Nagpur");
[Link]("Vijaywada");
[Link]("Hyderabad");
[Link]("Jamshedpur");
//Serialization
FileOutputStream fos=new FileOutputStream("C:\\new\\[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);
//De-serialization
FileInputStream fis=new FileInputStream("C:\\new\\[Link]");
}
}
-----------------------------------------------------------------------
public void ensureCapacity(int minimumCapacity) :-
-----------------------------------------------
It is a predefined method of ArrayList class, by using this method we can resize
the capacity of ArrayList Object.
Here by specifying the parameter it ensures that it can hold at least the number of
elements specified by the minimum capacity argument.
-------------------------------------------------------------------
package [Link];
import [Link];
[Link]("Hyderabad");
[Link]("Mumbai");
[Link]("Delhi");
[Link]("Kolkata");
[Link]("ArrayList: " + city);
}
}
-----------------------------------------------------------------------
package [Link];
//Program on ArrayList that contains null values as well as we can pass the element
based on the index position
import [Link].*;
public class ArrayListDemo6
{
public static void main(String[] args)
{
ArrayList<Object> al = new ArrayList<>(); //Generic type
[Link](12);
[Link]("Ravi");
[Link](12);
[Link](3,"Hyderabad"); //add(int index, Object o)method of List
interface
[Link](1,"Naresh");
[Link](null);
[Link](11);
[Link](al); //12 Naresh Ravi 12 Hyderabad
}
}
----------------------------------------------------------------------
Limitation of ArrayList :
-------------------------
The time complexcity of ArrayList to insert and delete an element from the middle
would be O(n) because 'n' number of elements will be re-located so it is not a good
choice to perform insertion and deletion operation in the middle of the List.
On the other hand ArryList is good choice for retrieval operation because by using
index we can retrieve the element in O(1).
It is ordered by index position like ArrayList except the elements (nodes) are
doubly linked to one another. This linkage provide us new method for adding and
removing the elements from the middle of LinkedList.
*The important thing is, LikedList may iterate more slowely than ArrayList but
LinkedList is a good choice when we want to insert or delete the elements
frequently in the list.
From jdk 1.5 onwards LinkedList class has been enhanced to support basic queue
operation by implementing Deque<E> interface.
ArrayList is using Array data structure but LinkedList class is using LinkedList
data structure.
Constructor:
-------------
It has 2 constructors
3) Object getFirst()
4) Object getLast()
5) Object removeFirst()
6) Object removeLast()
import [Link];
import [Link];
public class LinkedListDemo
{
public static void main(String args[])
{
List<Object> list=new LinkedList<>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link](null);
[Link](42);
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);
}
}
---------------------------------------------------------------------
package [Link].linked_list;
[Link]([Link]());
[Link]([Link]());
[Link]();
[Link]();
[Link](list);
}
}
---------------------------------------------------------------------
ListIterator interface Methods:
-------------------------------
package [Link].linked_list;
//ListIterator methods
import [Link].*;
public class LinkedListDemo3
{
public static void main(String[] args)
{
LinkedList<String> city = new LinkedList<> ();
[Link]("Kolkata");
[Link]("Bangalore");
[Link]("Hyderabad");
[Link]("Pune");
[Link](city);
ListIterator<String> lt = [Link]();
while([Link]())
{
String cityName = [Link]();
if([Link]("Kolkata"))
{
[Link]();
}
else if([Link]("Hyderabad"))
{
[Link]("Ameerpet");
}
else if([Link]("Pune"))
{
[Link]("Mumbai");
}
}
[Link]([Link]::println);
}
}
----------------------------------------------------------------------
package [Link].linked_list;
while (true)
{
[Link]("Linked List: " + linkedList);
[Link]("1. Insert Element");
[Link]("2. Delete Element");
[Link]("3. Display Element");
[Link]("4. Exit");
[Link]("Enter your choice: ");
if(remove)
{
[Link]("Element "+elementToDelete+ " is
deleted Successfully" );
}
else
{
[Link](elementToDelete+" not available is
the LinkedList");
}
}
break;
case 3:
[Link]("Elements in the linked list.");
[Link](linkedList);
break;
case 4:
[Link]("Exiting the program.");
[Link]();
[Link](0);
default:
[Link]("Invalid choice. Please try again.");
}
}
}
}
---------------------------------------------------------------------
Merging of two Collection data :
----------------------------------
package [Link].linked_list;
import [Link];
import [Link];
import [Link];
import [Link];
}
----------------------------------------------------------------------
Vector :
--------
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 also stores the elements on index [Link] is dynamically growable with initial
capacity 10. The next capacity will be 20 i.e double of the first capacity.
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.
----------------------------------------------------------------------
Capacity method of Vector :
---------------------------
//Vector Program on capacity
package [Link];
import [Link].*;
public class VectorDemo1
{
public static void main(String[] args)
{
Vector<Integer> v = new Vector<>(100, 10); //initial capacity is 100
[Link]("Initial capacity is :"+[Link]());
for(Integer i : v)
{
[Link](i+"\t");
if(i%5==0)
[Link]();
}
}
}
----------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class Employee
{
private Integer employeeId;
private String employeeName;
private Double employeeSalry;
@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" +
employeeName + ", employeeSalry="
+ employeeSalry + "]";
}
}
//Stream API
[Link]().filter(e1 -> [Link]()<40000.00).forEach(d->
[Link](d));
}
}
----------------------------------------------------------------------
27-12-2023
----------
package [Link];
//Array To Collection
import [Link].*;
public class VectorDemo3
{
public static void main(String args[])
{
Vector<Integer> v = new Vector<>();
int x[]={22,20,10,40,15,58};
package [Link];
import [Link];
import [Link];
startTime = [Link]();
Vector<Integer> v = new Vector<>();
for(int i=0; i<=1000000; i++)
{
[Link](i);
}
endTime = [Link]();
[Link]("The total time taken by Vector to complete the task
:"+(endTime - startTime)+" ms");
}
}
----------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
for(Integer i : v)
{
if(i%2==0)
{
[Link](i);
}
}
[Link]([Link]::println);
[Link]("............");
//Java 8 Stream API
List<Integer> collect = (List<Integer>) [Link]().filter(n-> n
%2==0).sorted().collect([Link]());
[Link]([Link]::println);
}
}
----------------------------------------------------------------------
Stack :
Stack :
------
public class Stack<E> extends Vector<E>
ListIterator interface will not work with Set because it does not maintain any
order while retrieving the element.
---------------------------------------------------------------------
Hierarchy of Set interafce :
----------------------------
Available in the Diagram (27-DEC-23)
----------------------------------------------------------------------
28-12-2023
-----------
Methods of Set interface :
--------------------------
a) int size(): Returns the number of elements in this set.
c) boolean contains(Object o): Returns true if this set contains the specified
element.
d)boolean add(E e): Adds the specified element to this set if it is not already
present (optional operation).
e) boolean remove(Object o): Removes the specified element from this set if it is
present (optional operation).
g) boolean addAll(Collection<? extends E> c): Adds all of the elements in the
specified collection to this set if they're not already present
h) boolean retainAll(Collection<?> c): Retains only the elements in this set that
are contained in the specified collection . In other words, removes from this set
all of its elements that are not contained in the specified collection.
i) boolean removeAll(Collection<?> c): Removes from this set all of its elements
that are contained in the specified collection .
j) void clear(): Removes all of the elements from this set (optional operation).
The set will be empty after this call returns.
---------------------------------------------------------------------
HashSet (UNSORTED, UNORDERED , NO DUPLICATES)
---------------------------------------------
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Clonabale,
Serializable
It is a predefined class available in [Link] package under Set interface.
*It 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.
[Link](str-> [Link](str));
}
}
----------------------------------------------------------------------
//HashSet does not maintain any order to fetch the elements
import [Link].*;
public class HashSetDemo1
{
public static void main(String[] argv)
{
HashSet<String> hs=new HashSet<>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
[Link]("Palavi");
[Link]("Sweta");
[Link](null);
[Link](null);
[Link](str -> [Link](str));
}
}
----------------------------------------------------------------------
import [Link].*;
public class HashSetDemo2
{
public static void main(String[] args)
{
boolean[] ba = new boolean[6];
Note :- From this program it is clear that add(Object o) method return type is
boolean.
----------------------------------------------------------------------
import [Link];
import [Link];
switch (choice)
{
case 1:
[Link]("Enter the element to add: ");
String elementToAdd = [Link]();
if ([Link](elementToAdd))
{
[Link]("Element added successfully.");
}
else
{
[Link]("Element already exists in the
HashSet.");
}
break;
case 2:
[Link]("Enter the element to delete: ");
String elementToDelete = [Link]();
if ([Link](elementToDelete))
{
[Link]("Element deleted successfully.");
}
else
{
[Link]("Element not found in the HashSet.");
}
break;
case 3:
[Link]("Elements in the HashSet:");
for (String element : hashSet) {
[Link](element);
}
break;
case 4:
[Link]("Exiting the program.");
[Link]();
[Link](0);
default:
[Link]("Invalid choice. Please try again.");
}
[Link]();
}
}
}
-----------------------------------------------------------------------
LinkedHashSet
-------------
public class LinkedHashSet extends HashSet implements Set, Clonable, Serializable
It is 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 elments 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);
}
}
----------------------------------------------------------------------
29-12-2023
----------
SortedSet interface :
---------------------
1) It is the sub interface of Set interface
2) If we don't want duplicate elements and want to store the elements based on some
sorting order i.e default natural sorting order then we should go with SortedSet(I)
Program on Comparable :
-----------------------
2 Files :
---------
[Link]
--------------
package [Link];
[Link]
-----------------------
package [Link];
import [Link];
import [Link];
[Link](listOfEmployee);
[Link](emp-> [Link](emp));
}
---------------------------------------------------------------------
Limitation of Comparable interface :
-----------------------------------------
1) We need to modify the original source code (BLC class), If the source code is
not available then it is not possible to perform sorting operation.
2) We can provide only one sorting logic if we want to provide mutiple sorting
logic then it is not possible.
public Product() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Product [productId=" + productId + ", productName=" +
productName + ", productPrice=" + productPrice
+ "]";
}
}
[Link]
-----------------------
package [Link];
import [Link];
import [Link];
import [Link];
[Link]("............................");
[Link](listOfProduct, cmpName);
[Link]("SORTING BASED ON THE PRODUCT NAME");
[Link](prod -> [Link](prod));
--------------------------------------------------------------------
Program that describes, how to provide descending order for Integer object using
Comparator interface.
package [Link];
import [Link];
import [Link];
import [Link];
[Link](al, cmp);
[Link]([Link]::println);
}
}
---------------------------------------------------------------------
30-12-2023
-----------
TreeSet :
----------
TreeSet :
----------
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet, Clonable,
Serializable
TreeSet, TreeMap and PriorityQueue are the three sorted collection in the entire
Collection Framework so these classes never accepting hetrogeneous kind of the
data.
It will sort the elements in natural sorting order i.e ascending order in case of
number, and alphabetical order or Dictionary order in the case of String. In order
to sort the elements It uses Comparator interface.
It does not accept hetrogeneous type of data if we try to insert it will throw a
runtime exception i.e [Link]
[Link](t1);
@Override
public String toString()
{
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentFees=" + studentFees
+ "]";
}
}
[Link]
------------------------------
package [Link].treeset_comp;
import [Link];
import [Link];
[Link]([Link]::println);
[Link](".....................");
TreeSet<Student> ts2 = new TreeSet<>(new IdDescendingComparator());
[Link](new Student(111, "Zuber", 12000.90));
[Link](new Student(444, "Satish", 15000.90));
[Link](new Student(222, "Rahul", 13000.90));
[Link](new Student(333, "Aniket",14000.90));
[Link]([Link]::println);
[Link](".....................");
TreeSet<Student> ts3 = new TreeSet<>(new NameAscendingComparator());
[Link](new Student(111, "Zuber", 12000.90));
[Link](new Student(444, "Satish", 15000.90));
[Link](new Student(222, "Rahul", 13000.90));
[Link](new Student(333, "Aniket",14000.90));
[Link]([Link]::println);
[Link](".....................");
TreeSet<Student> ts4 = new TreeSet<>(new NameDescendingComparator());
[Link](new Student(111, "Zuber", 12000.90));
[Link](new Student(444, "Satish", 15000.90));
[Link](new Student(222, "Rahul", 13000.90));
[Link](new Student(333, "Aniket",14000.90));
[Link]([Link]::println);
}
}
------------------------------------------------------------------------
HW :- Re-write the same program using Lambda
-----------------------------------------------------------------------
Methods of SortedSet interface :
--------------------------------
public E first() :- Will fetch first element
public 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(I) :
-----------------
With the help of SortedSet interface method we can find out the range of values but
we can't navigate among those elements.
Now to frequently navigate among those range of elements, Java software people
introduced new interface called NavigableSet from 1.6V
-------------------------------------------------------------
import [Link].*;
}
}
-----------------------------------------------------------------------
01-01-2024
-----------
Map interface :
---------------
As we know Collection interface is used to hold single Or individual object but Map
interface will hold group of objects in the form key and value pair.
Map interface works with key and value pair introduced from 1.2V.
Each key and value pair is creating one Entry.(Entry is nothing but the combination
of key and value pair)
interface Map
{
interface Entry
{
}
}
8) Object get(Object key) :- It will return corresponding value of key, if the key
is not present then it will return null.
11) putIfAbsent(Object key, Object value) :- It will insert an entry if and only if
key is not present , if the key is already available then it will not insert the
Entry to the Map Collection
Set<[Link]> entrySet() :- It will return key and value pair in the form of
Entry.
b) Whenever we add any new key to verify whether key is unique or duplicate,
HashMap internally uses hashCode(), == operator and equals method.
c) While adding the key object in the HashMap, first of all it will invoke the
hashCode() method to retrieve the corresponding key hashcode value.
Example :- [Link](key,value);
then internally [Link]();
d) If the newly added key and existing key hashCode value both are same (Hash
collision), then only == operator is used for comparing those keys by using
reference or memory address, if both keys references are same then existing key
value will be replaced with new key value.
If the reference of both keys are different then equals(Object obj) method
is invoked to compare those keys by using state(data).
If the equals(Object obj) method returns true (content wise both keys are
same), this new key is duplicate then existing key value will be replaced.
If equals(Object obj) method returns false, this new key is unique, new entry
(key-value) will be inserted.
Note :- equals(Object obj) method is invoked only when two keys are having
same hashcode as well as their references are different.
e) Actually by calling hashcode method we are not comparing the objects, we are
just storing the objects in a group so the currently adding key object will be
compared with its HASHCODE GROUP objects, but not with all the keys which are
available in the Map.
f) The main purpose of storing objects into the corresponding group to decrease the
number of comparison so the efficiency of the program will increase.
h) Now, for storing same hashcode object into a single group, hash table data
structure internally uses one more data structure called Bucket.
i) The Hash table data structure internally uses Node class array object.
*If equals() method invoked on two objects and it returns true then hashcode of
both the objects must be same.
-----------------------------------------------------------------
package [Link].abstract_ex;
import [Link];
import [Link];
Integer i1 = 128;
Integer i2 = 128;
[Link]([Link](i2));
[Link](i1==i2);
}
----------------------------------------------------------------------
HashMap [Unsorted, Unordered, No Duplicate keys]
--------------------------------------------------
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,
Serializable, Clonable
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.
----------------------------------------------------------------------
import [Link].*;
class Employee
{
int eid;
String ename;
@Override
public boolean equals(Object obj) //obj = e2
{
if(obj instanceof Employee)
{
Employee e2 = (Employee) obj; //downcasting
[Link](map); //{}
[Link]([Link](null)); //6390
[Link]([Link]("Virat")); //null becoz key is not a
}
}
-----------------------------------------------------------------------
//Program to search a particular key and value in the Map collection
import [Link].*;
public class HashMapDemo1
{
public static void main(String args[])
{
HashMap<Integer,String> hm = new HashMap<>();
[Link](1, "JSE");
[Link](2, "JEE");
[Link](3, "JME");
[Link](4,"JavaFX");
[Link](5,null);
[Link](6,null);
for([Link] m : [Link]())
{
[Link]([Link]()+" : "+[Link]());
}
}
}
-----------------------------------------------------------------------
//Program on remove(Object key) method
import [Link].*;
public class HashMapDemo3
{
public static void main(String args[])
{
HashMap<Integer,String> map = new HashMap<>(10,8.5f);
[Link](1, "Java");
[Link](2, "is");
[Link](3, "best");
[Link](3); //will remove the complete Entry
String val=(String)[Link](3);
[Link]("Value for key 3 is: " + val);
[Link]((k,v)->[Link](k +" : "+v));
}
}
----------------------------------------------------------------------
//To merge two Map Collection (putAll)
import [Link].*;
public class HashMapDemo4
{
public static void main(String args[])
{
HashMap<Integer,String> newmap1 = new HashMap<>();
[Link](1, "SCJP");
[Link](2, "is");
[Link](3, "best");
[Link](4, "Exam");
[Link](newmap1);
[Link]((k,v)->[Link](k+" : "+v));
}
}
----------------------------------------------------------------------
Collection views method :
-------------------------
import [Link].*;
public class HashMapDemo5
{
public static void main(String[] argv)
{
Map<String,String> map = new HashMap<>(9, 0.85f);
[Link]("key", "value");
[Link]("key2", "value2");
[Link]("key3", "value3");
[Link]("key7","value7");
}
}
-----------------------------------------------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]([Link]("ravi@[Link]"));
[Link]([Link]("ravi_@#"));
}
----------------------------------------------------------------------
//getOrDefault() method
import [Link].*;
public class HashMapDemo6
{
public static void main(String[] args)
{
Map<String, String> map = new HashMap<>();
[Link]("A", "1");
[Link]("B", "2");
[Link]("C", "3");
//if the key is not present, it will return default value .It is used to
avoid null
String value = [Link]("D","Key is not available");
[Link](value);
[Link](map);
}
}
----------------------------------------------------------------------
//interconversion of two HashMap
import [Link].*;
public class HashMapDemo7
{
public static void main(String args[])
{
HashMap<Integer, String> hm1 = new HashMap<>();
[Link](1, "Ravi");
[Link](2, "Rahul");
[Link](3, "Rajen");
If We want to fetch the elements in the same order as they were inserted then we
should go with LinkedHashMap.
It accepts one null key and multiple null values.
It is not synchronized.
[Link]((k,v)->[Link](k+" : "+v));
}
}
-----------------------------------------------------------------------
Hashtable :
------------
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Clonable,
Serializable
Like Vector, Hashtable is also form the birth of java so called legacy class.
//[Link](5,null);
[Link](map);
[Link](".......................");
for([Link] m : [Link]())
{
[Link]([Link]()+" = "+[Link]());
}
}
}
-----------------------------------------------------------------------
import [Link].*;
public class HashtableDemo1
{
public static void main(String args[])
{
Hashtable<Integer,String> map=new Hashtable<>();
[Link](1,"Priyanka");
[Link](2,"Ruby");
[Link](3,"Vibha");
[Link](4,"Kanchan");
[Link](5,"Bina");
[Link](24,"Pooja");
[Link](26,"Ankita");
[Link](1,"Sneha");
[Link]("Updated Map: "+map);
}
}
-----------------------------------------------------------------------
WeakHashMap :
-------------
public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>
While working with HashMap, keys of HashMap are of strong reference type. This
means the entry of map will not be deleted by the garbage collector even though
the key is set to be null and still it is not eligible for Garbage Collector.
On the other hand while working with WeakHashMap, keys of WeakHashMap are of weak
reference type. This means the entry of a map is deleted by the garbage collector
if the key value is set to be null because it is of weak type.
So, HashMap dominates over Garbage Collector where as Garbage Collector dominates
over WeakHashMap.
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.
t = null;
[Link](5000);
[Link](map); //{}
}
}
class Test
{
@Override
public String toString()
{
return "Test Nit";
}
@Override
public void finalize() //called automaticaly if an object is eligible 4 GC
{
[Link]("finalize method is called");
}
}
If the corresponding object will be deleted from one end then the entry will be
deleted from map collection but map collection must be of WeakHashMap type.
-----------------------------------------------------------------------
04-01-2024
-----------
IdentityHashMap :
-----------------
public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,
Clonable, Serializable.
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.
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)
-----------------------------------------------------------------------
import [Link].*;
public class IdentityHashMapDemo
{
public static void main(String[] args)
{
HashMap<String,Integer> hm = new HashMap<>();
[Link]("Ravi",23);
[Link](new String("Ravi"), 24);
[Link]("Ravi",23);
[Link](new String("Ravi"), 27); //compares based on == operator
}
-----------------------------------------------------------------------
SortedMap(I)
---------------
It is a predefined interface available in [Link] package under Map interface.
We should use SortedMap interface when we want to insert the key element based on
some sorting order i.e the default natural sorting order.
------------------------------------------------------------------
TreeMap :
----------
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V> ,
Clonable, Serializable
It is a sorted map that means it will sort the elements by natural sorting order
based on the key using Comparator interface.
It will accept homogeneous keys (comparable keys as an Object) only because it will
sort the entry of TreeMap based on the key.
[Link](t);
}
}
----------------------------------------------------------------------
import [Link].*;
public class TreeMapDemo1
{
public static void main(String args[])
{
TreeMap map = new TreeMap();
[Link]("one","1");
[Link]("two",null);
[Link]("three","3");
[Link]("four",4);
displayMap(map);
}
static void displayMap(TreeMap map)
{
Collection c = [Link](); //Set<[Link]>
Iterator i = [Link]();
[Link](x -> [Link](x));
}
}
----------------------------------------------------------------------
//firstKey() lastKey() headMap() tailMap() subMap()
import [Link].*;
public class TreeMapDemo2
{
public static void main(String[] argv)
{
Map map = new TreeMap();
[Link]("key2", "value2");
[Link]("key3", "value3");
[Link]("key1", "value1");
[Link](map);
2 Files :
---------
[Link]
-------------
package [Link].tree_map_customized;
[Link]
-----------------------
package [Link].tree_map_customized;
import [Link];
}
----------------------------------------------------------------------
package [Link].treemap_comparator;
import [Link];
----------------------------------------------------------------------
Methods of SortedMap interface :
--------------------------------
1) firstKey() //first key
}
}
----------------------------------------------------------------------
NavigableMap method (H.W)
---------------------------
Properties :
------------
Properties class:
-----------------
Properties class is used to maintain the data in the key-value form. It takes both
key and value as a string. Properties class is a subclass of Hashtable and avilable
in [Link] package.
It provides the methods to store properties in a properties file and to get the
properties from the properties file. [Link]() returns the all system
properties.
[Link]
-------------
driver = [Link]
user = system
password = tiger
import [Link].*;
import [Link].*;
public class PropertiesExample1
{
public static void main(String[] args)throws Exception
{
FileReader reader=new FileReader("[Link]");
Properties class provides a method called getProperty() where we will pass the key
of properties file and it will return the corresponding key value from that key.
Here after making changes in the property file we need not to re-compile the source
code as shown in the above program.
----------------------------------------------------------------------
import [Link].*;
import [Link].*;
public class PropertiesExample2
{
public static void main(String[] args)throws Exception
{
Properties p=[Link]();
Set set=[Link]();
Iterator itr=[Link]();
while([Link]())
{
[Link] entry=([Link])[Link]();
[Link]([Link]()+" = "+[Link]());
}
} }
By using getProperties() static method of System class we can get the complete
properties of the System
----------------------------------------------------------------------*Generics :
-----------
Why generic came into picture :
------------------------------------
As we know our compiler is known for Strict type checking because java is a
statically typed checked language.
The basic problem with collection is It can hold any kind of Object.
By looking the above code it is clear that Collection stores everything in the form
of Object so here even after adding String type only we need type casting as shown
below.
import [Link].*;
class Test1
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
[Link](12);
[Link](15);
[Link](18);
[Link](22);
[Link](24);
Even after type casting there is no guarantee that the things which are coming from
ArrayList Object is Integer only because we can add anything in the Collection as a
result [Link] as shown in the program below.
----------------------------------------------------------------------
import [Link].*;
class Test2
{
public static void main(String[] args)
{
ArrayList t = new ArrayList(); //raw type
[Link]("alpha");
[Link]("beta");
for (int i = 0; i < [Link](); i++)
{
String str =(String) [Link](i);
[Link](str);
}
[Link](1234);
[Link](1256);
for (int i = 0; i < [Link](); ++i)
{
String obj= (String)[Link](i); //we can't perform type casting
here
[Link](obj);
}
}
}
----------------------------------------------------------------------
To avoid all the above said problem Generics came into picture from JDK 1.5 onwards
-> It deals with type safe Object so there is a gurantee of both the end i.e
putting inside and getting out.
Example:-
ArrayList<String > al = new ArrayList<>();
Now here we have a gurantee that only String can be inserted as well as only
String will come out from the Collection so we can perform String related
operation.
Advantages :-
---------------
a) Type safe Object (No compilation warning)
24-01-2024
----------
import [Link].*;
public class Test3
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<>(); //Generic type
[Link]("Ravi");
[Link]("Ajay");
[Link]("Vijay");
import [Link].*;
public class Test4
{
public static void main(String [] args)
{
Dog d1 = new Dog();
Dog d2 = [Link]().get(2);
[Link](d2);
}
}
class Dog
{
public List<Dog> getDogList()
{
ArrayList<Dog> d = new ArrayList<>();
[Link](new Dog());
[Link](new Dog());
[Link](new Dog());
return d;
}
}
Note :- In the above program the compiler will stop us from returning anything
which is not compaitable List<Dog> and there is a gurantee that only "type safe
list of Dog object" will be returned so we need not to provide type casting as
shown below
Dog d2 = (Dog) [Link]().get(0); //before generic.
-----------------------------------------------------------------
//Mixing generic with non-generic
import [Link].*;
class Car
{
}
public class Test5
{
public static void main(String [] args)
{
ArrayList<Car> a = new ArrayList<>();
[Link](new Car());
[Link](new Car());
[Link](new Car());
[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);
[Link](4);
[Link](6);
UnknownClass u = new UnknownClass();
int total = [Link](myList);
[Link](total);
}
}
class UnknownClass
{
public int addValues(List list)
{
[Link](5); //adding object to raw type
Iterator it = [Link]();
int total = 0;
while ([Link]())
{
int i = ((Integer)[Link]());
total += i;
}
return total;
}
}
Here Compiler will generate warning message because the unsafe object is inserting
the value 5 to safe object.
------------------------------------------------------------------------
*Type Erasure
------------
In the above program the compiler will generate warning message because the
unsafe List Object is inserting the Integer object 5 so the type safe Integer
object is getting value 5 from unsafe type so there is a problem to the caller
method.
By writing ArrayList<Integer> actually JVM does not have any idea that our
ArrayList was suppose to hold only Integers.
All the type safe information does not exist at runtime. All our generic code is
Strictly for compiler. There is a process done by java compiler called "Type
erasure" in which the java compiler converts generic version to non-generic type.
At the compilation time it is fine but at runtime for JVM the code becomes
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.
Eg:-
[Link]("Success");
}
}
------------------------------------------------------------------------
Wild card character(?) :
------------------------
<?> -: Many possibilities
<Animal>-: Only <Animal> can assign, but not Dog or sub type of animal
<? super Dog> -: Dog, Animal, Object can assign (Compiler has
surity)
<? extends Animal> -: Below of Animal(Child of Animal) means, sub classes of Animal
(But the compiler does not have surity because you can have many sub classes of
Animal in the future, so chances of wrong collections)
------------------------------------------------------------------------
//program on wild-card chracter
import [Link].*;
class Parent
{
}
class Child extends Parent
{
}
public class Test12
{
public static void main(String [] args)
{
List<?> lp = new ArrayList<Parent>();
[Link]("Wild card....");
}
}
------------------------------------------------------------------------
import [Link].*;
public class Test13
{
public static void main(String[] args)
{
List<? extends Number> list1 = new ArrayList<Double>();
class Alpha
{
}
class Beta extends Alpha
{
}
-------------------------------------------------------------------------
import [Link].*;
public class Test14
{
public static void main(String[] args)
{
try
{
List<Object> x = new ArrayList<>(); //Array of Object[java 9]
[Link](10);
[Link]("Ravi");
[Link](true);
[Link](34.89);
[Link](x);
}
catch (Exception e)
{
[Link](e);
}
}
}
------------------------------------------------------------------------
class MyClass<T>
{
T obj;
public MyClass(T obj) //Student obj
{
[Link]=obj;
}
T getObj()
{
return obj;
}
}
public class Test15
{
public static void main(String[] args)
{
Integer i=12;
MyClass<Integer> mi = new MyClass<Integer>(i);
[Link]("Integer object stored :"+[Link]());
Float f=12.34f;
MyClass<Float> mf = new MyClass<Float>(f);
[Link]("Float object stored :"+[Link]());
Double d=99.34;
MyClass<Double> md = new MyClass<Double>(d);
[Link]("Double object stored :"+[Link]());
class Student
{
@Override
public String toString()
{
return "Student toString";
}
}
-----------------------------------------------------------------------
25-01-2024
----------
//E stands for Element type
class Fruit
{
}
class Apple extends Fruit //Fruit is the super, Apple is sub class
{
}
}
}
class Mango extends Fruit
{
}
----------------------------------------------------------------------
Queue interface :-
-------------------
1) It is sub interface of Collection(I)
3) It is an ordered collection.
5) From jdk 1.5 onwards LinkedList class implments Queue interface to handle the
basic queue operations.
PriorityQueue :
----------------
public class PriorityQueue extends AbstractQueue implements Serializable
It inserts the elements based on the priority HEAP (Using Binary tree).
The elements of the priority queue are ordered according to their natural ordering,
or by a Comparator provided at queue construction time, depending on which
constructor is used.
A priority queue does not permit null elements as well as It uses Binary tree to
insert the elements.
Constructor :
--------------
1) PriorityQueue pq1 = new PriorityQueue();
Methods :-
----------
add() / offer() :- Used to add an element in the Queue
poll() :- It is used to fetch the elements from top of the queue, after fetching it
will delete the element.
peek() :- It is also used to fetch the elements from top of the queue, Unlike poll
it will only fetch but not delete the element.
import [Link];
public class PriorityQueueDemo3
{
public static void main(String[] argv)
{
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](11);
[Link](2);
[Link](4);
[Link](6);
[Link](pq);
}
}
-----------------------------------------------------------------------
import [Link];
public class PriorityQueueDemo1
{
public static void main(String[] argv)
{
PriorityQueue<String> pq = new PriorityQueue<>();
[Link]("9");
[Link]("8");
[Link]("7");
[Link]([Link]() + " "); //7 3 5 6
[Link]("6"); // 6 7 8 9
[Link]("5");
[Link]("3");
[Link]("1");
[Link]([Link]() + " ");
if ([Link]("2"))
[Link]([Link]() + " ");
[Link]([Link]() + " " + [Link]());
[Link](pq);
}
}
-----------------------------------------------------------------------import
[Link];
public class PriorityQueueDemo2
{
public static void main(String[] argv)
{
PriorityQueue<String> pq = new PriorityQueue<>();
[Link]("2");
[Link]("4");
[Link]("6"); // 6 9
[Link]([Link]() + " "); //2 2 3 4 4
[Link]("1");
[Link]("9");
[Link]("3");
[Link]("1");
[Link]([Link]() + " ");
if ([Link]("2"))
[Link]([Link]() + " ");
[Link]([Link]() + " " + [Link]()+" "+[Link]());
}
}
-----------------------------------------------------------------------
import [Link];
[Link](pq);
}
}
It contains classes for processing sequence of elements over Collection object and
array.
Package Information :
---------------------
[Link] -> Base package
[Link] -> Functional interfaces
[Link] -> Multithreaded support
[Link] -> Processing of Collection Object
Map interface This makes forEach() operation available to all map classes.
Stream interface This makes forEach() operations available to all types of
stream.
----------------------------------------------------------------------
Creation of Streams to process the data :
-----------------------------------------------
We can create Stream from collection or array with the help of stream() and of()
methods:
Eg:-
List<String> items = new ArrayList<String>();
[Link]("Apple");
[Link]("Orange");
[Link]("Mango");
Stream<String> stream = [Link]();
-----------------------------------------------------------------------
import [Link].*; //Base package
import [Link].*; //Sub package
public class StreamDemo1
{
public static void main(String[] args)
{
List<String> items = new ArrayList<String>();
[Link]("Apple");
[Link]("Orange");
[Link]("Mango");
[Link]("...............................");
//Anonymous Array Object
Stream<Integer> strm = [Link]( new Integer[]{15,29,45,8,16} );
[Link](p -> [Link](p));
}
}
-----------------------------------------------------------------------
26-01-2024
-----------
Operation in Stream API :
-------------------------
In Java, the Stream API provides a wide range of operations that can be performed
on a stream of elements.
These operations can be categorized into two main types: intermediate operations
and terminal operations.
Intermediate Operations:
------------------------
filter(Predicate<T> predicate): Returns a new stream which contains filtered
elements based on the boolean expression using Predicate.
map(Function<T, R> mapper): Transforms elements in the stream using the provided
mapping function.
distinct(): Returns a stream with distinct elements (based on their equals method).
//Without Stream
List<Integer> listEven = new ArrayList<Integer>();
for(Integer i : list)
{
if(i%2==0)
[Link](i);
}
[Link](listEven);
[Link](".........................................");
List<String> sortedName =
[Link]().sorted().collect([Link]());
[Link](new Customer(1,"Aryan",25000f));
[Link](new Customer(2,"Ravi",30000f));
[Link](new Customer(3,"Sailesh",28000f));
[Link](new Customer(4,"Rohan",28000f));
[Link](new Customer(5,"Raj",90000f));
// filtering data
[Link]()
.filter(Customer -> [Link] < 27000)
.forEach(Customer ->
[Link]([Link]));
}
}
Assignment : Create and Store the Product object and by using java 8 Stream API
filter the Product data based on the price where price of the Product must be
greater than 50K.
-------------------------------------------------------------------------
public Stream map(Function<T,R> mapper) :
-------------------------------------------------
It is a predefined method of Stream interface.
It performs intermediate operation and consumes single element from input Stream
and produces single element to output Stream.
Here mapper function is functional interface which takes one input and provides one
output.
[Link](cubeOfNumbers);
}
}
-------------------------------------------------------------------------
//Program on map(Function<T,R> mapped)
package [Link];
import [Link].*;
import [Link].*;
public class StreamDemo8
{
public static void main(String args[])
{
List<Player> listOfPlayers = createMyPlayerList();
class Player
{
private String name;
private int age;
The map() method produces one output value for each input value in the stream. So
if there are n elements in the stream, map() operation will produce a stream of n
output elements.
//flatMap()
//map + Flattening [Converting Collections of collection into single collection]
//flatMap()
//map + Flattening [Converting Collections of collection into single collection]
package [Link];
import [Link].*;
import [Link].*;
public class StreamDemo9
{
public static void main(String[] args)
{
List<String> list1 = [Link]("A","B","C");
List<String> list2 = [Link]("D","E","F");
List<String> list3 = [Link]("G","H","I");
[Link](listOfAllStrings);
}
}
-------------------------------------------------------------------------
27-01-2024
-----------
import [Link];
import [Link];
import [Link];
List<List<Integer>> numbers =
[Link](primeNumbers,evenNumbers,oddNumbers);
[Link](collect);
}
}
-------------------------------------------------------------------------
//Fetching first character using flatMap()
package [Link].flat_map;
import [Link];
import [Link];
import [Link];
import [Link];
}
-------------------------------------------------------------------------
package [Link].flat_map;
import [Link];
import [Link];
class Product
{
private Integer productId;
private List<String> listOfProducts;
);
[Link]().flatMap(p ->
[Link]().stream()).forEach([Link]::println);
}
}
-------------------------------------------------------------------------
Difference between map() and flatMap()
--------------------------------------
map() method transforms each element into another single element.
flatMap() transforms each element into a stream of elements and then flattens those
streams into a single stream.
We should use map() when you want a one-to-one transformation, and we should use
flatMap() when dealing with nested structures or when you need to produce multiple
output elements for each input element.
------------------------------------------------------------------
public Stream distinct() :
--------------------------
It is a predefined method of Stream interface.
If we want to return stream from another stream by removing all the duplicates then
we should use distinct() method.
------------------------------------------------------------------------
package [Link];
import [Link];
public class StreamDemo10
{
public static void main(String[] args)
{
Stream<String> s = [Link]("Virat", "Rohit", "Dhoni", "Virat",
"Rohit","Aswin","Bumrah");
[Link]().sorted().forEach([Link]::println);
}
------------------------------------------------------------------------
public Stream<T> limit(long maxSize) :
----------------------------------------
It is a predefined method of Stream interface to work with sequence of elements.
The limit() method is used to limit the number of elements in a stream by providing
maximum size.
Elements which are not in the range or beyond the range of specified limit will be
ignored.
package [Link];
import [Link];
public class StreamDemo11
{
public static void main(String[] args)
{
Stream<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
[Link]([Link]::println);
}
}
-------------------------------------------------------------------------
public Stream<T> skip(long n) :
-------------------------------
It is a predefined method of Stream interface which is used to skip the elements
from begning of the Stream.
It returns a new stream that contains the remaining elements after skipping the
specified number of elements which is passed as a parameter.
package [Link];
import [Link];
public class StreamDemo12
{
public static void main(String[] args)
{
Stream<String> s = [Link]("Virat", "Rohit", "Dhoni", "Zaheer",
"Raina");
[Link](2).limit(3).forEach([Link]::println);
}
}
-------------------------------------------------------------------------
public Stream<T> peek(Consumer<? super T> action) :
--------------------------------------------
It is a predefined method of Stream interface which is used to perform a side-
effect operation on each element in the stream while the stream remains unchanged.
The peek() method takes a Consumer as an argument, and this function is applied to
each element in the stream. The method returns a new stream with the same elements
as the original stream.
package [Link];
import [Link];
import [Link];
import [Link];
}
-------------------------------------------------------------------------
public Stream<T> takeWhile(Predicate<T> predicate) :
-----------------------------------------------------
It is a predefined method of Stream interface introduced from java 9 which is used
to perform a side-effect operation on each element in the stream while the stream
remains unchanged.
*It is used to create a new stream that includes elements from the original stream
only as long as they satisfy a given predicate.
package [Link];
import [Link];
[Link]([Link]::println);
}
}
package [Link];
import [Link];
[Link]([Link]::println);
}
}
-------------------------------------------------------------------------
Optional<T> class in Java :
------------------------
It is a predefined final and immutable class available in [Link] package from
java 1.8v.
3) public T get() :
--------------------
It will get/fetch the value from the container, if the value is not available then
it will throw NoSuchElementException.
[Link]
-------------------
//Program to verify whether the container has value or not
package [Link].optional_class_demo;
import [Link];
}
---------------------------------------------------------------------------
29-01-2024
------------
//Writing different style of getter with Optional<T> class as a return
type
package [Link].optional_class_demo;
import [Link];
class Employee
{
private Integer empId;
private String empName;
public Employee() {}
}
}
---------------------------------------------------------------------------
//Program to verify value is available or not
package [Link].optional_class_demo;
import [Link];
import [Link];
import [Link];
[Link]([Link]("Ameerpet"));
[Link]([Link]("S.R Nager"));
[Link]([Link]("Begumpet"));
[Link]([Link]("Koti"));
[Link]([Link]());
package [Link].optional_class_demo;
import [Link];
public class OptionalDemo4
{
public static void main(String[] args)
{
Optional<String> initialOptional = [Link]("India");
[Link]([Link]());
Optional<String> modifiedOptional = modifyOptional(initialOptional);
[Link]([Link]());
if ([Link]())
{
return [Link]("Modified: " + [Link]());
}
else
{
return [Link]();
}
}
}
---------------------------------------------------------------------------
Record class :
--------------
public abstract class Record extends Object.
As we know only objects are moving in the network from one place to another place
so we need to write BLC class with nessacery requirements to make BLC class as a
Data carrier class.
Records are immutable data carrier so, now with the help of record we can send our
immutable data from one application to another application.
It is mainly used to concise our code as well as remove the boiler plate code.
In order to validate the outer world data, we can write our own constructor which
is known as compact constructor.
We can define static and non static method as well as static variable inside the
record. We cannot define instance variable inside the record.
[Link]
-------------------
package [Link];
import [Link];
@Override
public String toString() {
return "CustomerClass [id=" + id + ", name=" + name + ", bill=" + bill
+ "]";
}
@Override
public int hashCode() {
return [Link](bill, id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
CustomerClass other = (CustomerClass) obj;
return [Link](bill) ==
[Link]([Link]) && id == [Link]
&& [Link](name, [Link]);
}
}
--------------------------------------------------------------------------
[Link]
--------------------
package [Link];
if(id < 0)
{
throw new IllegalArgumentException("Id is invalid");
}
else
{
}
}
}
---------------------------------------------------------------------------
package [Link];
[Link](".................");