Java Jspider PDF
Java Jspider PDF
Keywords in Java
* not used
** added in 1.2
IDENTIFIERS :
Rules of Identifiers :
- A variables is a named memory location which holds the value for the
program.
- To use a variables we have to follow three steps :
1. Declaration
2. Initialization
3. Utilization (Usage)
Declaration of a variables :
Syntax :
Datatype variablename;
Eg : int age;
Initialization of a variable :
Syntax :
Variable=value;
Eg: age=25;
- It is a statement which is written to store the value into the variable using
assignment operator.
Utilization of a variables:
- Statements which are written to use the values of the variables are called
as utilization.
Default value
Byte 8 bits 1 byte 0
Integer Short 16 bits 2 byte 0
Int 32 bits 4 bytes 0
Long 64 bits 8 bytes Ol
Decimal Float 32 bits 4 bytes 0.0f
Double 64 bits 8 bytes 0.0
Char 16 bits 2 bytes Blank space
Boolean 8 bits 1 bytes false
CHAPTER 2 : OPERATORS
- It performs operations on the given operands and produce results.
Arithmatic Operator
Note- Variables of the program should not be printed with “double quotes”.
Formula to get how much a datatype maximum and min value range
-2n-1 to 2n-1-1
Eg : for bytes
-27 to 27-1
Program :
(a)
class Arithmetic
{
public static void main(String[] args)
{
System.out.println("Program start");
//declaration
int a;
int b;
int res;
//initialization
a=30;
b=60;
res=a+b;
System.out.println("Value of a");
System.out.println(a);
System.out.println("value of b");
System.out.println(b);
System.out.println("Addition of a and b");
System.out.println(res);
System.out.println("Program end!");
}
}
(b)
class Arithmetic2
{
public static void main(String[] args)
{
System.out.println("value of a"+a);
System.out.println("Value of b"+b);
System.out.println("Addition of a and b"+c);
}
}
(c )
class ArithmeticOperator
{
public static void main(String[] args)
{
int a=5;
int b=10;
System.out.println(a>b);
System.out.println(a>=b);
System.out.println(a<b);
System.out.println(a<=b);
System.out.println(a==b);
System.out.println(a!=b);
}}
Concatination Operator
Combination of Concatination
- 2+ “hello” – 2hello
- “hello”+123 – hello123
- “hello” + “World” – helloworld
- 2+3+ “hello” – 5hello
- “hello”+2+3 – hello2+3 – hello23
- 2+ “hello”+3 – 2hello3
(a)
class Increment
{
public static void main(String[] args)
{
System.out.println("Program start");
int a1=10;
int b1=10;
int res;
System.out.println("a1 = "+a1);
System.out.println("b1 = "+b1);
res=++a1 + 10;
System.out.println("res = "+res);
res=b1++ + 10;
System.out.println("res = "+res);
System.out.println("a1 = "+a1);
System.out.println("b1 = "+b1);
res=b1++ + 10;
System.out.println("res = "+res);
System.out.println("a1 = "+a1);
System.out.println("b1 = "+b1);
res=b1++ + 10;
System.out.println("res = "+res);
System.out.println("a1 = "+a1);
System.out.println("b1 = "+b1);
System.out.println("Program end");
}}
(b)
class Increment1
{
public static void main(String[] args)
{
System.out.println("Hello World!");
int a1=10;
System.out.println("a1 = "+a1);
a1++;
System.out.println( "a1 = "+a1);
}}
(C)
class Increment2
{
public static void main(String[] args)
{
int a1=10;
System.out.println(a1++);
System.out.println(++a1);
}}
(d)
class Increment3
{
public static void main(String[] args)
{
byte b1=10;
b1++;
System.out.println(b1);}}
Decrement Operator: (--)
If(condition) true
{
Statement;
}
Else
{
Statement;
}
Program
class IfElseStatement
{
public static void main(String... args)
{
int a=97;
if (a>b)
{
System.out.println("print a");
}
else
{
System.out.println("print b");
}
}}
IF-ELSE-IF STATEMENT
SYNTAX :
If(Boolean condition 1)
{
Statement;
}
Else if(condition 1 )
{
Statement;
}
Else {}
Program
class Ifelseif
{
public static void main(String[] args)
{
System.out.println("Program Start");
int marks=25;
if(marks>79 && marks<=100)
{
System.out.println("first class distinction");
}
else if (marks>=60 && marks<=79)
{
System.out.println("first class ");
}
else if (marks>=50 && marks<=59)
{
System.out.println("second class ");
}
else if (marks>=35 && marks <=49)
{
System.out.println("third class ");
}
else if (marks>100)
{
System.out.println("Invalid number");
}
else
{
System.out.println("You are fail");
}
}}
** note : logical operator are used to combine multiple conditions.
And operator (&&) Or operator (||)
C1 C2 Result C1 C2 Result
T T T T T T
T F F T F T
F T F F T T
F F F F F F
SWITCH CASE
- It is used whenever we have to compare the given value only equals (==)
conditions.
- Switch case statements provides more readability for the program.
- It is not possible to compare the conditions other than equals conditions.
- Syntax :
Switch(choice)
{
Case 1: Statement;
Break;
Case 2: Statement;
Break;
Default : Statement;
}
- Note : Break statement stop the execution of the given block at a given
line of code. Writing break statement after default case is not mandatory
in switch case statement.
Program
class Switch
{
public static void main(String[] args)
{
System.out.println("Program Start");
char a='C';
switch(a)
{
case 'A': System.out.println("alphabet A ");
break;
case 'C' : System.out.println("aphabet C ");
break;
default : System.out.println("Invalid ");
}
}
}
LOOPING STATEMENTS
- They are used to perform repetitive task in the given program with lesser
lines of code.
- Different types of loops are :-
(a) For loop
(b) While loop
(c) Do-while loop
(d) For each loop /advanced/enhanced loop
FOR LOOP (ITERATION) :
- One complete execution cycle of a loop is called as iteration.
- The number of iteration of a loop depends on the condition of the loop.
- Syntax :
For(initialization; condition; counter)
{
Statement;
}
- For loop is a type of loop which is used whenever the logical start and
logical end is well defined.
Basic Program :
Class Basic
{
Public static void main (String ar[])
{ (1) (2) (4)
For(int count=1; count<=3; count++)
{ (3)
System.out.println(“Hello World”);
}
}}
Op – Hello World
Hello World
Hello World
Iteration 1st – 1, 2, 3, 4
Iteration 2nd – 2,3,4,
Iteration 3rd – 2,3,4
Tracing :
Count=1
Count<=3, 1<=3, true print hello world
Count=2
Count<=3, 2<=3, true print hello world
Count=3
Count<=3, 3<=3, true print hello world
Count=4
Count<=3, 4<=3, false terminate
Pgm : wap to display number between 1 to 100 which are divisible by both 2
and 5.
For( int i=1; i<=100;i++)
{
If(i%2==0 && i%5==0)
{
System.out.println(i);
}}
NESTED FOR LOOPS
- A for loop written within the body of another for loop is called as nested
for loop.
- Syntax :
For(initialization; condition; counter)
{
For(initialization; condition; counter)
{
Statement ;
}
Statement
}}
Pgrm :
Class A
{
Public static void main (String ar[])
{
For(int i=1;i<=3;i++)
{
System.out.println(“outer loop”);
For(int j=1; j<=3;j++)
{
System.out.println(“inner loop”);}}}
Tracing
I=1
I<=3, 1<=3 return true print outer loop and goes to inner loop
J=1
J<=3, 1<=3 return true print inner loop
J=2
J<=3, 2<=3 return true print inner loop
J=3
J<=3, 3<=3 return true print inner loop
J=4
J<=3; 4<=3 return false inner loop terminate and outer loop execute again
I=2
I<=3, 2<=3 return true print outer loop and goes to inner loop
J=1
J<=3, 1<=3 return true print inner loop
J=2
J<=3, 2<=3 return true print inner loop
J=3
J<=3, 3<=3 return true print inner loop
J=4
J<=3; 4<=3 return false inner loop terminate and outer loop execute again
I=3
I<=3, 3<=3 return true print outer loop and goes to inner loop
J=1
J<=3, 1<=3 return true print inner loop
J=2
J<=3, 2<=3 return true print inner loop
J=3
J<=3, 3<=3 return true print inner loop
J=4
J<=3; 4<=3 return false inner loop terminate and outer loop execute again
I=4
I<=3, 4<=3 return false and terminate outer loop
Prgm : wap to print pattern
*****
*****
*****
For(int i=1;i<=3;i++)
{
For(int j=1;j<=3;j++)
{
System.out.print(“ * ”);
}
System.out.println(); // moves to next line
}
Tracing
I=1
I<=3; 1<=3, return true , inner loop is executed
J=1
J<=3;1<=3 return true print *
J=2
J<=3;2<=3 return true print *
J=3
J<=3;3<=3 return true print *
J=4
J<=3;4<=3 return false and inner loop is terminated, condition again goes to
outer for loop.
I=2
I<=3; 2<=3, return true , inner loop is executed
J=1
J<=3;1<=3 return true print *
J=2
J<=3;2<=3 return true print *
J=3
J<=3;3<=3 return true print *
J=4
J<=3;4<=3 return false and inner loop is terminated, condition again goes to
outer for loop.
I=3
I<=3; 3<=3, return true , inner loop is executed
J=1
J<=3;1<=3 return true print *
J=2
J<=3;2<=3 return true print *
J=3
J<=3;3<=3 return true print *
J=4
J<=3;4<=3 return false and inner loop is terminated, condition again goes to
outer for loop.
I=4
I<=3; 4<=3, return false, outer loop is terminated.
WHILE LOOP
Syntax :
While(Boolean_condition)
{
Statement1;
}
- It is a type of looping statement. It is used whenever the logical start and
logical end is not well defined.
- Pgm
Int count=1;
While(count<=5)
{
System.out.println(count);
Count;
}
DO-WHILE LOOP
Syntax :
Do
{
Statement;
}
While(Boolean condition);
Prgm :
Int count=1;
Do
{
System.out.println(count);
Count++;
}
While(count<=5);
CHAPTER 4 : METHODS IN JAVA
S.O.P. (“Hello”);
S.O.P. (“good morning”);
}
Public static void main (String ar[])
{
displayMsg();
displayMsg();
}}
CHAPTER 5 : ARRAYS (BASICS)
- An array is homogeneous group of elements which has fixed size and
index.
- Using array we can manage the data easily to perform different
operations.
(a) Array Declaration
Syntax :
Datatype [] array_name;
Eg : int [] marks;
Or Datatype array_name[];
Int marks[];
(b) Array Creation
Syntax :
Array_name = new datatype [size];
Eg marks = new int[5];
Bucket
Index 0 1 2 3 4
To Declare and Create Array in Single line
Syntax :
Datatype arrayname [] = new datatype [size];
Eg int marks[]=new int[5];
- After array creation every bucket of the array will be initialize with
default values according to datatype of the array. For eg. If the datatype
of an array is int then all the bucket will be filled with 0. Or if the
datatype of an array is Boolean then all the bucket will be filled with
false.
(c) Initialize Array
Syntax :
Arrayname[index]=value;
For eg: marks[0]=20;
Pgm
class Array
{
public static void main(String[] args)
{
int marks[]=new int[5];
marks[0]=67;
marks[1]=20;
marks[2]=62;
marks[3]=85;
marks[4]=55;
for(int index=0; index<5; index++)
{
System.out.println(marks[index]);
}
}}
Op – 67 20 62 85 55
Length (variables of array):
- It contains count of number of bucket present in the given array.
Notes :
- If you know the size of the array and the data to be stored in the array in
advance then you can declare and initialize the array in same line.
- Syntax :
Datatype[] arrayname = {val1, val2….};
pgm
class Array1
{
public static void main(String[] args)
{
String [] days={"mon", "tue", "wed", "thurs", "fri", "sat", "sun"};
for (int index=0;index<days.length;index++ )
{
System.out.println(days[index);
}}}
ArrayIndexOutOfBoundsException
- Whenever we try to add the elements to array execiding the size of array
then JVM throws ArrayIndexOutOfBoundsException.
- If you try to retrieve the elements from the array execiding the size of the
last index of the array then JVM throws
ArrayIndexOutOfBoundsException.
Pgm
//wap of array to find first middle and last element of an array
class Array2
{
public static void printNum(int[] a1)
{
int first=0;
int last=a1.length-1;
int mid=last/2;
Notes :
First Index = 0;
Last Index = length -1;
Middle Index = last index /2;
CHAPTER 6 : STRING IN JAVA (BASICS)
boolean res2=s1.equals(s3);
System.out.println("Equals or not = " +res2);
boolean res3=s1.equalsIgnoreCase(s3);
System.out.println("Equals or not = " +res1);
char c1=s1.charAt(4);
System.out.println("Character at index = " +c1);
char [] ar1=s1.toCharArray();
for(int index=0; index<ar1.length;index++)
{
System.out.print(ar1[index]);
}
}}
OBJECT ORIENTED PROGRAMMING SYSTEM
CHAPTER 1 : CLASS & OBJECTS
OBJECTS : Any entity which has states and behaviour is called as objects. For
eg. Pen, account, building.
Pen Account Student
State Behaviour State Behaviour State Behaviour
Color Writing a/c no. Debit Name Studying
Brand Drawing Type of ac Credit Id Exam
Shape Pointing Bank name Payment Gender Reading
Price ….. Balance ….. Age writing
…. etc
CLASS : -
- A class is blueprint of an objects.
- A class contains or defines states and behaviours of an objects.
- The states of the class are called as data members and the behaviours of
the objects are called as function members.
- The data members of the class are represented by variables and the
functions members of the class are represented by methods.
JAVA NAMING CONVENTION :
Class :
- Any entity in java which starts with upper case declared with the keyword
class is called as java class.
- Class names should be nouns, in mixed case with first letter of each
internal word capitalize.
Eg. Account, AccountName;
Interface :
- Any entity in java which starts with upper case and declared with the
keyword interface is called java interface.
- Interface name should be capitalize like class name.
- Eg. : interface Storing, interface RunnableInterface
Methods :
- It defines the action which is performed on data members of the class.
- Methods should be in mixed case with the first letter lower case, with the
first letter of each internal word capitalize.
- Eg : run(), getData()
Variables :
- Variables should be declared in mixed case with a lowercase first letter.
Internal words starts with capital letters.
- Eg: i, c, myWidth;
Constants :
- The constants should be all uppercase with words separated by
underscore (“ _” ).
- Eg. MIN_WIDTH = 5;
The members of class be classified into two types :
(a) Static Members (b) Non-Static members
Static members
- Any members of the class which is declared using static keyword is
called as static members.
Static Members present in Same Class:
- If a static method is trying to access the static members present in the
same class then it can refer to them directly with the name of static
member.
Program
class Demo
{
static int v1=100;
public static void test()
{
System.out.println("this is test() of demo class");
}
public static void main (String ar[])
{
System.out.println("V1 is = " + v1);
test();
}}
Program 2
class Demo
{
int v1=100;
public static void test()
{
System.out.println("this is test() of demo class");
}
public static void main (String ar[])
{
System.out.println("V1 is = " + v1);
test();
}}
Program :
// static member used by static method use in different class by
classname.member
class Demo
{
static int v1=100;
public static void test()
{
System.out.println("this is test() of demo class");
}}
class MainClass2
{
public static void main (String ar[])
{
System.out.println("V1 is = " + Demo.v1);
Demo.test();
}}
NON-STATIC MEMBERS :
- Any member of the class which is declared without using static keyword
is called as non-static members.
- We can access non-static members of a class only by creating the object
for the class.
Object creation
Syntax :
New className()
Eg.
New Sample()
Here New is a keyword which creates a new object and Sample() is
a constructor call which copy all the non-static member to object.
- A non static method can access non-static data members or non static
function members present in the same class without creating any object.
Program : calling non-static member and method from main method in a
single class by not creating any object
class Abc
{
int z1=123;
public void view()
{
System.out.println("this is view() of Abc");
System.out.println("value of a = " + z1);
}
public static void main(String[] args)
{
System.out.println("Z1 = " + new Abc().z1);
new Abc().view();
}}
Program :
// use of non static members and function in other class
class Mainclass
{
double k1=123.45;
public void count()
{
System.out.println("this is view() of Demo");
}}
class Mainclass2
{
public static void main(String[] args)
{
System.out.println("Program Strts ");
System.out.println("k1 = " + new Mainclass().k1);
new Mainclass().count();
System.out.println("Progrm end " );
}
}
RefVariable r2 = r1;
System.out.println("Value of r2 = " +r2.r);
}
}
- Static members are called as class members because they can be accessed
using the classname.
- Non static members are called as instance members because they can be
accessed only by creating the object or instance.
- Static members of the class will have only one copy in the memory.
Static int v1 = 50;
/S.O.P (Sample.v1);
Sample.V1=50;
- Non-static members will have multiple copies in the memory depending
on number of objects created.
Int v1= 100;
S.O.P ( new Simple().V1);
S.O.P (new Simple().V2);
Program
class Account
{
int actno=12345;
String name = "Dinga";
String branch = "basvangudi";
double balance = 5000;
String type = "Savings";
a1.showAccount();
}
}
GLOBAL LOCAL
PRIMITIVE REFERENCE
PRIMITIVE REFERENCE
GLOBAL VARIABLES
- A variables which is declared within the scope of the class is called as
global variables.
- Global variables can be accessed by all the methods present in the present
in the same class.
LOCAL VARIABLES
- Any variables which is declare within the method declaration or method
definition are called as local variables.
- Local variables can be accessed only within the methods in which they
are declared.
- Local variables can not be declared as static or non static.
Program : Declaration of local and global variables
class Abc
{
int z1=123; // global variables
public static void view()
{
int y = 20; // local variables
System.out.println("Value of y = " +y)
}
public static void main(String[] args)
{
System.out.println("Z1 = " + new Abc().z1);
new Abc().view();
}}
Program : local variable can not used outside the method.
class Abc
{
int z1=123;
public void view()
{
int a = 20;
System.out.println("this is view() of Abc");
System.out.println("value of a = " + z1);
System.out.println("value of a = " + a);
}
}
}
- If variables and local variables have same names then the compiler
always give the preference to local variables.
class Abc
{
static int z1=123;
class Abc
{
static int z1=123;
}
}
JVM ARCHITECTURE
STATCK HEAP
METHOD
AREA
STATIC POOL
Stack
- Any method which is in execution state will be present in stack.
Method Area
- It contains method definition of both static and non-static methods.
Static Pool
- It contains static members in the respective static pools of the respective
classes.
Heap
- Every object which is created using new operator will be present in heap
area.
Program
class Sample
{
static int v1 = 351;
double v2 = 2.5;
public static void test()
{
System.out.println("This is test()");
return;
}
public void test1()
{
System.out.println("this is test1()");
}
}
class Jvm
{
public static void main(String[] args)
{
System.out.println("Value of V1 = " + Sample.v1);
Sample.test();
Sample s = new Sample();
System.out.println("Value of V2 " + s.v2);
s.test1();
}
}
V=2.35 V=2.35
Test1() Test1()
Psvm()
{
S Binding here
S2
}
Heap
{ ……
} Jvm.class Sample.class
Stack Test()
Psvm() V1=351
{
…..
}
Method area Static pool
Jvm.class
Javac Jvm. Java
Jvm.class Sample.clas
s Java Jvm
Important Notes :
}
public void display()
{
System.out.println(" name is = " + name);;
System.out.println(" id is = " + id);;
System.out.println(" salary is = " + sal);;
}
}
class DefaultValue
{
public static void main(String[] args)
{
Sample s = new Sample();
s.display();
}
}
Constructor are used to initialize the data members (static and non static)
of the class.
Parameterized Constructor
class Sample
{
String name;
int id;
double sal;
}
}
public SampleThis()
{
System.out.println("this is sample()");
}
public void test()
{
System.out.println("this = "+this);
}
s1.test();
}}
- This keyword differentiate between global and local variables.
For eg :
public Sample()
{
this(10); // call the argumented constructor
System.out.println("this is zero -a argument const");
This(10); if we write like this then it throw error.
}
public Sample(int a)
{
System.out.println("This is int a const...");
}
- We can not write multiple this() statement within the constructor
body.
public Sample()
{
this(10); // call the argumented constructor
this(20); // if we write like this it throws an error
System.out.println("this is zero -a argument const");
}
public Sample(int a)
{
System.out.println("This is int a const...");
}
- The called constructor can not call back calling constructor using
this() statement because it leads to recursive constructor invocation
error.
public Sample()
{
this(10); // call the argumented constructor
System.out.println("this is zero -a argument const");
}
public Sample(int a)
{
This(); // if we call like this then it throw error.
System.out.println("This is int a const...");
}
- The constructor can not call itself with this statement, because it
leads to recursive constructor invocation.
public Sample()
{
this(); // calling itself which throws an recursive
constructor invocation
System.out.println("this is zero -a argument const");
}
public Sample(int a)
{
System.out.println("This is int a const...");
}
Simple this() statement program
class Sample
{
public Sample()
{
this(10);
System.out.println("this is zero argument const");
}
public Sample(int a)
{
System.out.println("This is int a const...");
}
}
class ThisStatement
{
public static void main(String[] args) {
Sample s=new Sample();
}}
Has-A Has –A
College student
Library
Composition Aggregation
Aggregation :
- It is a type of Has-A relation where existence of one object is not
dependent on another object.
- The aggregation is achieved by creating a static reference variable
pointing to the object of another class.
Program
class Sample
{
String name;
int id;
int nbo;
String branch;
public Sample(String name, int id, int nbo, String branch)
{
this.name=name;
this.id=id;
this.nbo=nbo;
this.branch=branch;
}
public void showDetails()
{
System.out.println("Name = "+name);
System.out.println(" id = " + id);
System.out.println ( " no of book issued " +nbo);
System.out.println(" branch = "+branch);
}}
class Library
{
/*creating a static reference variable of class Sample where s1 points
to object of Sample()*/
static Sample s1 = new Sample("aatif", 101, 2, "cse");
public static void issueBook()
{
System.out.println("book is issued to "+s1.name);
s1.nbo++;
}
}
class Program1
{
public static void main(String[] args)
{
//calling the methods of sample class by using the object
Library.s1.showDetails();
Library.issueBook();
}}
Eg of account class
Account
Actno : int
Name : string
Branch : string
Balance : double
Type : String
Bankname : string
Library Student
S1 : library Name : string
1:n Id : int
Mob : int
Aggregation Branch : String
issueBooks : void
Email Attachment
A1 : attachment Name : string
Sender : string Size : int
Subject : string Type : String
1:n
Msg : string
Composition
Email (sender, subject, msg) Attachment(name, size, type)
openMail : void showDetails : void
issueBooks : void
Parent
child
Program
class Super1
{
int a =50;
}
class Child extends Super1
{
int d=10;
public void test()
{
System.out.println("this is child class " +d);
System.out.println("this is super class " + a);
}}
class FinalClass{
public static void main(String[] args) {
Child c = new Child();
c.test();
}}
Multi-level inheritance
- One sub-class inheriting from one super class and that super class is
inheriting from another super class is called as multilevel inheritance.
Class v1
Class v2 extends v1
Class v3 extends v2
Program
class WhatsappV1
{
public void msg()
{
System.out.println("this is msg ()");
}
}
class WhatsappV2 extends WhatsappV1
{
public void voiceMsg()
{
System.out.println("this is voice msg " );
}}
class WhatsappV3 extends WhatsappV2
{
public void video()
{
System.out.println("This is video ()");
}
}
class MultilevelInheritance{
public static void main(String[] args) {
WhatsappV3 v=new WhatsappV3();
v.msg();
v.voiceMsg();
v.video();
only object creation to see which class to call which method
WhatsappV2 v2= new WhatsappV2();
v2.msg();
v2.voiceMsg();
WhatsappV1 v1= new WhatsappV1();
v1.msg();
}
}
Multiple Inheritance
- One subclass inheriting from two or more superclass is called as multiple
inheritance.
SuperClass 1 SuperClass 2
Subclass
Superclass
subclass Subclass
savingAcount LoanAcnt
SUPER(); STATEMENT
- It is used to call the super class constructor from subclass
constructor.
class Super1
{
public Super1()
{
System.out.println("this is super constructor");
}
}
class Base extends Super
{
public Base()
{
super();
System.out.println("this is base constructor");
}
}
class SuperStatement
{
public static void main(String[] args) {
Object class
- It is the supermost class in java. Every class in java directly or indirectly
extends from object class.
- If the class is not extending from any class then the compiler makes the
object class as superclass by writing “extends object” implicitely.
Constructor chaining
- Subclass constructor calling super class constructor, superclass
constructor calling object class constructor is called as constructor
chaining.
Note :
- within the same constructor body it is not possible to write both this()
statement
class Super1 extends Object
{
public Super1()
{
System.out.println("this is super constructor");
}
}
class Base extends Super
{
public Base()
{
this();
super(); // here it throws an error that superl ine should
be first line
System.out.println("this is base constructor");
}
}
class SuperStatement
{
public static void main(String[] args) {
OBJECT CLASS
SUPERCLASS 1 SUPERCLASS 2
TEST() TEST()
{} {}
SUBCLASS
Subclass s1=new Subclass();
S1.test();
- It creates an ambiguity for the compiler to choose the path from where
the properties of object class should be copied to subclass.
- To call constructor of two super-class two super(); statement are required
and this is not supported in java.
- Note : multiple super statements are not allowed because super class
object should be created only once
- If two super class contains method with same name and arguments and if
you tried to call the method from subclass object, it results the ambiguity
for the compiler which choose the method for execution.
CHAPTER 6 : METHOD OVERLOADING
- Developing multiple methods with the same name within the same class
which differs in
(i) no. of arguments
(ii) data type of arguments
(iii) sequence of arguments
class Graphsheet
{
public void drawPoint()
{
System.out.println("drawing poitn at 0,0");
}
public void drawPoint(int x, char cord)
{
System.out.println("drawing point at "+cord + " , "+x);
}
public static void drawPoint(int x, int y)
{
System.out.println("drawing point at " +x + " , " + y);
}
public static void main(String[] args)
{
Graphsheet g=new Graphsheet();
g.drawPoint();
g.drawPoint(10, 'X');
Graphsheet.drawPoint(10,20);
}
}
- Two overloaded method can have different return datatypes.
class Graphsheet
{
public void drawPoint() // return type is void
{
System.out.println("drawing poitn at 0,0");
}
public int drawPoint(int x, char cord) // return type is int
{
System.out.println("drawing point at "+cord + " , "+x);
return 10;
}
public static void main(String[] args)
{
Graphsheet g=new Graphsheet();
g.drawPoint();
g.drawPoint(10, 'X');
}
}
- with the help of method overloading we can achieve code flexibility.
- Method overloading is the best example for compile time polymorphism
- The binding of method declaration to method definition is done at the
compile time and hence it is called as compile time binding or early
binding.
- Since the binding is done at the compile time it can not be changed at
runtime and hence it is called as static binding.
- It makes easy for the programmer to remember the methods name and
increase the readability of program.
Disadvantage of Method Overloading
- The overloaded methods should have required java documents in order to
understand the functionality of every overloaded method.
Application of Method Overloading
- Whenever the project or application has same logic to be executed with
different type of arguments then we go for method overloading.
Program
class Graphsheet
{
public void drawPoint()
{
System.out.println("drawing poitn at 0,0");
}
public void drawPoint(int x, char cord)
{
System.out.println("drawing point at "+cord + " , "+x);
}
public void drawPoint(int x, int y)
{
System.out.println("drawing point at " +x + " , " + y);
}
public void drawPoint(double x, double y)
{
System.out.println("drawing point at "+x+ " ," + y);
}
public static void main(String[] args)
{
Graphsheet g=new Graphsheet();
g.drawPoint();
g.drawPoint(10, 'X');
g.drawPoint(10,20);
g.drawPoint(10.2, 25.2);
}}
CHAPTER 7 : METHOD OVERRIDING
- Subclass inheriting the method of super class and changing the method
definition without changing method declaration (no. of arguments and
method name should be same) according to subclass specificiation is
called as Method Overriding.
Program
class Superclass
{
public void count(int n)
{
for (int i=1; i<n;i++)
{
System.out.println(i);
}
}
}
class Sublcass extends Superclass
{
public void count(int n) // METHOD DECLATION IS
SAME
{
for(int i=n;i>1;i--) // CHANGE THE DEFINITION
{
System.out.println(i);
System.out.println();
}}
}
class MainOverride
{
public static void main(String[] args)
{
Superclass sup1=new Superclass();
sup1.count(10);
Sublcass sub1=new Sublcass();
sub1.count(5);}}
@override :
- Override annotation helps in addition compile time verification in the
subclass to ensure the programmer overriding is overriding the proper
method of superclass.
- It will also improvise code readability.
- It is not mandatory to write @override.
- If we don’t write @override then if the method name in subclass different
then it treat as a another method and not doing overriding.
Program
class Superclass
{
public void disp()
{
System.out.println("this is disp method of superclass");
}
}
class Sublcass extends Superclass
{
@Override // Here if we write anotation then only it
differentiate between superclass and subclass method
public void count()
{
System.out.println("This is disp() method f subclass");
}
}
class MainOverride
{
public static void main(String[] args)
{
Superclass sup1=new Superclass();
sup1.disp();
Sublcass sub1=new Sublcass();
sub1.disp();
}
}
If we don’t write @override annotation then it does not throw an error if
superclass and subclass method is different in name.
class Superclass
{
public void disp()
{
System.out.println("this is disp method of superclass");
}
}
class Sublcass extends Superclass
{
public void count() // here method is different
{
System.out.println("This is disp() method f subclass");
}
}
class MainOverride
{
public static void main(String[] args)
{
Superclass sup1=new Superclass();
sup1.disp();
Sublcass sub1=new Sublcass();
sub1.count();
}
}
Note :
- Static method can not be overridden.
Program
class Superclass
{
public static void disp()
{
System.out.println("this is disp method of superclass");
}
}
class Subclass extends Superclass
{
@Override
public static void disp()
{
System.out.println("This is disp() method f subclass");
}
}
class MainOverride
{
public static void main(String[] args)
{
Superclass.disp();
Subclass.disp();
}
}
Here it throw a compile time error as method does not override
or implement a method from a supertype.
- If subclass and super class have same static methods with same
declaration and same definition then it is called as method hiding.
Program :
class Superclass
{
public static void disp()
{
System.out.println("this is disp() of superclass");
}
}
class Subclass extends Superclass
{
public static void disp()
{
System.out.println("This is disp() method of subclass");
}
}
class MainOverride
{
public static void main(String[] args)
{
Subclass.disp();
}
}
Note :
**
- if subclass and superclass contains method with same name but
different arguments then the subclass will contain 2 overloaded
methods.
Program :
class Superclass
{
public void disp()
{
System.out.println("this is disp() of superclass");
}
public void disp(int n)
{
System.out.println("this is disp(int n) of superclass");
}
}
class Subclass extends Superclass
{
@Override
public void disp(int n)
{
System.out.println("This is disp() method f subclass");
}
}
class MainOverride
{
public static void main(String[] args)
{
Superclass s1=new Superclass();
s1.disp(10);
s2.disp();
s2.disp(5);
}
}
}
class Subclass extends Superclass
{
//@Override
public void disp()
{
System.out.println("This is disp() method of subclass");
}
}
class MainOverride
{
public static void main(String[] args)
{
Subclass s1=new Subclass();
s1.disp();
}
}
//output of this program is this is disp() method of subclass, because it
call always overridden method.
- If we want to execute the overridden implementation of the method and
original implementation o the method present in superclass then we can
use super keyword from the subclass method to call superclass method.
Program
class SuperClass
{
public void view()
{
System.out.println("This is view() of SuperClass");
}
public void disp()
{
System.out.println("This is display() of SuperClass");
}
}
class Subclass extends SuperClass
{
public void view()
{
super.view();
System.out.println("this is the view() of Subclass");
}
public void disp(int n)
{
System.out.println("this is the disp(int n) of
subclass");
}
}
class SuperClassOverride
{
public static void main(String[] args)
{
Subclass ref1=new Subclass();
ref1.view();
ref1.disp();
ref1.disp(10);
}
}
CHAPTER 8 : TYPE CASTING
- Converting one type to another type is called as typecasting.
- It is of two type
(i) Primitive casting
(ii) Derived Casting
Primitive Casting
- Converting one primitive type of another primitive type is called as
primitive casting.
narrowing
Program
class TypeCastingLossOfData
{
public static void main(String[] args)
{
int x1=127;
byte y1=(byte) x1;
System.out.println("x1 = "+x1);
System.out.println("y1 = "+y1);
int a=240;
byte b = (byte)a;
System.out.println("a = "+a);
System.out.println("b = "+b);
}
} // in the above program while in 1st it does not loss of data
because byte holds the data upto 128 bytes but in the second
there is loss of data because we want o store 240 in byte, but the
capacity of byte is only 128.
Op :
X1 = 127
Y1= 127
A= 240
B= -16 // here loss of data
Program :
class TypeCasting
{
public static void main(String[] args)
{
double x1=20;
int y1=(int)x1;
System.out.println("x1 = "+x1);
System.out.println("y1 = "+y1);
}
}
o/p – x1=20.0
y1 = 20
- If we directly doing narrowing then it throws an error
Program :
class TypeCasting
{
public static void main(String[] args)
{
double x1=20;
int y1=x1;
System.out.println("x1 = "+x1);
System.out.println("y1 = "+y1);
}
}
//it throws an error as possible loss of precision
Simple typeCasing Program
class TypeCasting
{
public static void main(String[] args)
{
int a=20;
double b= a; // widening
System.out.println("a = "+a);
System.out.println("b = "+b);
double x1=20;
int y1=(int) x1; // narrowing
System.out.println("x1 = "+x1);
System.out.println("y1 = "+y1);
}
}
Op– x1=20
y1 = 20.0
x1=20.0
y1 = 20
- If you try to convert a character to integer then integer variable will
be containing Unicode value for the given character.
Program
class CharacterTypeCasting
{
public static void main(String[] args)
{
char c1 = 'A';
int i = c1; // widening
System.out.println("c1 = "+c1);
System.out.println("i = " + i);
int j = 77;
char c2 = (char)j; // narrowing
System.out.println(" j = " + j);
System.out.println( " c2 = " + c2);
}
}
Program : Write a Function or method which converts any given string to
lower case and print the same.
- For a method expecting primitive value we can pass the same
primitive datatype value and all its lower primitive datatype value.
Program
class Mainclass13
{
public static void test(int x )
{
System.out.println("this is test(int x) of sample");
}
public static void main(String[] args)
{
byte s = 10;
test(s);
short a = 52;
test(a);
int b=25;
test(b); }}
b
-
- For a method expecting primitive value then if we pass the higher
primitive datatype value then it throws an error.
Program
class Mainclass13
{
public static void test(int x )
{
System.out.println("this is test(int x) of sample");
}
public static void main(String[] args)
{
double d = 10.5;
test(d);
long l = 25.3;
test(l);
}
}
- If a class contains two overloaded methods one expecting lower
datatype value, other expecting higher datatype value and if you pass
a lower datatype value to call the method then always method with
lower datatype value will be executed.
Program
class Over
{
public static void test(int x )
{
System.out.println("This is test(int x) ");
System.out.println("print x = " + x);
}
public static void test(double x )
{
System.out.println("This is test(double x)");
System.out.println("print x = " + x);
}
public static void main(String[] args)
{
int v1=10;
test(v1);
}
}
// op : this is test(int x )
// print x = 10
Derived Casting
- Converting one reference type to another reference type is called as
derived casting.
- Derived Casting is of two type :
(i) Upcasting
(ii) Downcasting
Upcasting
- Converting subclass or childclass reference to superclass or parent
class reference is called as upcasing.
Program
class SuperClass
{
public void test()
{
System.out.println("This is test() ");
}
}
class Subclass extends SuperClass
{
public void view()
{
System.out.println("This is view()");
}
}
class Upcasting
{
public static void main(String[] args)
{
SuperClass sup1 = new Subclass(); //Upcasting
sup1.test();
or we can also write like this
Subclass sub1 = new Subclass();
SuperClass sup2=sub1; // Upcasting
sup2.test();
}
}
// op : this is test
- Using upcasted reference variables can access only superclass or
parent class property.
Program
class SuperClass
{
public void test()
{
System.out.println("This is test() ");
}
}
class Subclass extends SuperClass
{
public void view()
{
System.out.println("This is view()");
}
}
class Upcasting
{
public static void main(String[] args)
{
SuperClass sup1 = new Subclass();
sup1.view(); /* here it throw an error as cannot find the
symbol because Superclass reference can only access the
superclass method not a subclass method. */
}
}
- Upcasting will be done by the compiler implicitly.
- Upcasting is achieved by storing the address of child class object into
parent class reference variable.
SuperClass sup1 = new Subclass();
In the above line sup1 is the reference variable which store the
address of Sublclass object
Downcasting
- Converting the upcasted reference back to subclass reference is called as
downcasting.
- Downcasting should be done by the programmer explicitly by writing
casting statement.
Program
class SuperClass
{
public void test()
{
System.out.println("This is test() ");
}
}
class Subclass extends SuperClass
{
public void view()
{
System.out.println("This is view()");
}
}
class Upcasting
{
public static void main(String[] args)
{
SuperClass sup1 = new Subclass();
Subclass sub1 = (Subclass)sup1; // downcasting,
done by writing downcasting statment
sub1.test();
sub1.view();
}}
- We can downcast only upcasted reference. If we downcast directly
superclass into subclass then JVM throws an exception as
ClassCastException at runtime.
Program
class SuperClass
{
public void test()
{
System.out.println("This is test() ");
}
}
class Subclass extends SuperClass
{
public void view()
{
System.out.println("This is view()");
}
}
class Upcasting
{
public static void main(String[] args)
{
SuperClass sup1 = new SuperClass();
Subclass sub1 = (Subclass)sup1; // downcast directly
superclass without upcasting
sub1.test();
sub1.view();
}}
Derived Downcasting with Multilevel Inheritance
class SuperClass
{
public void display()
{
System.out.println("this is display() of SuperClass");
}}
class SuperClass2 extends SuperClass
{
public void click()
{
System.out.println("this is click() method of SuperClass2");
}
}
class Subclass extends SuperClass2
{
public void count()
{
System.out.println("this is count() of Subclass");
}}
class SuperClass1
{
public static void main(String[] args)
{
System.out.println("Program start....");
SuperClass2 ref1=new Subclass(); //upcasting
ref1.click();
ref1.display();
System.out.println();
- If you want to relate to unrelated classes then you can use Object Class
as the common superclass to perform derived casting, achieve runtime
polymorphism
Program
public static void connect(Object obj)
// here Object is the SuperClass of Mouse and Pendrive Class.
- If a method expecting superclass reference then for the same method
you can pass reference of superclass and all its subclass.
Program
class Mouse
{
public void click()
{
System.out.println("mouse button clicked");
}
}
class Pendrive
{
public void read()
{
System.out.println("reading data from pendrive");
}
public void write()
{
System.out.println("Write data to pendrive");
}
}
class Usb_Port
{
public static void connect(Object obj)
{
System.out.println("this is object obj of Usb_Port1");
}}
class Mainclass15
{
public static void main(String[] args)
{
Mouse m1= new Mouse();
Usb_Port.connect(m1); // pass the subclass reference to
connect method which expecting superclass reference
Pendrive p1 = new Pendrive();// pass the subclass reference
to connect method which expecting superclass reference
Usb_Port.connect(p1);
Object obj=new Object();
Usb_Port.connect(obj); // pass the superclass reference to
connect method which expecting superclass reference
}}
-
-
-
-
-
- If the class do not override the abstract methods of super class then the
class should be declared as abstract.
Program
}
class ab extends Sub
{
public void test()
{
System.out.println("this is test()");
}
}
class Practice
{
public static void main(String[] args) {
ab a = new ab();
a.test();
}
}
- Abstract class do not declared as final. It throw a compile time error.
Program
- Abstract method can not be declared as static, because static method can
not be overridden. It throw a compile time error.
Program
abstract class Sample
{
abstract public static void test(); // can not declare abstract
method as static
public void count()
{
System.out.println("this is count() of sample");
}}
class Mainclass9
{
public static void main(String[] args)
{
System.out.println("Program start");
}}
- Abstract class can not be declared as private.
Program
private abstract class Sample
{
abstract public void test();
public void count()
{
System.out.println("this is count() of sample");
}}
class Mainclass9
{ public static void main(String[] args)
{
System.out.println("Program start");
System.out.println("Program end ");
}}
- the static member of abstract class directly call by using
classname.datamember name
Program
abstract class Sample
{
static int x = 50;
abstract public void test();
}
class Mainclass12
{
public static void main(String[] args)
{
System.out.println("value of x " + Sample.x);
}
}
Program
}
public static void main(String[] args) {
System.out.println("program start");}}
(ii) data members are default static
Program
interface Run
{
int a =10; //default take as static
static int b = 20;
public void test();
}
class Mainclass2 implements Run
{
public void test()
{
System.out.println("hello");
}
public static void main(String[] args) {
System.out.println("program start");
System.out.println("value of a " + Run.a);
System.out.println("value of b " + Run.b);
}
}
- Till j.D.k. 1.7 it was not possible to write concrete method inside the
interface.
Program
interface Run
{
public void disp() // it throws an error
{
}}
class Mainclass2 implements Run
{
public static void main(String[] args) {
}}
- interface do not extends from any class (not even object class)
- interface do not have any constructor.
Program
interface Run
{
Run() // interface dont have a constructor
{
}
}
class Sub implements Run
{
}
class Mainclass7
{
public static void main(String[] args) {
}}
- one interface can only extends another interface but can not implements
it.
Program
interface Run
{
}
interface Run1 extends Run{
}
class Sub implements Run, Run1
{
}
class Mainclass7
{
public static void main(String[] args) {
System.out.println("Program Start");
}}
Op- Program Start
- if we write implements instead of extends then it throw an error
Program
interface Run
{
}
interface Run1 implements Run{
}
class Sub implements Run, Run1
{
}
class Mainclass7
{
public static void main(String[] args) {
System.out.println("Program Start");
}}
- A class can extends one class and implements an interface at the same
time.
Program
interface Run
{
}
class Super
{
}
class Sub extends Super implements Run //here extending a class and
implementing a interface at same time
{
}
class Mainclass7
{
public static void main(String[] args) {
System.out.println("Program Start");
}}
Op- Program Start
- One class implements any number of interfaces.
Program
interface Run
{
}
interface Run1
{}
interface Run2
{}
class Sub implements Run, Run1, Run2 // implementing morethan one
interface at a time
{
}
class Mainclass7
{
public static void main(String[] args) {
System.out.println("Program Start");
}}
Op- Program Start
- One interface can extends any number of interface.
Program
interface Run
{
}
interface Run1
{}
interface Run2 extends Run, Run1 // interface extending morethan one
interface
{}
class Sub implements Run2
{
}
class Mainclass7
{
public static void main(String[] args) {
System.out.println("Program Start");
}}
Op – Program Start
Extends
<<Run>>
Test();
<<Run1>>
count();
Sample
Program
interface Run
{
public void test();
}
interface Run1 extends Run
{
public void disp();
}
class Sample implements Run1
{
public void test()
{
System.out.println("This is test method");
}
public void disp()
{
System.out.println("This is disp method");
}
}
class Mainclass8
{
public static void main(String[] args) {
Sample s = new Sample();
s.test();
s.disp();
}
}
Op – this is test method
This is disp method
Multiple inheritance using interface
Program
interface Run
{
public void test();
}
interface Run1
{
public void disp();
}
class Sample implements Run1, Run
{
public void test()
{
System.out.println("This is test method");
}
public void disp()
{
System.out.println("This is disp method");
}
}
class Mainclass8
{
public static void main(String[] args) {
Sample s = new Sample();
s.test();
s.disp();
}
}
Op – this is test method
This is disp method
Marker interface
- An interface which do not contain any methods is called as master
interface
Program
interface Run
{
}
Functional interface
- An interface which contains only one abstract method is called as
functional interface.
Program
interface Run
{
public void disp();
}
CHAPTER 11 : POLYMORPHISM
- One entity showing different behaviours at different places is called as
polymorphism.
- Polymorphism helps in code flexibility
- There are two type of polymorphism.
(i) Compile time polymorphism
(ii) Runtime polymorphism
Compile time polymorphism
- Binding the method declaration to method definition by the compiler at
compile time based on the arguments is called as compile time
polymorphism.
- It is also called as static binding.
- Eg. Method overloading and constructor overloading
Runtime polymorphism
- Binding the method declaration to method definition by the jvm at run
time based on the object is called as runtime polymorphism.
- It is also called as dynamic binding.
- Eg. Method overriding.
Note :
Using an upcasted reference if you call an overridden method then you
always get overridden implementation on subclass implementation.
- To achieve runtime polymorphism we have to follow three steps :
(i) Inheritance
(ii) Method overriding
(iii) Upcasting
Program
class Superclass
{
public void test()
{
System.out.println("this is test(");
}
}
class Subclass extends Superclass // inheritance
{
public void test() // method overriding
{
System.out.println("overriding of test () in subclass");
}
}
class Mainclass1
{
public static void main(String[] args) {
Program
interface card
{
public void makePayment();
}
class Debit implements card
{
public void makePayment()
{
System.out.println("payment done by Debit");
}
}
class Credit implements card
{
public void makePayment()
{
System.out.println("payment done by credit");
}
}
class Swipemachine
{
public static void swipe(card c)
{
c.makePayment();
}
}
class Mainclass10
{
public static void main(String[] args) {
Credit c = new Credit();
Swipemachine.swipe(c);
Debit d = new Debit();
Swipemachine.swipe(d);}}
11. ABSTRACTION
- Hiding the implementation details of the class and exposing only the
behaviours or services is called as abstraction.
- To achieve abstraction we have to follow three steps :
(i) Generalize the methods of implementation class and store them
inside the interface.
Program
interface Account
{
public void deposit();
public void withdraw();
}
class Saving implements Account
{
public void deposit()
{
System.out.println("Money is deposit in saving account");
}
public void withdraw()
{
System.out.println("money is withdraw from saving
account");
}
}
class Fd implements Account
{
public void deposit()
{
System.out.println("money is deposit in FD account");
}
public void withdraw()
{
System.out.println("money is withdraw from FD account");
}
}
(ii) Create the object of implementation class and store the address in
interface reference variable.
Program
class AcntMgr
{
public static Account createAcnt(char type)
{
Account a1; // interface reference
if(type=='S')
{
a1 = new Saving(); //create he object of
implementation class and store the address in interface reference
return a1;
}
else
{
a1 = new Fd();
return a1;
}}}
(iii) Use the interface reference variables to access the methods of
implementation class.
Program
Program
interface Account
{
public void deposit();
public void withdraw();
}
class Saving implements Account
{
public void deposit()
{
System.out.println("Money is deposit in saving account");
}
public void withdraw()
{
System.out.println("money is withdraw from saving
account");
}
}
class Fd implements Account
{
public void deposit()
{
System.out.println("money is deposit in FD account");
}
public void withdraw()
{
System.out.println("money is withdraw from FD account");
}
}
class AcntMgr
{
public static Account createAcnt(char type)
{
Account a1;
if(type=='S')
{
a1 = new Saving();
return a1;
}
else
{
a1 = new Fd();
return a1;
}}}
class Mainclass1
{
public static void main(String[] args)
{
Account a1 = AcntMgr.createAcnt('S');
a1.deposit();
a1.withdraw(); }}
12. JAVA PACKAGES
GMAIL
SRC BIN
PUBLIC
visibility
PROTECTED
security
PACKAGE LEVEL
PRIVATE
- Access specifier are use to provide security for the clases and its members
by controlling visibility.
Public :
- If you declare any entity with public access specifier then it can be
accessed from the classes present in same package or different package.
- Public classes and its members will have highest visilibty and lowest
security.
- Used in same package .
package com.jspider.pkg1;
public class Demo
{
public int v1=100;
public void test()
{
System.out.println( "this is public void test()");
}
}
2nd Program which use the first package
package com.jspider.pkg1; // if we use public datamembers or methods
in same package and in different class then there is no need of using
any import statement or fully qualified classname. We can directly
use
public class Sample {
public static void main(String[] args) {
Demo d = new Demo();
System.out.println("v1 = " + d.v1);
d.test();
}
}
Op- v1 = 100
this is public void test()
- Used in different package
(i) It is mandatory to use import or fully qualified classname when we
want to access the members and methods of different packages. If
we don’t do it, then it throw a compile time error.
package com.jspider.pkg2;
import com.jspider.pkg1.Demo;
public class Run {
public static void main (String ar[])
{
Demo d1 = new Demo();
d1.test();
System.out.println("v1 = " + d1.v1);
}}
Op- v1 = 100
this is public void test()
Protected :
- If you declare any entity with protected access specifier then it can be
accessed from the classes present in the same package.
- It is partially visibile to another packages.
- Used in same packages
Program 1
package com.jspider.pkg3;
public class Demo1 {
protected int a = 10;
protected void test()
{
System.out.println("protected test() from com.jspider.pkg3; ");
}}
Program 2
package com.jspider.pkg3;
public class Sample1 {
Package-level :
- If you declare any entity without any access specifier keyword then those
members are considered as package level members.
- Package level members can be accessed only by classes present in same
packages.
- Used in same packages
Program
package com.jspider.pkglevel;
public class PkgLevel1 {
int v=20;
void test()
{
System.out.println("this is pkglevel test()");
}}
Program 2
package com.jspider.pkglevel;
public class Pkglevel2 {
public static void main(String[] args) {
System.out.println("a = " +PkgLevel1.v);
PkgLevel1.test();
}} op a = 20
this is pkglevel test()
- Used in different packages
Program
package com.jspider.pkglevel2;
import com.jspider.pkglevel.PkgLevel1;
public class Run2 {
public static void main(String[] args) {
PkgLevel1 pk = new PkgLevel1();
System.out.println("a = " + PkgLevel1.a);
PkgLevel1.test();
}
}
// in this program it throw an error because a datamember or
methods defined with package-level specifier can not be accessed
from different packages.
Private
- If you declare any entity as private specifier then it can be accessed only
within the class in which the members are declared.
- Compared to other access specifier private members will have highest
security and lowest visibility.
- Used in same class
Program
package com.jspider.privates;
public class Demo1 {
private int a = 20;
private void test()
{
System.out.println("a = " + a);
}
public static void main(String[] args) {
Demo1 d= new Demo1();
d.test();
}}
Op – a = 20
- Used in same package in different class
Program
package com.jspider.privates;
public class Sample1 {
public static void main(String[] args) {
superclass subclass
public public
protected public
protected
pkg-level pkg-level
public
protected
private can’nt be inherited
class Account
{
private int actno = 1234;
private double bal;
public void setBal(double amt)
{
if(amt>0)
{
bal=bal+amt;
}
else
{
System.out.println("invalid amount");
}
}
public double getBal(int actno)
{
if(actno==1234)
{
return bal;
}
else
{
return -777;
}
}
public int showAcnt(int pin)
{
if(pin==1234)
{
return actno;
}
else
{
return -777;
}
}
}
public class Mainclass {
System.out.println(com.jsp.innerclass.OuterClass.StaticNestedClass.z1);
// 1st execution from here 2.142
com.jsp.innerclass.OuterClass.StaticNestedClass ref1 =
new com.jsp.innerclass.OuterClass.StaticNestedClass();
ref1.count(); //print all the statement
}
} op –
2.142
this is count() of StaticNestedClass
V1 = 10
z1 = 2.142
(ii) by using import statement
Program
package com.jsp.innerclass;
import com.jsp.innerclass.OuterClass.StaticNestedClass;
class OuterClass
{
static int v1 = 10;
static class StaticNestedClass
{
static double z1 = 2.142;
public void count()
{
System.out.println("this is count() of StaticNestedClass");
System.out.println("V1 = "+v1);
System.out.println("z1 = " +z1);
}}}
public class Mainclass1 {
System.out.println(StaticNestedClass.z1);
}
public class Sample {
}
interface Run1
{
public void disp();
}
class Demo implements Run, Run1
{
@Override
public void disp()
{
System.out.println("this is overriding method");
}
}
public class Sample {
}} op – hello
hi
- If a class implements two interfaces which contains same static methods
which have same name and arguments then we can differentialte with the
help of interface name to call those methods.
Program
package practice;
interface Run
{
public static void disp()
{
System.out.println("hello");
}
}
interface Run1
{
public static void disp()
{
System.out.println("hi");
}
}
public class Test {
public static void main(String[] args) {
Run.disp();
Run1.disp(); // calling static method of interface
}}
FUNCTIONAL PROGRAMMING
- Passing a function as the argument to another function is called as
functional programming.
- functional programming in java can be done only with the help of
functional interface.
LAMBDA FUNCTION/EXPRESSION
- It is an anonymous function which written to give the implementation for
abstract method class present in functional interface.
- Syntax :
interface_name refvar = (arglist) ->
{ };
-> - it is called as lambda operator
Program
package practice;
interface Run
{
public void disp();
}
public class Test {
public static void main(String[] args) {
Run r = ()->
{
System.out.println("this is lambda function");
};
r.disp();
}} op – this is lambda function
Lambda Function with return value
Program
package practice;
interface Run
{
public int add(int a, int b);
}
public class Test {
public static void main(String[] args) {
Run r = (int a, int b)-> //passing the arguments
{
int c= a+b;
return c;
};
int res = r.add(10,20); // return a value and save it in a variable
System.out.println("res = "+res); }}
op – res = 30
Functional Programming with Lambda
package practice;
interface Run
{
public void draw();
}
class ShapeDrawer
{
public static void drawAnyThing(Run r)
{
r.draw();
}
}
public class Test {
public static void main(String[] args) {
Run r = ()->
{
System.out.println("drawing square");
};
Run r1 = ()->
{
System.out.println("drawing rectangle");
};
ShapeDrawer.drawAnyThing(r); // passing the reference
variable of a method to another method
ShapeDrawer.drawAnyThing(r1);
}} op – drawing square
drawing rectangle
JAVA LIBRARY
Object Class
- It is the supermost class in java
- Every class directly or indirectly inherits from object class.
- Object class is present in java.lang.package.
- Every methods of Object class is non-static.
Methods of Object Class :
- hashcode() - int
- toString() - String
- equals(Object ref) - Boolean
- wait() - void -final
- wait(long mills) - void final
- wait(long mills, int num) void final
- notify() - void final
- notifyAll() - void final
- finalize() - void
- clone() - Object
- getClass() - Object final
hashCode()
- This method returns hashcode value of the given object
- hashCode value is an unique integer value which is generated based on
the address of the objct.
Program
package com.inbuiltpackages.library;
public class Mainclass {
public static void main(String[] args) {
Object obj1 = new Object();
Object obj2 = new Object();
int h1=obj1.hashCode();
int h2 = obj2.hashCode();
System.out.println("h1 = " +h1);
System.out.println("h2 = "+h2);
}} - op - h1 = 1603195447
h2 = 792791759
toString() –
- This methods returns string representation of the object.
- The string representation of object contains :
(i) fully qualified classname
(ii) @ character
(iii) hexadecimal value of hashcode.
syntax
fullyqualifiedclassname@hexadecimal of hashcode
eg: java.lang.Object@4352625
Program
package com.inbuiltpackages.library;
toString()
System.out.println(obj);
implicitely calls
Program
package com.inbuiltpackages.library;
public class Mainclass {
public static void main(String[] args) {
Object obj1 = new Object();
Object obj2 = new Object();
System.out.println("obj1 = " +obj1);
System.out.println("obj2 = " +obj2);
}
} op - obj1 = java.lang.Object@5f8ed237
obj2 = java.lang.Object@2f410acf
equals(Object ref)
- This method compares hashCode value of given two object and returns
true if they are equals else it returns false it depends on hashCode.
Program
package com.inbuiltpackages.library;
Program
package com.jsp.string;
public class Mainclass2 {
public static void main(String[] args) {
java
s2 javaj2ee
s8 s8
s4 s9
j2ee
s5
non-constant
non- pool(duplicate
constant pool allowed)
(duplicate allowed)
java
s1 javaj2ee
java
javaj2ee S6
s3
S7
String Pool
Question : String class is immutable class explain ?
- if you try to change the existing string object, instead of changing the
given object a new object will be created with the changes. The reference
variable stops pointin to new object.
- The given object now becomes dereferences.
- only the object is created without using new keyword is immutable.
Advantages :
- If you referenced variables pointing to same string object then changes
done from one reference variable will not effect other reference variables.
Disadvantages :
- The dereferenced object wil be present in the heap memory for the future
use but these referenced object if not controlled results in
OutOfMemoryError
Program
package com.jsp.string;
public class StringBuffer1 {
public static String firstHalf(String str)
{
int mid = (str.length()-1)/2;
String res=" ";
for(int i =0; i<=mid; i++)
{
res = res+str.charAt(i);
System.out.println(res);
System.out.println(i);
}
return res;
}
public static void main(String[] args)
{
String s1 = new String("aaaaaabbbbbbbbbbbbb");
firstHalf(s1);
}}
// here 8 derefenced object are created.
- To overcome disadvantages of immutable property of string class java
introduced two new classes.
(i) StringBuffer
(ii) StringBuilder
String Function
Program
package strings;
System.out.println(a.indexOf("l")); //2
System.out.println(a.indexOf("l", 1)); //2
System.out.println(a.indexOf("l", 3)); //3
System.out.println(a.lastIndexOf("l")); //3
System.out.println(a.toUpperCase()); //HELLO
System.out.println(d.toLowerCase()); //hello
System.out.println(a.substring(3)); //lo
System.out.println(e.substring(2,10)); //pider ja
System.out.println(a.compareTo(d)); // 32
System.out.println(a.compareToIgnoreCase(b)); //0
s.append("friend");
System.out.println(s); //javayoufriend
s.insert(4, "for");
System.out.println(s);//javaforyoufriend
System.out.println(s.charAt(2)); //v
System.out.println(sb1); //javaorld
}
}
toString() of object class is overridden in StringBuffer class which returns the
string value present in the given StringBuffer Object.
//inheriting property of object class
package com.jsp.string;
public class Mainclass4 {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("hello");
int h1 = sb1.hashCode(); // not overriden
int h2 = sb2.hashCode();
System.out.println("h1 = "+h1);
System.out.println("h2 = "+h2);
String str = sb1.toString(); // overriden
System.out.println(sb1);
boolean b1 = sb1.equals(sb2); // not overriden
System.out.println(b1);
}
}
op –
h1 = 792791759
h2 = 1191747167
hello
false
StringBuilder (jdk 1.5)
- StringBuilder is not thread safe class.
- The methods of StringBuilder class are not synchronize.
- It is the immediate subclass of object class.
- StringBuilder class is present in java.lang.package
- StringBuilder implements serializable, appendable and charSequence
interface.
- StringBuilder class is declared as final and it can not be inherited.
- StringBuilder is mutable class.
- StringBuilder objects can be created only by using new operator.
- StringBuilder is not a thread-safe class.
- Every method of StringBuilder is not synchronized.
toString() of object class is overridden in StringBuilder class which returns the
string value present in the given StringBuffer Object.
Throwable
OutOfMemoryError LinkageError
System.out.println("Program start");
test(0);
System.out.println("Program ends");
}
}
op-
Program start
enter test
caught Arithmetic Exception
invalid number for division
exit test()
Program ends
try with multiple catch block
- for a single try block we can write any number of catch blocks.
Program
package com.object.exception;
public class Mainclass {
public static void test(int n)
{
int a1 [] = {10,20,30};
System.out.println("enter test");
try // one try block
{
System.out.println("result : "+10/n);
System.out.println("array element : "+a1[n]);
}
catch(ArithmeticException ref) // multiple catch statement
{
System.out.println("caught Arithmetic Exception");
System.out.println("invalid number for division");
}
catch(ArrayIndexOutOfBoundsException ref2) // multiple catch statement
{
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("invalid index");}
System.out.println("exit test()");
}
public static void main(String[] args) {
System.out.println("Program start");
test(5);
System.out.println("Program ends");
}}
op - Program start
enter test
result : 2
ArrayIndexOutOfBoundsException
invalid index
exit test()
Program ends
Generic try-catch block
Program
package com.object.exception;
public class Mainclass2 {
public static void test(int n)
{
System.out.println("enter test");
int a1 [] = {10,20,30};
String s1 = "hello";
Object obj = s1; // upcasting of string into object class
try
{
System.out.println("result : "+10/n);
System.out.println("array element : "+a1[n]);
StringBuffer sb1 = (StringBuffer)obj; //direct downcasting of object class into
StringBuffer throw ClassCastException
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("Program start");
test(2);
System.out.println("Program ends");
}}
Program start
enter test
result : 5
array element : 30
java.lang.ClassCastException: java.base/java.lang.String cannot be
cast to java.base/java.lang.StringBuffer
at com.object.exception.Mainclass2.test(Mainclass2.java:16)
at com.object.exception.Mainclass2.main(Mainclass2.java:27)
Program ends
printStackTrace()
Program
catch(Exception e)
{
e.printStackTrace();
}
Checked Exception
- Exceptions which are checked by the compiler at compile time are called
as checked exceptions.
- All the exceptions which are immediate subclass (ignore Runtime
Exception) are checked Exceptions.
- eg. InteruptedException, IOException , SqlException
Program
package com.object.exception;
public class Mainclass4 {
public static void test(int n)
{
Thread.sleep(1000); // checked Exception at compiletime
}
public static void main(String[] args)
{
System.out.println("program start");
test(0);
System.out.println("program end");
}}
op- Exception in thread "main" program start
java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException
at com.object.exception.Mainclass4.test(Mainclass4.java:7)
at com.object.exception.Mainclass4.main(Mainclass4.java:12)
Unchecked Exception
- Exceptions which are not checked by the compiler at compile time are
called as unchecked Exceptions.
- All the exceptions which are subclass of RuntimeExceptionClass are
unchecked exception.
Exceptions Propogation:
- Passing the exceptions object from called method to calling method is
known as Exception Propogation.
- Unchecked exceptions will be propagated implicitely by JVM.
- we can handle the exceptions of called methods in calling method.
Program
package com.object.exception;
public class Mainclass4 {
public static void test(int n) // called method
{
System.out.println("result = "+10/n);
}
public static void main(String[] args)
{
System.out.println("program start");
try // handle the exception in calling method
{
test(0);
}
catch (ArithmeticException ae)
{
ae.printStackTrace();
}
System.out.println("program end");
}}
Op
program start
java.lang.ArithmeticException: / by zero
at com.object.exception.Mainclass4.test(Mainclass4.java:7)
at com.object.exception.Mainclass4.main(Mainclass4.java:14)
program end
throws keyword :
- throws keyword is used to propagate checked exceptions from called
method to calling method explicitely.
- throws keyword should be written with method declaration.
- Using throws keyword we can propagate both checked and unchecked
exceptions.
Program
package com.object.exception;
public class Mainclass3 {
public static void test(int n) throws Exception
{
System.out.println("enter test");
System.out.println("result : "+10/n);
System.out.println("exit test");
Thread.sleep(2000); //checked exception
}
public static void main(String[] args) {
System.out.println("Program Start");
try
{
test(0);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Program end");
}}
object :
java.lang.ArithmeticException: / by zero
Program Start
enter test
at com.object.exception.Mainclass3.test(Mainclass3.java:8)
at com.object.exception.Mainclass3.main(Mainclass3.java:18)
Program end
- we can also call number of methods from calling propagated try block
Program
package practice;
public class Abc
{
public static void test(int x)
{
System.out.println("result ="+10/x);
}
public static void count(int y)
{
int a[]= {10,20,30};
System.out.println(a[y]);
}
public static void main(String[] args) {
try
{
test(10); //calling the method
count(5); //calling the method
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
op –
result =1
java.lang.ArrayIndexOutOfBoundsException: 5
at practice.Abc.count(Abc.java:12)
at practice.Abc.main(Abc.java:20)
throw keyword
- throw keyword is used to throw the exceptions explicitely.
- throw keyword is written within the method definition.
Program
public double getBal(int actno)
{
if(this.actno==actno)
{
return bal;
}
else
{
String msg = "invalid actno";
IllegalArgumentException ie = new IllegalArgumentException(msg);
throw ie; // throw keyword inside a method
}}}
- After throw keyword it is not possible to write any other line of codes.
Program
public double getBal(int actno)
{
if(this.actno==actno)
{
return bal;
}
else
{
String msg = "invalid actno";
IllegalArgumentException ie = new IllegalArgumentException(msg);
throw ie;
System.out.println("hello"); // throw a compile time error
}}}
- we can pass extra message about the exception with the constructor of
exception class.
Program
String msg = "invalid actno";
IllegalArgumentException ie = new IllegalArgumentException(msg);
Program
package com.object.exception;
class Account1
{
private int actno=1234;;
private double bal=520.5;
Stack
Program
package com.ds.stack;
class MyStack {
public MyStack()
{
stack = new int [DEFAULT_SIZE];
capacity = DEFAULT_SIZE;
}
public MyStack(int user_size)
{
stack = new int [user_size];
capacity = user_size;
}
public boolean push (int value)
{
if (size != stack.length)
{
stack [++top]= value;
size ++; //
return true;
}
else
{
return false;
}
}
public int pop()
{
if(size !=0)
{
size--;
return stack [top--];
}
else
{
String msg = "stack is empty";
IndexOutOfBoundsException e1 = new IndexOutOfBoundsException(msg);
throw e1;
}
}
public int getsize ()
{
return size;
}
public int getCapacity()
{
return capacity;
}
}
public class Test {
public static void main(String[] args)
{
Mainclass m = new Mainclass();
boolean b;
for (int i =0; i<m.getCapacity();i++)
{
b=m.push(225);
System.out.println(b);
}
for(int i=0;i<m.getCapacity();i++ )
{
int a =m.pop();
System.out.println(a);
}
}
}
/* in the case of pop element if you use getsize() then in this case every element
is not printed
* because at a when i becomes greater than size because every time size get
decremented
* and for loop terminated, thats y we use m.getCapacity() because capacity
remains same
* as the size and does not change.
* */
op –
true
true
true
true
true
225
225
225
225
225
Queue
package com.ds.queue;
class MyQueue1 {
private final int DEFAULT_SIZE = 5;
private int[] queue;
private int size = 0;
private int start = -1;
private int capacity = 0;
private int end = -1;
public MyQueue1()
{
queue= new int [DEFAULT_SIZE]; //initialize the array
capacity = DEFAULT_SIZE;// store default size into capacity
}
public MyQueue1(int user_size)
{
queue = new int [user_size]; // intialize the array
capacity = user_size; // store user size into capacity
}
public boolean eQueue(int value)
{
if(size!=queue.length)//check the size of queue
{
queue[++end]=value; // add the element into queue
size++; // increment the size
return true; //
}
else
{
return false;
}
}
public int dequeue()
{
if(size !=0)// check the size of queue
{
int v1 = queue[++start]; // dequeue element
size--; // decrement the size of queue
return v1;
}
else
{
String msg = "queue is empty";
IndexOutOfBoundsException e1 = new IndexOutOfBoundsException(msg);
throw e1;
}
}
public int size() // to get access of private data members
{
return size;
}
public int getCapacity()
{
return capacity;
}
}
public class test {
Composition
- A Node can be considered as an object which contains two parts.
(i) Data (ii) Address of next node
Program
package com.ds.linkedlist;
class Node1 {
int data;
Node next;
public Node1(int data)
{
this.data=data;
}
public void setNext(Node next)
{
this.next=next;
}
public Node getNext()
{
return next;
}
}
class MyLinkedList1 {
private int size=0;
private Node first;
private Node last;
public MyLinkedList1()
{
first=null;
last=null;
}
public boolean addToLast(int value)
{
Node n1= new Node(value);// create the object of node class
size++; // update size whenever an object is created
if(first==null) // if the size is null
{
first=n1; //
last=n1;
}
else
{
last.setNext(n1);
last=n1;
}
return true;
}
public int getValue(int position)
{
if(position<=size)
{
if(position==1)
{
return first.data;
}
else if (position==size)
{
return last.data;
}
else
{
Node temp =first.getNext();
for(int i=2;i<position;i++)
{
temp=temp.getNext();
}
return temp.data;
}
}
else
{
String msg = "invalid position";
IllegalArgumentException ie = new IllegalArgumentException(msg);
throw ie;
}
}
public int size()
{
return size;
}
}
public class Test {
public static void main(String[] args) {
System.out.println("------------");
int sz = m1.size();
for(int i =1; i<=sz;i++)
{
int v2 = m1.getValue(i);
System.out.println(v2);
}}}
op –
40
------------
20
40
60
80
100
120
140
OBJECT ARRAY
- It is a type of array where every bucket of the array represents a reference
variable of the given class or interface.
- Syntax :
classname [] ref_var = new classname[size];
eg :
ref_Var
0 1 2 3 4 5
name =
blake
id= 1234
Program
package com.arry.objectarray;
class Employee
{
String name;
int id;
double bal;
Employee(String name, int id, double bal)
{
this.name=name;
this.id=id;
this.bal=bal;
}}
public class Mainclass {
public static void main(String[] args) {
Employee[] emplist = new Employee[2];
emplist[0]= new Employee("blake", 142,252.5);
emplist[1]= new Employee("Martin", 122,525.5);
processSalary(emplist);
}
public static void processSalary(Employee[] emp)
{
for(int i=0; i<emp.length;i++)
{
System.out.println("name = "+emp[i].name);
System.out.println("Id = "+emp[i].id);
System.out.println("-----------");
}}}
eg :
name = blake
Id = 142
-----------
name = Martin
Id = 122
-----------
Program 2
package com.arry.objectarray;
class VehicleCar
{
String model;
String name;
double price;
VehicleCar(String model, String name, double price)
{
this.model=model;
this.name=name;
this.price=price;
}
@Override
public String toString()
{
return "Model = " +model + "Name = "+ name + " price = " +price ;
}}
class VehicleBike
{
String model;
String name;
double price;
VehicleBike(String model, String name, double price)
{
this.model=model;
this.name=name;
this.price=price;
}
@Override
public String toString()
{
return "Model = " + model + " Name = "+name + " price = " +price ;
}
}
class Mainclass
{
public static void main(String[] args) {
LIST
Types of List
- ArrayList
- Linked List
- Stack
- Vector
Features of List
- Duplicates are allowed
- Indexed type collection
- Multiple Null values are allowed.
- Insertion order is preserved.
ArrayList (JDK 1.2)
- Arraylist implements list, collection, iterable seralizable, cloneable and
random access interfaces.
- The underline data structure for arraylist is resizable array.
- The time required to retrieve first element or last element of arraylist is
always constant or same.
Constructor
- Arraylist()
Construct an empty list with an initial capacity of ten.
- Arraylist(int intial capacity)
Construct an empty list with the specified intial capacity.
- Arraylist(Collection e)
This Constructor creates a list by converting given collection.
Program 1
package com.ds.collectionframework;
class Employee
{
String name;
int id;
double sal;
Employee(String name, int id, double sal)
{ this.name=name;
this.id=id;
this.sal=sal;
}}
Program2 to usitilize it
//arraylist Program
package com.ds.collectionframework;
import java.util.ArrayList;
public class Mainclass {
public static void main(String[] args) {
ArrayList emplist = new ArrayList();
emplist.add(new Employee ("Blake", 1234, 2341.3));
emplist.add(new Employee ("Sundar", 1274, 2346.3));
processSalary(emplist);
}
public static void processSalary(ArrayList ref)
{
for (int i =0; i<ref.size(); i++)
{
Employee e1 = (Employee) ref.get(i);
System.out.println("name = "+e1.name);
System.out.println("salary = "+e1.sal);
}}}
Functions of ArrayList
package com.jsp.arraylist;
import java.util.*;
public class Mainclass2 {
public static void main(String[] args) {
a.set(1, "sadaf");
System.out.println("elements present "+a);
//elements present [aatif, sadaf]
int pos= a.indexOf("aatif");
System.out.println("position of = "+pos);
//posiition of = 0
int pos1= a.indexOf("preeti");
System.out.println("position of = "+pos1);
//position of = -1
String sb = (String) a.get(1); //upcasted to object type
System.out.println("at index = " +sb);
//at index = sadaf
Boolean b = a.contains("salman");
System.out.println(b); // returns false
a.clear();
System.out.println("Elements after clear " +a);
//elements after clear = []; empty
}}
showVehicleDetails(vlist);
}
public static void showVehicleDetails(ArrayList ref)
{
for(int i=0; i<ref.size();i++)
{
if (ref.get(i)instanceof VehicleCar)
{
VehicleCar c1 = (VehicleCar)ref.get(i);
System.out.println(c1);
}
else
{
VehicleBike b1 = (VehicleBike)ref.get(i);
System.out.println(b1);
}}}}
op-
Model = hondaName = city price = 25.2
Model = hyundaiName = i20 price = 8.2
Model = KTM Name = Duke price = 1.75
Model = Royal Name = Classic price = 2.75
st
or Program 1 program
package com.ds.collectionframework;
class VehicleCar
{
String model;
String name;
double price;
VehicleCar(String model, String name, double price)
{
this.model=model;
this.name=name;
this.price=price; }
@Override
public String toString()
{
return "Model = " +model + "Name = "+ name + " price = " +price ;
}}
class VehicleBike
{
String model;
String name;
double price;
VehicleBike(String model, String name, double price)
{
this.model=model;
this.name=name;
this.price=price;
}
@Override
public String toString()
{
return "Model = " + model + " Name = "+name + " price = " +price ;
}}
Program 2 to implement it
package com.ds.collectionframework;
import java.util.*;
public class Mainclass7 {
public static void main(String[] args) {
ArrayList vlist = new ArrayList();
vlist.add(new VehicleCar("honda", " city", 25.2));
vlist.add(new VehicleCar("hyundai", "i20", 8.20));
vlist.add(new VehicleBike("KTM", "Duke", 1.752));
vlist.add(new VehicleBike("Royal", "Classic", 2.75));
showVehicleDetails(vlist);
}
public static void showVehicleDetails(ArrayList ref)
{
for(int i=0; i<ref.size();i++)
{
Object obj= ref.get(i);
System.out.println(ref.get(i));
System.out.println("--------");
}}}
op –
Model = hondaName = city price = 25.2
--------
Model = hyundaiName = i20 price = 8.2
--------
Model = KTM Name = Duke price = 1.752
--------
Model = Royal Name = Classic price = 2.75
--------
Generics
- Generics in collection are used to achieve two goals.
(i) type-safety by writing : collection<classname>
(ii) Avoid unnecessary downcasting of object.
Program
package com.ds.collectionframework;
import java.util.ArrayList;
public class Mainclass6 {
public static void main(String[] args) {
ArrayList<Employee> emplist = new ArrayList<Employee>();
emplist.add(new Employee ("Blake", 1234, 2341.3));
emplist.add(new Employee ("Sundar", 1274, 2346.3));
processSalary(emplist);
}
public static void processSalary(ArrayList<Employee> ref)
{
for (int i =0; i<ref.size(); i++)
{
Employee e1 = (Employee) ref.get(i);
System.out.println("name = "+e1.name);
System.out.println("salary = "+e1.sal);
}}}
op- name = Blake
salary = 2341.3
name = Sundar
salary = 2346.3
Functions of Stack
import java.util.Stack;
public class A {
for eg :
for(Employee e1 : ref)
arraylist
{ ref
S.O.P(e1.name);
S.O.P(e1.sal);
} object object
Program
//arraylist Program
package com.ds.collectionframework;
import java.util.ArrayList;
public class Mainclass6 {
public static void main(String[] args) {
ArrayList<Employee> emplist = new ArrayList<Employee>();
emplist.add(new Employee ("Blake", 1234, 2341.3));
emplist.add(new Employee ("Sundar", 1274, 2346.3));
processSalary(emplist);
}
public static void processSalary(ArrayList<Employee> ref)
{
for(Employee e1 : ref)
{
System.out.println(e1.name);
System.out.println(e1.sal);
}}}
op - Blake
2341.3
Sundar
2346.3
for-each Method()
- This method is introduced from JDK 1.8 which helps the programmer to
iterate collections.
- For-each method acceps consumer(interface) type references.
Consumer interface
- It is a functions interface which contains only one abstract method by the
name Accept(T t)
Program
package com.ds.collectionframework;
//use of for each method
import java.util.ArrayList;
import java.util.function.Consumer;
public class Mainclass9 {
public static void main(String[] args) {
ArrayList<String> a1 = new ArrayList<String>();
a1.add(new String("hello"));
a1.add(new String("java"));
a1.add(new String("Android"));
for(int i=0; i<a1.size();i++)
{
String str = a1.get(i);
System.out.println(str.length());
//System.out.println(a1.get(i).length()); we can also write like that }
/we can also write like this lambda function
Consumer<String> ref = (String s1)->
{
System.out.println(s1.length()); };
a1.forEach(ref);
//we can also write like this lambda function
Consumer <String> ref1= (String s2) -> System.out.println(s2.length());
a1.forEach(ref1);
//we can also write like this lambda function
a1.forEach((String s3)-> System.out.println(s3.length()));;
//we can also write like this lambda function
a1.forEach(s4-> System.out.println(s4.length()));
}}
Vector (JDK 1.0)
- All the methods are synchronized
- Vector is thread safe class.
- Vector implements list, collection, iterable seralizable, cloneable and
random access interfaces.
- The underline data structure for Vector is resizable array.
- The time required to retrieve first element or last element of Vector is
always constant or same.
Constructor
- Vector()
Construct an empty list with an initial capacity of ten.
- Vector(int intial city)
Construct an empty list with the specified intial capacity.
- Vector(Collection e)
This Constructor creates a list by converting given collection.
Note :
- The load factor decides when should be new collection created to add
new elements.
- The load factor of arrraylist and vector is 100% or 1.
- The new capacity of arraylist is calculated using the below formulae.
New Capacity = (old capacity*3/2)+1
- New Capaicty of vector is calculated with below formulae.
New Capacity = old capacity *2
SET
- Set do now allow duplicates.
- Set do not have index.
- only one null value can be stored.
- insertion order is not preserved.
(a) Set do not allow duplicates
Program
package com.cf.set;
import java.util.HashSet;
public class Mainclass1 {
public static void main(String[] args) {
h.forEach(s4-> System.out.println(s4));
}}
op - hi
java
hello
- only one null value can be stored.
Program
import java.util.HashSet;
public class Mainclass1 {
public static void main(String[] args) {
HashSet<String> h = new HashSet<String>();
h.add(new String("hello"));
String s=null;
String b = null;
h.add(s);
h.add(b);
h.add(new String("java"));
h.forEach(s4-> System.out.println(s4));
}}
op –
null
java
hello
- insertion order is not preserved.
Program
import java.util.HashSet;
import java.util.function.Consumer;
public class Mainclass1 {
public static void main(String[] args) {
h.forEach(s4-> System.out.println(s4));
}}
op - hi
java
hello
hashSet
- hashSet implements iterable, collection, set, clonable and serializable
interfaces.
- The underline data structure for hashset is hash table.
- hashSet preserve uniqueness by compairing hashcode value of given
objects.
Constructors of hashSet:
(i) public hashSet()
construct a new empty set with default initial capacity(16) and load
factors (0.75)
(ii) public hashSet(int initialcapacity)
construct a new empty set with given initial capacity and load
factor(0.75)
(iii) public hashset(int initialcapaicty, float loadfactor)
construct a new empty set with given initial capacity and load factor.
(iv) public hashSet(Collection c)
construct a new set with given collection.
- if you try to add duplicates value, we don’t get any compile time error
and runtime exceptions.
Adding unique user defined object :
- if you want to add unique user defined object to the set then you should
override hashcode method and equals method in the given user defined
class.
Program
package com.cf.set;
public class Employee {
String name;
int id;
double sal;
Employee(String name, int id, double sal)
{ this.name=name;
this.id=id;
this.sal=sal;
}
@Override
public boolean equals(Object obj)
{
Employee emp=(Employee)obj;
if(this.hashCode()==emp.hashCode())
{
return true; }
else
{
return false;
}}
@Override
public int hashCode()
{
return id;
}
@Override
public String toString()
{
String info = name + " " +id + " "+ sal;
return info;
}}
nd
2 Program
package com.cf.set;
import java.util.HashSet;
public class Mainclass3 {
public static void main(String[] args) {
HashSet<Employee> hs = new HashSet<Employee>();
hs.add(new Employee("Blake",101,2012.2));
hs.add(new Employee("Rohit",102,2052.2));
hs.add(new Employee("Blake",101,2012.2));
hs.forEach(emp -> System.out.println(emp));
}}
op - Blake 101 2012.2
Rohit 102 2052.2
LinkedHashSet
- The underline data structure is hashtable and linkedList.
- LinkedHashSet preserve insertion order
Program
import java.util.HashSet;
import java.util.LinkedHashSet;
}} op – android
java
(ii) Treeset do not have any index, but return sorted result.
Program
import java.util.TreeSet;
public class Mainclass {
public static void main(String[] args) {
package com.jsp.treeset;
import java.util.TreeSet;
public class Mainclass {
public static void main(String[] args) {
}}
op – here it throw a runtime exception as
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.TreeMap.put(Unknown Source)
at java.base/java.util.TreeSet.add(Unknown Source)
at com.jsp.treeset.Mainclass.main(Mainclass.java:10)
(i) Insertion order is not preserved
Program
import java.util.TreeSet;
public class Mainclass {
public static void main(String[] args) {
int val=this.id-emp.id;
return val;
} */
/*@Override // sorted on the base of salary
public int compareTo(Employee emp) {
int val=(int)(this.sal-emp.sal);
return val;
}*/
@Override // sorted on the base of name
public int compareTo(Employee emp) {
String n1=this.name;
String n2=emp.name;
int val = n1.compareTo(n2);
return val;
}}
2nd Program to implement it
package com.jsp.treeset;
import java.util.TreeSet;
public class Mainclass1
{
public static void main(String[] args) {
}}
op- It returns output on the basis of sorting of name in ascending order
Aatif 1895 2358.3
Blake 1234 2341.3
Satya 1525 9684.3
Sundar 1274 2346.3
aatif 1895 2358.3
Customized Sorting
- Sorting of inbuilt classes such as String according to programmer choice.
- Comparator interface is used for Customized Sorting.
- Comparator interface is a part of java.util. package.
- Comparator interface is a functional interface having one abstract method
as compare(T o1, T o2)
Program
package com.jsp.treeset;
import java.util.Comparator;
import java.util.TreeSet;
public class Mainclass2 {
public static void main(String[] args) {
// using lambda function here because Comparator is an functional
interface
Comparator<String> c1= (String s1, String s2)->
{
int v1 = s2.compareTo(s1);
return v1;
};
passing the reference of interface to the constructor of TreeSet
TreeSet<String> ts = new TreeSet<String>(c1);
ts.add("java");
ts.add("android");
ts.add("bigdata");
ts.add("python");
ts.add("eclipse");
ts.add("class");
}}
op-
android
bigdata
class
eclipse
java
python
import java.util.LinkedList;
op-
java
java
java
(ii) Index is present
Program
package com.ds.queuecollection;
import java.util.LinkedList;
op-
bigdata
op-
null
null
null
LinkedList Collection
- The underline data structure for linked list collection is LinkedList data
structure.
- LinkedList implements List and Queue interface.
- LinkedList can be used as a list and as well as queue.
- We can retrieve the elements from the linkedList using two method.
(i) get(index)
(ii) poll()
Constructor of LinkedList :
(i) public LinkedList()
construct an empty list.
(ii) public LinkedList(Collection c)
Construct a list from the given collection.
Poll()
- It returns the head elements from the queue and also removes it from the
queue.
Peek()
- It returns head elements from the queue but doesn’t remove it from
queue.
Use of Poll method
Program
package com.ds.queuecollection;
import java.util.LinkedList;
key value
name phone
a 1425
b 525
a 2536
int x1=10;
double y1=22.13;
double y1=22.13;
Double d1=y1; // auto-boxing
Double d4=d1; // auto-unboxing without using new operator
System.out.println("y1 = "+y1);
System.out.println("d1 = "+d1);
System.out.println("d4 = "+d4);
}}
op-
y1 = 22.13
d1 = 22.13
d4 = 22.13
- toString() of object class is overridden in every wrapper class which
returns the value present in the given object.
- If you try to assign a primitive value to object class reference then jvm
performs two operations –
(i) It creates an wrapper class object for the given primitive value
(auto-boxing)
(ii) The wrapper class object will be upcasted to object class
reference.
Program
public class Mainclass2 {
public static void add(Object i1, Object i2)
{
System.out.println("this is add method");
}
public static void disp(Integer i1, Integer i2)
{
System.out.println("this is disp()");
}
public static void main(String[] args) {
}
}
op-
this is add method
this is disp()
String n1="100";
String n2= "200";
int a = 150;
int b = 150;
System.out.println("res = " +(a+b));
String s1 = String.valueOf(a);
String s2 = String.valueOf(b);
System.out.println("res = " +s1+s2);
}
}
op –
res = 300
res = 150150
Thread & MultiThreading
- Thread is an independent part of same program which gets its own stack
and cpu-time for the execution.
- Threads are used to achieve program level multitasking and concurrency.
- Whenever jvm starts the execution it will create three threads.
(i) Main Thread
(ii)Thread Schedular
(iii) Garbage collector
// create the object of subclass and using the subclass object call Start
method.
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
t1.start(); // start method internally call run method and execute business logic
t2.start();
System.out.println("Program end");
}}
op –
Program starts
Program end
executing task one
executing task two
note – here output change every time, because start method provide a cpu
time to every thread, in which time cpu is free the thread is executed.
Implementing Runnable Interface
- Runnable is a functional interface and supports lambda function.
- create a lambda function for runnable interface.
i) create the object of thread class and pass the lambda function
references to the constructor of thread class.
ii) use the thread object and call start method.
iii) Start method is the method of Thread class only.
Program
package com.threads;
public class Mainclass2 {
public static void main(String[] args) {
System.out.println("program start");
//create a lambda function for runnable interface.
Runnable r1 = () ->
{
System.out.println("executing task one ");
};
Runnable r2 = () ->
{
System.out.println("executing task two ");
};
create the object of thread class and pass the lambda function references to
the constructor of thread class.
}}
op –
Program starts
Program end
executing task one
executing task two
note – here output change every time, because start method provide a cpu
time to every thread, in which time cpu is free the thread is executed.
- Question : Why runnable interface was introduced in java.
Ans : - If a class is already extending another super class then it is not
possible to extend thread class because it leads to multiple inheritance
and multiple inheritance is not supported in java.
t1.setName("task 1 ");
String t3Name = t1.getName();
System.out.println("t3 name user define name = " +t3Name);
t2.setName("tast 2");
String t4Name = t2.getName();
System.out.println("t4 name user definmed name = " +t4Name);
t1.start();
t2.start();
}}
op-
program start
t1 name default name = Thread-0
t2 name default name = Thread-1
t3 name user define name = task 1
t4 name user definmed name = tast 2
executing task one
executing task two
Id :
- The id of the thread will be assigned by the thread scheduler and hence it
can not be changed by the programmer.
Program
package com.threads;
public class Mainclass4 {
public static void main(String[] args) {
Runnable r1 = () ->
{
};
Runnable r2 = () ->
{
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}}
op -
t1 id = 12
t2 id = 13
Priority :
- The priority of the thread helps the thread scheduler to order the
execution of the threads.
- The priority of the thread can be changed by using setPriority method.
- The priority of the thread should be always within the range of 1 to 10,
where 1 is the lowest priority, 5 is the normal priority and 10 is the
highest priority.
Program
package com.threads;
public class Mainclass4 {
public static void main(String[] args) {
System.out.println("program start");
Runnable r1 = () ->
{
System.out.println("executing task one ");
};
Runnable r2 = () ->
{
System.out.println("executing task two ");
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}}
op –
program start
executing task two
executing task two
executing task one
executing task one
sleep() :
- sleep() will pause the execution of given thread for the specified time
limit in millisecond and gives the chance for the other thread which is
having same or higher priority.
- here in this program there is a limit of 1 second.
Program
package com.threads;
public class Mainclass4 {
public static void main(String[] args) {
System.out.println("program start");
Runnable r1 = () ->
{
try {
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
for(int i =1; i<3;i++)
{
System.out.println("executing task one ");
}};
Runnable r2 = () ->
{
for(int i =1; i<3;i++)
{
System.out.println("executing task two ");
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}}
op –
program start
executing task two
executing task two
executing task one
executing task one
join() :
- join() will pause the execution of all threads until the given thread
completes the execution.
- join() is a non static method of thread class and it should be called only
from the thread object.
- join() is used after the start method.
Program
package com.threads;
public class Mainclass4 {
public static void main(String[] args) {
System.out.println("program start");
Runnable r1 = () ->
{
for(int i =1; i<3;i++)
{
System.out.println("executing task one ");
}
};
Runnable r2 = () ->
{
for(int i =1; i<3;i++)
{
System.out.println("executing task two ");
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
try {
t1.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Program end");
}}
op - program start
executing task one
executing task two
executing task two
executing task one
Program end
output changes
Race Condition
t1
customer …..
print
{ …….
}
…..
t1
Account ……
Resource
t1
inconsistent data
Bank
Race Condition:
t2
t1.start();
t2.start(); }}
output
program start
t1 waitingg to lock s1
t2 waiting to lock s1
t1 locked to s1
s1 = hijava
t1 released lock on s1
t2 locked to s1
s1 = hijavahello
t2 released lock on s1
Deadlock
- Deadlock is a situation where thread one is waiting to acquire the object
lock of thread two and thread two and thread two is waiting to acquire
object lock on thread one and both threads wait for infinite period of time.
s1
t1
t1 s2
Runnable r1 = () ->
{
System.out.println("t1 waiting to lock s1");
synchronized(s1)
{
System.out.println("t1 locked to s1");
t1.start();
t2.start();
}}
op-
program start
t1 waiting to lock s1
t1 locked to s1
t1 waiting to lock s2
t2 waiting to lock s2
t2 locked to s2
output will be changed.
wait() :
- wait() will pause the execution of the thread and also releases all the
object locks the given thread is holding.
- wait() can be called only from synchronized block or synchronized
method.
- If you call wait() from a non-synchronized method or non-synchronized
block then JVM throws IllegalMonitorStateException
notify()
- notify() is used to communicate termination state of one thread to another
thread.
notifyAll()
- This methods is used to communicate the termination status of one thread
to every other thread of the given programmes.
Program
package com.threads;
public class Mainclass8 {
static String s1= new String("hi");
static String s2= new String("android");
try {
System.out.println("t1 going to wait state ");
s1.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("t1 waiting to lock s2");
synchronized(s2)
{
System.out.println("t1 locked to s2");
System.out.println("t1 released lock on s2");
}}
System.out.println("t1 released lock on s1");
};
Runnable r2 = () ->
{
System.out.println("t2 waiting to lock s2");
synchronized(s2)
{
System.out.println("t2 locked to s2");
synchronized(s1)
{
System.out.println("t2 locked to s1");
System.out.println("t2 released lock on s1");
s1.notify();
}}
System.out.println("t2 released lock on s2");
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}}
op
program start
t1 waiting to lock s1
t1 locked to s1
t1 going to wait state
t2 waiting to lock s2
t2 locked to s2
t2 locked to s1
t2 released lock on s1
t1 waiting to lock s2
t2 released lock on s2
t1 locked to s2
t1 released lock on s2
t1 released lock on s1
Thread Life Cycle
wait
Running/
new Runnable Dead
execution
start() run() stop()
blocked
yield()
join()
sleep()
sleep
Differences
Run() Sleep
1- Run() executes all the business 1- It creates a new thread and
logic written in main thread executes all the business logics
of run() in the new thread
2- Run method should be 2- It can be overridden but not
overridden to write the business recommended because all the
logics. business logic will be executed
in main thread.
Sleep() wait()
1- sleep() pause the execution and 1- wait() pause the execution of the
does not release the object lock thread and release the object
lock.
2- it can not be used for Inter 2- It should be used for Inter
Thread Communication Thread Communication
3- sleep() is present in thread class 3- wait() is present in object class
Garbage Collector
- Garbage collector is used to remove the unused objects which are de-
referenced from the heap area.
- Garbage collector can be called explicitely by using System.gc().
- finalize() of object class will be called implicitely by the garbage
collector just before the object is removed from the heap area.
- If you want to execute any lines of codes just before the object is
removed from heap area, then we should override finalize of object class.
- It is always a best practice to re-initialize referenced variables to NULL,
once the uses of object is over.
- Garbage collector only clear the de-referenced object.
package com.jsp.garbagecollector;
class Student{
String name = "Smith";
int id=1234;
@Override
protected void finalize()
{
System.out.println("Object removed....");
}}
public class Mainclass {
public static void main(String[] args) {
System.out.println("Program starts....");
Heap F1
E1
object o/p and byte
fout
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
e.printStackTrace();
}
finally
{
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}}}}
Op –
Object written
Deserilization
Jvm Hard Disk
Heap Emp.ser
E1
object i/p and byte
fin
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
class Employee implements Serializable
{
int id;
String name;
public Employee(int id, String name)
{
super();
this.id=id;
this.name=name;
}
}
public class Mainclass6 {
e.printStackTrace();
}}}}
Op -
123
Abc
Object Cloning
- Creating an object from an existing object with the same data is called as
object cloning.
- If you want to clone an object then the class should implements clonable
interface(which is market interface).
- You should also override clone method of object class to perform
cloning.
- Copying all the data from exisiting object to cloned object is called as
deep-copying.
Program
package com.jsp.clone;
class Emp extends Object implements Cloneable
{ String name;
int id;
Double salary;
Emp(String name, int id, Double salary){
this.name=name;
this.id=id;
this.salary=salary;
}
@Override
public String toString()
{
String info = id+ " "+name+ " "+salary;
return info; }
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}}
public class Mainclass2 {
public static void main (String ar[])
{
Emp e1 = new Emp("Blake", 123, 2314.14);
System.out.println("Hashcode =" +e1.hashCode());
System.out.println(e1);
try
{
Emp e2 = (Emp) e1.clone();
System.out.println("Hashcode = " +e2.hashCode());
System.out.println(e2);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}}}
Op-
Hashcode =792791759
123 Blake 2314.14
Hashcode = 434176574
123 Blake 2314.14
- Copying only required data from the existing object to cloned object
is called as shallow copying.
Program
package com.jsp.clone;
this.name=name;
this.id=id;
this.salary=salary;
}
@Override
public String toString()
{
String info = id+ " "+name+ " "+salary;
return info;
}
@Override
protected Object clone() throws CloneNotSupportedException
{
Emp emp = new Emp (name, 0, salary);
return emp;
}
}
public class Mainclass2 {
this.name=name;
this.id=id;
this.salary=salary;
}
@Override
public String toString()
{
String info = id+ " "+name+ " "+salary;
return info; }
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}}
public class Mainclass2 {
static
{
System.out.println("this is static block-1 ");
}
public static void main(String[] args)
{
System.out.println("Program start");
System.out.println("Program end");
}
static
{
System.out.println("this is static block 2");
}
}
Op
this is static block-1
this is static block 2
Program start
Program end
- If any block is non-static block then we can call the non-static block only
by creating the object of that class.
Program
package classfornam;
public class Mainclass3 {
{
System.out.println("this is non-static block ");
}
public static void main(String[] args)
{ Mainclass3 m = new Mainclass3();
System.out.println("Program start");
System.out.println("Program end");
}}
this is non-static block
Program start
Program end
- If in a class there is non-static block and static block both present, and
non-static block comes before the static block, in this case also static
block executed first.
Program
package classfornam;
public class Mainclass3 {
{
System.out.println("this is non-static block ");
}
static
{
System.out.println("this is static block-1 ");
}
public static void main(String[] args)
{
- The .class file of the program will be loaded to the memory in two cases :
i) If you create the object of class.
ii) Refer to any static members of class.
- We can load the .class file to the memory explicitely by using
class.forName()
- If the constructor of the class is private and there is no static data
members and methods present in the class, then to create the object of the
class in another class is not possible, due to private constructor, and in
this case if we want to create the object it throw a compile time error.
then in this case we have to use Class.forName().
Class.forName()
- For this method we have to pass fully qualified classname as the
arguments in string data type.
Class loads
- create the object
- refer to any static Static block
Once class load will be executed
members Of class.
Demo.class
package classfornam;
class Sample1
{
private Sample1()
{
}
static
{
System.out.println("this is static block");
}}
public class Mainclass3 {
public static void main(String[] args)
{
System.out.println("Program start");
try {
Class.forName("classfornam.Sample1");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Program end");
}}
Program start
this is static block
Program end
- If the given class is not present in the given package, then this method
will throw ClassNotFoundException.
Program
package classfornam;
class Sample1
{ private Sample1()
{
}
static
{
System.out.println("this is static block");
}}
public class Mainclass3 {
- Properties file is a type of the file where the data is stored in key value
format.
- We can write the data to properties file using setProperty().
Program
public static void createProp() // to create properties file
{
Properties p1 = new Properties();
p1.setProperty("username", "scott");
p1.setProperty("Password","tiger");
String path = "G:\\JavaFile/DB.prop";
FileOutputStream fos;
try {
fos = new FileOutputStream(path);
p1.store(fos, "Oracle 10g details");
System.out.println("File created .....");
}
- Once the data is set, we can store the key and value to the properties file
by using store()
Program
fos = new FileOutputStream(path);
p1.store(fos, "Oracle 10g details");
- To read the data from the properties file we can use load().
Program
FileInputStream fis = new FileInputStream(path);
p1.load(fis);
- To load() creates a temporary hashtable and copies all the key, values,
from properties file to hashtable.
- We can get the values from the hashtable using getProperty() by passing
valid keys.
Program
public static void readProp() // to read properties file
{
String path = "G:\\JavaFile/DB.prop";
Properties p1 = new Properties();
try {
FileInputStream fis = new FileInputStream(path);
p1.load(fis);
String us=p1.getProperty("username");
String pwd = p1.getProperty("Password");
System.out.println(us);
System.out.println(pwd);
}
catch (Exception e) {
e.printStackTrace();
}
}
Program
//properties file nothing but hashtable
package classfornam;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class Mainclass2 {
public static void createProp() // to create properties file
{
Properties p1 = new Properties();
p1.setProperty("username", "scott");
p1.setProperty("Password","tiger");
String path = "G:\\JavaFile/DB.prop";
FileOutputStream fos;
try {
fos = new FileOutputStream(path);
p1.store(fos, "Oracle 10g details");
System.out.println("File created .....");
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void readProp() // to read properties file
{
String path = "G:\\JavaFile/DB.prop";
Properties p1 = new Properties();
try {
FileInputStream fis = new FileInputStream(path);
p1.load(fis);
String us=p1.getProperty("username");
String pwd = p1.getProperty("Password");
System.out.println(us);
System.out.println(pwd);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String ar[])
{
System.out.println("program start");
// createProp();
readProp();
System.out.println("Program end ");
}
}
Op-
program start
scott
user123
Program end
Singleton Class
- A class for which we can create only one single object is called as
singleton clas.
- To create a singleton class, we have to follow two steps :
i) Declare the constructors of the class as private.
Program
private Demo()
{
System.out.println("Object created");
}
ii) Create a public static method which returns address of same
objects.
Program
public static Demo getObject()
{
if(ref==null)
{
Demo ref = new Demo();
}
return ref;
}
Simple Program
package com.jsp.singletonclass;
class Demo
{
static Demo ref = null;
private Demo()
{
System.out.println("Object created");
}
public static Demo getObject()
{
if(ref==null)
{
ref = new Demo();
}
return ref;
}
}
public class Mainclass {
Demo d1 = Demo.getObject();
System.out.println("d1 = "+d1);
Op –
Object created
d1 = com.jsp.singletonclass.Demo@2f410acf
d2 = com.jsp.singletonclass.Demo@2f410acf
Factory Method
- A method which returns object of same class using which it is called is
known as factory methods.
Eg : Demo d1 = Demo.getObject();
What is the use of Singelton Class
- In the case of thread, every interface can be created the object of class, so
in this case, there will be a chance of multiple resources, so here no race
condition will be occurred. To create a race condition, we can use
singleton class.
Program
package com.jsp.singletonclass;
class Count
{
static int value = 0;
static Count ref = null;
private Count()
{
System.out.println("Object created");
}
public static Count getObject()
{
if(ref==null)
{
ref=new Count();
}
return ref;
}
public void intcrement()
{
value++;
}
public void decrement()
{
value--;
}
public void showValue()
{
System.out.println("value = "+value);
}
}
public class Mainclass2 {
public static void main(String[] args) {
System.out.println("program start");
Runnable r1 = () ->
{
Count c1 = Count.getObject();
c1.intcrement();
c1.showValue();
};
Runnable r2 = () ->
{
Count c1 = Count.getObject();
c1.decrement();
c1.showValue();
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}}
Op
program start
Object created
value = 1
value = 0
output will be changed.
EXTRA TOPICS
BLOCKS IN JAVA
Initialization of Datamembers in java :
i) At declaration
ii) Using blocks
iii) Using Constructors
Blocks
- Set of statements enclosed within curly braces without any declaration is
known as blocks.
- There are two types of blocks
i) Static block
ii) Non-static bloc
Flow of JVM
i) Load
ii) Initialize
a) Declaration
b) Block
c) Constructor – non static
d) Execute
Static block
- The blocks declared with static key word are known as static blocks.
- Static blocks are used to initialized only static data members of the class
not, not non-static methods.
- Within the class if both main method and static blocks are present first
static blocks are executed then main method.
Program
package practice;
class Demo
{
static double b ;
static
{ b = 3.2;
System.out.println("executing static block");
}
public static void main(String[] args)
{ System.out.println("main method started...");
System.out.println("b= "+Demo.b);
System.out.println("Main method end"); }}
Op-
executing static block
main method started...
b= 3.2
Main method end
- Static blocks get executed at class loading time.
- Static blocks get executed only once per class.
- Within a same class first static block are executed when the class loading
then main() executed.
- But for a different class class, first main() executed then static block
get executed at time of class loading.
Program
package practice;
class Abc_1
{
static double b ;
static
{
b = 3.2;
System.out.println("executing static block");
}
}
class Demo
{
public static void main(String[] args)
{
System.out.println("main method started...");
System.out.println("b= "+Abc_1.b);
System.out.println("Main method end");
}}
Op-
main method started...
executing static block
b= 3.2
Main method end
Multiple Static blocks within a Class:
Program
package practice;
class Demo
{
static char ch ;
static
{
ch ='a';
System.out.println("executing static block-1");
}
static
{
ch ='b';
System.out.println("executing static block-2");
}
public static void main(String[] args)
{
System.out.println("main method started...");
System.out.println("ch= "+ch);
System.out.println("Main method end");
}
static
{
ch = 'c';
System.out.println("executing of static block 3");
}
}
Op-
executing static block-1
executing static block-2
main method started...
ch= b
Main method end
- With static block JVM can access blocks before main methods.
Non-static Block
- The blocks which are declared without static keyword is known as non-
static block.
Syntax
{
}
- It can be initialized both static members as well as non-static members of
the class.
- Non-static block can be executed only at the time of object creation.
Program
package practice;
class Demo
{
static int a;
double b;
{
a=133;
b=7.6;
System.out.println("executing non-static block-1");
}
public static void main(String[] args)
{
System.out.println("main method started...");
System.out.println("a = "+a);
Demo d = new Demo();
System.out.println("after object creation, a = "+a);
System.out.println("b = "+d.b);