Batch_37_Notes
Batch_37_Notes
com
22nd August 2024
While Working with '+' operator, if any of the operand is String type then '+'
operator will behave as String concatenation operator.
}
}
----------------------------------------------------------------------
Command Line Argument :
-----------------------
If we pass an argument to the main method then it is called command line Argument.
By using command line argument, We can pass some value at runtime i.e. at the time
of execution of the program.
The advantage is, Single time compilation and number of time execution with
different values.
}
}
javac Command.java
java Command Virat Rohit Scott
}
}
javac FullName.java
java FullName "Virat Kohli"
javac CommandDemo.java
javac AcceptInteger.java
java AcceptInteger 100 -> It will print 100
java AcceptInteger 12.90 -> It will print 12.90
java AcceptInteger A -> It will print A
Note : All Command Line Arguments are treated as String Object, even if they
represent another data type like number.
------------------------------------------------------------------------
29-08-2024
-----------
Program to add two numbers by using Command Line Argument :
----------------------------------------------------------
public class CommandAdd
{
public static void main(String[] x)
{
System.out.println(x[0] + x[1]);
}
}
javac CommandAdd.java
java CommandAdd 100 200
It will print 100200 [Here '+' operator will work as String concatenation operator]
-------------------------------------------------------------------------
How to convert a String value into integer :
---------------------------------------------
There is a predefined class called Integer, available in java.lang package. It
contains a predefined static method parseInt(String x), by using this method we can
convert a String into integer value.
Example :
---------
public class Integer
{
public static int parseInt(String x)
{
//Will accept String and convert into integer
}
}
------------------------------------------------------------------------
//Adding two numbers by converting then into integer
}
}
=========================================================================
WAP that describes how exactly Integer.parseInt() is working internally ?
-------------------------------------------------------------------------
public class Calculate
{
public static int doSum(int x, int y)
{
return x+y;
}
By using Eclipse IDE, We can develop, compile and execute our java program in a
single window.
The main purpose of eclipse IDE is reduce the development time, once development
time will be reduced then automatically the cost of the project will be reduced.
------------------------------------------------------------------------
What is a package?
------------------
A package is folder in windows. In java to create a package we are using package
keyword, It must be first statement of the program.
Example :
---------
package basic;
Here one folder will be created called basic (package name ) and Hello.class file
will be automatically placed in the basic folder.
Types of Packages :
---------------------------
1) Predefined OR Built-in package : The packages which are created by java software
people for arranging the programs are called predefined package.
2) Userdefined Package OR Custom package : The packages which are created by user
for arranging the user-defined programs are called user-defined package.
Example :
basic;
com.ravi.basic;
com.tcs.online_shopping;
------------------------------------------------------------------------
How to execute command line argument program by using Eclipse IDE :
-------------------------------------------------------------------
package basic;
Right click on the program -> Run As -> Run configuration -> Check your main class
name -> select argument tab -> pass the appropriate value -> Run
------------------------------------------------------------------------
Write a program to find out the area of Rectangle where length and breadth of the
Rectangle must be taken from user from command line argument.
package basic;
Example :
---------
ThisIsExampleOfClass
System
String
Integer
DataInputStream
ArrayIndexOutOfBoundsException
Object
BufferedReader
Example :
thisIsExampleOfMethod
parseInt()
readLine()
read()
print()
println()
toUpperCase()
toLowerCase()
Example :
----------
rollNumber
customerName
customerBill
studentName
playerName
Example :
Integer.MIN_VALUE [MIN_VALUE is final and static variable]
Integer.MAX_VALUE [MAX_VALUE is final and static variable]
com.nit.basic
com.tcs.introduction
com.wipro.shopping
-------------------------------------------------------------------------
Tokens in java :
----------------
Token is the smallest unit of the program which is identified by the compiler.
1) Keyword
2) Identifier
3) Literal
4) Punctuators (Seperators)
5) Operator
Keyword
--------
A keyword is a predefined word whose meaning is already defined by the compiler.
In java all the keywords must be in lowercase only.
A keyword we can't use as a name of the variable, name of the class or name of the
method.
true, false and null look like keywords but actually they are literals.
Ex:-
class Fan
{
int coil ;
void switchOn()
{
}
}
Here Fan(Name of the class), coil (Name of the variable) and switchOn(Name of the
Method) are identifiers.
-----------------------------------------------------------------------------------
-
Rules for defining an identifier :
------------------------------------
1) Can consist of uppercase(A-Z), lowercase(a-z), digits(0-9), $ sign, and
underscore (_)
2) Begins with letter, $, and _
3) It is case sensitive
4) Cannot be a keyword
5) No limitation of length
-------------------------------------------------------------------------
Literal :
---------
The constant values which we are assigning to a variable is called literal.
1) Integral Literal
2) Floating Point Literal
3) Character Literal
4) Boolean Literal
5) String Literal
a) Decimal Literal
b) Octal Literal
c) Hexadecimal Literal
d) Binary Literal (Available from JDK 1.7)
Decimal Literal :
-----------------
By default our numeric literals are decimal literal. Here base is 10 so, It accepts
10 digits i.e. from 0-9.
Example :
int x = 20;
int y = 123;
int z = 234;
Octal Literal :
---------------
If any Integer literal starts with 0 (Zero) then it will become octal literal. Here
base is 8 so it will accept 8 digits i.e 0 to 7.
Example :
Hexadecimal Literal :
---------------------
If a numeric literal starts with 0X (Zero capital X) OR 0x (zero small x) then it
will become Hexadecimal literal. Here base is 16 so it will accept 16 digits i.e 0
to 9 and A - F.
Example :
Binary Literal :
---------------
If a numeric literal starts with 0B (Zero capital B) or 0b (Zero small b) then it
will become Binary literal. Binary literal is available from JDK 1.7v.
Here base is 2 so it will accept 2 digits i.e 0 and 1.
Note : As a developer we can represent a numeric literal into octal, hexadecimal
and binary but to get the output(result), JVM will convert into decimal format
only.
-------------------------------------------------------------------------
//Octal Literal
public class Test1
{
public static void main(String [] args)
{
int x = 015;
System.out.println(x);
}
}
------------------------------------------------------------------------
//Hexadecimal Literal
public class Test2
{
public static void main(String [] args)
{
int x = 0Xadd;
System.out.println(x);
}
}
------------------------------------------------------------------------
//Binary Literal
public class Test3
{
public static void main(String [] args)
{
int x = 0B101;
System.out.println(x);
}
}
-------------------------------------------------------------------
By default every integral literal is of type int only. byte and short are below
than int so we can assign integral literal(Which is by default int type) to byte
and short but the values must be within the range. [for Byte -128 to 127 and for
short -32768 to 32767]
Actually whenever we are assigning integral literal to byte and short data type
then compiler internally converts into corresponding type.
Note : User is responsible to provide Explicit type casting (In case user is trying
to assign bigger to smaller type) but here there is chance of loss of data.
-------------------------------------------------------------------------
public class Test7
{
public static void main(String[] args)
{
byte x = (byte) 127L;
System.out.println("x value = "+x);
long l = 29L;
System.out.println("l value = "+l);
}
}
-----------------------------------------------------------------------
Is java pure Object Oriented Language ?
---------------------------------------
No, Java is not a pure object oriented langauge because it is accepting primary
data type, Actually any language which accepts primary data type is not a pure
object oriented language.
Only Objects are moving in the network but not the primary data type so java has
introduced Wrapper class concept to convert the primary data types into
corresponding wrapper object.
Note : Apart from these 8 data types, Everything is an object in java so, if we
remove all these 8 data types then java will become pure OOP language.
-------------------------------------------------------------------------
//Wrapper claases
public class Test8
{
public static void main(String[] args)
{
Integer x = 24;
Integer y = 24;
Integer z = x + y;
System.out.println("The sum is :"+z);
Boolean b = true;
System.out.println(b);
Double d = 90.90;
System.out.println(d);
Character c = 'A';
System.out.println(c);
}
}
------------------------------------------------------------------------
How to find out the minimum, maximum value as well as size of different data
types :
The Warpper classes like Byte, Short, Integer and Long has provided predefined
static and final variables to represent minimum value, maximum value as well as
size of the respective data type.
Example :
If we want to get the minimum value, maximum value as well as size of byte data
type then Byte class (Wrapper class) has provided the following final and static
variables
Byte.MIN_VALUE : -128
Byte.MAX_VALUE : 127
-------------------------------------------------------------------------
//Program to find out the range and size of Integeral Data type
public class Test9
{
public static void main(String[] args)
{
System.out.println("\n Byte range:");
System.out.println(" min: " + Byte.MIN_VALUE);
System.out.println(" max: " + Byte.MAX_VALUE);
System.out.println(" size :"+Byte.SIZE);
}
}
------------------------------------------------------------------------
Providing _ (underscore) in integeral Literal :
------------------------------------------------
In Order to enhance the readability of large numeric literals, Java software people
has provided _ (underscore) from JDK 1.7v. While writing the big numbers to
separate the numbers we can use _
We can't start or end an integral literal with _ we will get compilation error.
}
------------------------------------------------------------------------
Converting from Decimal to another number System :
---------------------------------------------------
If we want to convert decimal to another numeber system then Integer class has
provided the following methods toBinaryString(), toOctalString(), toHexString() to
convert from decimal to binary, octal and hexadecimal repectively.
//decimal to Octal
System.out.println(Integer.toOctalString(15)); //17
//decimal to Hexadecimal
System.out.println(Integer.toHexString(2781)); //add
}
}
------------------------------------------------------------------------
02-09-2024
-----------
floating point literal :
------------------------
*If a numeric literal contains decimal or fraction then it is called Floating point
Literal.
Example : 78.90, 89.45, 12.90
*But if we try to assign double literal directly to the float type then we will
get compilation error.
*We can represent double type into float type by using the following 3 ways
*Even though, every floating point literal is of type double only, compiler has
provided the following two flavors to represent the double value explicitly, just
to enhance the redability of the code.
double d1 = 12D;
double d2 = 56d;
* An integral literal (byte, short, int and long) we can assign to floating point
literal but a floating point literal we can't assign to
integral literal directly.
-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
float f = 2.0; //error
System.out.println(f);
}
}
------------------------------------------------------------------------
public class Test1
{
public static void main(String[] args)
{
float b = 15.29F;
float c = 15.25f;
float d = (float) 15.30;
}
}
-------------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
double d = 15.15;
double e = 15d;
double f = 15.15D;
double y = 0167;
System.out.println(x+","+y+","+z);
}
}
-------------------------------------------------------------------------
class Test4
{
public static void main(String[] args)
{
double x = 0X29;
System.out.println(x+","+y);
}
}
-------------------------------------------------------------------------
public class Test5
{
public static void main(String[] args)
{
double d1 = 15e-3;
System.out.println("d1 value is :"+d1);
double d2 = 15e3;
System.out.println("d2 value is :"+d2);
}
}
-------------------------------------------------------------------------
public class Test6
{
public static void main(String[] args)
{
double a = 0791;
double b = 0791.0;
double c = 0777;
double d = 0Xdead;
double e = 0Xdead.0;
}
}
------------------------------------------------------------------------
public class Test7
{
public static void main(String[] args)
{
double a = 1.5e3;
float b = 1.5e3; //error
float c = 1.5e3F;
double d = 10;
int e = 10.0; //error
long f = 10D; //error
int g = 10F; //error
long l = 12.78F; //error
}
}
-------------------------------------------------------------------------
//Range and size of floating point literal
public class Test8
{
public static void main(String[] args)
{
System.out.println("\n Float range:");
System.out.println(" min: " + Float.MIN_VALUE);
System.out.println(" max: " + Float.MAX_VALUE);
System.out.println(" size :"+Float.SIZE);
We have only one data type i.e. char data type which accepts 16 bits of memory.
b) In older languages like C and C++, which support ASCII value and range of value
is 0 - 255 that means we can assign 0 - 255 to represent
ASCII value of that particular character.
But in java we can assign 0 - 65535 to represent different characters from
different languages because Java support UNICODE chracter System.
Example :
char ch1 = 65535; //Valid
char ch2 = 65536; //Invalid
c) In order to get the UNICODE value of the character, we can assign char literal
to integral literal.
Example :
int x = 'A';
Example :
char ch = '\n';
'\uXXXX'
}
}
-----------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
int ch = 'A';
System.out.println("ch value is :"+ch);
}
}
-----------------------------------------------------------------------
//The UNICODE value for ? character is 63
public class Test3
{
public static void main(String[] args)
{
char ch1 = 63;
System.out.println("ch1 value is :"+ch1);
Note : We will get the output ? and ? because in the current system the
language translator is not available so itis unable to translate the given
UNICODE value into corresponding character.
-----------------------------------------------------------------------
//Addition of two character in the form of Integer
public class Test5
{
public static void main(String txt[ ])
{
int x = 'A';
int y = 'B';
System.out.println(x+y); //131
System.out.println('A' + 'A'); //130
}
}
------------------------------------------------------------------------
//Range of UNICODE Value (65535) OR '\uffff'
class Test6
{
public static void main(String[] args)
{
char ch1 = 65535;
System.out.println("ch value is :"+ch1);
}
}
-----------------------------------------------------------------------
public class Test11
{
public static void main(String[] args)
{
System.out.println(Character.MIN_VALUE); //white space
System.out.println(Character.MAX_VALUE); //?
System.out.println(Character.SIZE); //16 bits
}
}
------------------------------------------------------------------------
Boolean Literal :
------------------
In boolean literal we have only data type i.e boolean data type.
System.out.println(isValid);
System.out.println(isEmpty);
}
}
-----------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
boolean c = 0; //error
boolean d = 1; //error
System.out.println(c);
System.out.println(d);
}
}
-----------------------------------------------------------------------
public class Test3
{
public static void main(String[] args)
{
boolean x = "true"; //error
boolean y = "false"; //error
System.out.println(x);
System.out.println(y);
}
}
-----------------------------------------------------------------------
String Literal :
----------------
String is a collection of characters which will be enclosed with double quotes.
}
}
------------------------------------------------------------------------
//String is collection of alpha-numeric character
public class StringTest2
{
public static void main(String[] args)
{
String x="B-61 Hyderabad";
System.out.println(x);
String y = "123";
System.out.println(y);
String z = "67.90";
System.out.println(z);
String p = "A";
System.out.println(p);
}
}
-----------------------------------------------------------------------
IQ
--
//IQ
public class StringTest3
{
public static void main(String []args)
{
String s = 15+29+"Ravi"+40+40;
System.out.println(s);
}
}
======================================================================
4) Punctuators :
----------------
It is also called separators.
It is used to inform the compiler how things are grouped in the code.
() {} [] ; , . @ � (var args)
-----------------------------------------------------------------
5) Operators
------------
It is a symbol which describes that how a calculation will be performed on
operands.
Types Of Operators :
------------------------
1) Arithmetic Operator (Binary Operator)
2) Unary Operators
3) Assignment Operator
4) Relational Operator
7) Bitwise Operators (^ ~)
8) Ternary Operator
-----------------------------------------------------------------------
Basic Concepts of Operators :
-----------------------------
class Test
{
public static void main(String[] args)
{
int x = 15;
int y = x++;
System.out.println(x + " : "+ y);
}
}
-----------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
int x = 15;
int y = --x;;
System.out.println(x + " : "+ y);
}
}
------------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
int x = 15;
int y = ++5;
System.out.println(x + " : "+ y);
}
}
-----------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
int x = 5;
int y = ++(++x);
System.out.println(x +": "+y);
}
}
-----------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
char ch = 'A';
ch++;
System.out.println(ch);
}
}
------------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
double d1 = 12.12;
d1++;
System.out.println(d1);
}
}
Note :- Increment and Decrement Operator we can apply with any data type except
boolean.
----------------------------------------------------------------
04-09-2024
-----------
What is local variable ?
------------------------
If we declare any variable inside a method OR block OR constructor then it is
called local/ stack/ temporary/ automatic variable.
Example :
---------
public void m1()
{
int x = 100; //Local Variable
}
A local variable must be initialized by the developer before use becuase we don't
have default value for local variable.
We can't apply any kind of access modifier on local variable except final.
A local variable can be use from the same method, block or constructor only.[Scope
is within the same method, block or constructor]
--------------------------------------------------------------------
Example :
----------
public class Test
{
public static void main(String [] args)
{
final int x = 10;
System.out.println(x);
}
}
In java, Methods are executed in a special memory area called Stack area.
In java whenever we call a method then one stack frame is cretaed internally.
This Stack frame will automatically deleted, once the execution of the method is
completed so with that stack frame all the local variables and parameter variables
are also deleted from the memory as shown in the Program below.
In Command line Argumenet we can't ask to enter the value from our end user as
shown in the Program.
Scanner class :
---------------
It is a predefined class available in java.util package available from JDK 1.5v.
By using Scanner class we can read appropriate data from the end user.
import java.util.Scanner;
}
-----------------------------------------------------------------------
//Reading the name from the end user
package com.ravi.scanner_ex;
import java.util.Scanner;
}
-----------------------------------------------------------------------
package com.ravi.scanner_ex;
import java.util.Scanner;
}
------------------------------------------------------------------------
05-09-2024
----------
Expression Conversion :
-----------------------
Whenever we are working with Arithmetic Operator (+,-,*,/,%) or unary minus
operator, after expression exeution the result will be converted (Promoted) to int
type, Actually to store the result minimum 32 bits format is required.
After Arithmetic operator expression the result will be promoted to int type so, to
hold the result minimum 32 bit data is required.
-----------------------------------------------------------------------
Unary minus operator :
----------------------
public class Test
{
public static void main(String [] args)
{
int x = 15;
System.out.println(-x);
}
-----------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
byte b = 1;
short c = -b; //error
System.out.println(c);
In Arithmetic operator OR Unary minus operator, the result will be promated to int
type (32 bits) so to hold the result int data type is reqd.
-----------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
byte b = 1;
b += 2;
System.out.println(b);
In the above program we are using short hand operator so we will get the result in
byte format also.
------------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
int z = 5;
if(++z > 5 || ++z > 6) //Logical OR
{
z++;
}
System.out.println(z); //7
System.out.println("................");
z = 5;
if(++z > 5 | ++z > 6) //Boolean OR
{
z++;
}
System.out.println(z); //8
}
}
-----------------------------------------------------------------------
Program on Boolean AND operator :
----------------------------------
public class Test
{
public static void main(String [] args)
{
int z = 5;
if(++z > 6 & ++z> 6)
{
System.out.println("Inside If");
z++;
}
System.out.println(z);
}
-----------------------------------------------------------------------
Working with Bitwise AND(&), Bitwise OR(|) and Bitwise X-OR (^) :
------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
System.out.println(false ^ true);
Note : If both the inputs are alternate of each other then we will get true
otherwise we will get false.[Same input output will be false]
----------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
System.out.println(5 & 6); //4
System.out.println(5 | 6); //7
System.out.println(5 ^ 6); //3
}
-----------------------------------------------------------------------
Bitwise Complement Operator (~) :
---------------------------------
It will not work with boolean type.
}
-----------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
System.out.println(~-5); // 4
System.out.println(~5); //-6
}
-----------------------------------------------------------------------
Member access operator (.) :
-----------------------------
It is called Member access operator, by using this we can access the member of the
class.
In the following program we have static method in the Welcome class, in order to
call the static method we can use Welcome class and to access the static method of
Welcome class we should use .(Dot) operator.
class Welcome
{
public static void m1() //static Method
{
System.out.println("M1 static Method");
}
}
public class Test
{
public static void main(String [] args)
{
Welcome.m1();
}
}
------------------------------------------------------------------------
class Welcome
{
public void m1() //non static Method
{
System.out.println("M1 non-static Method");
}
}
public class Test
{
public static void main(String [] args)
{
Welcome w = new Welcome();
w.m1();
}
}
Note : In order to call static method, Object is not required but to call non
static method, Object is required.
-----------------------------------------------------------------------
new Keyword :
-------------
It is also an operator.
It is used to create the object and initialize the non static member with default
value.
class Welcome
{
public void m1() //non static Method
{
System.out.println("M1 non-static Method");
}
}
public class Test
{
public static void main(String [] args)
{
Welcome w = new Welcome();
w.m1();
}
}
-----------------------------------------------------------------
Limitation of if else :
-----------------------
The major drawback with if condition is, it checks the condition again and again so
It increases the burdon over CPU so we introduced switch-case statement to reduce
the overhead of the CPU.
06-09-2024
-----------
Switch case statement in java :
-------------------------------
It is a selective statement so, we can select one statement among the available
statements.
break is optional but if we use break then the control will move from out of the
switch body.
We can write default so if any statement is not matching then default will be
executed.
In switch case we can't pass long, float and double and boolean value.
We can pass String from JDK 1.7v and we can also pass enum from JDK 1.5v.
------------------------------------------------------------------------
import java.util.*;
public class SwitchDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter a Character :");
char colour = sc.next().toLowerCase().charAt(0);
switch(colour)
{
case 'r' : System.out.println("Red") ; break;
case 'g' : System.out.println("Green");break;
case 'b' : System.out.println("Blue"); break;
case 'w' : System.out.println("White"); break;
default : System.out.println("No colour");
}
System.out.println("Completed") ;
}
}
-----------------------------------------------------------------------
import java.util.*;
public class SwitchDemo1
{
public static void main(String args[])
{
System.out.println("\t\t**Main Menu**\n");
System.out.println("\t\t**100 Police**\n");
System.out.println("\t\t**101 Fire**\n");
System.out.println("\t\t**102 Ambulance**\n");
System.out.println("\t\t**139 Railway**\n");
System.out.println("\t\t**181 Women's Helpline**\n");
switch(choice)
{
case 100:
System.out.println("Police Services");
break;
case 101:
System.out.println("Fire Services");
break;
case 102:
System.out.println("Ambulance Services");
break;
case 139:
System.out.println("Railway Enquiry");
break;
case 181:
System.out.println("Women's Helpline ");
break;
default:
System.out.println("Your choice is wrong");
}
}
}
----------------------------------------------------------------------
Passing String value in switch case :
--------------------------------------
import java.util.*;
public class SwitchDemo2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the name of the season :");
String season = sc.next().toLowerCase();
case "rainy" :
System.out.println("It is Rainy Season!!");
break;
}
}
}
-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
long l = 12L;
switch(l) //error
{
case 12L :
System.out.println("It is case 12");
break;
}
}
}
----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
float l = 12L;
switch(l)
{
case 12 :
System.out.println("It is case 12");
break;
}
}
switch(x)
{
case y :
System.out.println("It is case 12");
break;
}
}
}
-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
byte b = 90;
switch(b)
{
case 128 : //error
System.out.println("It is case 127");
break;
}
}
Note : Value 128 is out of the range of byte and same applicable for short data
type
------------------------------------------------------------------------
Loops in java :
---------------
A loop is nothing but repeatation of statements based on the
specified condition.
while(x>=-10)
{
System.out.println(x);
x--;
}
}
}
-----------------------------------------------------------------------
Program on for loop :
---------------------
public class ForLoop
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
System.out.println(i);
}
}
}
------------------------------------------------------------------------
For Each loop :
----------------
It is an enhanced for loop.
It is introduced from JDK 1.5v.
It is used to retrieve OR Iterate the values one by one from the Collection like
array.
for(int x : arr)
{
System.out.println(x);
}
}
}
-----------------------------------------------------------------------
How to sort Array data :
--------------------------
In java.util pacakge, there is a predefined class called Arrays which has various
static methods to sort the array in ascending or alphabetical order.
Example :
Arrays.sort(int []arr); //For sorting int array
Arrays.sort(Object []arr) //For sorting String array
-----------------------------------------------------------------------
//Sorting the integer array
package com.ravi.foreach_demo;
import java.util.Arrays;
Arrays.sort(arr);
for(int x : arr)
{
System.out.println(x);
}
}
-----------------------------------------------------------------------
//Sorting the string array
package com.ravi.foreach_demo;
import java.util.Arrays;
Arrays.sort(fruits);
}
------------------------------------------------------------------------
In java, Can we hold hetrogeneous types of data using array ?
-------------------------------------------------------------
Yes, by using Object array we can hold hetrogeneous type of data but we can't
peform sorting operation using Arrays.sort(), It will generate
java.lang.ClassCastException
package com.ravi.foreach_demo;
}
-----------------------------------------------------------------------
09-09-2024
-----------
What is BLC and ELC class in java ?
------------------------------------
BLC :
------
BLC statnds for Business Logic class, In this class we are responsible to write the
logic. This class will not contain main method.
The main purpose of this BLC class to reuse this class in various packages.
Example :
----------
//BLC
public class Calculate
{
//Here We are responsible to write the logic
}
ELC :
-----
It stands for Executable Logic class, It will not contain any logic but the
execution of the program will start from this ELC class because it contains main
method.
Example :
---------
//ELC
public class Main
{
public static void main(String [] args)
{
}
}
======================================================================
How to reuse a class in java ?
-------------------------------
The slogan of java is "WORA" write once run anywhere.
A public class created in one package can be reuse from different packages also by
using import statement.
Each .java file can contain only one public class.The file name must match with the
class name.
*In a single java file, we can write only one public class and multiple non-public
classes but it is not a recommended approach because the non public class we can
use within the same package only.
So the conclusion is, we should declare every java class in a separate file to
enhance the reusability of the BLC classes.
[Note we have 10 classes -> 10 java files]
For a public class in a single file which contains n number of non public classes
then compiler will generate n number of .class file.
Example :
----------
Test.java
----------
public class Test
{
class A
{
}
class B
{
}
class C
{
}
In order to call a static method, Object is not required, We can call static method
directly with the help of class name.
----------------------------------------------------------------------
How to call a static method available in the same class :
---------------------------------------------------------
If a static method is available in the same class (ELC class) then we can directly
call the static method from another static method, Here class name is also not
required as shown in the program.
//A static method can be directly call within the same class
package com.ravi.pack1;
GetSquare.java(BLC)
-------------------
package com.ravi.pack2;
//BLC
public class GetSquare
{
public static void getSquareOfNumber(int num)
{
System.out.println("Square of "+num+" is :"+(num*num));
}
}
Test2.java(ELC)
----------------
package com.ravi.pack2;
import java.util.Scanner;
//ELC
public class Test2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the side :");
int side = sc.nextInt();
GetSquare.getSquareOfNumber(side);
sc.close();
}
}
//BLC
public class FindSquare
{
public static int getSquare(int x)
{
return (x*x);
}
}
Test3.java
-----------
package com.ravi.pack3;
import java.util.Scanner;
//ELC
public class Test3
{
public static void main (String[] arg)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of side :");
int side = sc.nextInt();
sc.close();
}
}
package com.ravi.pack4;
//BLC
public class Calculate
{
public static int getSquareAndCube(int num)
{
if(num <=0)
{
return -1;
}
else if(num % 2==0)
{
return num*num;
}
else
{
return num*num*num;
}
}
Test4.java
------------
package com.ravi.pack4;
import java.util.Scanner;
}
--------------------------------------------------------------------------
2 files :
---------
Rectangle.java
--------------
package com.ravi.pack5;
//BLC
public class Rectangle
{
public static double getAreaOfRectangle(double length, double breadth)
{
return (length * breadth);
}
Test5.java
-----------
package com.ravi.pack5;
import java.util.Scanner;
//BLC
public class EvenOrOdd
{
public static boolean isEven(int num)
{
return (num % 2 == 0);
}
}
Test6.java
----------
package com.ravi.pack6;
import java.util.Scanner;
//ELC
public class Test6
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number :");
int num = sc.nextInt();
isEven = EvenOrOdd.isEven(num);
System.out.println(num+" is Even ?:"+isEven);
sc.close();
}
}
-----------------------------------------------------------------------
How to provide formatting for Decimal number :
----------------------------------------------
In java.text package, there is a predefined class called DecimalFormat through
which we can provide formatting for Decimal number.
Note :- format is non static method of DecimalFormat class which accpts double as a
parameter, and return type of this method is
String.
package com.ravi.pack7;
public class Circle
{
public static String getAreaOfCircle(double radius)
{
if(radius <= 0)
{
return ""+(-1);
}
else
{
double PI = 3.14;
double areaOfCircle = PI * radius * radius;
return ""+areaOfCircle;
}
}
}
Test7.java
-----------
package com.ravi.pack7;
import java.text.DecimalFormat;
import java.util.Scanner;
//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]
Test8.java
-----------
package com.ravi.pack8;
}
------------------------------------------------------------------------
Note : We can't invoke a method from System.out.println() statement whose return
type is void, It will generate CE.
Example :
----------
class A
{
public static void m1()
{}
}
class Main
{
public static void main(String [] args)
{
System.out.println(A.m1()); //CE
}
}
------------------------------------------------------------------------
2 files :
---------
Table.java
----------
package com.ravi.pack9;
//BLC
public class Table
{
public static void printTable(int num) //[9 X 1 = 9]
{
for(int i=1; i<=10; i++)
{
System.out.println(num+" X "+i+" = "+(num*i));
}
System.out.println("==============================");
}
}
Test9.java
-----------
package com.ravi.pack9;
//ELC
public class Test9
{
public static void main(String[] args)
{
for(int i = 1; i<=9; i++)
{
Table.printTable(i);
}
}
}
========================================================================
Types of Variable in java :
---------------------------
Based on the data type we have only 2 types of variable in java :
1) Primitive Variables
2) Reference Variables
1) Primitive Variables :
------------------------
If a variable is declared with primitive data type like byt, short, int, long and
so on then it is called Primitive Variables.
Example :
int x = 100;
boolean y = true;
2) Reference Variable :
-----------------------
If a variable is declared with class name, interface name, enum , record and so on
then it is called reference variable.
Example :
Student s; //s is reference variable
Scanner sc = new Scanner(System.in); //sc is reference variable
Integer y = null; //y is reference variable
Note : With primitive variable we can't call a method as well as we can't assign
null literal.
int y = 45;
y.m1(); //Invalid
-------------------------------------------------------------------------
Program on Reference Variables :
---------------------------------
package com.ravi.variables;
import java.util.Scanner;
class Student
{
acceptStudentObject(stud);
}
public static void acceptStudentObject(Student st) //Reference + Parameter
{
}
}
-------------------------------------------------------------------------
11-09-2024
----------
Object Oriented Programming (OOPs)
----------------------------------
What is an Object?
------------------
An object is a physical entity which exist in the real world.
Example :- Pen, Car, Laptop, Mouse, Fan and so on
OOP is a technique through which we can design or develop the programs using class
and object.
Advantages of OOP :
--------------------
1) Modularity (Dividing the bigger task into smaller task)
2) Reusability (We can reuse the component so many times)
3) Flexibility (Easy to maintain [By using interface])
Features of OOP :
-----------------
1) Class
2) Object
3) Abstraction
4) Encapsulation
5) Inheritance
6) Polymorphism
======================================================================
What is a class?
-----------------
A class is model/blueprint/template/prototype for creating the object.
A class is a user-defined data type which contains data member and member function.
2 files :
---------
Student.java
-------------
package com.ravi.oop;
//BLC
public class Student
{
String studentName; //Instance Variable
double studentHeight; //Instance Variable
int studentRollNumber; //Instance Variable
StudentDemo.java
-----------------
package com.ravi.oop;
//ELC
public class StudentDemo
{
public static void main(String[] args)
{
Student raj = new Student();
//Initialize the properties (Variables)
raj.studentRollNumber = 111;
raj.studentName = "Raj Gourav";
raj.studentHeight = 5.8;
//Calling the behavior
raj.talk();
raj.writeExam();
}
}
=======================================================================
Steps for creating Object Orineted Programming
Step 1 :- Create the Object based on the BLC class inside ELC
class.[main method]
Step 3 :- Initialize all the object properties with user friendly value by using
reference variable.
2 files :
----------
Customer.java
-------------
package com.ravi.oop;
CustomerDemo.java
------------------
package com.ravi.oop;
import java.util.Scanner;
scott.buyProduct(); scott.billPayment();
sc.close();
}
-----------------------------------------------------------------------
Initializing the Object properties through Methods :
-----------------------------------------------------
We can also initialize the object properties through methods as shown in the
program.
2 files :
---------
Employee.java
--------------
package com.ravi.oop;
EmployeeDemo.java
------------------
package com.ravi.oop;
Note : Upto here, we have learned the following two types to initialize the Object
properties
a) By using Object Reference
b) By using Methods
-----------------------------------------------------------------------
What is an instance variable ?
-------------------------------
If a non static variable is declared inside a class and outside of the
method then it is called instance variable.[class level variable]
class Test
{
int x = 100; //Instance Variable
}
An instance variable will automatically initalized with default value (even the
variable final) at the time of Object creation.
Without an object the life of the instance variable will not be started.
In java, There is a special memory for object where object and its properties
(Instance Variable) are available called HEAP Memory.
The scope of instance variable is within the class as well as it depends upon the
access modifier.
=======================================================================
What is a constructor [Introduction Only]
------------------------------------------
If the name of the class and name of the method both are exactly same and It does
not contain any type of return type (Without return type)
then it is called constructor.
Example :
---------
class Student
{
public Student() //Constructor
{
}
}
-----------------------------------------------------------------------
Default constructor added by the compiler :
-------------------------------------------
In java, whenever we write a class and if we don't write any kind
of constructor in the class then automatically java compiler will add one default
constructor to the class.
Test.java
----------
public class Test
{
Test.class
-----------
public class Test
{
public Test() //default constructor added by the compiler
{
}
}
Every java class must have at-least one constructor either explicitly
written by user OR implicitly added by compiler.
2) As we know only class level variables are having default values so, default
constructor will initialize all the instance variables with default values with the
help of new keyword.
Student.java
--------------
package com.ravi.oop;
Note : Even we are not initializing our instance variable but it will
be initialized by default constructor using new keyword [super () ]
-------------------------------------------------------------------
How to provide our own user-defined values for the instance variable :
----------
2 files :
----------
Manager.java
------------
package com.ravi.oop;
import java.util.Scanner;
ManagerDemo.java
-----------------
package com.ravi.oop;
}
-------------------------------------------------------------------
How to initialize the Object properties through parameter variable :
-------------------------------------------------------------------
We can initialize the instance variable by using method parameter as
shown in the program
2 files :
---------
Player.java
------------
package com.ravi.oop;
PlayerDemo.java
---------------
package com.ravi.oop;
}
--------------------------------------------------------------------
How to initialize the instance variable through parameter variable as per
requirement.
2 files :
----------
Employee.java
-------------
package com.ravi.oop;
EmployeeDemo.java
-------------------
package com.ravi.oop;
}
--------------------------------------------------------------------
Variable Shadow :
-----------------
Variable shadowing in Java occurs when a variable declared within a certain scope
(like a method or a block or Constructor) has the same name as a variable declared
in an outer scope (class Level).
In variable Shadow, the variable in the inner scope hides the variables in Outer
scope so known as variable shadowing.
This means that within the inner scope (Method, block Or Constructor), when we
refer to the variable directly by name, We are actually referring to the inner
variable, not the outer variable.
2 files :
---------
Student.java
-------------
package com.ravi.oop;
System.out.println(studentId);
System.out.println(studentName);
}
}
VariableShadow.java
--------------------
package com.ravi.oop;
}
--------------------------------------------------------------------
this keyword in java :
----------------------
Whenever instance variable name and parameter variable name both are same then at
the time of instance variable initialization our runtime environment will provide
more priority to parameter variable/local variable, parameter variables are hiding
the instance variables (Due to variable shadow)
To avoid the above said problen, Java software people introduced "this" keyword.
this keyword always refers to the current object and instance variables are the
part of the object so by using this keyword we can represent instance variable.
We cannot use this (non static member) keyword from static area (Static context).
-------------------------------------------------------------------
2 files :
----------
Customer.java
--------------
package com.ravi.oop;
}
ThisKeywordDemo.java
---------------------
package com.ravi.oop;
}
===================================================================
How to print object properties by using toString() method :
-----------------------------------------------------------
If we want to print our object properties (Instance Variables) then we should
generate(override) toString() method in our class from Object class.
Now with the help of toString() method we need not to write any display kind of
method to print the object properties i.e instance variable.
In order to call this toString() method, we need to print the corresponding object
reference by using System.out.println() statement.
2 files :
-----------
Trainer.java
------------
package com.ravi.oop;
@Override
public String toString()
{
return "Trainer [trainerId=" + trainerId + ", trainerName=" +
trainerName + ", trainerSubject=" + trainerSubject
+ "]";
}
ToStringDemo.java
------------------
package com.ravi.oop;
System.out.println(scott); //toString()
}
==================================================================
16-09-2024
-----------
Role of instance variable while creating the Object :
-----------------------------------------------------
Whenever we create an objet in java, a separate copy of all the instance variables
will be created with each and every object.
Program :
---------
package com.ravi.oop;
++t1.x; --t2.x;
System.out.println(t1.x); //11
System.out.println(t2.x); //9
}
}
------------------------------------------------------------------
What is a static field ?
------------------------
It is a class level variable.
In order to access the static member, we need not to create an object, here class
name is required.
package com.ravi.oop;
++d1.x; ++d2.x;
System.out.println(d1.x); //12
System.out.println(d2.x); //12
}
Instance Variable :
-------------------
If the value of the variable is different with respect to objects then we should
declare a variable as a instance variable.
Static Variable :
------------------
If the value of the variable is common to all the objects then we should declare a
variable as a static variable.
Program :
---------
2 files :
---------
package com.nit;
@Override
public String toString() {
return "Student [rollNumber=" + rollNumber + ", studentName=" +
studentName + ", studentAddress="
+ studentAddress + ", college name="
+Student.collegeName+", course name = "+ Student.courseName+" ]";
VariableDeclaration.java
-------------------------
package com.nit;
}
=================================================================
18-09-2024
----------
What is Data Hiding ?
----------------------
Data hiding is nothing but declaring our data members with private access modifier
so our data will not be accessible from outer world that means no one can access
our data directly from outside of the class.
*We should provide the accessibility of our data through methods so we can perform
VALIDATION ON DATA which are coming from outer world.
2 files :
---------
Customer.java
-------------
package com.ravi.data_hiding;
BankApplication.java
---------------------
package com.ravi.data_hiding;
}
-----------------------------------------------------------------
Constructor :
-------------
What is Constructor ?
---------------------
What is the advantage of writing constructor in our class ?
------------------------------------------------------------
If we don't write a constructor in our program then variable initialization and
variable re-initialization both are done in two different lines.
If the name of the class and name of the method both are exactly same and it does
not contain any return type then it is called Constructor.
Example :
----------
public class Student
{
public Student() //Constructor
{
}
Every java class must contain at-least one constructor, either explicitly written
by developer OR implicitly added by compiler.
A constructor never contain any return type but internally it returns current class
object (this keyword)
package com.ravi.constructor;
new Employee().getSalary();
}
}
Every time we create an object by using new keyword, at-least one constructor must
be invoked.
================================================================
Program that describes difference between Method and Constructor
2 files :
---------
Student.java
-------------
package com.ravi.data_hiding;
StudentDemo.java
-----------------
package com.ravi.data_hiding;
3) Parameterized Constructor
-----------------------------------------------------------------
Default No Argument Constructor :
---------------------------------
Whenever we write a class and if we don't write any type of constructor then
automatically one default constructor is added by the compiler.
The access modifier of default constaructor would be same as class access modifier.
Example.java
--------------
public class Example
{
}
javac Example.java
Example.class
------------
public class Example
{
public Example() //default constructor
{
}
}
--------------------------------------------------------------------
No Argument Constructor :
--------------------------
If a user defines a constructor inside a class without argument then it is called
no argument constructor.
No argument constructor and default constructor, both look like same the only
difference is, default constructor means added by compiler and no argument
constructor means written by user.
2 files :
----------
Person.java
------------
package com.ravi.constructor_demo;
@Override
public String toString()
{
return "Person [personId=" + personId + ", personName=" + personName +
"]";
}
}
package com.ravi.constructor_demo;
Note : In the above program we have 2 objects scott and smith but both the objects
initialized with scott data.
Example :
----------
public class Employee
{
int id;
String name;
@Override
public String toString()
{
return "Dog [dogName=" + dogName + ", dogHeight=" + dogHeight + ",
dogColor=" + dogColor + "]";
}
}
ParameterizedConstructor.java
------------------------------
package com.ravi.constructor_demo;
}
}
--------------------------------------------------------------------
How to write setter and getter methods :
-----------------------------------------
public class Customer
{
private double customerBill;
//Writing getter to retrieve the private data value outside of BLC class
public double getCustomerBill()
{
return this.customerBill;
}
}
--------------------------------------------------------------------
FINAL CONCLUSION :
-------------------
Parameterized Constructor : To initialize the Object properties with user values.
Setter : To modify the existing object data.[Only one data at a time] OR Writing
Operation
Encapsulation ensures that our private data (Object Properties) must be accessible
via public methods like setter and getter.
It provides security because our data is private (Data Hiding) and it is only
accessible via public methods WITH PROPER DATA VALIDATION.
1) Declare all the data members with private access modifiers (Data Hiding OR Data
Security)
Note : If we decalre all our data with private access modifier then it is called
TIGHTLY ENCAPSULATED CLASS. On the other hand if we declare our data other then
private access modifier then it is called Loosely Encapsulated class.
Program on encapsulation :
--------------------------
2 files :
----------
Employee.java
--------------
package com.ravi.constructor_demo;
@Override
public String toString()
{
return "Employee [employeeSalary=" + employeeSalary + "]";
}
SetterAndGetter.java
----------------------
package com.ravi.constructor_demo;
if(empSalary >=60000)
{
System.out.println("Scott is Developer");
}
else if(empSalary >=40000)
{
System.out.println("Scott is Designer");
}
else
{
System.out.println("Scott is Tester");
}
}
--------------------------------------------------------------------
20-09-2024
-----------
Method return type as a class :
-------------------------------
While declaring a method in java, return type is compulsory.
As a method return type we have following options
3) Any class name/interface / enum / record we can take as a return type of the
method.
Example 1 :
-----------
package com.nit;
Example 2 :
-----------
package com.nit;
public Demo(int x)
{
this.x = x;
}
}
}
Note : Here the return value depends upon the available constructor in the class.
====================================================================
What is a Factory Method :
--------------------------
If a method return type is class name menas it is returning the Object of the class
then it is called Factory Method.
--------------------------------------------------------------------
2 files :
---------
Product.java
-------------
package com.ravi.factory_method;
@Override
public String toString() {
return "Product [productId=" + productId + ", productName=" +
productName + ", productPrice=" + productPrice
+ "]";
}
ProductDemo.java
-----------------
package com.ravi.factory_method;
2 files :
----------
Employee.java
--------------
package com.ravi.factory_method;
import java.util.Scanner;
@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" +
employeeName + ", employeeSalary="
+ employeeSalary + "]";
}
EmployeeDemo.java
------------------
package com.ravi.factory_method;
import java.util.Scanner;
sc.close();
}
}
--------------------------------------------------------------------
What is Shallow and Deep copy in java :
----------------------------------------
Shallow Copy :
--------------
In Shallow copy, Only one Object will be created but the same object will be
refered by multiple reference variables.
If we modify the object properties by any of the reference variable then original
object will be modified as shown in the program.
package com.ravi.object_duplication;
@Override
public String toString() {
return "Laptop [laptopPrice=" + laptopPrice + ", laptopBrand=" +
laptopBrand + "]";
}
System.out.println("Before Change");
System.out.println(laptop1);
System.out.println(laptop2);
laptop2.laptopBrand = "DELL";
laptop2.laptopPrice = 95000;
System.out.println("After Change");
System.out.println(laptop1);
System.out.println(laptop2);
}
--------------------------------------------------------------------
Deep Copy :
-----------
In deep copy two different objects will be created, the 2nd object will copy the
content of first object.
If we modify the object by using reference variable then only one object will be
modified because both the objects are created in two different memory location as
shown below.
package com.ravi.object_duplication;
@Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" +
customerName + "]";
}
System.out.println("Before Change");
System.out.println(c1);
System.out.println(c2);
System.out.println("..................");
System.out.println("After change in 2nd Object");
c2.customerId = 222;
c2.customerName = "Smith";
System.out.println(c1);
System.out.println(c2);
}
}
===============================================================
**Pass by Value :
-----------------
Java does not support pointers so java only works with pass by value.
Pass by value means we are sending the copy of orginal data to the method.
package com.ravi.pass_by_value;
public class PassByValueDemo1 {
class Customer
{
private int customerId = 111;
accept(c1);
System.out.println(c1.getCustomerId()); //555
}
Here we will get the Output 111 and 555, here we are working with
reference variable, the reference variable c1 is assigned to reference variable
cust hence, if we modify by using cust variable then original object will be
modified.
--------------------------------------------------------------------
package com.ravi.pass_by_value;
class Product
{
private int productId = 111;
accept(p1);
System.out.println(p1.getProductId()); //111
}
Here on p1 reference variable we are assigning one new Product object so the old
object value will remain unchaged.
--------------------------------------------------------------------
package com.ravi.object_duplication;
public class Customer
{
private double customerBill = 4000;
c2.customerBill = 9000;
System.out.println(c1.customerBill); //9000
System.out.println(c2.customerBill); //9000
}
-------------------------------------------------------------------
package com.ravi.object_duplication;
System.out.println(c1.customerBill); //4000
System.out.println(c2.customerBill); //10000
}
---------------------------------------------------------------
HEAP and STACK Diagram :
------------------------
What is Garbage Collector in java -----------------------------------
It is an automatic memory management technique in java.
In java language, Programmer is only responsible to allocate the memory, Memory de-
allocation is automatically done by garbage collector.
It internally uses an algorithm called Mark and Sweep algorithm to delete the un-
used objects.
System.gc();
==============================================================
How many ways we can make an object eligible for Garbage Collector :
--------------------------------------------------------------------
There are 3 ways we can make an object eligible for GC.
Earlier e3 variable was poting to Employee object after that a new Employee Object
is created which is pointing to another memory location so the first object is
eligible for GC.
===============================================================
Memory in java :
------------------
In java, whenever we create an object then Object and its content (properties and
behavior) are stroed in a special memory called HEAP Memory. Garbage collector
visits heap memory only.
All the local variables and parameters variables are executed in Stack Frame and
available in Stack Memory.
--------------------------------------------------------------
HEAP and Stack Diagram for CustomerDemo.java :
-----------------------------------------------
class Customer
{
private String name;
private int id;
m1(c);
System.out.println(c.getId());
}
cust.setId(9);
System.out.println(cust.getId());
}
}
//Output 9 5
--------------------------------------------------------------
public class Sample
{
private Integer i1 = 900;
Sample s3 = modify(s2);
s1 = null;
System.out.println(s2.i1);
}
public static Sample modify(Sample s)
{
s.i1=9;
s = new Sample();
s.i1= 20;
System.out.println(s.i1);
s=null;
return s;
}
}
//20 9
--------------------------------------------------------------
public class Test
{
Test t;
int val;
t2.t = t3;
t3.t = t4;
t1.t = t2.t;
t2.t = t4.t;
System.out.println(t1.t.val);
System.out.println(t2.t.val);
System.out.println(t3.t.val);
System.out.println(t4.t.val);
}
}
--------------------------------------------------------------
public class Employee
{
int id = 100;
e1.id = val;
update(e1);
System.out.println(e1.id);
e2.id = 900;
System.out.println(e1.id);
System.out.println(e2.id);
}
The following program explains how to copy the content of Employee object to
initialize Manager class properties :
3 files :
----------
Employee.java
--------------
package com.ravi.copy_constructor;
Manager.java
-------------
package com.ravi.copy_constructor;
@Override
public String toString() {
return "Manager [managerId=" + managerId + ", managerName=" +
managerName + "]";
}
}
CopyConstructorDemo1.java
---------------------------
package com.ravi.copy_constructor;
Note : In the above program we are initializing the Manager data through Employee
Data.
The following program explains how to initialize the same class data in another
object.
2 files :
---------
Player.java
-----------
package com.ravi.copy_constructor;
@Override
public String toString() {
return "Player [name1=" + name1 + ", name2=" + name2 + "]";
}
}
CopyConstructorDemo2.java
--------------------------
package com.ravi.copy_constructor;
}
---------------------------------------------------------------
Lab Program :
-------------
Lab Program :(Method return type as a class + Passing Object ref)
----------------------------------------------------------------
A class called Customer is given to you.
The task is to find the applicable Credit card Type and create CardType object
based on the Credit Points of a customer.
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 which contains Main method to test the working of the above.
4 Files :
----------
Customer.java
---------------
package com.ravi.scenario_program;
@Override
public String toString()
{
return this.customerName;
}
}
CardType.java
---------------
package com.ravi.scenario_program;
@Override
public String toString()
{
//The Customer 'Rajeev' Is Eligible For 'Gold' Card.
CardsOnOffer.java
------------------
package com.ravi.scenario_program;
ELC.java
---------
package com.ravi.scenario_program;
import java.util.Scanner;
sc.close();
}
---------------------------------------------------------------
25-09-2024
----------
Modifiers on Constructor :
---------------------------
Constructor can accept all types of access modifiers which are apllicable for
accessibility level like private, default, protected and public.
package com.ravi.constructor;
@Override
public String toString() {
return "Sample [x=" + x + ", y=" + y + "]";
}
}
----------------------------------------------------------------
package com.ravi.constructor;
}
----------------------------------------------------------------
Note : We can't apply static, final, abstract and synchronized modifier on
constructor.
----------------------------------------------------------------
IQ :
----
Why we should declare a constructor with private Access modifier ?
We can declare a constructor with private access modifier due to the following two
reasons :
1) If we want to declare only static variables and static methods inside a class
then we should decalre constructor with private access modifier [Object is not
required]
2) If we want to develop singleton class, for singleton class we should create only
one object by the class itself then we should declare the constructor with private
access modifier.
package com.ravi.constructor;
}
-------------------------------------------------------------------
What is an instance block OR instance initializer in java ?
------------------------------------------------------------
It is a special block in java which is automatically executed at the time of
creating the Object.
Example :
{
//Instance OR Non static block
}
If a constructor contains first line as a super() statement then only compiler will
add instance block in the 2nd line of constructor otherwise it will not be added by
the compiler.
If constructor contains super() then non static block will be executerd before the
body of the constructor.
The main purpose of instance block to initialize the instance variables (So It is
called Instance Iniatilizer) of the class OR to write a common logic which will be
applicable to all the objects.
If a class contains multiple non static blocks then it will be executed according
to the order [Top to bottom]
Instance initializer must be executed normally that menas we can't interrupt the
execution flow of any initializer hence we can't write return statement inside non
static block.
If a user defines non static block after the body of the constructor then compiler
will not placed in the 2nd line of the constructor. It will be executed as it is
because compiler will search the NSB in the class level.
-----------------------------------------------------------------
package com.ravi.instance_block;
class Test
{
{
System.out.println("Instance OR Non static Block ");
}
}
class Sample
{
int x;
{
x = 100;
}
class Sample1
{
public Sample1()
{
System.out.println("No Arg Constr");
}
public Sample1(int x)
{
System.out.println("Parameterized Constructor");
}
{
System.out.println("Non Static Block");
}
Note : Non static block will be added to all the constructors which contains
super().
-------------------------------------------------------------------
package com.ravi.instance_block;
class NIT
{
public NIT()
{
super();
//NSB
System.out.println("No Arg constr");
}
{
System.out.println("Instance Block OR Non static Block");
}
}
Note : Non static block will not be added to the constructor which contains this()
------------------------------------------------------------------
package com.ravi.instance_block;
class Demo1
{
int x;
{
x = 100;
System.out.println(x);
}
{
x = 200;
System.out.println(x);
}
{
x = 300;
System.out.println(x);
}
public Demo1()
{
x = 400;
System.out.println(x);
}
}
{
// TODO Auto-generated method stub
}
Note : no return keyword inside non static block
-----------------------------------------------------------------
package com.ravi.instance_block;
class General
{
public General()
{
System.out.println("Constructor Body");
{
System.out.println("Non Static Block");
}
}
}
Note : Here non static block will be executed after the body of constructor.
----------------------------------------------------------------
Order of instance variable initialization in the program life cycle :
All the instance variables are initialized in the following order during the life
cycle :
2) Now control will verify whether, we have initailized at the time of variable
declaration or not.
5) Now control will verify whether, we have initailized in the method body or not
but it is not recommended because Object is already created, we need to call the
method explicitly, It is not the part of the object.
Default value [new keyword] => At the time of declaration => in the body of non
static block => in the body of constructor => Inside method body [Not Recommended]
package com.ravi.instance_initialization;
class Demo
{
int x = 100; //Initialization Order1
Demo()
{
this.x = 300; //Initialization Order3
}
{
x = 200; //Initialization Order2
}
}
}
----------------------------------------------------------------
What is blank final field in java ?
------------------------------------
If a final instance variable is not initialized at the time of declaration then it
is called blank final field.
class Test
{
final int A; //Blank final field
A blank final field must be explicitly initialized by the user till the execution
of constructor body.[Till Object creation]. It can be iniatialized in the following
two places :
class Test
{
final int A ; //Blank final field
{
A = 100;
}
* A blank final field can also have default values as shown the in the program.
class Test
{
final int A ; //Blank final field
{
printDefaultValue();
A = 100;
}
package com.ravi.basic;
class Sample
{
private final int x;
public Sample()
{
x = 100;
}
public Sample(int y)
{
x = y;
}
}
=================================================================
Relationship between the classes :
----------------------------------
In java we have 2 types of relation in between the classes :
a) IS-A Relation
b) HAS-A Relation
IS-A Relation :
---------------
class Car
{
}
class Ford extends Car //[Ford IS-A car ]
{
}
HAS-A Relation :
-----------------
class Engine
{
}
class Car
{
private Engine engine; //Car HAS-A Engine.
}
27-09-2024
------------
Inheritance (IS-A Relation) :
--------------------------------
Deriving a new class (child class) from existing class (parent class) in such a way
that the new class will acquire all the properties and features (except private)
from the existing class is called inheritance.
It is one of the most imporatnt feature of OOPs which provides "CODE REUSABILITY".
Using inheritance mechanism the relationship between the classes is parent and
child. According to Java the parent class is called super class and the child class
is called sub class.
*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.
class Father
{
public void house()
{
System.out.println("3 BHK House");
}
}
class Son extends Father
{
public void car()
{
System.out.println("Audi Car");
}
}
class Super
{
private int x,y;
}
---------------------------------------------------------------
28-09-2024
-----------
How to initialize the super class properties :
----------------------------------------------
In order to initialize the super class properties we should use super keyword in
the sub class as a first line of constructor.
Just like this keyword, super keyword (non static member) also we can't use inside
static context.
In order to access super class variable i.e super class memory, we should use super
keyword as shown in the program.
VariableHiding.java
-------------------
package com.ravi.super_keyword;
class Father
{
protected double balance = 50000;
}
class Son extends Father
{
protected double balance = 9000; //Variable Hiding
}
---------------------------------------------------------------
2) To call super class method :
-------------------------------
If the super class non static method name and sub class non static method name both
are same (Method Overriding) and if we create an object for sub class then sub
class method will be
executed (bottom to top), if we want to call super class method from sub class
method body then we we should use super keyword as shown in the program.
class Super
{
public void show()
{
}
--------------------------------------------------------------
3) To access the super class constructor (Constructor Chaining) :
----------------------------------------------------------------
Whenever we write a class in java and we don't write any kind of constructor to the
class then the java compiler will automatically add one default no argument
constructor to the class.
THE FIRST LINE OF ANY CONSTRUCTOR IS RESERVERD EITHER FOR super() or this() keyword
that means first line of any constructor is used to call another constructor of
either same class OR super class.
In the first line of any constructor if we don't specify either super() or this()
then the compiler will automatically add super() to the first line of constructor.
Now the purpose of this super() [added by java compiler], to call the default
constructor or No-Argument constructor of the super class.
In order to call the constructor of super class as well as same class, we have
total 4 cases.
---------------------------------------------------------------
Case 1:
-------
super() : Automatically added by java compiler to maintain the
hierarchy in the first line of the Constructor. It
is used to call default OR no argument constructor
of super class.
package com.ravi.constructor_demo;
class Alpha
{
public Alpha()
{
super();
System.out.println("Alpha class");
}
}
class Beta extends Alpha
{
public Beta()
{
super();
System.out.println("Beta class");
}
}
}
---------------------------------------------------------------
Case 2 :
---------
super("Java") : Must be explicitly written by user in the
first line of constructor [not inside a method]. It is used to call
the parameterized constructor of super class.
package com.ravi.constructor_demo;
class Super
{
protected String name;
}
class Sub extends Super
{
public Sub()
{
super("Java"); //Calling Parameterized constr
}
}
--------------------------------------------------------------
Program that describes default constructor and super() will be added by the
compiler.
ConstructorDemo.java
---------------------
package com.ravi.super_demo;
class Alpha
{
public Alpha()
{
System.out.println("Alpha class Constructor!!!");
}
}
class Beta extends Alpha
{}
30-09-2024
----------
Case 3 :
--------
this() : Must be explicitly written by user in the
first line of constructor. It is used to call
no argument constructor of current class.
package com.ravi.super_demo;
class Super
{
public Super()
{
System.out.println("Super class no argument constructor");
}
public Super(String msg)
{
this();
System.out.println("Super class Parameterized constructor :"+msg);
}
}
class Sub extends Super
{
public Sub()
{
super("Java");
System.out.println("Sub class no argument constructor");
}
}
}
----------------------------------------------------------------
Case 4 :
---------
this(15) : Must be explicitly written by user in the
first line of constructor. It is used to call
parameterized constructor of current class.
package com.ravi.super_demo;
class Base
{
public Base()
{
this(15);
System.out.println("No Argument Constructor of Base class");
}
public Base(int x)
{
System.out.println("Parameterized Constructor of Base class :"+x);
}
}
}
----------------------------------------------------------------
Program on super keyword :
--------------------------
package com.ravi.super_demo;
class Shape
{
protected int x;
public Shape(int x)
{
super();
this.x = x;
System.out.println("x value is :"+x);
}
}
class Square extends Shape
{
}
----------------------------------------------------------------
Another Program on super keyword :
----------------------------------
package com.ravi.super_demo;
class Shape
{
protected int x;
public Shape(int x)
{
super();
this.x = x;
System.out.println("x value is :"+x);
}
}
}
================================================================
HOW MANY WAYS WE CAN INITIALIZE THE OBJECT PROPERTIES ?
-------------------------------------------------------
The following are the ways to initialize the object properties :
----------------------------------------------------------------
public class Test
{
int x,y;
}
Example :
Here the drawback is all objects will be initialized with same value.
-----------------------------------------------------------------------
Here we are getting different values with respect to object but here the program
becomes more complex.
---------------------------------------------------------------
3) By using methods :
Here the Drawback is initialization and re-initialization both are done in two
different lines so Constructor introduced.
----------------------------------------------------------------------
4) By using Constructor
This is the best way to initialize our instance variable because variable
initialization and variable re-initialization both will be done in the same line as
well as all the objects will be initialized with different values.
public Test()
{
System.out.println(x); //100
System.out.println(y); //200
}
//Instance block
{
x = 100;
y = 200;
}
------------------------------------------------------------------
5) By using super keyword :
class Super
{
int x,y;
new Sub();
================================================================
WAP in java for Single Level Inheritance :
-------------------------------------------
package com.ravi.super_demo;
class TemporaryEmployee
{
protected int employeeNumber;
protected String employeeName;
protected String employeeAddress;
@Override
public String toString()
{
return "PermanentEmployee [employeeNumber=" + employeeNumber + ",
employeeName=" + employeeName
+ ", employeeAddress=" + employeeAddress + ", department="
+ department + ", designation=" + designation
+ "]";
}
}
import java.util.Scanner;
class Employee
{
protected double employeeSalary;
public Employee(double employeeSalary)
{
super();
this.employeeSalary = employeeSalary;
}
}
class Developer extends Employee
{
public Developer(double developerSalary)
{
super(developerSalary);
}
@Override
public String toString()
{
return "Developer [employeeSalary=" + employeeSalary + "]";
}
}
class Designer extends Employee
{
public Designer(double designerSalary)
{
super(designerSalary);
}
@Override
public String toString()
{
return "Designer [employeeSalary=" + employeeSalary + "]";
}
}
}
----------------------------------------------------------------
Program on Multilevel inheritance :
-----------------------------------
package com.ravi.inheritance;
class Student
{
protected int studentId;
protected String studentName;
protected String studentAddress;
@Override
public String toString()
{
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentAddress=" + studentAddress
+ "]";
}
}
}
class PCM extends Science
{
protected int maths;
@Override
public String toString()
{
return super.toString()+"PCM [maths=" + maths + "]";
}
}
----------------------------------------------------------------
**Why java does not support multiple Inheritance ?
--------------------------------------------------
Multiple Inheritance is a situation where a sub class wants to inherit the
properties two or more than two super classes.
In every constructor we have super() or this(). When compiler will add super() to
the first line of the constructor then we have an ambiguity issue that super() will
call which super class constructor as shown in the diagram [01-OCT-24]
================================================================
Access modifiers in java :
---------------------------
In order to define the accessibility level of the class as well as member of the
class we have 4 access modifiers :
private :
---------
It is the most restrictive access modifier because the member declared as private
can't be accessible from outside of the class.
In Java we can't declare an outer class as a private or protected. Generally we
should declare the data member(variables) as private.
In java outer class can be declared as public, abstract, final, sealed and non-
sealed only.
default :-
----------
It is an access modifier which is less restrictive than private. It is such kind of
access modifier whose physical existance is not avaialble that means when we don't
specify any kind of access modifier before the class name, variable name or method
name then by default it would be default.
As far as its accessibility is concerned, default members are accessible within the
same folder(package) only. It is also known as private-package modifier.
protected :
------------
It is an access modifier which is less restrictive than default because the member
declared as protected can be accessible from the outside of the package (folder)
too but by using inheritance concept.
2 files :
----------
Test.java [It is in com.nit.m1 package]
---------------------------------------
package com.nit.m1;
import com.nit.m1.Test;
Note : From the above programs it is clear that protected members are accessible
from outside of the pacakge but by using Inheritance.
public :
-------
It is an access modifier which does not contain any kind of restriction that is the
reason the member declared as public can be accessible from everywhere without any
restriction.
According to Object Oriented rule we should declare the classes and methods as
public where as variables must be declared as private or protected according to the
requirement.
In order to load the .class file into JVM Memory, It uses an algorithm called
"Delegation Hierarchy Algoroithm".
1) LOADING
2) LINKING
3) INITIALIZATION
LOADING :
---------
In order to load the required .class file, JVM makes a request to class loader sub
system. The class loader sub system follows delegation hierarchy algorithm to load
the required .class files from different areas.
To load the required .class file we have 3 different kinds of class loaders.
It has the highest priority becuase Bootstrap class loader is the super class for
Platform class loader.
It is the sub class of Bootstrap class loader and super class of Application class
loader so it has more priority than Application class loader.
It has the lowest priority because it is the sub class Platform class loader.
Bootstrap class loader will load the .class file from lib folder(jrt.jar) and then
by pass the request back to extension class loader, Extension class loader will
load the .class file from ext folder(*.jar) and by pass the request back to
Application class loader, It will load the .class file from environment variable
into JVM memory.
Note :-
------
If all the class loaders are failed to load the .class file into JVM memory then we
will get a Runtime exception i.e java.lang.ClassNotFoundException.
In this method chaining, always for calling next method we depend upon last method
return type.
The final return type of the method depends upon last method call as shown in the
program.
MethodChainingDemo1.java
-------------------------
package com.ravi.method_chaining;
MethodChainingDemo2.java
-------------------------
package com.ravi.method_chaining;
}
---------------------------------------------------------------
Role of java.lang.Class class in class loading :
----------------------------------------------------
There is a predefined class called Class available in java.lang pacakge.
In JVM memory whenever we load a class then it is loaded in special memory called
Method Area and retutn type is java.lang.Class.
ClassLoadingReturnType.java
---------------------------
package com.ravi.class_loading;
class Customer{}
class Employee{}
class Player{}
cls = Player.class;
System.out.println("class name is :"+cls.getName());
cls = Employee.class;
System.out.println("class name is :"+cls.getName());
}
}
----------------------------------------------------------------
WAP that describes Application class loader is responsible to
load the user defined .class file
This method will provide the class loader name which is responsible to load
the .class file into JVM Memory.
Test.java
-----------
package com.ravi.class_loading;
}
---------------------------------------------------------------
WAP that describes Platform class Loader is the super class for
Application class loader
package com.ravi.class_loading;
}
----------------------------------------------------------------
package com.ravi.class_loading;
Note :- Here we will get the output as null because it is built in class loader
for JVM which is used for internal purpose (loading only predefined .class file) so
implementation is not provided hence we are getting null.
----------------------------------------------------------------
verify :-
-------
It ensures the correctness of the .class files, If any suspicious activity is there
in the .class file then It will stop the execution immediately by throwing a
runtime error i.e java.lang.VerifyError.
----------------------------------------------------------------
prepare :
---------
[Static variable memory allocation + static variable initialization with default
value]
It will allocate the memory for all the static data members, here all the static
data member will get the default values so if we have static int x = 100; then for
variable x memory will be allocated (4 bytes) and now it will initialize with
default value i.e 0, even the variable is final.
Note :- By using above command we can read the internal details of .class file.
-----------------------------------------------------------------
04-10-2024
-----------
Initialization :
-----------------
Here class initialization will take place. All the static data member will get
their actual value and we can also use static block for static data member
initialization.
Here, In this class initialization phase static variable and static block is having
same priority so it will executed according to the order.(Top to bottom)
--------------------------------------------------------------
Static Block in java :
-----------------------
It is a special block in java which is automatically executed at the time of
loading the .class file.
Example :
static
{
Static blocks are executed only once because in java we can load the .class files
only once.
If we have more than one static block in a class then it will be executed according
to the order [Top to bottom]
The main purpose of static block to initialize the static data member of the class
so it is also known as static initializer.
static blocks are executed before the main or any static method.
A static blank final field must be initialized inside the static block only.
static
{
A = 100;
}
If we don't declare static variable before static block body execution then we can
perform write operation(Initialization is possible due to prepare phase) but read
operation is not possible directly otherwise we will get an error Illegal forward
reference, It is possible with class name bacause now compiler knows that it is
coming from class area OR Method area.
--------------------------------------------------------------
//static block
class Foo
{
Foo()
{
System.out.println("No Argument constructor..");
}
{
System.out.println("Instance block..");
}
static
{
System.out.println("Static block...");
}
}
public class StaticBlockDemo
{
public static void main(String [] args)
{
System.out.println("Main Method Executed ");
}
Here Foo.class file is not loaded into JVM Memory so static block of Foo class will
not be executed.
--------------------------------------------------------------
class Test
{
static int x;
static
{
x = 100;
System.out.println("x value is :"+x);
}
static
{
x = 200;
System.out.println("x value is :"+x);
}
static
{
x = 300;
System.out.println("x value is :"+x);
}
}
public class StaticBlockDemo1
{
public static void main(String[] args)
{
System.out.println("Main Method");
System.out.println(Test.x);
}
}
Note : If a class contains more than 1 static block then it will be executed from
top to bottom.
--------------------------------------------------------------
class Foo
{
static int x;
static
{
System.out.println("x value is :"+x);
}
}
static
{
a = 100;
System.out.println(a);
}
}
public class StaticBlockDemo3
{
public static void main(String[] args)
{
System.out.println("a value is :"+Demo.a);
}
}
Note : A blank static final field must be initialized through static block only.
--------------------------------------------------------------
class A
{
static
{
System.out.println("A");
}
{
System.out.println("B");
}
A()
{
System.out.println("C");
}
}
class B extends A
{
static
{
System.out.println("D");
}
{
System.out.println("E");
}
B()
{
System.out.println("F");
}
}
public class StaticBlockDemo4
{
public static void main(String[] args)
{
new B();
}
}
Note : Always Parant class will be loaded first then only Child class will be
loaded.
--------------------------------------------------------------
//illegal forward reference
class Demo
{
static
{
i = 100;
}
static int i;
}
Note : For static variable i, already memory is allocated in the prepare phase so
we can initialize (can perform write operation)
in the static block without pre-declaration.
--------------------------------------------------------------
class Demo
{
static
{
i = 100;
//System.out.println(i); //Invalid
System.out.println(Demo.i);
}
static int i;
}
Note : We can't write return statement in static and non static block
----------------------------------------------------------
public class StaticBlockDemo8
{
final static int x; //Blank static final field
static
{
m1();
x = 15;
}
static
{
System.out.println("static block");
}
{
System.out.println("Non static block");
}
Test()
{
super();
System.out.println("No Argument Constructor");
}
}
Note : First non static block, constructor then only static block will be executed.
--------------------------------------------------------------
Variable Memory Allocation and Initialization :
-------------------------------------------------
1) static field OR Class variable :
-----------------------------------
Memory allocation done at prepare phase of class loading and initialized with
default value even variable is final.
It will be initialized with Original value (If provided by user at the time of
declaration) at class initialization phase.
When JVM will shutdown then during the shutdown phase class will be un-loaded from
JVM memory so static data members are destroyed. They have long life.
When object is eligible for GC then object is destroyed and all the non static data
memebers are also destroyed with corresponding object. It has less life in
comparison to static data members becuase they belongs to object.
3) Local Variable
------------------
Memory allocation done at stack area (Stack Frame) and developer is responsible to
initialize the variable before use. Once metod execution is over, It will be
deleted from stack Frame henec it has shortest life.
4) Parameter variable
----------------------
Memory allocation done at stack area (Stack Frame) and end user is responsible to
pass the value at runtime. Once metod execution is over, It will be deleted from
stack Frame henec it has shortest life.
It was possible to write a java program without main method till JDK 1.6V. From JDK
1.7v onwards, at the time of loading the .class file JVM will verify the presence
of main method in the .class file. If main method is not available then it will
generate a runtime error that "main method not found in so so class".
--------------------------------------------------------------
How many ways we can load the .class file into JVM memory :
-----------------------------------------------------------
There are so many ways to load the .class file into JVM memory but the following
are the common examples :
javac Test.java
java Test
Here we are making a request to class loader sub system to load Test.class file
into JVM memory
4) By using inheritance
class Demo
{
static int x = 10;
static
{
System.out.println("Static Block of Demo class Executed!!! :"+x);
}
}
public class ClassLoading
{
public static void main(String[] args)
{
System.out.println("Main Method");
//new Demo();
System.out.println(Demo.x);
}
}
-------------------------------------------------------------
//Program that describes whenever we try to load sub class, first of all super
class will be loaded. [before parent, child can't exist]
class Alpha
{
static
{
System.out.println("Static Block of super class Alpha!!");
}
}
class Beta extends Alpha
{
static
{
System.out.println("Static Block of Sub class Beta!!");
}
}
class InheritanceLoading
{
public static void main(String[] args)
{
new Beta();
}
}
--------------------------------------------------------------
Loading the .class file by using Reflection API :
-------------------------------------------------
java.lang.Class class has provided a predefined static and factory method called
forName(String className), It is mainly used to load the given .class file at
runtime, The return type of this method is java.lang.Class
Program :
---------
package com.nit.iq; //FQN com.nit.iq.Sample
class Sample
{
static
{
System.out.println("Static Block");
}
}
public class DynamicLoading
{
public static void main(String[] args) throws Exception
{
Class.forName("com.nit.iq.Sample"); //FQN
}
}
java.lang.ClassNotFoundException :-
-----------------------------------------
It occurs when we try to load the required .class file at RUNTIME by using
Class.forName(String className) statement or loadClass() static of ClassLoader
class and if the required .class file is not available at runtime then we will get
an exception i.e java.lang.ClassNotFoundException
Note :- It does not have any concern at compilation time, at run time, JVM will
simply verify whether the required .class file is available or not available.
class Test
{
static
{
System.out.println("Static Block");
}
}
public class DynamicLoading
{
public static void main(String[] args) throws Exception
{
Class.forName("Employee");
}
}
class Sample
{
public void greet()
{
System.out.println("Hello Everyone");
}
}
public class NoClassDefFoundErrorDemo
{
public static void main(String[] args)
{
Sample s1 = new Sample();
s1.greet();
}
}
After compilation either delete Sample.class or put this .class file in another
folder[remove from the current folder]
--------------------------------------------------------------
** A static method does not act on instance variable directly why?
All the static members (static variable, static block, static method, static
nested inner class) are loaded/executed at the time of loading the .class file into
JVM Memory.
At class loading phase object is not created because object is created in the 2nd
phase i.e Runtime data area so at the TIME OF EXECUTION OF STATIC METHOD AT CLASS
LOADING PAHSE, NON STATIC VARIABLE WILL NOT BE AVAILABLE henec we can't access non
static variable from static context[static block, static method and static nested
inner class]
class Sample
{
private int x;
public Sample(int x)
{
this.x = x;
}
}
public class StaticDemo
{
public static void main(String[] args)
{
Sample s1 = new Sample(10);
Sample.access();
}
}
--------------------------------------------------------------
07-10-2024
-----------
Runtime Data Areas :
---------------------
It is also known as Memory Area.
Once a class is loaded then based on variable type method type it is divided into
different memory areas which are as follows :
1) Method Area
2) HEAP Area
3) Stack Area
4) PC Register
5) Native Method Stack
Method Area :
-------------
Whenever a class is loaded then the class is dumpped inside method area and returns
java.lang.Class class.
It provides all the information regarding the class like name of the class, name of
the package, static and non static fields available in the class, methods available
in the class and so on.
We have only one method area per JVM that means for a single JVM we have only one
Method area.
2 files :
---------
Test.java
----------
package com.ravi.method_area;
import java.util.Scanner;
ClassDescription.java
-----------------------
package com.ravi.method_area;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
Field and Method both the classes are providing getName() method to get the name of
the field and Method.
--------------------------------------------------------------
HEAP AREA :
-----------
Whenever we create an object in java then the properties and behavior of the object
are strored in a special memory area called HEAP AREA.
Whenever we call a method in java then internally one stack Frame will be created
to hold method related information.
class Alpha
{
int val;
ar[0] = am1;
System.out.println(ar[0].val);
System.out.println(ar[1].val);
}
return fa;
}
}
--------------------------------------------------------------
08-10-2024
-----------
PC Register :
-------------
It stands for Program counter Register.
Native method stack will hold the native method information in a separate stack.
---------------------------------------------------------------------
Execution Engine : [Interpreter + JIT Compiler]
Interpreter
------------
In java, JVM contains an interpreter which executes the program line by line.
Interpreter is slow in nature because at the time of execution if we make a mistake
at line number 9 then it will throw the execption at line number 9 and after
solving the execption again it will start the execution from line number 1 so it is
slow in execution that is the reason to boost up the execution java software people
has provided JIT compiler.
JIT Compiler :
--------------
It stands for just in time compiler. The main purpose of JIT compiler to boost up
the execution so the execution of the program will be completed as soon as
possible.
JIT compiler holds the repeated instruction like method signature, variables,
native method code and make it available to JVM at the time of execution so the
overall execution becomes very fast.
--------------------------------------------------------------
HAS-A Relation :
----------------
If we use any class as a property to another class then it is called HAS-A
relation.
class Engine
{
}
class Car
{
private Engine engine; //HAS-A relation
}
Association :
---------------
Association is a connection between two separate classes that can be built up
through their Objects.
The association builds a relationship between the classes and describes how much a
class knows about another class.
Example:-
One to One: A person can have only one PAN card
One to many: A Bank can have many Employees
Many to one: Many employees can work in single department
Many to Many: A Bank can have multiple customers and a customer can have multiple
bank accounts.
3 files :
----------
Student.java
-------------
package com.ravi.association;
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" +
studentName + ", studentMarks=" + studentMarks
+ "]";
}
Trainer.java
-------------
package com.ravi.association;
import java.util.Scanner;
if(id==obj.getStudentId())
{
System.out.println(obj);
}
else
{
System.err.println("Id is not matching");
}
}
}
AssociationDemo.java
----------------------
package com.ravi.association;
}
--------------------------------------------------------------
Composition (Strong reference) :
--------------------------------
Composition in Java is a way to design classes such that one class contains an
object of another class. It is a way of establishing a "HAS-A" relationship between
classes.
Composition represents a strong relationship between the containing class and the
contained class.If the containing object (Car object) is destroyed, all the
contained objects (Engine object) are also destroyed.
A car has an engine. Composition makes strong relationship between the objects. It
means that if we destroy the owner object, its members will be also destroyed with
it. For example, if the Car is destroyed the engine will also be destroyed as well.
Program Guidelines :
--------------------
One object can't exist without another object
We will not create two separate objects
3 files :
----------
Engine.java
------------
package com.ravi.composition;
@Override
public String toString() {
return "Engine [engineType=" + engineType + ", horsePower=" +
horsePower + "]";
}
}
Car.java
---------
package com.ravi.composition;
@Override
public String toString() {
return "Car [carName=" + carName + ", carModel=" + carModel + ",
engine=" + engine + "]";
}
CompositionDemo.java
---------------------
package com.ravi.composition;
}
Assignemnts :
--------------
Develop one program based on composition
MotherBoard and Laptop
Department and University.
--------------------------------------------------------------
Aggregation (Weak Referance) :
------------------------------
Aggregation in Java is another form of association between classes that represents
a "HAS-A" relationship, but with a weaker bond compared to composition.
In aggregation, one class contains an object of another class, but the contained
object can exist independently of the container. If the container object is
destroyed, the contained object can still exist.
3 files :
----------
College.java
-------------
package com.ravi.aggregation;
@Override
public String toString() {
return "College [collegeName=" + collegeName + ", collegeLocation=" +
collegeLocation + "]";
}
}
Student.java
-------------
package com.ravi.aggregation;
AggregationDemo.java
---------------------
package com.ravi.aggregation;
System.out.println();
package com.nit.m1;
class Hello
{
public static String out = "Hyderabad"; //HAS-A Relation
}
}
--------------------------------------------------------------
***Polymorphism :
-----------------
Poly means "many" and morphism means "forms".
In our real life a person or a human being can perform so many task, in the same
way in our programming languages a method or a constructor can perform so many
task.
Eg:-
--------------------------------------------------------------
09-10-2024
-----------
Types of Polymorphism :
-----------------------
Polymorphism can be divided into two types :
In static polymorphism, compiler has very good idea that which method is invoked
depending upon METHOD PARAMETER.
Here the binding of the method is done at compilation time so, it is known as early
binding.
2) Dynamic Polymorphism
-----------------------
The polymorphism which exist at runtime is called Dynamic polymorphim Or Runtime
Polymorphism.
*Here compiler does not have any idea about method calling, at runtime JVM will
decide which method will be invoked depending upon CLASS TYPE OBJECT.
Here method binding is done at runtime so, it is also called Late Binding.
-----------------------------------------------------------------
Method Overloading :
--------------------
Writing two or more methods in the same class or even in the super and sub class in
such a way that the method name must be same but the argument must be different.
While Overloading a method we can change the return type of the method.
If parameters are same but only method return type is different then it is not an
overloaded method.
Method overloading is possible in the same class as well as super and sub class.
While overloading the method the argument must be different otherwise there will be
ambiguity problem.
IQ :
----
Can we overload the main method/static method ?
Yes, we can overload the main method OR static method but the execution of the
program will start from main method which accept String [] array as a parameter.
Note :- The advantage of method overloading is same method name we can reuse for
different functionality for refinement of the method.
Example :
----------
public void makePayment(Cash c)
{
}
public void makePayment(UPI c)
{
}
public void makePayment(CreditCard c)
{
}
-----------------------------------------------------------------
2 files :
----------
Addition.java
-------------
//Program on Constructor Overloading
package com.ravi.constructor_overloading;
Main.java
---------
package com.ravi.constructor_overloading;
}
-----------------------------------------------------------------
Program on Method Overloading :
-------------------------------
2 Files :
---------
Sum.java
---------
package com.ravi.method_overload;
Main.java
----------
package com.ravi.method_overload;
2 files :
----------
Test.java
----------
package com.ravi.var_args;
Main.java
----------
package com.ravi.var_args;
}
---------------------------------------------------------------
//Program to add sum of parameters passes inside a method using var args
2 files :
---------
Test.java
---------
package com.ravi.var_args1;
}
}
Main.java
---------
package com.ravi.var_args1;
}
---------------------------------------------------------------
Program that describes Var args must be only one and last argument .
2 files :
---------
Test.java
---------
package com.ravi.var_args2;
/*
* public void accept(float ...x, int ...y) { }
*
* public void accept(int ...x, int y) { }
*
* public void accept(int...x, int ...y) {}
*/
for (int z : y)
{
System.out.println(z);
}
}
}
Main.java
---------
package com.ravi.var_args2;
}
}
---------------------------------------------------------------
//Program to show that var args can hold hetrogeneous elements
Test.java
----------
package com.ravi.var_args3;
Main.java
---------
package com.ravi.var_args3;
}
---------------------------------------------------------------
Wrapper classes in java :
-------------------------
We have 8 primitive data types in java i.e byte, short, int, long and so on.
If we remove these 8 primitive data types then only java can become pure object
oriented language.
On these primitive data types, we can't assign null or we can't invoke a method.
These primitive data types are unable to move in the network, only objects are
moving in the network.
To avoid the above said problems, From JDK 1.5v, java software people has provided
the following two concepts :
a) Autoboxing
b) Unboxing
Autoboxing
--------------
When we convert the primitive data types into corresponding wrapper object then it
is called Autoboxing as shown below.
int y = 15;
Integer i = y; //From 1.5 onwards compiler takes care
System.out.println(i);
}
}
--------------------------------------------------------------
public class AutoBoxing2
{
public static void main(String args[])
{
byte b = 12;
Byte b1 = Byte.valueOf(b);
System.out.println("Byte Object :"+b1);
short s = 17;
Short s1 = Short.valueOf(s);
System.out.println("Short Object :"+s1);
int i = 90;
Integer i1 = Integer.valueOf(i);
System.out.println("Integer Object :"+i1);
long g = 12;
Long h = Long.valueOf(g);
System.out.println("Long Object :"+h);
float f1 = 2.4f;
Float f2 = Float.valueOf(f1);
System.out.println("Float Object :"+f2);
double k = 90.90;
Double l = Double.valueOf(k);
System.out.println("Double Object :"+l);
char ch = 'A';
Character ch1 = Character.valueOf(ch);
System.out.println("Character Object :"+ch1);
boolean x = true;
Boolean x1 = Boolean.valueOf(x);
System.out.println("Boolean Object :"+x1);
}
}
In the above program we have used 1.4 approach so we are converting primitive to
wrapper object manually.
--------------------------------------------------------------
Overloaded valueOf() method :
-----------------------------
1) public static Integer valueOf(int x) : It will convert the given int value into
Integer Object.
//Integer.valueOf(String str)
//Integer.valueOf(String str, int radix/base)
public class AutoBoxing3
{
public static void main(String[] args)
{
Integer a = Integer.valueOf(15);
Integer b = Integer.valueOf("25");
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
---------------------------------------------------------------
public class AutoBoxing4
{
public static void main(String[] args)
{
Integer i1 = new Integer(100);
Integer i2 = new Integer(100);
System.out.println(i1==i2);
Integer a1 = Integer.valueOf(15);
Integer a2 = Integer.valueOf(15);
System.out.println(a1==a2);
}
}
--------------------------------------------------------------
Converting primtive to String type :
------------------------------------
Integer class has provided a static method toString() which will convert the int
value into String type.
Wrapper Primitive
Object type
---------- ----------
Byte - byte
Short - short
Integer - int
Long - long
Float - float
Double - double
Chracter - char
Boolean - boolean
-----------------------------------------------------------------
We have total 8 Wrapper classes.
Among all these 8, 6 Wrapper classes are the sub class of Number class which
represent numbers (either decimal OR non decimal)
so all the following six wrapper classes (Which are sub class of Number class) are
providing the following common methods.
Example :
package com.ravi.basic;
Long a = 12L;
Double d = 90D;
Double d1 = 90.78;
Float f = 12F;
}
}
---------------------------------------------------------------
Ambiguity issue while overloading a method :
---------------------------------------------
When we overload a method then compiler is selecting appropriate method among the
available methods based on the following types.
In order to solve the ambiguity issue while overloading a method compiler has
provided the following rules :
}
}
}
}
Here char will be executed because char is the most specific type
--------------------------------------------------------------
class Test
{
public void accept(short ...d)
{
System.out.println("short");
}
public void accept(char ...d)
{
System.out.println("char");
}
}
public class AmbiguityIssue {
}
}
Note : Here int will be executed because int is the nearest type
--------------------------------------------------------------
class Test
{
public void accept(int d, long l)
{
System.out.println("int-long");
}
public void accept(long s, int i)
{
System.out.println("long-int");
}
}
public class AmbiguityIssue {
}
}
Here Object will be executed
--------------------------------------------------------------
class Test
{
public void accept(Object s)
{
System.out.println("Object");
}
public void accept(String s)
{
System.out.println("String");
}
}
public class AmbiguityIssue {
}
}
String will executed because String is the nearest type.
--------------------------------------------------------------
class Test
{
public void accept(Object s)
{
System.out.println("Object");
}
public void accept(String s)
{
System.out.println("String");
}
public void accept(Integer i)
{
System.out.println("Integer");
}
}
public class AmbiguityIssue {
}
}
Here Beta will be executed.
--------------------------------------------------------------
class Test
{
public void accept(Number s)
{
System.out.println("Number");
}
public void accept(Integer i)
{
System.out.println("Integer");
}
}
public class AmbiguityIssue {
}
}
}
}
Here Autoboxing will be executed.
--------------------------------------------------------------
16-10-2024
-----------
***Method Overriding :
----------------------
Writing two or more non static methods in super and sub class in such a way that
method name along with method parameter (Method Signature) must be same is called
Method Overriding.
Generally we can't change the return type of the method while overriding a method
but from JDK 1.5v there is a concept called Co-variant (In same direction) through
which we can change the
return type of the method.
Example :
---------
class Super
{
public void m1()
{
}
}
class Sub extends Super
{
public void m1() //Overridden Method
{
}
}
Downcasting :
-------------
By default we can't assign super class object to sub class reference variable.
Even if we type cast Animal to Lion type then compiler will allow but at runtime
JVM will not convert Animal object (Generic type) into Lion object (Specific type)
and it will throw an exception java.lang.ClassCastException
class Animal
{
public void eat()
{
System.out.println("Generic Animal is eating");
}
}
class Lion extends Animal
{
public void eat()
{
System.out.println("Lion Animal is eating");
}
}
class Horse extends Animal
{
public void eat()
{
System.out.println("Horse Animal is eating");
}
}
}
-----------------------------------------------------------------
@Override Annotation :
--------------------------
In Java we have a concept called Annotation, introduced from JDK 1.5 onwards. All
the annotations must be start with @ symbol.
If we use @Override annotation before the name of the overridden method in the sub
class and if the method is not available in the super class then it will generate a
compilation error so it is different from comments because comment will not
generate any kind of compilation error if method is not an overridden method, so
this is how it is different from comment.
package com.ravi.mo;
class Bird
{
public void fly()
{
System.out.println("Genric Bird is flying");
}
}
class Parrot extends Bird
{
@Override
public void fly()
{
System.out.println("Parrot Bird is flying");
}
}
class Peacock extends Bird
{
@Override
public void fly()
{
System.out.println("Paecock Bird is flying");
}
}
}
----------------------------------------------------------------
Method Overloading is also possible in super and sub class as shown below
package com.ravi.mo;
class Bird
{
public void fly()
{
System.out.println("Genric Bird is flying");
}
}
class Parrot extends Bird
{
//Method Overloading
public int fly(double height)
{
System.out.println("Parrot is flying with :"+height);
return 0;
}
@Override
public void roam()
{
System.out.println("Parrot Bird is roamig");
}
}
public class MethodOverridingDemo1 {
}
----------------------------------------------------------------
18-10-2024
-----------
Variable Hiding concept in upcasting :
---------------------------------------
class Super
{
int x = 100;
}
class Sub exetnds Super
{
int x = 200; //Variable Hiding
}
Only non static methods are overridden in java but not the variables[variables are
not overridden in java] because behavior will change but not the
property(variable).
Note : In upcasting variable will be always executed besed on the current reference
class variable.
package com.ravi.method_overriding;
class Vehicle
{
protected String name = "Generic Vehicle";
@Override
public String run()
{
return "Car Vehicle is running";
}
}
public class VariableHiding
{
public static void main(String[] args)
{
Vehicle v = new Car();
System.out.println(v.name+" : "+v.run());
System.out.println(".................");
Car c1 = new Car();
Vehicle v1 = c1;
System.out.println(c1.name +" : "+v1.name);
}
}
-----------------------------------------------------------------
Can we override private method ?
--------------------------------
No, We can't override private method because private methods are not visible (not
available) to the sub class hence we can't override.
We can't use @Override annotation on private method of sub class because it is not
overridden method, actually it is re-declared by sub class developer.
package com.ravi.method_overriding;
class Super
{
private void m1()
{
System.out.println("Private method of super class");
}
}
class Sub extends Super
{
//It is not an overridden method
private void m1() //Re-declare m1 method is sub class
{
System.out.println("Private method of Sub class");
}
}
Note :- private method of super class is not available or not inherited in the sub
class so if the sub class declare the method with same signature then it is not
overridden method, actually it is re-declared in the sub class.
-----------------------------------------------------------------
Role of access modifier while overriding a method :
---------------------------------------------------
While overriding the method from super class, the access modifier of sub class
method must be greater or equal in comparison to access modifier of super class
method otherwise we will get compilation error.
**So the conclusion is we can't reduce the visibility of the method while
overriding a method.
Note :- private method is not availble (visible) in sub class so it is not the part
of method overriding.
package com.ravi.method_overriding;
class RBI
{
public void loan()
{
System.out.println("Instruction to provide loan");
}
}
class SBI extends RBI
{
@Override
protected void loan() //error due to protected
{
System.out.println("SBI provides loan @ 9.2%");
}
}
public class AccessibilityLevel {
class Animal
{
public void sleep()
{
}
}
}
}
Note : error, return type int is not compaitable with void.
----------------------------------------------------------------
But from JDK 1.5 onwards we can change the return type of the method in only one
case that the return type of both the METHODS(SUPER AND SUB CLASS METHODS) MUST BE
IN INHERITANCE RELATIONSHIP (IS-A relationship so it is compatible) called Co-
Variant as shown in the program below.
Note :- Co-variant will not work with primitive data type, it will work only with
classes.
class Alpha
{
}
class Beta extends Alpha
{
}
class Animal
{
import java.io.IOException;
class Alpha
{
public Object m1()
{
System.out.println("Super class m1 method");
return new String();
}
}
class Beta extends Alpha
{
public Double m1()
{
System.out.println("Sub class m1 method");
return null;
}
}
}
----------------------------------------------------------------
21-10-2024
-----------
package com.ravi.co_variant;
class Vehicle
{
public Vehicle run()
{
System.out.println("Generic Vehicle is Running");
return this;
}
}
class Car extends Vehicle
{
@Override
public Car run()
{
System.out.println("Car Vehicle is Running");
return this;
}
}
}
----------------------------------------------------------------
While working with co-variant (In the same direction), sub class method return type
object, if we can assign to super class method return then only it is compatible
and it is co-variant as shown in the program.
package com.ravi.co_variant;
class Bird
{
public Object fly()
{
System.out.println("Generic Bird is flying");
return null;
}
}
class Sparrow extends Bird
{
@Override
public String fly()
{
System.out.println("Sparrow Bird is flying");
return "NIT";
}
}
Note : According to Liskov substitution principle (LSP), super class object can be
replace by sub class object but to support co-variant (In the same direction) sub
class object we can assign super class object i.e super class methdo return type
i.e in one direction.
----------------------------------------------------------------
**What is Method Hiding in java ?
OR
Can we override static method ?
OR
Can we override main method ?
Case 1 :
--------
A public static method of super class by default available to sub class so, from
sub class we can call super class static method with the help of Class name as well
as object reference as shown in the below program
class Super
{
public static void m1()
{
System.out.println("Static Method of Super class..");
}
}
class Sub extends Super
{
}
}
}
----------------------------------------------------------------
Case 2 :
-------
We can't override a static method with non static method because static method
belongs to class and non static method belongs to object, If we try to override
static method with non static method then it will generate an error i.e overridden
method is static as shown below.
class Super
{
public static void m1()
{
System.out.println("Static Method of Super class..");
}
}
class Sub extends Super
{
public void m1() //error
{
System.out.println("Non Static Method of Sub class..");
}
}
}
----------------------------------------------------------------
Case 3 :
--------
We can't override any non static method with static method, If we try then it will
generate an error, Overriding method is static.
class Super
{
public void m1()
{
System.out.println("Non Static Method of Super class..");
}
}
class Sub extends Super
{
public static void m1() //error
{
System.out.println("Static Method of Sub class..");
}
}
}
}
So, the conclusion is we cannot overide static with non static method as well as
non-static with static method because static method belongs to class and non-static
method belongs to object.
----------------------------------------------------------------
Case 4 :
-------
Program that describes method hiding as well as sub class method can't hide super
class method because return type is not compaitable
class Super
{
public static void m1()
{
System.out.println("Non Static Method of Super class..");
}
}
class Sub extends Super
{
public static int m1()
{
System.out.println("Static Method of Sub class..");
return 0;
}
}
}
}
class Animal
{
public static void m1()
{
System.out.println("Animal");
}
}
class Dog extends Animal
{
//Method Hiding
public static void m1()
{
System.out.println("Dog");
}
}
Note : Here we assign Dog object or Horse Object, Output will be same i.e Animal.
Note : static variable, instance variable and static method of super class are not
overridden so we will get super class output.
----------------------------------------------------------------
Progrm that describes Polymorphic behaviour of sub classes :
-----------------------------------------------------------
package com.ravi.polymorphic_behavior;
class Animal
{
public void sleep()
{
System.out.println("Generic Animal is sleeping");
}
}
class Lion extends Animal
{
@Override
public void sleep()
{
System.out.println("Lion is sleeping");
}
}
class Dog extends Animal
{
@Override
public void sleep()
{
System.out.println("Dog is sleeping");
}
}
public class AnimalDemo
{
public static void main(String[] args)
{
Animal lion = new Lion();
Animal dog = new Dog();
callSleepingAnimal(lion);
callSleepingAnimal(dog);
Note : From above program it is clear that based on the runtime object appropriate
method is invoked.
---------------------------------------------------------------
package com.ravi.polymorphic_behavior;
class Animal
{
public void sleep()
{
System.out.println("Generic Animal is sleeping");
}
}
class Lion extends Animal
{
@Override
public void sleep()
{
System.out.println("Lion is sleeping");
}
}
class Dog extends Animal
{
@Override
public void sleep()
{
System.out.println("Dog is sleeping");
}
}
public class AnimalDemo
{
public static void main(String[] args)
{
Animal lion = new Lion();
Animal dog = new Dog();
callSleepingAnimal(lion);
callSleepingAnimal(dog);
class Person
{
public int getAge()
{
return 32;
}
}
----------------------------------------------------------------
package com.ravi.dynamic_method_dispatch;
class Person
{
public int getAge()
{
return 32;
}
}
public class DynamicMethodDispatch
{
public static void main(String[] args)
{
new Student().printInfo();
}
}
---------------------------------------------------------------
package com.ravi.dynamic_method_dispatch;
class Bird
{
protected int weathers = 2;
public class IQ {
}
----------------------------------------------------------------
instanceof operator :
---------------------
It is a relational operator so it returns boolean value.
It is also a keyword.
It is used to describe whether a reference variable is holding an object of
particular type or not.
There must be an IS-A relation between reference variable and partcular class OR
interface type.
It is used to avoid java.lang.ClassCastException.
Programs :
-----------
package com.ravi.instance_of;
class Bird
{
}
class Fish
{
}
}
----------------------------------------------------------------
package com.ravi.instance_of;
class Test
{
}
---------------------------------------------------------------
package com.ravi.instance_of;
}
----------------------------------------------------------------
package com.ravi.instance_of;
class A{}
}
================================================================
package com.ravi.polymorphic_behavior;
class Animal
{
public void sleep()
{
System.out.println("Generic Animal is sleeping");
}
}
class Lion extends Animal
{
@Override
public void sleep()
{
System.out.println("Lion is sleeping");
}
}
class Dog extends Animal
{
@Override
public void sleep()
{
System.out.println("Dog is sleeping");
}
}
================================================================
*What is the limitation of 'new' keyword ?
OR
What is the difference between new keyword and newInstance() method?
OR
How to create the Object for the classes which are coming dynamically from the
database or from some file at runtime.
The limitation with new keyword is, It demands the class name at the begning or at
the time of compilation so new keyword is not suitable to create the object for the
classes which are coming from database or files at runtime dynamically.
In order to create the object for the classes which are coming at runtime from
database or files, we should use newInstance() method available in java.lang.Class
class.
Methods :
----------
public Object newInstance() : Predefined non static method of
java.lang.Class. It is used to
create the object for dynmacilly
loaded classes.
public native java.lang.Class getClass() :Predefined non static method of Object
class.
----------------------------------------------------------------
class Student
{
}
class Employee
{
}
public class ObjectAtRuntime
{
public static void main(String[] args) throws Exception
{
Object obj = Class.forName(args[0]).newInstance();
System.out.println("Object created for :"+obj.getClass().getName());
}
}
Methods :
---------
Note : We can pass any class at runtime, newInstance() method will create the
Object.
----------------------------------------------------------------
class Ravi
{
public void hi()
{
System.out.println("Hello Hyderabad");
}
}
class Sample
{
public void greet()
{
System.out.println("Hello India");
}
}
public class ObjectAtRuntime1
{
public static void main(String[] args) throws Exception
{
Object obj = Class.forName(args[0]).newInstance();
}
}
===============================================================
final keyword in java :
-----------------------
It is used to provide some kind of restriction in our program.
We can use final keyword in ways 3 ways in java.
We should declare a class as a final if the composition of the class (logic of the
class) is very important and we don't want to share the feature of the class to
some other developer to modify the original behavior of the existing class, In that
situation we should declare a class as a final.
Declaring a class as a final does not mean that the variables and methods declared
inside the class will also become as a final, only the class behavior is final that
means we can modify the variables value as well as we can create the object for the
final classes.
Note :- In java String and All wrapper classes are declared as final class.
--------------------------------------------------------------
final class A
{
private int x = 100;
}
}
Note : If a class contains private constructor then we should declare that class
with final access modifier.
---------------------------------------------------------------
Sealed class in Java :
-----------------------
It is a new feature introduced from java 15v (preview version) and become the
integral part of java from 17v.
It is one kind of restriction that describes which classes and interfaces can
extend or implement from Sealed class Or interface.
It is similar to final keyword with less restriction because here we can permit the
classes to extend from the original Sealed class.
The class which is inheriting from the sealed class must be final, sealed or non-
sealed.
3) permits : We can provide permission to the sub classes, which are inheriting
through Sealed class.
4) final : we can declare permitted sub class as final so, it cannot be extended
further.
---------------------------------------------------------------
Programs :
-----------
SealedDemo1.java
------------------
package com.ravi.m1;
}
--------------------------------------------------------------
SealedDemo2.java
-----------------
package com.ravi.m1;
}
---------------------------------------------------------------
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;
Note : Here Program will compile and execute because private method of super class
is not available to sub class.
--------------------------------------------------------------
3) To declare a variable/Field as a final :
--------------------------------------------
In older langugaes like C and C++ we use "const" keyword to declare a constant
variable but in java, const is a reserved word for future use so instead of const
we should use "final" keyword.
class A
{
final int A = 10;
public void setData()
{
A = 10; //error
System.out.println("A value is :"+A);
}
}
class FinalVarEx
{
public static void main(String[] args)
{
A a1 = new A();
a1.setData();
}
}
--------------------------------------------------------------
class Student
{
private int rollNumber;
private String studentName;
}
class FinalVarEx1
{
public static void main(String[] args)
{
final Student s1 = new Student(111,"Scott");
s1 = new Student(222,"Smith"); //error
}
}
--------------------------------------------------------------
24-10-2024
----------
Nested classes in java :
-------------------------
In java it is possible to define a class (inner class) inside another class (outer
class) called nested class.
interface Drawable
{
//interface
}
enum Direction
{
record Student()
{
@interface Hello
{
}
-------------------------------------------------------------
package com.ravi.inner_class_concept;
public interface Demo2
{
public class Test
{
}
enum Direction
{
}
record Student()
{
@interface Hello
{
}
--------------------------------------------------------------
package com.ravi.inner_class_concept;
interface Printable
{
record Student()
{
@interface Hello
{
}
--------------------------------------------------------------
package com.ravi.inner_class_concept;
}
interface Drawable
{
enum Season
{
@interface Hello
{
}
--------------------------------------------------------------
package com.ravi.inner_class_concept;
interface Moveable
{
enum Color
{
record Employee()
{
}
--------------------------------------------------------------
Inner classes in Java create a strong encapsulation and HAS-A relationship
between the inner class and its outer class.
We can apply private, default, protected, public, abstract and final modifiers on
non static nested class.
With the help of outer class we can load inner class also, If inner class contains
non static member then object is required for Outer class as well as inner class.
Inner class we can't represent directly, we need to take the support of Outer class
because inner class is a non static member of Outer class.
class Inner
{
public void displayValue()
{
System.out.println("Value of a is " + a);
}
}
}
public class Test1
{
public static void main(String... args)
{
Outer out = new Outer();
in.displayValue();
}
}
Note : An inner class can directly access the private data of Outer class.
--------------------------------------------------------------
class MyOuter
{
private int x = 7;
public void makeInner()
{
MyInner in = new MyInner();
System.out.println("Inner y is "+in.y);
in.seeOuter();
}
class MyInner
{
private int y = 15;
public void seeOuter()
{
System.out.println("Outer x is "+x);
}
}
}
public class Test2
{
public static void main(String args[])
{
MyOuter m = new MyOuter();
m.makeInner();
}
}
-------------------------------------------------------------
Variable Shadow in Nested class :
----------------------------------
If outer class and inner class variable names are same then inner class variable
will be access with inner class object (Variable Shadow bacause in the same scope),
If we want to access Outer class variable from inner class then we need
ClassName.this.variableName.
package com.ravi.inner_class;
class Outer1
{
private int x = 100;
}
}
public class InnerClassDemo2
{
public static void main(String[] args)
{
Outer1.Inner1 in = new Outer1().new Inner1();
in.show();
}
}
--------------------------------------------------------------
class MyOuter
{
private int x = 15;
class MyInner
{
public void seeOuter()
{
System.out.println("Outer x is "+x);
}
}
}
public class Test3
{
public static void main(String args[])
{
//Creating inner class object in a single line
MyOuter.MyInner m = new MyOuter().new MyInner();
m.seeOuter();
}
}
--------------------------------------------------------------
class MyOuter
{
static int x = 7;
class MyInner
{
public static void seeOuter() //MyInner.seeOuter();
{
System.out.println("Outer x is "+x);
}
}
}
//Inner class
private class Engine
{
private int horsePower;
myCar.startCar();
myCar.stopCar();
}
}
-----------------------------------------------------------------
25-10-2024
-----------
class Laptop
{
private String brand;
private String model;
private Motherboard motherboard;
laptop.switchOn();
}
}
--------------------------------------------------------------
class Person
{
private String name;
private int age;
private Heart heart;
public Heart()
{
this.beatsPerMinute = 72;
}
}
}
}
public class Test8
{
public static void main(String[] args)
{
cs.displayDepartmentDetails();
ee.displayDepartmentDetails();
}
}
---------------------------------------------------------------
class OuterClass
{
private int x = 200;
class InnerClass
{
public void display() //Inner class display method
{
System.out.println("Inner class display method");
}
new OuterClass().display();
}
}
Note : From inner class object, we can access inner class display() method, If we
want to call Outer class display method
then Outer class Object is reqd.
---------------------------------------------------------------
class OuterClass
{
int x;
abstract class InnerClass
{
int x;
}
}
public class Test10
{
}
Note : In a non static nested inner class we can apply private, default, protected,
public, abstract and final modifiers.
---------------------------------------------------------------
static nested inner class :
----------------------------
It is class level nested class.
If we decalre a static class inside another class then it is called Static nested
inner class.
For static nested inner class, Outer class object is not required.
If static nested inner class contains only static memebr then inner class object is
also not required.
If static nested inner class contains non static member then inner class object is
required.
We cann't access non static member of Outer class from static nested inner class
[Static context].
---------------------------------------------------------------
//static nested inner class
class BigOuter
{
static class Nest //static nested inner class
{
void go() //Instance method of static inner class
{
System.out.println("Hello welcome to static nested class");
}
}
}
class Test11
{
public static void main(String args[])
{
BigOuter.Nest n = new BigOuter.Nest();
n.go();
}
}
---------------------------------------------------------------
class Outer
{
static int x = 15;
}
}
}
class Test13
{
public static void main(String args[])
{
Outer.Inner.msg();
}
}
---------------------------------------------------------------
class Outer
{
int x=15; //error (not possible because try to access instance variable)
static class Inner
{
void msg()
{
System.out.println("x value is "+x);
}
}
}
class Test14
{
public static void main(String args[])
{
Outer.Inner obj=new Outer.Inner();
obj.msg();
}
}
---------------------------------------------------------------
package com.ravi.m1;
class Outer
{
static int x = 200;
static
{
System.out.println("Outer class static block");
}
Here We are accessing inner class static method from main method so, first of all
inner class static block will be executed and from inner class static method, we
are accessing Outer class static variable so Outer class will be loaded and static
block will be executed.
===============================================================
Method level inner class :
--------------------------
Local OR Method Local Inner class :
------------------------------------
If we define a class with class name inside the method body then it is called Local
OR Method local inner class.
The Scope of this method local inner class within the same stack frame only so we
can't use local inner class outside of the method.
We can't apply any kind of access modifier on method local inner class except final
and abstract.
---------------------------------------------------------------
//program on method local inner class
class MyOuter3
{
private String x = "Outer class private data";
}
public class Test15
{
public static void main(String args[])
{
MyOuter3 m = new MyOuter3();
m.doSttuff();
}
}
---------------------------------------------------------------
//local inner class we can't access outside of the method
class MyOuter3
{
private String z = "Outer class Data";
class MyInner
{
String z = "CLASS instance variable";
public void seeOuter()
{
System.out.println("Outer x is "+MyOuter3.this.z);
System.out.println("Class variable z is : "+this.z);
System.out.println("Local variable is : "+x);
}
}
}
MyInner mi = new MyInner();
mi.seeOuter();
}
public class Test16
{
public static void main(String args[])
{
MyOuter3 m = new MyOuter3();
m.doSttuff();
}
}
Note : Method local inner class we can't access outside of the method.
--------------------------------------------------------------
26-10-2024
----------
Anonymous inner class
----------------------
If we decalre a class inside a method without any name then it
is called Anonymous inner class.
The anonymous inner class declaration (without name) and object creation both will
be done in the same line.
We can create only object for anonymous inner class so it is a singleton class.
*A normal class can extend a class as well as implement many number of interfaces
but an anonymous inner can either extend
a class or implement an interface.
Inside an anoymous inner class we can write static and non static variable, static
and non static block. We can't define constructor as well as we can't declare
abstract method.
--------------------------------------------------------------
package com.ravi.anonymous_demo;
class Vehicle
{
public void run()
{
System.out.println("Generic Vehicle is Running");
}
}
}
---------------------------------------------------------------
package com.ravi.anonymous_demo;
class Card
{
public void payment()
{
System.out.println("Payment through Generic card");
}
creditCard.payment();
}
=============================================================
Abstraction : [Hiding the complexcity]
---------------------------------------
Showing the essential details without showing the background details is called
abstraction.
=============================================================
In java whenever action is common but implementations are different then we should
use abstract method, Generally we declare abstract method in the super class and
its implementation must be provided in the sub classes.
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.
Note :- We can't declare an abstract method as final, private and static (illegal
combination of modifiers)
--------------------------------------------------------------
AbstractDemo1.java
-------------------
abstract class Bird
{
public abstract void fly();
}
class Parrot extends Bird
{
@Override
public void fly()
{
System.out.println("Parrot Bird is flying");
}
}
class Sparrow extends Bird
{
@Override
public void fly()
{
System.out.println("Sparrow Bird is flying");
}
}
public Bike()
{
System.out.println("Bike class Constructor");
}
}
-------------------------------------------------------------
28-10-2024
------------
How to initialize the abstract class properties :
--------------------------------------------------
package com.ravi.abstract_demo;
abstract class Shape
{
protected String shapeType;
@Override
public void draw()
{
System.out.println("Drawing "+shapeType);
}
}
@Override
public void draw()
{
System.out.println("Drawing "+shapeType);
}
}
}
-------------------------------------------------------------
IQ :
----
What is the advantage of taking instance variable OR writing constructor inside
abstract class ?
As we know we can't create an object for abstract class but still we can take
object properties (Instance variable) and
constructor, To call the abstract class constructor for initialization of instance
variable we should use sub class object (Using super keyword)
-------------------------------------------------------------
Anonymous inner class using abstract method :
----------------------------------------------
package com.ravi.abstract_demo;
}
------------------------------------------------------------
package com.ravi.abstract_demo;
}
}
Note : From the above program it is clear that all the abstract methods must be
overridden in the sub classes otherwise sub class will become as an abstract class
so, object will not be created.
-------------------------------------------------------------
Polymorphism with Array :
--------------------------
package com.ravi.abstract_demo;
animalCheck(dogs);
System.out.println("..........");
animalCheck(lions);
System.out.println("..........");
animalCheck(horses);
Upto JDK 1.7 an interface contains only abstract method that means there is a
guarantee that inside an interfcae we don't have concrete or general or instance
methods.
From java 8 onwards we have a facility to write default and static methods.
By using interface we can achieve 100% abstraction concept because it contains only
abstract methods.
In order to implement the member of an interface, java software people has provided
implements keyword.
All the methods declared inside an interface is by default public and abstract so
at the time of overriding we should apply public access modifier to sub class
method.
All the variables declared inside an interface is by default public, static and
final.
We should override all the abstract methods of interface to the sub classes
otherwise the sub class will become as an abstract class hence object can't be
created.
We can't create an object for interface, but reference can be created.
-----------------------------------------------------------
package com.ravi.interface_demo;
interface Moveable
{
int SPEED = 120; //public + static + final
}
-----------------------------------------------------------
BankApplication.java
---------------------
package com.ravi.interface_demo;
interface Bank
{
void deposit(double amount);
void withdraw(double amount);
}
class Customer implements Bank
{
private double balance;
@Override
public void deposit(double amount)
{
if(amount <=0)
{
System.err.println("Amount can't be deposited!!");
}
else
{
this.balance = this.balance + amount;
System.out.println("Amount after deposit is :"+this.balance);
}
}
@Override
public void withdraw(double amount)
{
if(amount > this.balance)
{
System.err.println("Insufficient Balance!!");
}
else
{
this.balance = this.balance - amount;
System.out.println("Amount after Withdraw is :"+this.balance);
}
}
}
public class BankApplication
{
public static void main(String[] args)
{
Bank b = new Customer(1000);
b.deposit(10000);
b.withdraw(5000);
}
-----------------------------------------------------------
Program on loose coupling :
----------------------------
Loose Coupling :- If the degree of dependency from one class object to another
class is very low then it is called loose coupling. [interface]
6 files :
-----------
HotDrink.java
---------------
package com.ravi.loose_coupling;
Tea.java
---------
package com.ravi.loose_coupling;
Coffee.java
------------
package com.ravi.loose_coupling;
Restaurant.java
---------------
package com.ravi.loose_coupling;
Horlicks.java
---------------
package com.ravi.loose_coupling;
public class Horlicks implements HotDrink
{
@Override
public void prepare()
{
System.out.println("Preparing Horlicks");
LooseCoupling.java
-------------------
package com.ravi.loose_coupling;
}
-----------------------------------------------------------
It is always better to take method return type as interface so we can return any
implementer class object as shown in the example below
The sub class constructor super keyword will move to Object class constructor.(29-
OCT)
package com.ravi.mi;
interface A
{
void m1();
}
interface B
{
void m1();
}
}
-----------------------------------------------------------
Extending interface :
---------------------
One interface can extends another interface, it cannot implement because interface
cannot provide implementation for the abstract method.
package com.ravi.interface_demo;
interface Alpha
{
void m1();
}
interface Beta extends Alpha
{
void m2();
}
@Override
public void m2()
{
System.out.println("M2 method Implemented!!");
}
}
}
-----------------------------------------------------------
interface from JDK 1.8 onwards :
--------------------------------
Limitation of abstract method :
OR
Maintenance problem with interface in an Industry upto JDK 1.7
The major maintenance problem with interface is, if we add any new abstract method
at the later stage of development inside an existing interface then all the
implementer classes have to override that abstract method otherwise the
implementer class will become as an abstract class so it is one kind of boundation.
We need to provide implementation for all the abstract methods available inside an
interface whether it is required or not?
To avoid this maintenance problem java software people introduced default method
inside an interface.
--------------------------------------------------------------
What is default Method inside an interface?
------------------------------------------------
default method is just like concrete method which contains method body and we can
write inside an interface from java 8 onwards.
*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.
default method we can write inside an interface only but not inside a class.
-------------------------------------------------------------
4 files :
----------
Vehicle.java(I)
----------------
package java8;
Car.java(C)
-----------
package java8;
@Override
public void horn()
{
System.out.println("Car has horn");
}
@Override
public void digitalMeter()
{
System.out.println("Car has Digital Meter Facility");
}
}
Bike.java(C)
-------------
package java8;
@Override
public void horn()
{
System.out.println("Bike has horn");
}
Main.java
----------
package java8;
}
}
Note :- abstract method is a common method which is used to provide easiness to the
programmer so, by looking the abstract method we will get confirmation that this is
common behavior for all the sub classes and it must be implemnted in all the sub
classes.
MethodPriority.java
-------------------
package java8;
interface A
{
default void m1()
{
System.out.println("Default Method of interface A");
}
}
class B
{
public void m1()
{
System.out.println("Concrete Method of class B");
}
}
}
public class MethodPriority
{
public static void main(String[] args)
{
C c1 = new C();
c1.m1();
package java8;
interface Alpha
{
public default void m1()
{
System.out.println("Default method of Alpha interface");
}
}
interface Beta
{
public default void m1()
{
System.out.println("Default method of Beta interface");
}
}
}
--------------------------------------------------------------
What is static method inside an interface?
------------------------------------------
We can define static method inside an interface from java 1.8 onwards.
static method is only available inside the interface, It is not available to the
implementer classes.
Main.java
----------
package com.ravi.java8;
}
-------------------------------------------------------------
Program that describe that static method of an interface is only available to
interface only that means we can access the static method of an interface by using
only one way i.e interface name.
interface Hello
{
public static void m1()
{
System.out.println("m1 static method");
}
}
package com.ravi.interface_demo;
class A
{
public static void m1()
{
System.out.println("Static method A");
}
}
class B extends A
{
}
public class Demo
{
public static void main(String [] args)
{
A.m1();
B.m1(); //valid
new B().m1(); //valid
}
}
--------------------------------------------------------------
Interface from java 9v version
-------------------------------
Yes, From java 9 onwards we can also write private static and private non-static
methods inside an interface.
package com.ravi.interface_demo;
interface Acceptable
{
void m1(); //[Abstract Method, JDK 1.0]
}
class Implementer implements Acceptable
{
@Override
public void m1()
{
System.out.println("Abstract method Implemented");
}
}
public class InterfaceMember
{
public static void main(String[] args)
{
Acceptable a1 = new Implementer();
a1.m1();
a1.m2();
Acceptable.m3();
//a1.m6();
Note : We can achieve 100% abstraction by using private method inside interface.
--------------------------------------------------------------
Can an interface extend a class [Oracle Documentation 9.2]:
------------------------------------------------------------
An interface can't extend a class, It can extend only interface.
Every public method of Object class is implicitly re-declare inside every interface
as an abstract method to support upcasting.
package com.ravi.interface_class;
interface Acceptable
{
}
--------------------------------------------------------------
package com.ravi.interface_class;
interface Hello
{
public default String toString() //error
{
return null;
}
}
public class InterfaceMethods1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
interface Hello
{
@Override
public String toString();
@Override
public boolean equals(Object obj);
@Override
public int hashCode();
}
public class InterfaceMethods1 {
The above program is valid but now compiler will not add these 3 public methods of
Object class.
--------------------------------------------------------------
Anonymous inner class with interface:
--------------------------------------
package com.ravi.anonymous_inner_class;
@FunctionalInterface
interface Student
{
void writeExam();
}
}
};
science.writeExam();
};
arts.writeExam();
}
}
---------------------------------------------------------------
Introduction to Functional Programming :
----------------------------------------
What is Lambda Expression in java ?
------------------------------------
It is a new feature introduced in java from JDK 1.8 onwards.
It is an anonymous function i.e function without any name.
In java it is used to enable functional programming.
It is used to concise our code as well as we can remove boilerplate code.
It can be used with functional interface only.
If the body of the Lambda Expression contains only one statement then curly braces
are optional.
We can also remove the variables type while defining the Lambda Expression
parameter.
If the lambda expression method contains only one parameter then we can remove ()
symbol also.
In lambda expression return keyword is optional but if we use return keyword then
{} are compulsory.
Lamda target can't be class or abstract class, it will work with functional
interface only.
-------------------------------------------------------------
Program on Lambda Expression :
------------------------------
package com.ravi.lambda_expression;
@FunctionalInterface
interface Printable
{
void print();
}
public class LambdaDemo1
{
public static void main(String[] args)
{
Printable p = ()-> System.out.println("Printing");
p.print();
}
}
----------------------------------------------------------------------
package com.ravi.lambda_expression;
interface Vehicle
{
void run();
}
public class LambdaDemo2 {
}
-----------------------------------------------------------------------
package com.ravi.lambda_expression;
@FunctionalInterface
interface Calculate
{
void doSum(int x, int y);
}
}
-----------------------------------------------------------------------
package com.ravi.lambda_expression;
@FunctionalInterface
interface Length
{
int getStringLength(String str);
}
public class LambdaDemo4 {
}
-----------------------------------------------------------------------
package com.ravi.lambda_expression;
import java.util.Scanner;
@FunctionalInterface
interface Calculator
{
double getSquareAndCube(int num);
}
System.out.println(calc.getSquareAndCube(no));
}
-----------------------------------------------------------------------
What is type parameter<T> in java ?
------------------------------------
It is a technique through which we can make our application indepenedent of data
type. It is represented by <T>
In java we can pass Wrapper classes as well as User-defined classes to this type
parameter.
package com.ravi.lambda_expression;
class Accept<T>
{
private T x;
public Accept(T x)
{
super();
this.x = x;
}
public T getX()
{
return x;
}
}
}
-----------------------------------------------------------------------
30-07-2024
-----------
Note :-
-------
All these predefined functional interfaces are provided as a part of
java.util.function sub package.
It contains an abstract method test() which takes type parameter <T> and returns
boolean value. The main purpose of this interface to test one argument boolean
expression.
@FunctionalInterface
public interface Predicate<T>
{
boolean test(T x);
}
Note :- Here T is a "type parameter" and it can accept any type of User defined
class as well as Wrapper class like Integer, Float, Double and so on.
import java.util.Scanner;
import java.util.function.Predicate;
}
----------------------------------------------------------------------
package com.ravi.functional_interface_demo;
import java.util.Scanner;
import java.util.function.Predicate;
}
-----------------------------------------------------------------------
package com.ravi.functional_interface_demo;
import java.util.Scanner;
import java.util.function.Predicate;
}
-----------------------------------------------------------------------
Assignments :
-------------
1) Using Predicate verify whether a person is eligible for vote or not?
@FunctionalInterface
public interface Consumer<T>
{
void accept(T x);
}
-----------------------------------------------------------------------
package com.ravi.functional_interface_demo;
import java.util.function.Consumer;
record Employee(Integer employeeId, String employeeName)
{
}
-----------------------------------------------------------------------
Function<T,R> functional interface :
-----------------------------------------
Type Parameters:
T - the type of the input to the function.
R - the type of the result of the function.
It provides an abstract method apply that accepts one argument(T) and produces a
result(R).
Note :- The type of T(input) and the type of R(Result) both will be decided by the
user.
@FunctionalInterface
public interface Function<T,R>
{
public abstract R apply(T x);
}
----------------------------------------------------------------------
package com.ravi.functional_interface_demo;
import java.util.Scanner;
import java.util.function.Function;
sc.close();
}
}
-----------------------------------------------------------------------
Supplier<T> Functional Interface :
----------------------------------
Supplier<T> prdefined functional interface :
--------------------------------------------
It is a predefined functional interface available in java.util.function sub
package.
It provides an abstract method get() which does not take any argument but
produces/supply a value of type T.
@FunctionalInterface
public interface Supplier<T>
{
T get();
}
-----------------------------------------------------------------------
package com.ravi.functional_interface_demo;
import java.util.Scanner;
import java.util.function.Supplier;
}
-----------------------------------------------------------------------
package com.ravi.functional_interface_demo;
import java.util.function.Supplier;
}
-----------------------------------------------------------------------
31-07-2024
-----------
How to create our own functional interfaces with Type parameter :
-----------------------------------------------------------------
package com.ravi.functional_interface_ex;
@FunctionalInterface
interface TriFunction<T,U,V,R>
{
R apply(T t, U u, V v);
}
}
-----------------------------------------------------------------------
BiPredicate<T,U> functional interface :
-----------------------------------
It is a predefined functional interface available in java.util.function sub
package.
The BiPredicate interface has method named test, which takes two parameters and
returns a boolean value, basically this BiPredicate is same with the Predicate,
instead, it takes 2 arguments for the metod test.
@FunctionalInterface
public interface BiPredicate<T, U>
{
boolean test(T t, U u);
}
Type Parameters:
System.out.println(isSumEven.test(2, 3));
System.out.println(isSumEven.test(5, 7));
}
}
-----------------------------------------------------------------------
BiConsumer<T, U> functional interface :
---------------------------------------
It is a predefined functional interface available in java.util.function sub
package.
It takes a method named accept, which takes two parameters and performs an action
without returning any result.
@FunctionalInterface
public interface BiConsumer<T, U>
{
void accept(T t, U u);
}
-----------------------------------------------------------------------
import java.util.function.BiConsumer;
updateVariables.accept(number, text);
// Values after the update (note that the original values are unchanged)
System.out.println("Original values: " + number + ", " + text);
}
}
-----------------------------------------------------------------------
BiFunction<T, U, R> Functional interface :
---------------------------------
It is a predefined functional interface available in java.util.function sub
package.
The BiFunction interface has a method named apply that takes two arguments and
returns a result.
@FunctionalInterface
public interface BiFunction<T, U, R>
{
R apply(T t, U u);
}
-----------------------------------------------------------------------
import java.util.function.BiFunction;
}
}
----------------------------------------------------------------------
UnaryOperator<T> :
------------------
It is a predefined functional interface available in java.util.function sub
package.
It has a single type parameter, T, which represents both the operand type and the
result type.
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T,R>
{
public abstract T apply(T x);
}
-----------------------------------------------------------------------
import java.util.function.*;
public class Lambda15
{
public static void main(String[] args)
{
UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(5));
This is a specialization of BiFunction for the case where the operands and the
result are all of the same type.
It has two parameters of same type, T, which represents both the operand types and
the result type.
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,U,R>
{
public abstract T apply(T x, T y);
}
----------------------------------------------------------------------
import java.util.function.*;
public class Lambda16
{
public static void main(String[] args)
{
BinaryOperator<Integer> add = (a, b) -> a + b;
System.out.println(add.apply(3, 5));
}
}
--------------------------------------------------------------
*What is marker interface in java ?
-----------------------------------
A marker interface is an interface which does not contain any field or method,
basically a marker interface is an empty interface or tag interface.
The main purpose of Marker interface to provide additional information to the JVM
regarding the object like object is Serilizable, Clonable OR
randomly accessible or not.
Note : We can create our own marker interface by using instanceof operator.
--------------------------------------------------------------
****What is difference between abstract class and interface ?
----------------------------------------------------------------
The following are the differences between abstract class and interface.
1) An abstract class can contain instance variables but interface variables are by
default public , static and final.
2) An abstract class can have state (properties) of an object but interface can't
have state of an object.
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.
------------------OOPs Completed..............................
Exception Handling :
--------------------
What is an execption ?
----------------------
An execption is a runtime error.
1) java.lang.ArithmeticException
int x = 10;
int y = 0;
int z = x/y;
System.out.println(z);
2) java.lang.ArrayIndexOutOfBoundsException
If we try to access the index of the array where element is not available then
we will get java.lang.ArrayIndexOutOfBoundsException
3) java.lang.NagativeArraySizeException
Whenever we create an array and if we pass some negative value as
a size of an array then we will will get java.lang.NagativeArraySizeException
4) java.lang.NullPointerException
Whenever we want to call any non static method on the reference
variable which is pointing to null then we will get
java.lang.NullPointerException
5) java.lang.NumberFormatException
If we try to convert any String into numeric format but the String
value is not in a proper format then we will get
java.lang.NumberFormatException
6) java.util.InputMismatchException
At the time of taking the input from the Scanner class if input is
not valid from user then we will get java.util.InputMismatchException
-------------------------------------------------------------------
Exception format :
------------------
The java software people has provided the format of exception so whenever we print
exception object then the format is
package com.ravi.basic;
import java.io.IOException;
package com.ravi.basic;
import java.util.Scanner;
In the above program, If we put the value of y as 0 then program will be terminated
in the middle, IT IS CALLED ABNORMAL TERMINATION.
Actually JVM has a default exception handler which is responsible to handle the
execption and terminate the program in the middle abnormaly.
--------------------------------------------------------------------
In order to work with exception, java software people has provided the following
keywords :
1) try block
2) catch block
3) finally block [Java 7 try with resourses]
4) throw
5) throws
====================================================================
Key points to remember :
--------------------------------
-> With try block we can write either catch block or finally block or both.
-> In between try and catch we can't write any kind of statement.
-> try block will trace our program line by line.
-> If we have any exception inside the try block,With the help of JVM, try block
will automatically create the appropriate Exception object and then throw the
Exception Object to the nearest catch block.
-> In the try block whenever we get an exception the control will directly jump to
the nearest catch block so the remaining code of try block will not be executed.
-> catch block is responsible to handle the exception.
-> catch block will only execute if there is an exception inside try block.
--------------------------------------------------------------
try block :
-----------
Whenever our statement is error suspecting statement OR Risky statement then we
should write that statement inside the try block.
try block must be followed either by catch block or finally block or both.
*try block is responsible to trace our code line by line, if any execption
encounter then with the help of JVM, TRY BLOCK WILL CREATE APPROPRIATE EXECPTION
OBJECT, AND THROW THIS EXCEPTION OBJECT to the nearest catch block.
After the execption in the try block, the remaining code of try block will not be
executed because control will directly transfer to the catch block.
In between try and catch block we cannot write any kind of statement.
catch block :
--------------
The main purpose of catch block to handle the exception which is thrown by try
block.
catch block will only executed if there is an exception in the try block.
-------------------------------------------------------------------
package com.ravi.basic;
import java.util.Scanner;
try
{
System.out.print("Enter the value of x :");
int x = sc.nextInt();
}
catch(Exception e)
{
System.out.println("Inside Catch Block");
System.err.println(e);
}
System.out.println("Main method ended....");
sc.close();
}
}
In the above program if we put the value of y as 0 but still program will be
executed normally because we have used try-catch so it is a
normal termination even we have an exception in the program.
--------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
try
{
// System.out.println(10/0);
// OR
throw new ArithmeticException("Ravi is dividing be zero");
}
catch (Exception e)
{
System.out.println("Inside Catch Block");
System.err.println(e);
}
}
}
From the above program it is clear that try block implicitly creating the exception
object with the help of JVM and throwing the execption object to the nearest catch
block.
--------------------------------------------------------------------
he main purpose of Exception handling to provide user-friendly message to our end
user as shown in the program.
package com.ravi.basic;
import java.util.Scanner;
}
catch(Exception e)
{
System.err.println("Sir, don't put zero");
}
sc.close();
System.out.println("Thank you for Visiting my application..");
}
}
package com.ravi.basic;
}
--------------------------------------------------------------------
Working with Specific Exception :
---------------------------------
While working with exception, in the corresponding catch block we can take
Exception (super class) which can handle any type of Exception.
On the other hand we can also take specific type of exception (ArithmetiException,
InputMismatchException and so on) which will handle only one type i.e specific type
of exception.
--------------------------------------------------------------------
public class Test
{
public static void main(String [] args)
{
try
{
throw new OutOfMemoryError();
}
catch (Error e) //Specific
{
System.err.println("Some User message");
}
System.out.println("Completed");
}
}
Note : From the try block we are throwing the OutOfmemoryError so , Error OR
Throwable is required in the catch block for handling purpose, If we pass Exception
then catch block will not be executed.
--------------------------------------------------------------------
Working with Infinity and Not a number(NaN) :
---------------------------------------------
10/0 -> Infinity (Java.lang.ArithmeticException)
10/0.0 -> Infinity (POSITIVE_INFINITY)
While dividing a number with Integral literal in both the cases i.e Infinity (10/0)
and Undefined (0/0) we will get java.lang.ArithmeticException because java software
people has not provided any final, static variable support to deal with Infinity
and Undefined.
On the other hand while dividing a number with with floating point literal in the
both cases i.e Infinity (10/0.0) and Undefined (0/0.0) we have final, static
variable support so the program will not be terminated in the middle which are as
follows
10/0.0 = POSITIVE_INFINITY
-10/0.0 = NEGATIVE_INFINITY
0/0.0 = NaN
package com.ravi.basic;
}
-------------------------------------------------------------------
Working with multiple try catch :
---------------------------------
According to our application requirement we can provide multiple try-catch in my
application to work with multiple execptions.
package com.ravi.basic;
public class MultipleTryCatch
{
public static void main(String[] args)
{
System.out.println("Main method started!!!!");
try
{
int arr[] = {10,20,30};
System.out.println(arr[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Array index is out of limit!!!");
}
try
{
String str = null;
System.out.println(str.length());
}
catch(NullPointerException e)
{
System.err.println("ref variable is pointing to null");
}
While working with multiple catch block always the super class catch block must be
last catch block.
From java 1.7v this multiple exceptions we can write in a single catch block by
using | symbol.
If try block is having more than one exception then always try block will entertain
only first exception because control will transfer to the nearest catch block.
package com.ravi.basic;
public class MultyCatch
{
public static void main(String[] args)
{
System.out.println("Main Started...");
try
{
int c = 10/0;
System.out.println("c value is :"+c);
catch(ArrayIndexOutOfBoundsException e1)
{
System.err.println("Array is out of limit...");
}
catch(ArithmeticException e1)
{
System.err.println("Divide By zero problem...");
}
catch(Exception e1)
{
System.out.println("General");
}
System.out.println("Main Ended...");
}
}
--------------------------------------------------------------------
package com.ravi.basic;
}
-------------------------------------------------------------------
finally block [100% Guaranteed for Exceution]
---------------------------------------------
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.
package com.ravi.basic;
try
{
System.out.println(10/0);
}
finally
{
System.out.println("Finally Block");
}
Note :- In the above program finally block will be executed, even we have an
exception in the try block but here only the resourses will be handled but not the
exception.
---------------------------------------------------------------
package com.ravi.basic;
}
finally
{
System.out.println("Resources will be handled here!!");
}
System.out.println("Main method ended!!!");
}
}
In the above program exception and resourses both are handled because we have a
combination of try-catch and finally.
Note :- In the try block if we write System.exit(0) and if this line is executed
then finally block will not be executed.
--------------------------------------------------------------------
Limitation of finally Block :
------------------------------
The following are the limitation of finally block :
package com.ravi.basic;
import java.util.InputMismatchException;
import java.util.Scanner;
Case 1:
-------
try(resource1 ; resource2) //Only the resources will be handled
{
}
Case 2 :
----------
//Resources and Exception both will be handled
try(resource1 ; resource2)
{
}
catch(Exception e)
{
}
Case 3 :
----------
try with resourses enhancement from java 9v
try(r1; r2)
{
}
catch(Exception e)
{
}
Whenever we pass any resourse class as part of try with resources as a parameter
then that class must implements either Closeable or AutoCloseable interface so, try
with resourses will automatically call the respective class
close() method even an exception is encountered in the try block.
The following program explains how try block is invoking the close() method
available in DatabaseResource class and FileResourse class.
3 files :
----------
DatabaseResourse.java
-----------------------
package com.ravi.try_with_resourse;
FileResourse.java
------------------
package com.ravi.try_with_resourse;
import java.io.Closeable;
import java.io.IOException;
Main.java
-----------
package com.ravi.try_with_resourse;
}
--------------------------------------------------------------------
//Program to close Scanner class automatically using try with resourses
package com.ravi.try_with_resourse;
import java.util.InputMismatchException;
import java.util.Scanner;
try(sc)
{
System.out.print("Enter your Roll :");
int roll = sc.nextInt();
System.out.println("Your Roll is :"+roll);
}
catch(InputMismatchException e)
{
System.err.println("Please provide numeric value");
}
System.out.println("Execution Completed");
Whenver we write try with resourses then automatically compiler will generate
finally block internally to close the resourses automatically.
====================================================================
16-11-2024
-----------
Nested try block :
------------------
If we write a try block inside another try block then it is called Nested try
block.
The execution of inner try block depends upon outer try block that means if we have
an exception in the Outer try block then inner try block will not be executed.
--------------------------------------------------------------------
package com.ravi.basic;
}
catch(NumberFormatException e)
{
System.err.println("Number is not in a proper format");
}
}
catch(NullPointerException e)
{
System.err.println("Null pointer Problem");
}
}
}
------------------------------------------------------------------
Writing try-catch inside catch block :
---------------------------------------
We can write try-catch inside catch block but this try-catch block will be exceuted
if the catch block will executed that means if we have an exception in the try
block.
package com.ravi.basic;
import java.util.InputMismatchException;
import java.util.Scanner;
try(sc )
{
System.out.print("Enter your Roll number :");
int roll = sc.nextInt();
System.out.println("Your Roll is :"+roll);
}
catch(InputMismatchException e)
{
System.err.println("Provide Valid input!!");
try
{
System.out.println(10/0);
}
catch(ArithmeticException e1)
{
System.err.println("Divide by zero problem");
}
}
finally
{
try
{
throw new ArrayIndexOutOfBoundsException("Array is out of
bounds");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Array is out of Bounds");
}
}
}
We can also write return statement inside the finally block only, if the finally
block is present. After this return statement we cannot write any kind of
statement. (Unrechable)
Always finally block return statement having more priority then try-catch return
statement.
-------------------------------------------------------------------
package com.ravi.advanced;
public class ReturnExample
{
public static void main(String[] args)
{
System.out.println(methodReturningValue());
}
}
}
--------------------------------------------------------------------
package com.ravi.advanced;
@SuppressWarnings("finally")
public static int m1()
{
try
{
System.out.println("Inside try");
return 100;
}
catch(Exception e)
{
System.out.println("Inside Catch");
return 200;
}
finally
{
System.out.println("Inside finally");
return 300;
}
If we initialize inside the try block only then from catch block we cannot access
local variable value, Here initialization is compulsory inside catch block.
--------------------------------------------------------------------
package com.ravi.basic;
}
--------------------------------------------------------------------
**Difference between Checked Exception and Unchecked Exception :
----------------------------------------------------------------
Checked Exception :
----------------------
A checked exception is a common exception that must be declared or handled by the
application code where it is thrown, Here compiler takes very much care and wanted
the clarity regarding the exception by saying that, by using this code you may face
some problem at runtime and you did not report me how would you handle this
situation at runtime are called Checked exception, so provide either try-catch or
declare the method as throws.
Eg:
---
FileNotFoundException, IOException, InterruptedException,ClassNotFoundException,
SQLException, CloneNotSupportedException, EOFException and so on
Unchecked Exception :-
--------------------------
An unchecked exception is rare and any exception that does not need to be declared
or handled by the application code where it is thrown, here compiler does not take
any care are called unchecked exception.
Unchecked exceptions are directly entertain by JVM because they are rarely occurred
in java.
Unchecked Exception :
----------------------
1) Rare Exception
2) Comiler will not take any care
3) Handling is not Compulsory
4) Sub class of RuntimeException
throws :
--------
throws keyword describes that the method might throw an Exception, It also might
not. It is used only at the end of a
method declaration to indicate what exceptions it supports OR what type of
Exception it might throw which will be handled by JVM.
Note :- It is always better to use try catch so we can provide appropriate user
defined messages to our client.
--------------------------------------------------------------------
*Why compiler takes very much care regarding the checked Exception ?
---------------------------------------------------------------
As we know Checked Exceptions are very common exception so in case of checked
exception "handling is compulsory" because checked Exception depends upon other
resources as shown below.