JAVA NOTES
JAVA NOTES
Table of Contents
INTRODUCTION ____________________________________________________________ 8
1.Core Java: _________________________________________________________________________________ 8
1.1CoreJava provides the following programming Concepts: ___________________________________________________ 8
1.2 CoreJava provides the following Object Oriented Programming features: _____________________________________ 9
Programming components needed to construct the program: Error! Bookmark not defined.
define program? ______________________________________________________ Error! Bookmark not defined.
The following are minimum programming components needed to construct the program: _ Error! Bookmark not
defined.
wt is the diff b/w (i)Functions (ii)Member functions (iii)Methods ______________ Error! Bookmark not defined.
define Class? _________________________________________________________ Error! Bookmark not defined.
define Object? ________________________________________________________ Error! Bookmark not defined.
Keywords: _________________________________________________________________________________ 24
Page
1
DataTypes in Java: _________________________________________________________ 24
1.Primitive DataTypes: _______________________________________________________________________ 24
2.NonPrimitive DataTypes: ____________________________________________________________________ 26
faq: why char 2 bytes in Java? ________________________________________________________________ 27
Behaviour: _________________________________________________________________________________ 56
2
define while loop? _________________________________________________________ 58
syntax: Flowchart: ________________________________________________________________ 58
__________________________________________________________________________________________ 58
'static' import?______________________________________________________________________________ 81
3
define sqrt() method? ________________________________________________________________________ 81
OVERRIDING _______________________________________________________________________________ 92
define Method Overriding process? _____________________________________________________________________ 92
4
InnerAbstractClass within the AbstractClass:(Nested AbstractClass) __________________________________ 125
Comparision Diagram:_______________________________________________________________________ 135
Summary:_________________________________________________________________________________ 166
5
WrapperClasses __________________________________________________________ 167
List of WrapperClasses: ______________________________________________________________________ 167
Hierarchy of WrapperClasses: _________________________________________________________________ 167
Boxing process _____________________________________________________________________________ 167
AutoBoxing process _________________________________________________________________________________ 171
Framework________________________________________________________________________________ 198
6
Generic Types _____________________________________________________________________________ 198
1.Set<E>: _________________________________________________________________________________ 199
2.List<E>: _________________________________________________________________________________ 200
Note: _____________________________________________________________________________________________ 204
(a)ArrayList<E>: _____________________________________________________________________________________ 206
(b)LinkedList<E>: ____________________________________________________________________________________ 206
Note: _____________________________________________________________________________________________ 207
(c)Vector<E>: _______________________________________________________________________________________ 208
Stack<E> __________________________________________________________________________________________ 211
7
Dt : 31/5/2021
INTRODUCTION
Java comes on under Langauge category.
=>Process of learning language:
Step-1 : Alphabets
Step-2 : Grammer
Step-3 : Construction Rules
Note:
=>Every Language will have its own Alphabets,Grammer and Construction rules.
=>In Learning process Java Language is available in two parts:
1.Core Java
2.Advanced Java
1.Core Java:
=>CoreJava provides the fundamental Building blocks which are used in
Constructing programs.
(Fundamental Building blocks means Java Alphabets or Programming Components)
List of programming components in Java:
(a)Variables
(b)Methods
(c)Blocks
(d)Constructors
(e)Classes
(f)Interfaces
(g)AbstractClasses
7.GUI Programming
8
1.2 CoreJava provides the following Object Oriented Programming
features:
1.Class
2.Object
3.Abstraction
4.Encapsulation
5.PolyMorphism
6.Inheritance
2.Advanced Java:
2.1 Advanced Java provides the following technologies to construct Web :
Applications:
(a)JDBC
(b)Servlet
(c)JSP
=>'JDBC' stands for Java DataBase
Connection and which is used to
interact with DataBase product.
=>'Servlet' is a Server program and
which is used to accept the request
from EndUser(clent) through
WebBrowser.
=>'JSP' stands for Java Server page and
which is response from the Web
Application.
Faq:
define Web Application?
=>The application which is executing in Web Environment or Internet Environment is known as Web
Application.
==============================================================================
Dt : 1/6/2021
faq:
Exp:
Page
9
CoreJava
(ii)Technology:
=>The process of applying the knowledge to realtime world for construction is known as Technology.
Exp:
JDBC
Servlet
JSP
(iii)Framework:
=>The Structure which is readily available for application development is known as Framework.
Exp:
Hibernate
Spring
--------------------------------------------------------------------------------------------------------------------------------------
define Program?(Syllabus)
=>Program is a 'set-of-Instructions'.
define programming?
=>The process of constructing program is known as Programming.
define programmer?
=>The person who writes the program is known as Programmer.
Note:
=>After writing the program,we save the program with language extention.
Exp:
Test.c
Test.cpp
Test.java
10
Page
10
=>The program will have the following two stages:
1.Compilation stage
2.Execution stage
1.Compilation stage:
=>The process of checking
the program constructed
within the rules of language
or not,is known as
Compilation process.
Note:
=>After Compilation process is successfull,
=>c and c++ languages generate Objective code and Java language generate Byte code.
2.Execution stage:
=>The process of running the compiled code and checking whether the required output is generated or
not,is known as Execution stage.
Note:
=>The Objective Code is converted into Executable code after 'loading and linking process' ,then the
Executable code will generate result.
=>The ByteCode is loaded onto JVM(Java Virtual Machine) for execution process.
-------------------------------------------------------------------------------------------------------------------------------------------
Dt : 2/6/2021
11
(ii)Byte Code:
=>The compiled code which is generated from Java programs is known as ByteCode.
=>while ByteCode generation operatingSysten is not participated,because of this reason ByteCode is
PlatForm independent code.
Advantage:
=>The Byte code which is generated from one platform can be executed on all the
PlatForms in realtime.
Note:
=>Java Language which is generating ByteCode is PlatForm independent language.
-------------------------------------------------------------------------------------------------------------------------------------------
Dt : 3/6/2021
faq:
define Translator?
=>Translator is used to convert HLL Codes into LLL Codes and ViceVersa.
12
Page
12
=>Translators are categorized into two types:
(i)Compilers
(ii)Interpreters
(i)Compilers:
=>Compilers will translate the total program at a
time.
(ii)Interpreters:
=>Interpreters will translate the program line-by-
line.
Java Versions:
=>JDK 1.9
13
=>JRE 1.9
2018 - Java10,Java11
2019 - Java12,Java13
2020 - Java14,Java15
2021 - Java16,Java17
=============================================================================
Dt : 4/6/2021
14
javax.servlet.jsp - JSP Programming package
(ii)JRE:
=>JRE stands for 'Java Runtime Environment' and
which is collection of
JavaLib and JVM.
Note:
=>In realtime JRE is used part of Servers(Web
Servers and Application Servers)
--------------------------------------------------------------------------------------------------------------------------------------------
15
java - Execution process
-------------------------------------------------------------------------
Dt : 5/6/2021
faq:
(ii)System Variables:
=>The information in the System
variables can be used by all the users
of Computer System.
Dt : 7/6/2021
Variables : a,b,c
a=12
b=13
c=25
Methods : add()
Starting point : main()
16
Page
import java.lang.System;
16
class Addition
{
int a,b,c;
void add()
{
c = a+b;
System.out.print(c);
}
public static void main(String args[])
{
Addition ad = new Addition();
ad.a = 12;
ad.b = 13;
ad.add();
}
}
Note:
=>'int' represents numeric data without decimal point.
=>'float' represents numeric data with decimal point.
=>'void' represents Non-Retutn_type methods
=>In JavaLang main() is having the following built-in Standard format:
'public static void main(String args[])'
17
JVM Architecture:
=>JVM stands for 'Java Virtual Machine' and which is used to execute JavaByteCode.
18
(i)BootStrap CL
(ii)Extention CL
(iii)Application CL
(i)BootStrap CL:
=>BootStrap CL will load the required files from the JavaLib.
Exp:
"System" and "String" classes are loaded by BootStrap CL
(ii)Extention CL:
=>Extention CL will load the required files from Built-in 'ext' folder of JDK.
(iii)Application CL:
=>Application CL will load the required files from the 'classpath' of Environment variables.
(b)Linker:
=>The Linker will link the loaded files into Current running program,in this process it internally uses the
following components:
(i)Verify
(ii)Prepare
19
(iii)Resolve
Page
19
(i)Verify:
=>Verify component will perform verification process,which means it checks the loaded files and the
required files are same or not.
(ii)Prepare:
=>Prepare component perform decoding process,which means identifying the programming
components like variables,methods,...
(iii)Resolve:
=>Resolve identifies the components are Static programming components orNonStatic programming
componenets based on 'static' keyword.
=>The programming components which are declared with 'static' keyword are known as Static
programming components and can be accessed with class_name.
=>The programming components which are declared without 'static' keyword are
known as NonStatic programming components and can be accessed with Object_name.
Note:
=>static programming components will get the memory within the class while class loadig.
=>NonStatic programming components will get the memory within the object while Object creation.
Exp:
From the above program,
Static programming components : main()
NonStatic programming components : a,b,c,add()
(c)Initiate:
=>Initiate component will perform initialization process,which means generates 'Runtime Data Area'
and the class is loaded onto Method_Area.
*imp
2.Runtime Data Area:
=>This Runtime Data Area internally divided into the following blocks:
(a)Method Area - where class is loaded
(b)Heap Area - where Objec is created
(c)Java Stack Area
20
20
(a)Method Area:
=>The memory block where the class is loaded is known as Method_Area.
=>while class loading static programming components will get the memory,in this process main() will
get the memory within the class and loaded automatically
onto JavaStackArea to start the execution process.
Dt : 11/6/2021
EXecution behaviour of 'new' keyword:
step-1: The 'new' keyword
specify the
ExecutionControl to create
reference(address) part of
Heap_area.
step-2: The 'new' keyword
specify the
ExecutionControl to check
the required class is
available on Method_Area
or not.
step-3: When the required
class is available on
Method_Area,then take
the NonStatic members
from the class and give
memory at reference.(Address)
step-4: After binding all the NonStatic members to reference(address),then load the reference onto
reference Varaible or Object_name.
Execution flow of Addition.java:
(b)Heap Area:
=>The memory block where the objects are created is known as Heap_Area.
21
(i)Object State
(ii)Object Behaviour
(iii)Object Identification
(i)Object State:
=>The variable part of object is known
as Object state.
(ii)Object Behaviour:
=>The method part of object is known
as Object Behaviour
(iii)Object Identification:
=>The variable which is holding the
reference of object is known as Object
Identification/Object Name/Object reference variable
=>ExecutionEngine will take the support of JNI(Java Native method Interface) to execute Native
Page
methods.
22
=>while execution JNI will use Native method Libraries.
Dt : 15/6/2021
3.Execution Engine:
=>ExecutionEngine is an executor of JVM and which is also known as Virtual Processor of JVM.
=>This ExecutionEngine will find the main() method from JavaStackArea and start the execution process.
=>This ExecutionEngine internally uses the following two translators:
(i)Interpreter
(ii)JIT(Just-In-Time) Compiler
(i)Interpreter:
=>Interpreter will start the execution process and execute normal instructions.
=>when Interpreter finds Stream Instructions(Multimedia Instructions) then the
control is transferred to the JIT-Compiler.
(ii)JIT(Just-In-Time) Compiler:
=>This JIT-Compiler will execute Stream Instructions(Multimedia Instructions).
-------------------------------------------------------------------------
*imp
packages:
23
23
Classes&Interfaces::
=>In calsses&Interfaces the starting letter must be capital or UpperCase.
Exp:
Addition
Employee
Variables&Methods:
=>In Variables and methods the first word must be in LowerCase and from Second word onwards the
starting letter must be capital.
Exp:
panCardNo
rollNo
getRollNo()
readLine()
...
Keywords:
=>Keywords means Pre-defined words or Built-In words from the S/W.
=>These keywords must be in LowerCase.
Exp:
void
public
static
...
-------------------------------------------------------------------------------------------------------------------------------------------
DataTypes in Java:
=>The types of data which we are expecting as input to JavaProgram are known as 'DataType in Java'.
=>DataTypes in java are categorized into two types:
1.Primitive DataTypes
2.NonPrimitive DataTypes
1.Primitive DataTypes:
=>The 'Single valued data formats' are known as Primitive DataTypes or Basic
DataTypes or Fundamental DataTypes.
24
Page
24
(a)Integer datatypes
(b)Float datatypes
(c)Character datatype
(d)Boolean datatype
(a)Integer datatypes:
=>The numeric data without decimal point representation is known as Integer datatype.
Exp:
12,13,14,...
Types:
byte - 1 Byte(8 bits)
short - 2 Bytes
int - 4 Bytes
long - 8 Bytes
(b)Float datatypes:
=>The numeric data with decimal point representation is known as Float datatype.
Exp:
12.45,23.45,...
Types:
float - 4 Bytes
double - 8 Bytes
(c)Character datatype:
=>The Single valued caharacter which is represented in single quotes is known as Character datatype.
Exp:
'A','k',...
Types:
char - 2 Bytes
(d)Boolean datatype:
=>The datatype which is available in the form of true or false is known Boolean datatype.
Exp:
true or false
Types:
boolean - 1 Bit
25
Page
25
2.NonPrimitive DataTypes:
=>The 'group valued data formats' are known as NonPrimitive DataTypes or referential DataTypes.
=>NonPrimitive DataTypes are categorized into the following:
(a)Class
(b)Interface
(b)Array
(c)Enum
-------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>byte and short is used for stream data.(Multimedia data)
=>int is used to hold normal int data part of applications.
=>long is used to hold large numbers in the applications like PhoneNo,accNO,...
=>we use "l" or "L" in the RHS of declaration while representing long value.
=>double is used to hold largest calculated Scientific values in the application.
=>float is used to hold normal float data in the application.
=>while declaring float data,we must use "f" or "F" in the RHS of declaration,
because by default JVM considers float data as double.
Exp program:
DVariables.java
import java.lang.System;
import java.lang.String;
class DVariables
{
public static void main(String[] args)
{
byte b = 127;
short s = 32767;
int i = 631234;
long l = 9898981234l;
float f = 12.34F;
double d = 123456.789;
26
char ch = 'A';
Page
boolean b2 = true;
26
System.out.println("byte value:"+b);
System.out.println("short value:"+s);
System.out.println("int value:"+i);
System.out.println("long value:"+l);
System.out.println("float value:"+f);
System.out.println("double value:"+d);
System.out.println("char value:"+ch);
System.out.println("boolean value:"+b2);
}
}
O/p:
byte value:127
short value:32767
int value:631234
long value:9898981234
float value:12.34
double value:123456.789
char value:A
boolean value:true
---------------------------------------------------------------------------------------------------------------------------------
21/6/2021
*imp
Page
27
Operators of Java:
=>Operator is a special symbol or keyword which perform operation.
=>The following are some important operators from Java:
1.Arithmetic operators
2.Relational operators
3.Logical Operators
4.Increment/Decrement Operators
1.Arithmetic operators:
=>The operators which perform basic operations are known as Arithmetic Operators.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
2.Relational operators:
=>The operators which perform comparaisions and generate boolean result are known as Relational
Operators.
Operator Meaning
> Greater Than
>= Greater Than or equal
< Less Than
<= Less Than or equal
== Is equal to
!= Not equal to
3.Logical Operators:
=>The operators which are used to compare comparisions and generate Boolean result.
Operator Meaning
&& Logical AND
|| Logical OR
28
! Logical Not
Page
28
Logical AND(&&):
A B A&&B
T T T
T F F
F T F
F F F
Logiacl OR(||)
A B A||B
TT T
TF T
FT T
FF F
Logical NOT(!):
A !A
T F
F T
4.Increment/Decrement Operators:
=>Increment operator is used to increment the value by 1 and decrement operator is used to decrement
the value by 1.
Operator Meaning
++ Increment
-- Decrement
==============================================================================
29
1.Selection Statements:
=>The statements which are used to execute some part of the program based on condition are known
as Selection Statements or Conditional Statements.
Types:
(a)Simple if
(b)if-else
(c)Nested if
(d)Ladder if-else
(e)switch-case
2.Iterative Statements:
=>The statements which are used to execute some lines of program repeatedly on some condition are
known as Iterative Statements or Repeatitive Statements or
Looping Structures.
Types:
(a)while loop
(b)do-while loop
(c)for loop
3.Branching Statements:
=>The statements which are used to transfer the execution control from one location to another
location of program are knwon as Branching Statements or
Transfer Statements.
Types:
(a)break
(b)continue
(c)exit
(d)return
Note:
=>There is no concept of 'goto' in Java.
==============================================================================
*imp
30
Page
30
Object oriented programming(OOPS):
=>The process of constructing programs using Class-Object concept is known as Object Oriented
Programming.
=>In Object Oriented Programming,we control the following NonPrimitive datatypes or Referential
datatypes:
(1)Class
(2)Interface
(3)Array
(4)Enum
(1)Class:
=>The Class is a 'Structured Layout' in java and which generates Objects.
=>The Classes in Java are categorized into two types:
(a)User defined classes
(b)Built-In Classes
(a)User defined classes:
=>The classes which are defined by the programmer are known as User defined
classes.
Exp:
Addition.java
(b)Built-In Classes:
=>The classes which are available from JavaLib are known as Built-In classes or
PreDefined classes.
ExP:
String
System
Scanner
....
31
-----------------------------------------------------------------------------------------------------------------------------------------
Page
31
Exp program:
wap to read employee bSal and display totSal?
totSal = bSal + HRA + DA;
HRA = 93% of bSal
DA = 63% of bSal
Note:
=>bSal of an employee must be min 5000/-(Condition)
import java.lang.String;
import java.lang.System;
import java.util.Scanner;
class Salary //SubClass
{
int bSal;//NonStatic component
void cal()//NonStatic component
{
if(bSal>=5000)
{
float totSal = bSal+(0.93F*bSal)+(0.63F*bSal);
System.out.println("BSal:"+bSal);
System.out.println("TotSal:"+totSal);
}//end of if
else
{
System.out.println("Invalid bSal...");
}
}
}
class SMainClass //MainClass
{
public static void main(String[] args)
{
32
32
Salary sl = new Salary();//User defined class object
System.out.println("Enter the bSal:");
sl.bSal = s.nextInt();//reading input from keyboard
sl.cal();//Method call
}
}
define 'Scanner'?
=>'Scanner' is a Built-in or PreDefined class from java.util package and which
provides the following some important methods to read data from console(Keyboard).
(1)nextByte()
(2)nextShort()
(3)nextInt()
(4)nextLong()
(5)nextFloat()
(6)nextDouble()
(7)nextBoolean()
(8)nextLine()
(1)nextByte():
=>This method is used to read byte data.
Method Signature:
public byte nextByte();
(2)nextShort():
=>This method is used to read short data.
Method Signature:
public short nextShort();
(3)nextInt():
=>This method is used to read int data.
Method Signature:
public int nextInt();
(4)nextLong():
=>This method is used to read long data.
33
Page
Method Signature:
33
public long nextLong();
(5)nextFloat():
=>This method is used to read float data.
Method Signature:
public float nextFloat();
(6)nextDouble():
=>This method is used to read double data.
Method Signature:
public double nextDouble();
(7)nextBoolean():
=>This method is used to read boolean data.
Method Signature:
public boolean nextBoolean();
(8)nextLine():
=>This method is used to read String data.
Method Signature:
public java.lang.String nextLine();
=>All the above methods are NonStatic methods of 'Scanner' class and all these methods will get the
memory within the 'Scanner class object' and can be accesedwith Object_name
syntax of object creation for 'Scanner' class:
Scanner s = new Scanner(System.in);
define 'System'?
=>'System' is a class from java.lang package and which provides the following static NonPrimitive
datatype variables:
(i)in - for input data
34
34
Accessing syntaxes:
System.in
System.out
System.err
=>'System.in' represents connecting the Input Buffer to the Scanner class object.
Execution flow of above program:
=========================================================================
Assignment:
wap to read and display CustDetails?
Classes:
CustDetails
=>accNo,custName,accType,bal
=>void getCustDetails()
35
CustMainClass
Page
import java.lang.String;
import java.lang.System;
import java.util.Scanner;
class CustDetails //SubClass
{
long accNo;
String custName,accType;
float bal;
void getCustDetails()
{
System.out.println("AccNo:"+accNo);
System.out.println("CustName:"+custName);
System.out.println("AccType:"+accType);
System.out.println("Balance:"+bal);
}
}
class CustMainClass //MainClass
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);//Built-in class object
CustDetails cd = new CustDetails();//User defined class object
System.out.println("Enter the AccNo:");
cd.accNo = s.nextLong();
s.nextLine();//reading \n from the Buffer
System.out.println("Enter the CustName:");
cd.custName = s.nextLine();
System.out.println("Enter the AccType:");
cd.accType = s.nextLine();
System.out.println("Enter the Balance:");
36
cd.bal = s.nextFloat();
Page
36
cd.getCustDetails();
}
}
import java.lang.String;
import java.lang.System;
import java.util.Scanner;
class Addition //SubClass
{
int add(int x,int y)
{
return x+y;
}
}
class Subtraction //SubClass
{
int sub(int x,int y)
{
return x-y;
}
}
class Multiplication //SubClass
{
int mul(int x,int y)
37
{
Page
return x*y;
37
}
}
class Division //SubClass
{
float div(int x,int y)
{
return (float)x/y;
}
}
class ModDivision //SubClass
{
int modDiv(int x,int y)
{
return x%y;
}
}
class MainClass1 //MainClass
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the value1:");
int v1 = s.nextInt();
System.out.println("Enter the value2:");
int v2 = s.nextInt();
System.out.println("====Choice====");
System.out.println("1.add\n2.sub\n3.mul\n4.div\n5.modDiv");
System.out.println("Enter the choice:");
int choice = s.nextInt();
switch(choice)
{
38
case 1:
Page
38
Addition ad = new Addition();
System.out.println("Sum:"+ad.add(v1,v2));
break;
case 2:
Subtraction sb = new Subtraction();
System.out.println("Sub:"+sb.sub(v1,v2));
break;
case 3:
Multiplication ml = new Multiplication();
System.out.println("Mul:"+ml.mul(v1,v2));
break;
case 4:
Division dv = new Division();
System.out.println("Div:"+dv.div(v1,v2));
break;
case 5:
ModDivision md = new ModDivision();
System.out.println("ModDiv:"+md.modDiv(v1,v2));
break;
default:
System.out.println("Invalid option...");
}//end of switch
}
}
=============================================================================
Dt : 24/6/2021
Assignment1:(Solution)
import java.util.Scanner;
class Product //SubClass
{
String pCode,pName;
39
Page
float pPrice;
39
int pQty;
void getProduct()
{
System.out.println("PCode:"+pCode+"\nPName:"+pName+
"\nPPrice:"+pPrice+"\nPQty:"+pQty);
}
}
class PMainClass //MainClass
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
Product p = new Product();
System.out.println("Enter the PCode:");
p.pCode = s.nextLine();
System.out.println("Enter the PName:");
p.pName = s.nextLine();
System.out.println("Enter the PPrice:");
p.pPrice = s.nextFloat();
System.out.println("Enter the PQty:");
p.pQty = s.nextInt();
p.getProduct();
}
}
Assignment2:(Solution)
import java.util.Scanner;
class BookData //SubClass
{
String bCode,bName,bAuthor;
float bPrice;
40
Page
int bQty;
40
void getBookData()
{
System.out.println("BCode:"+bCode+"\nBName:"+bName
+"\nBPrice:"+bPrice+"\nBQty:"+bQty);
}
}
class BMainClass //MainClass
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
BookData bc = new BookData();
System.out.println("Enter the BCode:");
bc.bCode = s.nextLine();
System.out.println("Enter the BName:");
bc.bName = s.nextLine();
System.out.println("Enter the BAuthor:");
bc.bAuthor = s.nextLine();
System.out.println("Enter the BPrice:");
bc.bPrice = s.nextFloat();
System.out.println("Enter the BQty:");
bc.bQty = s.nextInt();
bc.getBookData();
}
}
Assignment3:(solution)
import java.util.Scanner;
class SResult //SubClass
{
int s1,s2,s3,s4,s5,s6;
41
Page
void cal()
41
{
if((s1>=0 && s1<=100)&&(s2>=0 && s2<=100)&&(s3>=0 && s3<=100)
&&(s4>=0 && s4<=100)&&(s5>=0 && s5<=100)&&(s6>=0 && s6<=100))
{
int totMarks = s1+s2+s3+s4+s5+s6;
float per = (float)totMarks/6;//TypeCasting
System.out.println("TotalMarks:"+totMarks);
System.out.println("Percentage:"+per);
if(per>=70 && per<=100)
{
System.out.println("Result:Destinction");
}
else if(per>=60 && per<70)
{
System.out.println("Result:FisrtClass");
}
else if(per>=50 && per<60)
{
System.out.println("Result:SecondClass");
}
else if(per>=35 && per<50)
{
System.out.println("Result:ThirdClass");
}
else
{
System.out.println("Result:Fail");
}
}
else
{
42
System.out.println("Invalid Marks...");
Page
42
}
}
}
class StuMainClass //MainClass
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
SResult sr = new SResult();
System.out.println("Enter the marks of Telugu:");
sr.s1 = s.nextInt();
System.out.println("Enter the marks of Hindi:");
sr.s2 = s.nextInt();
System.out.println("Enter the marks of English:");
sr.s3 = s.nextInt();
System.out.println("Enter the marks of Maths:");
sr.s4 = s.nextInt();
System.out.println("Enter the marks of Science:");
sr.s5 = s.nextInt();
System.out.println("Enter the marks of Social:");
sr.s6 = s.nextInt();
sr.cal();
}
}
==============================================================================
Assignment4:
Update Assignment3 by displaying the result as "Fail",when any one subject entered
in b/w 0 to 34.
Assignment4:(Solution)
import java.util.Scanner;
{
Page
43
int s1,s2,s3,s4,s5,s6;
void cal()
System.out.println("TotalMarks:"+totMarks);
System.out.println("Percentage:"+per);
System.out.println("Result:Fail");
}//end of if
else
System.out.println("Result:Destinction");
System.out.println("Result:FisrtClass");
System.out.println("Result:SecondClass");
System.out.println("Result:ThirdClass");
44
}
Page
else
44
{
System.out.println("Result:Fail");
}//end of if
else
System.out.println("Invalid Marks...");
sr.s1 = s.nextInt();
sr.s2 = s.nextInt();
sr.s3 = s.nextInt();
sr.s4 = s.nextInt();
sr.s5 = s.nextInt();
sr.s6 = s.nextInt();
sr.cal();
}
45
Page
45
Variables in Java:
=>Variables are the data holders in the program.
Note:
Note:
(2)Static Variables
(1)NonStatic variables:
=>The variables which are declared without static keyword are known as NonStatic variables.
(a)Instance variables
(b)Local variables
(a)Instance variables:
def:
=>The NonStatic variables which are declared outside the methods are known as Instance variables.
Memory Location:
=>Instance variables will get the memory within the object while object creation.
LifeTime:
=>Instance variable is available until the object is available.
Scope:
=>Instance variables are accessed inside the object,which means accessed by the methods of Same object.
46
Note:
Page
=>Instance variables will get default values,when they are not initialized with any values.
46
(b)Local variables:
=>The NonStatic variables which are declared inside the methods are known as Local variables.
Memory Location:
=>Local variables will get the memory within the method_frame while method execution.
LifeTime:
=>Local variables are available until the method_frame is available.
Scope:
=>Local variables are accessed only inside the method.(within the method)
Note:
=>Local variables will not get default values,when they are not Initialized
(2)Static Variables:
=>The variables which are declared outside the methods with static keyword are known as static variables or Class
variables.
Note:
(compilation error)
Memory Location:
=>Static variables will get the memory within the class while class loading.
LifeTime:
=>Static variables are available until the class is available on MethodArea.
Scope:
=>Static variables are shared variables among multiple objects of same class.
Note:
=>Static variables will get default values,when they are not initialized.
===========================================================================
Methods in Java:
=>Methods are the actions which are performed to generate results.
(b)Static methods
=>These NonStatic methods or Instance methods will get the memory within the
47
47
Structure of Instance methods:
return_type method_name(para_list)
//method_body
Coding Rule:
=>NonStatic methods or Instance methods can access both Instance variables and
Static variables.
Exp:
(b)Static methods:
=>The methods which are declared with static keyword are known as static
methods.
=>These static methods will get the memory within the class while class
loading.
//method_body
Coding rule:
=>Static methods can access static variables directly,but cannot access instace variables directly.
48
48
(ii)User defined static methods
----------------------------------------------------------------
Exp program:
void m1()
a++;
k++;
System.out.println("====m1()====");
k++;
System.out.println("====m2()====");
}
49
49
public static void main(String[] args)
o/p:
====m1()====
====m1()====
====m2()====
ClassFiles:
Display.class
MainClass2.class
-----------------------------------------------------------------------------------------------------------------------------------------------
*imp
=>The class in java can generate any number of objects without restriction.
50
=>The multiple objects which are generated from the class are independent by their memory location in
Heap_Area
Page
50
Assignment:
wap to read amt and perform the following actions based on User choice?
1.WithDraw
2.Deposit
Note:
Classes:
WithDraw
=>amount
=>void wDraw()
o/p:
Deposit
=>amount
=>void deposit()
o/p:
BankMainClass
=>input 'amt'
==============================================================================
define parameters?
=>Parameters are the variables which are used to transfer the data from one
=>The methods which are declared without parameters are known as 0-parameter
51
methods or Methods without parameters.
Parameters - Variables
Arguments - Values
------------------------------------------------------------------------------------------------------------------------------------------------------
define return_type?
=>The return_type specify the methods return the value after method execution
or not.
(i)Non-Return_type methods
(ii)Return_type methods
(i)Non-Return_type methods:
=>The methods which donot return any value after method execution are known as
Non-Return_type methods.
Note:
=>The methods which are declared with 'void' are known as Non-Return_type methods.
(ii)Return_type methods:
=>The methods which return the value after method execution are known as
Return_type methods.
Note:
=>The methods which are declared without 'void' are known as Return_type methods.
=>we use 'return' statement to return the value after method execution.
------------------------------------------------------------------------------------------------------------------------------------------------
Exp program:
Note:
Classes:
Page
52
CheckDesignation
=>boolean k
=>boolean verify(desg)
MainClass3
import java.util.Scanner;
switch(desg)
case "SE":k=true;
break;
case "TE":k=true;
break;
case "ME":k=true;
break;
}//end of switch
return k;
53
if(p)
System.out.println("=====EmpDetails=====");
System.out.println("EmpName:"+eName);
System.out.println("EmpDesg:"+eDesg);
System.out.println("EmpId:"+eId);
}//end of if
else
System.out.println("Invalid desg...");
Dt : 29/6/2021
Explanation of MainClass1.java:
ClassFiles:
Addition.class
Subtraction.class
Multiplication.class
Division.class
54
ModDivision.class
Page
54
MainClass1.class
Note:
=>MainClas1 is loaded first and starts the execution process,in this process the
(i)Actual parameters
(ii)Formal parameters
(i)Actual parameters:
=>The parameters which hold orginal input data are known as Actual parameters.
Exp:
v1 and v2
(ii)Formal parameters:
=>The parameters which are declared part of method signature and used in
Exp:
x and y
Note:
=>we can have same variable names in Actual parameters and Formal parameters.
-------------------------------------------------------------------------------------------------------------------------------------------------
55
Page
55
define switch-case statement?
=>switch-case statement is used when we want to select one from multiple
structure of switch-case:
switch(value)
case 1:statements;
break;
case 2:statements;
break;
case n:statements;
break;
default:statements;
Behaviour:
=>The switch-value is compared with available options,if the switch-value ismached with any option,then the
statements are executed and we use 'break' to stop the switch-case execution.
=>If the switch-value is not matched with any available options then the defaultis executed.
--------------------------------------------------------------------------------------------------------------------------------------------------------
Assignment(Solution):
wap to read amt and perform the following actions based on User choice?
1.WithDraw
2.Deposit
Note:
import java.util.*;
{
Page
56
if(amt<=2000)
System.out.println("Amt wthDrawn:"+amt);
System.out.println("Balance Amount:"+(2000-amt));
System.out.println("Transaction completed...");
}//end of if
else
System.out.println("InSuffient fund...");
System.out.println("Amt Deposited:"+amt);
System.out.println("Balance Amount:"+(2000+amt));
System.out.println("Transaction completed...");
System.out.println("====Choice====");
System.out.println("1.WithDraw\n2.Deposit");
57
57
switch(choice)
case 1:
break;
case 2:
break;
default:
System.out.println("Invalid choice...");
}//end of switch
}//end of if
else
System.out.println("Invalid amount....");
syntax: Flowchart:
while(condition)
//loop_block;
=>'continue' statement is used to skip the statements from the iteration,whichmeans the line declared after the
Page
58
Note:
Modification of StuMainClass.java:
import java.util.Scanner;
System.out.println("TotalMarks:"+totMarks);
System.out.println("Percentage:"+per);
if(k)
System.out.println("Result:Fail");
System.out.println("Result:Destinction");
System.out.println("Result:FisrtClass");
System.out.println("Result:SecondClass");
System.out.println("Result:ThirdClass");
else
59
{
Page
System.out.println("Result:Fail");
59
}
int i=1,totM=0;
boolean k=false;
while(i<=6)
i++;
if(sub<0 || sub>100)//simple if
System.out.println("Invalid marks...");
i--;
k=true;
totM=totM+sub;
}//end of loop
}
60
Page
60
define 'for' loop?
=>'for' loop is more simple in declaration when compared to 'while' loop,because initialization,condition and
incre/Decre are declared in the same line.
syntax:
for(Initialization;Condition;Incre/Decre)
//Loop_block
Flowchart:
Execution flow of for loop:
Note:
Note:
-----------------------------------------------------------------------------------------------------------------------------------------------------
Exp program:
O/P : count=4
import java.util.Scanner;
61
String str = s.nextLine();
System.out.println("str:"+str);
System.out.println("length:"+len);
int count=0;
for(int i=0;i<len;i++)
switch(str.charAt(i))
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':count++;
break;
}//end of switch
}//end of loop
System.out.println("Count of Vowels:"+count);
--------------
--------------
--------------
--------------
---
62
Page
62
Assingnment:
------------------------------------------------------------------------
Dt : 1/7/2021
Assingnment:(Solution)
MainClass5.java
import java.util.Scanner;
for(int i=str.length()-1;i>=0;i--)
System.out.print(str.charAt(i));
}//end of loop
define Array?
=>Array is a sequenced collection of elements of same datatype.
syntax:
EXp program:
MainClass6.java
import java.util.Scanner;
63
63
{
String pCode,pName;
float pPrice;
int pQty;
void getProduct()
System.out.println(pCode+"\t"+pName+"\t"+pPrice+"\t"+pQty);
int n = s.nextInt();
for(int i=0;i<n;i++)
ob.pCode = s.nextLine();
ob.pName = s.nextLine();
ob.pPrice = s.nextFloat();
ob.pQty = s.nextInt();
p[i]=ob;
Page
}//end of loop
64
System.out.println("=====Display Product details====");
for(int k=0;k<p.length;k++)
p[k].getProduct();
}//end of loop
Assignment:
----------------------------------------------------------------------------
MainClass1.java(Modified)
import java.lang.String;
import java.lang.System;
import java.util.Scanner;
return x+y;
{
Page
65
int sub(int x,int y)
return x-y;
return x*y;
return (float)x/y;
return x%y;
int v1 = s.nextInt();
Page
66
int v2 = s.nextInt();
while(true){
System.out.println("====Choice====");
System.out.println
("1.add\n2.sub\n3.mul\n4.div\n5.modDiv\n6.exit");
switch(choice)
case 1:
System.out.println("Sum:"+ad.add(v1,v2));
break;
case 2:
System.out.println("Sub:"+sb.sub(v1,v2));
break;
case 3:
System.out.println("Mul:"+ml.mul(v1,v2));
break;
case 4:
System.out.println("Div:"+dv.div(v1,v2));
break;
case 5:
System.out.println("ModDiv:"+md.modDiv(v1,v2));
break;
case 6:
default:
67
System.out.println("Invalid option...");
Page
}//end of switch
67
}//end of while
define exit()?
=>exit() is a Built-in static method from java.lang.System class and which is used to stop or terminate the
program.
syntax:
System.exit(0);
syntax:
do
//loo
while(condition);
FlowChart:
======================================================================
68
Page
68
Summary of Variables and Methods:
(a)Variables
(i)static variables
(ii)NonStatic variables
=>Instance variables
=>Local Variables
(i)static variables
(ii)NonStatic variables
=>Instance variables
=>Local Variables
(b)Methods
Diagram:
69
============================ ==============================================================
Page
69
Blocks in Java:
=>The set of statements which are declared within the flower brackets and executed automatically is known as
block.
1.Static blocks:
=>The blocks which are declared with 'static' keyword are known as static blocks.
syntax:
static
//set-of-statements;
Behaviour:
=>static block is executed while class loading,in this process 'static block' executes only once because the class
loads only once.
Note:
=>In realtime static block is used to hold DataBase Connection code part of DAO(Data Access Object) Layer in
MVC(Model View Controller).
Exp program:
DemoBlock1.java
static
}
70
static
Page
70
System.out.println("=====MainClass static block====");
syntax:
{
//set-of-statements;
Behaviour:
=>Instance block is executed while object creation,in this process the instanceblock is executed for all the multiple
object creations.
Exp program:
DemoBlock2.java
}
71
}
Page
=============================================================================
71
faq: wt is the diff b/w (i)Block (ii)Method
=>Block is executed automatically,but method is executed on method_call.
Note:
=>Static block will have highest priority in execution when compared to static method.
=>Instance block will have highest priority in execution when compared to Instance method.
===============================================================================
Constructors in Java:
=>Constructor is a method having the same name of the class and executed while object creation because the
constructor call is available in object creation syntax attached with 'new' keyword.
Note:
=>while declaring constructor we must not use return_type,because the constructor by default having
class_return_type.
Structure of constructor:
Class_name(para_list)
//method_body
Exp program:
DCon1.java
class CTest
CTest()
72
Page
72
System.out.println("====0-parameter Constructor====");
void dis()
System.out.println("====dis() method====");
ob.dis();//Method_call
Exp program:
DCon2.java
class CTest
static
{
73
73
}
CTest()
System.out.println("====0-parameter Constructor====");
void dis()
System.out.println("====dis() method====");
ob.dis();//Method_call
*imp
Exp program:
DCon4.java
import java.util.Scanner;
class UserDetails
74
{
Page
String fName,lName,addr,mId;
74
long phNo;
this.fName=fName;
this.lName=lName;
this.addr=addr;
this.mId=mId;
this.phNo=phNo;
void getUserDetails()
System.out.println("FirstName:"+fName);
System.out.println("LastName:"+lName);
System.out.println("Address:"+addr);
System.out.println("MailId:"+mId);
System.out.println("PhoneNo:"+phNo);
String fN = s.nextLine();
String lN = s.nextLine();
75
75
System.out.println("Enter the MailId:");
ud.getUserDetails();
}}
Advantage of Constructor:
=>Constructors are used to initialize instance variables while object creation, which saves the execution time and
generates HighPerformance.
Note:
=>'this' keyword is used when we have same names in Local variables and Instancevariables.
----------------------------------------------------------------------------------------------------------------------------
=============================================================================
PACKAGES IN JAVA:
=>Package is a collection of classes and Interfaces.
1.Built-In packages
76
1.Built-In packages:
=>The packages which are available from JavaLib are known as Built-in packages or PreDefined packages.
CoreJava:
GUI:
AdvJava:
syntax:
package package_name;
Note:
=>The Classes,Interfaces and its members which are declared within the package
must be 'public'.
Exp Application:
package p1;
{
Page
77
if(bSal>=5000)
System.out.println("BSal:"+bSal);
System.out.println("TotSal:"+totSal);
else
System.out.println("Invalid bSal...");
Salary.java
javac -d . Salary.java
Note:
package p2;
import java.util.Scanner;
import p1.Salary;
sl.bSal = s.nextInt();
sl.cal();
78
}
Page
78
step1 : Save the program in ProjectFolder as SalaryMainClass.java
---------------------------------------------------------------------
Exp:
import java.util.Scanner;
import p1.Salary;
Exp:
import java.util.*;
import java.lang.*;
import p1.*;
Exp:
----------------------------------------------------------------------------------------------------------------------------------------------------------
79
Page
79
Access Modifiers?
=>Access modifiers specify the scope of programming components within the Project folder.
1.public
2.private
3.protected
4.default
1.public:
=>public components are accessed within the ProjectFolder.
2.private:
=>private components are accessed within the class.
3.protected:
=>Protected components are accessed within the package.
Note:
=>protected components can also be accessed by the CClass outside the package. (Inheritance process)
4.default:
=>default componentse are accessed within the package.
Note:
=>The components which are declared without any access modifiers are known as default components.
-------------------------------------------------------------------------------------------------------------------------------------------------
80
Page
80
'static' import?
=>The process of declaring 'import' statement with 'static' keyword is known as 'static' import.
syntax:
import static package_name.Class_name/Interface_name.*;
Note:
=>when we use 'static' import then the static members of Class or Interface can be accessed directly without
Class_name or Interface_name.
Method Signature:
syntax:
double z = Math.sqrt(val);
DemoMainClass.java
package maccess;
import java.util.Scanner;
double v = s.nextDouble();
}
81
Page
81
RelationShip b/w classes:
=>The process of establishing communication b/w classes is known as relationshipb/w classes.
(a)References
(b)Inheritance
(c)InnerClasses
(a)References:
=>The process of declaring NonPrimitive datatype variables part of classes and
these NonPrimitive datatype variables will hold the object references of another
Note:
=>Servlet Programming
=>Spring Framework
Exp Application:
ProjectName : EmployeeDetails
package : test
Address.java
package test;
public class Address {
public String hNo,sName,city;
public int pinCode;
}
Contact.java
package test;
public class Contact {
public String mId;
public long phNo;
}
Employee.java
package test;
import java.util.Scanner;
public class Employee {
public String eId,eName,eDesg;
public Address ad = new Address();//Reference variable
public Contact c = new Contact();//Reference variable
public void setEmployeeDetails(Scanner s)//read and load data to variables
82
{
System.out.println("Enter the EmpId:");
Page
eId = s.nextLine();
82
System.out.println("Enter the EmpName:");
eName = s.nextLine();
System.out.println("Enter the EmpDesg:");
eDesg = s.nextLine();
System.out.println("Enter the HNO:");
ad.hNo = s.nextLine();
System.out.println("Enter the StreetName:");
ad.sName = s.nextLine();
System.out.println("Enter the City:");
ad.city = s.nextLine();
System.out.println("Enter the PinCode:");
ad.pinCode = s.nextInt();
s.nextLine();
System.out.println("Enter the MailId:");
c.mId = s.nextLine();
System.out.println("Enter the PhNo:");
c.phNo = s.nextLong();
}
public void getEmployeeDetails()//Display data from variables
{
System.out.println("EmpId:"+eId);
System.out.println("EmpName:"+eName);
System.out.println("EmpDesg:"+eDesg);
System.out.println("HNO:"+ad.hNo);
System.out.println("SName:"+ad.sName);
System.out.println("City:"+ad.city);
System.out.println("PinCode:"+ad.pinCode);
System.out.println("MailId:"+c.mId);
System.out.println("PhoneNo:"+c.phNo);
}
}
package : maccess
EMainClass.java
package maccess;
import java.util.Scanner;
import test.Employee;
e.getEmployeeDetails();
}
83
}
Page
83
Diagram:
----------------------------------------------------------------------------------------------------------------------------------------------------
Exp Application:
BookData.java
package test;
public class BookData {
public String bCode,bName,bAuthor;
public float bPrice;
public int bQty;
public BookData(String bCode,String bName,String bAuthor,float bPrice,int
bQty){
this.bCode=bCode;
this.bName=bName;
this.bAuthor=bAuthor;
84
this.bPrice=bPrice;
this.bQty=bQty;
Page
}
84
public void getBookData(){
System.out.println("BookCode:"+bCode);
System.out.println("BookName:"+bName);
System.out.println("BookAuthor:"+bAuthor);
System.out.println("BookPrice:"+bPrice);
System.out.println("BookQty:"+bQty);
}
}
LoadBookData.java
package test;
public class LoadBookData {
public BookData load(String bCode,String bName,String bAuthor,float
bPrice,int bQty)
{
BookData bd = new BookData(bCode,bName,bAuthor,bPrice,bQty);//Constructor
call
return bd;
}
//load() method creating object for BookData and returning the reference
}
Display.java
package test;
public class Display {
public void dis(BookData bd)
{
bd.getBookData();
}
}
BMainClass.java
package maccess;
import java.util.Scanner;
import test.BookData;
import test.LoadBookData;
import test.Display;
String bC = s.nextLine();
String bN = s.nextLine();
85
String bA = s.nextLine();
85
System.out.println("Enter the BookPrice:");
float bP = s.nextFloat();
int bQ = s.nextInt();
BookData bd = lbd.load(bC, bN, bA, bP, bQ);//This method returns reference of BookData
s.close();
===============================================================================================
(b)Inheritance:
=>The process of establishing
communication b/w two classes using
'extends'
Diagram:
86
Page
86
syntax:
Class A
//members
class B extends A
//members
syntax:
B ob = new B();
----------------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>In Normal inheritance process,one reference is created and the reference is binded with all the NonStatic
members of PClass and all the NonStatic members of CClass.
Exp Application:
A.java
package test;
public class A {
public int x;
public void m1()
{
System.out.println("====PClass m1()====");
System.out.println("The value x:"+x);
}
{
System.out.println("====PClass NonStatic Block====");
}
}
87
B.java
Page
package test;
87
public class B extends A{
public int y;
public void m2()
{
System.out.println("====CClass m2()====");
System.out.println("The value y:"+y);
}
{
System.out.println("====CClass NonStatic block====");
}
}
Inheritance1.java
package maccess;
import java.util.Scanner;
import test.B;
ob.x = s.nextInt();
ob.y = s.nextInt();
ob.m1();//PClass method_call
ob.m2();//CClass method_call
s.close();
O/P:
12
13
====PClass m1()====
88
88
====CClass m2()====
-------------------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>According to Java Application development the resources(IO,File,DB,N/W,...)which are opened must be closed
after usage,to generate HighPerformance.
---------------------------------------------------------------------------------------------------------------------------------------------------------
Dt : 13/7/2021
Exp Application:
PClass.java
package test;
public class PClass {
public PClass()
{
System.out.println("====PClass Constructor====");
}
}
CClass.java
package test;
public class CClass extends PClass{
public CClass()
{
89
System.out.println("====CClass Constructor====");
Page
89
}
Inheritance2.java
package maccess;
import test.CClass;
public class Inheritance2 {
public static void main(String[] args) {
CClass ob = new CClass();//CClass Constructor_call
}
}
O/p:
====PClass Constructor====
====CClass Constructor====
Exp application:
PClass.java
package test;
public class PClass {
public PClass(int x){
System.out.println("====PClass Constructor====");
System.out.println("The value x:"+x);
}
}
CClass.java
package test;
public class CClass extends PClass{
public CClass(int x){
super(x);//PClass Constructor_call
}
}
Inheritance3.java
package maccess;
import java.util.Scanner;
import test.CClass;
int x = s.nextInt();
s.close();
Page
90
}
o/p:
123
====PClass Constructor====
=======================================================================
Exp Application:
PClass.java
package test;
public class PClass {
public static int x;
public static void m1(){
System.out.println("====PClass m1()====");
System.out.println("The value x:"+x);
}
static
{
System.out.println("====PClass static block====");
}
}
CClass.java
package test;
public class CClass extends PClass{
public static int y;
public static void m2(){
System.out.println("====CClass m2()====");
System.out.println("The value y:"+y);
}
static
{
System.out.println("====CClass static block====");
}
}
Inheritance4.java
package maccess;
import java.util.Scanner;
91
import test.CClass;
Page
91
public static void main(String[] args) {
CClass.x = s.nextInt();
CClass.y = s.nextInt();
CClass.m1();//PClass method_call
CClass.m2();//CClass method_call
s.close();
o/p:
12
13
====PClass m1()====
====CClass m2()====
OVERRIDING
faq:
Same return_type
Same method_name
Same para_list
Same para_type
Exp Application:
92
PClass.java
package test;
public class PClass {
public void m(int x)
{
System.out.println("====PClass m()====");
System.out.println("The value x:"+x);
}
}
CClass.java
package test;
public class CClass extends PClass{
public void m(int x)
{
System.out.println("====CClass m()====");
System.out.println("The value x:"+x);
}
}
Inheritance5java
package maccess;
import test.CClass;
public class Inheritance5 {
public static void main(String[] args) {
CClass ob = new CClass();//Constructor_call
ob.m(123);
}
}
o/p:
====CClass m()====
93
Page
93
Case-2 : Constructor Overriding process (No Concept of this overriding)
=>There is no concept of Constructor Overriding process,because we cannot have same constructor names in
PClass and CClass.
-----------------------------------------------------------------------------------------------------------------------------------------------------
METHOD HIDING
=>The static method with same method signature in PClass and CClass,then the PClass Static method is hided by
CClass Static method,is known as Method Hiding process.
EXp application:
PClass.java
package test;
public class PClass {
public static void show(int x)//Hided method
{
System.out.println("====PClass show()====");
System.out.println("The value x:"+x);
}
}
CClass.java
package test;
public class CClass extends PClass{
public static void show(int x){
System.out.println("=CClass show()=");
System.out.println("The value
x:"+x);
}
}
Inheritance6.java
package maccess;
import test.CClass;
public class Inheritance6 {
public static void main(String[] args)
{
CClass.show(123);
}
}
Note:
=>Same Instance method signature in PClass and CClass then it is known as Method Overriding process.
=>Same Static method signature in PClass and CClass then it is known as Method Hiding process.
Inheritance.
Page
94
Concept of super & this
wt is the diff b/w
(i)super
(ii)this
(i)super:
=>'super' keyword is used to access the variables and methods from the PClass or SuperClass
(ii)this:
=>'this' keyword is used to access the variables and methods from the same class or Current running class.
Exp program:
PClass.java
package test;
public class PClass {
public int a=10;
public void m(int x){
System.out.println("====PClass m()====");
System.out.println("The value x:"+x);
}
}
CClass.java
package test;
public class CClass extends PClass{
public int a=20;
public void m(int y){
System.out.println("====CClass m()====");
System.out.println("The value y:"+y);
}
public void dis(int x,int y){
System.out.println("PClass variable a:"+super.a);
System.out.println("CClass variable a:"+this.a);
super.m(x);//PClass method_call
this.m(y);//CClass method_call
}
}
Inheritance7.java
package maccess;
import test.CClass;
public class Inheritance7 {
public static void main(String[] args) {
CClass ob = new CClass();
ob.dis(123, 124);
}
}
o/p:
====PClass m()====
95
The value x:123
====CClass m()====
(i)super()
(ii)this()
(i)super():
=>super() is used to access the constructors from the PClass or SuperClass
(ii)this():
=this() is used to access the constructors from the Same class or Current
running class.
Exp application:
PClass.java
package test;
public class PClass {
public PClass(int x){
System.out.println("x:"+x);
}
}
CClass.java
package test;
public class CClass extends PClass{
public CClass(int x,int y,int z){
this(x,y);//Same class constructor_call
System.out.println("z:"+z);
}
public CClass(int x,int y){
super(x);//PClass Constructor_call
System.out.println("y:"+y);
}
}
Inheritance8.java
package maccess;
import test.CClass;
public class Inheritance8 {
public static void main(String[] args) {
CClass ob = new CClass(11,12,13);//CClass Constructor_call
}
}
96
Page
96
can we use 'super' and 'this' keywords to access static
members?
=>Yes,we can use 'super and 'this' keywords to access static members,but 'super'and 'this' keywords must be used
in NonStatic methods,becuase 'super' and 'this' are Built-in NonStatic reference variables.
Exp Application:
PClass.java
package test;
public class PClass {
public static void m(int x){
System.out.println("====PClass m()====");
System.out.println("The value x:"+x);
}
}
CClass.java
package test;
public class CClass extends PClass{
public static void m(int y){
System.out.println("====CClass m()====");
System.out.println("The value y:"+y);
}
public void dis(int x,int y){
super.m(x);//PClass method_call
this.m(y);//CClass method_call
}
}
Inheritance9.java
package maccess;
import test.CClass;
public class Inheritance9 {
public static void main(String[] args) {
CClass ob = new CClass();
ob.dis(123, 124);
}
}
METHOD OVERLOADING
=>More than one method with same method name but differentiated by their para_list or para_type is known as
Method Overloading process.
Note:
=>Instance method Overloading process is posible
Exp application:
Display.java
package test;
97
//Constructor Overloading
97
public Display(int p){
System.out.println("p:"+p);
}
public Display(int p,int q){
this(p);
System.out.println("q:"+q);
}
//Instance method Overloading
public void show(int x){
System.out.println("x:"+x);
}
public void show(float y){
System.out.println("y:"+y);
}
//Static method Overloading
public static void dis(int a){
System.out.println("a:"+a);
}
public static void dis(float b){
System.out.println("b:"+b);
}
}
Inheritance10.java
package maccess;
import test.Display;
public class Inheritance10 {
public static void main(String[] args) {
Display d = new Display(11,12);//Constructor_call
d.show(13);
d.show(14.45F);
Display.dis(15);
Display.dis(16.65F);
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------
Types of Inheritances:
=>The following are the types of Inheritances:
1.Single Inheritance
2.Multiple Inheritance
3.Multi-Level Inheritance
4.Hierarchal Inheritance
98
5.Hybrid Inheritance
Page
98
Diagrams:
(a)Single Inheritance
(b)Multiple Inheritance
(a)Single Inheritance:
=>The process of extracting the features from one class at-a-time is known as Single Inheritance.
Exp:
above programs
(b)Multiple Inheritance:
=>The process of extracting the features from more than one class at-a-time is known as Multiple Inheritance
99
Page
99
Note:
=>Multiple Inheritance process using classes is not available in Java,because which leads to replication of
programming components and raises ambiguity.The
=================================================================================
A.java
package test;
public class A {
public void m1(int a){
System.out.println("a:"+a);
}
}
B.java
package test;
public class B extends A{
public void m2(int b){
System.out.println("b:"+b);
}
}
C.java
package test;
public class C extends B{
public void m3(int c){
System.out.println("c:"+c);
}
}
Inheritance11.java
package maccess;
import test.C;
public class Inheritance11 {
public static void main(String[] args) {
C ob = new C();
ob.m1(11);
ob.m2(12);
ob.m3(13);
}
}
100
Page
100
Exp program:(Demonstrating Hierarchal Inheritance)
A.java
package test;
public class A {
public void m1(int a){
System.out.println("a:"+a);
}
}
B.java
package test;
public class B extends A{
public void m2(int b){
System.out.println("b:"+b);
}
}
C.java
package test;
public class C extends A{
public void m3(int c){
System.out.println("c:"+c);
}
}
D.java
package test;
public class D extends C{
public void m4(int d){
System.out.println("d:"+d);
}
}
E.java
package test;
public class E extends C{
public void m5(int e){
System.out.println("e:"+e);
}
}
Inheritance12.java
package maccess;
import test.*;
public class Inheritance12 {
public static void main(String[] args) {
System.out.println("===Class B===");
B ob1 = new B();
ob1.m1(11);
101
ob1.m2(12);
System.out.println("===Class D===");
D ob2 = new D();
Page
ob2.m1(13);
101
ob2.m3(14);
ob2.m4(15);
System.out.println("===Class E===");
E ob3 = new E();
ob3.m1(16);
ob3.m3(17);
ob3.m5(18);
}
}
o/p:
===Class B===
a:11
b:12
===Class D===
a:13
c:14
d:15
===Class E===
a:16
c:17
e:18
=================================================================================
Interfaces in Java:
=>Interface is a collection of variables and abstract methods up to Java7 version.
//method_body
102
}
Page
102
Coding rules of Interface:
Rule-1.we use 'interface' keyword to declare interfaces.
syntax:
interface Interface_name
//Interface_body
Rule-2.The programming components which are declared within the interface are automatically 'public'.
Rule-3.The interface can be declared with both Primitive DataType variables and NonPrimitive DataType
variables.
Rule-4.The variables which are declared within the interface are automatically static and final variables.
Note:
=>Static variables within the interface are binded to interface and access with Interface_name.
=>final variables must be initialized with an value and once initialized cannot be modified.
Exp program:
IDemo.java
package test;
public interface IDemo {
public static final int k=100;//Primitive DataType variable
public static final Display d=new Display();//NonPriitive DataType variable
}
Display.java
package test;
public class Display {
public int z=200;
}
Interface1.java
package maccess;
import test.*;
public class Interface1 {
public static void main(String[] args) {
System.out.println("The value k:"+IDemo.k);
System.out.println("The value z:"+IDemo.d.z);
}
}
Note:
=>There is no concept of NonStatic variables within the interface,because the variables declared within
t the Interface are automatically static variables
103
Rule-5.The methods which are declared within the interface are automatically NonStatic abstract methods.
Rule-6.we cannot instantiate interfaces,which means we cannot create object for Interafces because Interface are
Page
abstract components.
103
Rule-7.Interfaces are implemented to classes using 'implements' keyword and the classes are known as
implementation classes.
Rule-8.These implementation classes must construct bodies for all the abstract methods of Interface.
Exp application:
IComparable.java
package test;
public interface IComparable {
public abstract int compareTo(int x,int y);
}
Greater.java
package test;
public class Greater implements IComparable{
public int compareTo(int x,int y)
{
if(x>y) return x;
else return y;
}
}
Smaller.java
package test;
public class Smaller implements IComparable{
public int compareTo(int x,int y){
if(x<y) return x;
else return y;
}
}
Interface2.java
package maccess;
import test.*;
104
import java.util.*;
Page
104
public static void main(String[] args) {
int x = s.nextInt();
int y = s.nextInt();
System.out.println("====Choice====");
System.out.println("1.Greater\n2.Smaller");
switch(choice)
case 1:
break;
case 2:
break;
default:
System.out.println("Invalid choice..");
}//End of switch
s.close(); 105
Page
105
}
Diagram:
Assignment:
Concept as follows:
Diagram:
----------------------------------------------------------------------------------------------------------------------------------------------------
Rule-10.Interface can be extented from another interface,in this process one interface can use the features of
another Interface.
Exp application:
106
ITest1.java
Page
package test;
106
public interface ITest1 {
public abstract void m1(int x);
}
ITest2.java
package test;
public interface ITest2 extends ITest1{
public abstract void m2(int y);
}
IClass.java
package test;
public class IClass implements ITest2{
public void m1(int x){
System.out.println("====ITest1 m1()====");
System.out.println("x:"+x);
}
public void m2(int y){
System.out.println("====ITest2 m2()====");
System.out.println("y:"+y);
}
}
Interface3.java
package maccess;
import test.*;
public class Interface3 {
public static void main(String[] args) {
IClass ob = new IClass();
ob.m1(12);
ob.m2(13);
}
}
107
Page
107
=========================================================================
*imp
Exp Application:
ITest1.java
package test;
public interface ITest1 {
public abstract void m1(int x);
}
ITest2.java
package test;
public interface ITest2 {
public abstract void m2(int y);
}
IClass.java
package test;
public class IClass implements ITest1,ITest2{
public void m1(int x){
System.out.println("x:"+x);
}
public void m2(int y){
108
System.out.println("y:"+y);
}
Page
108
Interface4.java
package maccess;
import test.*;
public class Interface4 {
public static void main(String[] args) {
IClass ob = new IClass();
ob.m1(12);
ob.m2(13);
}
}
Model-2 : Extracting the features from one class and any number of interfaces into a
class.
PClass.java
package test;
public class PClass {
public void m1(int x){
System.out.println("x:"+x);
}
}
ITest.java
package test;
public interface ITest {
public abstract void m2(int y);
}
IClass.java
package test;
public class IClass extends PClass implements ITest{
public void m2(int y){
System.out.println("y:"+y);
}
}
Interface5.java
package maccess;
import test.*;
public class Interface5 {
public static void main(String[] args) {
IClass ob = new IClass();
ob.m1(12);
ob.m2(13);
}
}
Model-3 : Extracting the features from more than one interface into a Interface.
109
ITest1.java
package test;
Page
109
public interface ITest1 {
public abstract void m1(int x);
}
ITest2.java
package test;
public interface ITest2 {
public abstract void m2(int y);
}
ITest3.java
package test;
public interface ITest3 extends
ITest1,ITest2{
public abstract void m3(int z);
}
IClass.java
package test;
package maccess;
import test.*;
public class Interface6 {
public static void main(String[] args) {
IClass ob = new IClass();
ob.m1(12);
ob.m2(13);
ob.m3(14);
}
}
110
Page
110
================================================================
AbstractClasses in Java:
=>The classes which are declared with abstract keyword are known as abstract classes.
=>These abstract classes can hold both abstract methods and Concrete methods.
=>The abstract methods which are declared within the abstract classes must be declared with abstract keyword.
=>we cannot instantiate abstract classes,becuase abstract classes are abstract components in Java.
=>These abstract classes are extended to classes and the classes must construct body of abstract methods.
=>Abstract classes can have features of another abstract class using extends keyword.
Exp program:
AClass1.java
package test;
public abstract class AClass1 {
public int a;
public AClass1(int a){
this.a=a;
}
111
{
System.out.println("===AClass1 Block===");
}
Page
111
public abstract void m1(int x);
public void dis1(){
System.out.println("===dis1()===");
System.out.println("The value a:"+a);
}
}
AClass2.java
package test;
public abstract class AClass2 extends AClass1{
public int b;
public AClass2(int a,int b){
super(a);
this.b=b;
}
{
System.out.println("===AClass2 Block===");
}
package test;
public class EClass extends AClass2{
public EClass(int a,int b){
super(a,b);
}
public void m1(int x){
System.out.println("===m1()===");
System.out.println("x:"+x);
}
{
System.out.println("===EClass Block===");
}
package maccess;
import test.*;
Page
112
public static void main(String[] args) {
EClass ob = new EClass(10,20);//Constructor_call
ob.m1(12);
ob.m2(13);
ob.dis1();
ob.dis2();
}
}
o/p:
===AClass1 Block===
===AClass2 Block===
===EClass Block===
===m1()===
x:12
===m2()===
y:13
===dis1()===
===dis2()===
=========================================================================
Comparision diagram:
113
=======================================================================
Page
113
InnerClasses:
=>The classes which are declared within the class are known as InnerClasses or Nested Classes
1.Member InnerClasses
2.Local InnerClasses
3.Anonymous InnerClasses
1.Member InnerClasses:
=>The classes which are declared as members of the class are known as Member InnerClasses.
Coding Rules:
=>NonStatic member InnerClasses can be declared with only NonStatic members.
syntax:
OuterClass.InnerClass obj_name=OuterClass_object.new InnerClass();
Exp:
=>The methods of NonStatic member InnerClasses can access all the members of
outerClass directly.
Coding Rules:
=>static member InnerClasses can be declared with both static and NonStatic
members.
syntax:
OuterClass.InnerClass obj_name=new OuterClass.InnerClass();
114
=>The methods of Static member InnerClasses can access only static members of OuterClass directly.
Page
114
Exp Application:
SubClass1.java
package test;
public class SubClass1 {
public static int a=10;
public int b=20;
public class SubClass2{
public void m1(){
System.out.println("====NonStatic member InnerClass m1()=====");
System.out.println("a:"+a);
System.out.println("b:"+b);
}
}//NonStatic member InnerClass
public SubClass2 ob2 = new SubClass2();
package maccess;
import test.SubClass1;
public class InnerClass1 {
public static void main(String[] args) {
SubClass1 ob = new SubClass1();//OuterClass object
System.out.println("InnerClass objects created part of OuterClass");
ob.ob2.m1();
ob.ob3.m2();
SubClass1.SubClass3.m3();
System.out.println("InnerClass objects created part of MainClass");
SubClass1.SubClass2 ob4=ob.new SubClass2();
ob4.m1();
SubClass1.SubClass3 ob5=new SubClass1.SubClass3();
ob5.m2();
SubClass1.SubClass3.m3();
}
}
115
Page
115
2.Local InnerClasses:
=>The process of declaring InnerClass inside the method of OuterClass is known as Local InnerClass.
Coding Rule:
=>The Local InnerClass declaration,Object creation and method access must be declared inside the method of
OuterClass.
Exp Application:
SubClass22.java
package test;
public class SubClass11 {
public static int a=10;
public int b=20;
public void m1(){
class SubClass22{
public void m2(){
System.out.println("====Local InnerClass m2()====");
System.out.println("a:"+a);
System.out.println("b:"+b);
}
}//Local InnerClass
SubClass22 ob2 = new SubClass22();//Local InnerClass object
ob2.m2();
}//OuterClass method
}//OuterClass
InnerClass2.java(MainClass)
package maccess;
import test.SubClass11;
116
116
ob.m1();
}
}
3.Anonymous InnerClasses:
=>The InnerClasses which are declared without name are known as Anonymous InnerClasses.
Note:
-----------------------------------------------------------------------------------------------------------------
CClass.
syntax:
PClass ob = new CClass();
Exp Application:
PClass.java
package test;
public class PClass {
public void m1(int x) {
System.out.println("====PClass m1()=====");
117
System.out.println("x:"+x);
}
Page
117
System.out.println("====PClass m2()=====");
System.out.println("y:"+y);;
}
}
CClass.java
package test;
public class CClass extends PClass{
public void m1(int x) {
System.out.println("====CClass m1()=====");
System.out.println("x:"+x);
}
public void m3(int z) {
System.out.println("====CClass m3()=====");
System.out.println("z:"+z);
}
}
Generalization1.java
package maccess;
import test.*;
public class Generalization1 {
public static void main(String[] args) {
System.out.println("Normal Inheritance");
CClass ob1 = new CClass();
ob1.m1(12);
ob1.m2(13);
ob1.m3(14);
System.out.println("Generalization process");
PClass ob2 = new CClass();
ob2.m1(16);
ob2.m2(17);
//ob2.m3(18);//Compilation Error
}
}
o/p:
Normal Inheritance
====CClass m1()=====
x:12
====PClass m2()=====
y:13
====CClass m3()=====
z:14
Generalization process
====CClass m1()=====
x:16
118
====PClass m2()=====
Page
y:17
118
(ii)Using Interfaces:
=>In Generalization process using Interfaces,one reference is created and the reference
is binded with all the members of Interface and only Overriding members from the
Implementation class.
syntax:
Interface_name ob = new Impl_Class_name();
Exp:
Exp Application:
Arithmetic.java
package test;
public interface Arithmetic {
public abstract void process(int x,int y);
}
Addition.java
package test;
public class Addition implements Arithmetic{
public void process(int x,int y) {
System.out.println("====process()====");
System.out.println("x:"+x);
System.out.println("y:"+y);
System.out.println("Sum:"+(x+y));
}
public void dis(int k) {
System.out.println("====dis()====");
System.out.println("k:"+k);
}
}
Generalization2.java
package maccess;
import test.*;
public class Generalization2 {
public static void main(String[] args) {
System.out.println("Normal Inheritance process");
Addition ob1 = new Addition();
ob1.process(11, 10);
ob1.dis(14);
System.out.println("Generalization process");
Arithmetic ob2 = new Addition();
ob2.process(23,20);
//ob2.dis(123);//Generalization process
}
}
o/p:
====process()====
Page
x:11
119
y:10
Sum:21
====dis()====
k:14
Generalization process
====process()====
x:23
y:20
Sum:43
-------------------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>Generalization process using classes can be acheived using 'Anonymous InnerClass as class extention'.
=>Generalization process using Interfaces can be acheived using 'Anonymous InnerClass as Implementation class'
syntax:
class PClass
//PClass_body
//CClass_body
};
Exp Application:
PClass.java
package test;
public class PClass {
public void m1(int x) {
System.out.println("====PClass m1()=====");
System.out.println("x:"+x);
}
public void m2(int y) {
System.out.println("====PClass m2()=====");
System.out.println("y:"+y);;
120
}
}
Page
Anonymous1.java(MainClass)
120
package maccess;
import test.*;
public class Anonymous1 {
public static void main(String[] args) {
System.out.println("Generalization process");
PClass ob2 = new PClass()
{
public void m1(int x) {
System.out.println("====CClass m1()=====");
System.out.println("x:"+x);
}
public void m3(int z) {
System.out.println("====CClass m3()=====");
System.out.println("z:"+z);
}
};
ob2.m1(16);
ob2.m2(17);
//ob2.m3(18);//Compilation Error
}
}
o/p:
Generalization process
====CClass m1()=====
x:16
====PClass m2()=====
y:17
-----------------------------------------------------------------------
syntax:
interface Interface_name
//Interface_body
//Impl_Class_body
};
Exp Application:
121
Arithmetic.java
package test;
Page
Generalization process
====process()====
x:23
y:20
Sum:43
-------------------------------------------------------------------------------------
Assignment1:
Diagram:
122
Page
122
InnerClass within the Interface:
=>we can declare InnerClasses within the Interface and which are automatically static member InnerClasses.
Exp Application:
ITest.java
package test;
public interface ITest {
public static class SubClass2{
public void m2(int x) {
System.out.println("====m2()====");
System.out.println("x:"+x);;
}
}//InnerClass
}//OuterInterface
AClass.java
package test;
public abstract class AClass {
public static class SubClass22{
public void m22(int y) {
System.out.println("====m22()====");
System.out.println("y:"+y);
}
}//InnerClass
}//OuterClass
InnerClass3.java
package maccess;
import test.*;
public class InnerClass3 {
public static void main(String[] args) {
ITest.SubClass2 ob1 = new ITest.SubClass2();
AClass.SubClass22 ob2 = new AClass.SubClass22();
ob1.m2(12);
ob2.m22(13);
}
}
o/p:
====m2()====
x:12
====m22()====
y:13
----------------------------------------------------------------------------
=>we can declare InnerInterface within the Class and which can be Static or NonStatic memner InnerInterface.
Page
123
InnerInterface within the Interface:
=>we can also declare InnerInterface within the Interface and which is automatically Static member
InnerInterface.(Nested Interface)
Exp Application:
SubClass1.java
package test;
public class SubClass1 {
public static interface ITest1{
public abstract void m1(int x);
}//InnerInterface
}//OuterClass
ITest.java
package test;
public interface ITest {
public static interface ITest2{
public abstract void m2(int y);
}//InnerInterface
}//OuterInterface
AClass.java
package test;
public abstract class AClass {
public static interface ITest3{
public abstract void m3(int z);
}//InnerInterface
}//OuterClass
InnerInterface1.java
package maccess;
import test.*;
public class InnerInterface1 {
public static void main(String[] args) {
SubClass1.ITest1 ob1 = new SubClass1.ITest1() {
public void m1(int x) {
System.out.println("====m1()====");
System.out.println("x:"+x);
}
};
124
System.out.println("====m3()====");
System.out.println("z:"+z);
}
};
ob1.m1(12);
ob2.m2(13);
ob3.m3(14);
}
}
o/p:
====m1()====
x:12
====m2()====
y:13
====m3()====
z:14
------------------------------------------------------------------------------
Exp Application:
SubClass1.java
package test;
public class SubClass1 {
public static abstract class AClass1{
public abstract void m1(int a);
}//InnerAbstractClass
}//OuterClass
ITest.java
package test;
public interface ITest {
public static abstract class AClass2{
public abstract void m2(int b);
}//InnerAbstractClass
}//OuterInterface
125
AClass.java
Page
package test;
125
public abstract class AClass {
public static abstract class AClass3{
public abstract void m3(int c);
}//InnerAbstractClass
}//OuterAbstractClass
InnerAbstractClass1.java
package maccess;
import test.*;
public class InnerAbstractClass1 {
public static void main(String[] args) {
SubClass1.AClass1 ob1 = new SubClass1.AClass1() {
public void m1(int a) {
System.out.println("===m1()===");
System.out.println("a:"+a);
}
};
ob1.m1(12);
ob2.m2(13);
ob3.m3(14);
}
}
o/p:
===m1()===
a:12
===m2()===
b:13
===m3()===
c:14
------------------------------------------------------------------------------
Dt : 26/7/2021
Assignment:(Solution)
126
Convert BankMainClass.java program in to packages and also use the Interface Concept.
Page
Balance.java
126
package test;
public class Balance {
public double bal=2000;
public void getBalance() {
System.out.println("Balance Amt:"+bal);
}
}
Transaction.java
package test;
public interface Transaction {
public static final Balance b = new Balance();
public abstract void process(int amt);
}
CheckPinNo.java
package test;
public class CheckPinNo {
public boolean k=false;
public boolean verify(int pinNo) {
switch(pinNo) {
case 1111:k=true;
break;
case 2222:k=true;
break;
case 3333:k=true;
break;
}//end of switch
return k;
}
}
WithDraw.java
package test;
public class WithDraw implements Transaction{
public void process(int amt) {
if(amt<=b.bal) {
System.out.println("Amt WithDrawn:"+amt);
b.bal=b.bal-amt;
b.getBalance();
System.out.println("Transaction Completed...");;
}else {
System.out.println("Insufficient Fund...");
}
}
}
Deposit.java
package test;
public class Deposit implements Transaction{
public void process(int amt) {
System.out.println("Amt deposited:"+amt);
b.bal=b.bal+amt;
127
b.getBalance();
System.out.println("Transaction Completed...");
}
Page
127
}
BankTransaction1.java(MainClass)
package maccess;
import test.*;
import java.util.*;
int count=0;
xyz:
while(true) {
boolean k = cpn.verify(pinNo);
if(k) {
System.out.println("====Choice====");
System.out.println("1.WithDraw\n2.Deposit");
switch(choice) {
case 1:
int a1 = s.nextInt();
wd.process(a1);
}else {
System.out.println("Invalid amt...");
break xyz;
case 2:
128
int a2 = s.nextInt();
Page
128
if(a2>0 && a2%100==0) {
dp.process(a2);
}else {
System.out.println("Invalid amt...");
break xyz;
default:
System.out.println("Invalid Choice...");
break xyz;
}//End of switch
}else {
System.out.println("Invalid PinNo...");
count++;
if(count==3) {
break xyz;
}//End of loop
s.close();
==============================================================================
Assignment2:(Solution)
Balance.java
package test;
public class Balance {
public double bal=2000;
public void getBalance() {
System.out.println("Balance Amt:"+bal);
129
}
}
Page
Transaction.java
129
package test;
public interface Transaction {
public static final Balance b = new Balance();
public abstract void process(int amt);
}
CheckPinNo.java
package test;
public class CheckPinNo {
public boolean k=false;
public boolean verify(int pinNo) {
switch(pinNo) {
case 1111:k=true;
break;
case 2222:k=true;
break;
case 3333:k=true;
break;
}//end of switch
return k;
}
}
BankTransaction2.java(MainClass)
package maccess;
import test.*;
import java.util.*;
int count=0;
xyz:
while(true) {
boolean k = cpn.verify(pinNo);
if(k) {
System.out.println("====Choice====");
System.out.println("1.WithDraw\n2.Deposit");
switch(choice) {
Page
case 1:
130
System.out.println("Enter the amt:");
int a1 = s.nextInt();
if(amt<=b.bal) {
System.out.println("Amt WithDrawn:"+amt);
b.bal=b.bal-amt;
b.getBalance();
System.out.println("Transaction Completed...");;
}else {
System.out.println("Insufficient Fund...");
};
wd.process(a1);
}else {
System.out.println("Invalid amt...");
break xyz;
case 2:
int a2 = s.nextInt();
System.out.println("Amt deposited:"+amt);
b.bal=b.bal+amt;
b.getBalance();
System.out.println("Transaction Completed...");
131
}
Page
};
131
dp.process(a2);
}else {
System.out.println("Invalid amt...");
break xyz;
default:
System.out.println("Invalid Choice...");
break xyz;
}//End of switch
}else {
System.out.println("Invalid PinNo...");
count++;
if(count==3) {
break xyz;
}//End of loop
s.close();
ClassFiles:
package : test
Balance.class
Transaction.calss
CheckPinNo.class
package : maccess
BankTransaction2.java(MainClass)
BankTransaction2$1.class
BankTransaction2$2.class
======================================================================================
Assignment1:(Solution)
132
132
Arithmetic.java
package test;
public interface Arithmetic {
public abstract void process(int x,int y);
}
DArithmeic.java(MainClass)
package maccess;
import test.*;
import java.util.*;
int x = s.nextInt();
int y = s.nextInt();
System.out.println("====Choice====");
System.out.println("1.add\n2.sub\n3.mul\n4.div\n5.modDiv");
switch(choice) {
case 1:
System.out.println("Sum:"+(x+y));
};
ad.process(x, y);
break;
case 2:
{
Page
133
{
System.out.println("Sub:"+(x-y));
};
sb.process(x, y);
break;
case 3:
System.out.println("Mul:"+(x*y));
};
ml.process(x, y);
break;
case 4:
System.out.println("Div:"+(float)x/y);
};
dv.process(x, y);
break;
case 5:
System.out.println("ModDiv:"+(x%y));
134
}
Page
};
134
md.process(x, y);
break;
default:
System.out.println("Invalid choice...");
}//end of switch
s.close();
ClassFiles:
package : test
Arithmetic.class
package : maccess
DArithmetic.class(MainClass)
DArithmetic$1.class
DArithmetic$2.class
DArithmetic$3.class
DArithmetic$4.class
DArithmetic$5.class
=====================================================================================
Comparision Diagram:
135
Page
135
Summary and Conclusion of Programming
components:(Java Alphabets)
(a)Variables
1.Primitive DataType variables
(i)static variables
(ii)NonStatic variables
=>Instance variables
=>Local Variables
2.NonPrimitive DataType variables
(i)static variables
(ii)NonStatic variables
=>Instance variables
=>Local Variables
(b)Methods
1.static methods
2.NonStatic methods(Instance methods)
(c)Blocks
1.static block
2.NonStatic block(Instance block)
(d)Constructors
=>NonStatic Constructor
(There is no concept of static Constructor)
136
(e)Classes
=>Static classes(Only InnerClasses)
Page
=>NonStatic Classes
136
(f)Interfaces
=>Static Interfaces(Only InnerInterfaces)
=>NonStatic Interfaces
(g)AbstractClasses
=>static abstract classes(Only InnerAbstractClasses)
=>NonStatic abstract classes
==============================================================================
define Exception?
=>The disturbance which is occured from the application is known as Exception.
2.catch block
3.finally block
1.try block:
=>try block will hold the statements which will raise the exception.
=>when the exception is raised then one object is created for exception_type_class and
syntax:
try
//set-of-statements
2.catch block:
=>The catch block will hold the object reference and the required msg is generated from the catch block.
syntax:
catch(exception_type_class ref_var)
//msg
}
137
3.finally block :
=>finally block is part of exception handling process ,but executed independently without depending on
Page
exception.
137
syntax:
finally
//resource_closing_operations
Note:
=>In realtime finally block will hold resource closing operations like IO Close,File Close,DB Close,N/W close,...
--------------------------------------------------------------------------------------------------------------------------------------------------------
2.Exception
138
1.Error:
=>The disturbance which is occured from the environment is known as error.
=>'java.lang.Error' is the ParentClass or SuperClass of all the errors raised from the Enviroment.
2.Exception:
=>The disturbance which is occured from the application is known as exception.
=>The exceptions which are raised from the application are categorized into two types:
(a)Unchecked Exceptions
(b)Checked Exceptions
(a)Unchecked Exceptions:
=>The exceptions which are raised at execution stage are known as UnChecked exceptions or Runtime
exceptions.
Exp:
java.lang.NumberFormatException
java.util.InputMismatchException
java.lang.ArithmeticException
...
139
Exp program:
package maccess;
Page
import java.util.*;
139
public class DException1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try {
System.out.println("Enter the value:");
int x = s.nextInt();//Exception for Non integer input
int k = 44/x;//Exception when x=0
System.out.println("The value k:"+k);
}//end of try
catch(InputMismatchException ime)
{
System.out.println("Enter only Integer value...");
}
catch(ArithmeticException ae)
{
System.out.println("Enter only NonZero value....");;
}
finally
{
s.close();
}
}
}
Dt : 28/7/2021
Diagram:
Method Signature:
public jva.lang.String getMessage();
140
syntax:
String msg = obj.getMessage();
Page
140
faq: define printStackTrace() method?
=>printStackTrace() method is also from java.lang.Throwable class and which is used to display the complete
details of exception like exception_type_class_name,msg,method_name and line_no.
Method Signature:
public void printStackTrace();
syntax:
obj.printStackTrace();
------------------------------------------------------------------------------------
step-4 : If the condition is true then raise exception,which means create object for user
step-5 : use 'throw' keyword to throw the reference of object onto catch block.
step-6 : catch block will hold object reference and display the required msg.
Exp program:
wap to read employee bSal and calculate totSal?
DException2.java
package maccess;
import java.util.*;
public class DException2 extends Exception//step1
{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try //step2
{
System.out.println("Enter the bSal:");
int bSal = s.nextInt();
if(bSal<5000)//step3 raise exception
{
DException2 ob = new DException2();//step4
throw ob;//step5 throwing the reference onto catch block
}
float totSal = bSal+(0.93F+bSal)+(0.63F*bSal);
System.out.println("BSal:"+bSal);
141
System.out.println("TotSal:"+totSal);
}//end of try
catch(DException2 e)//step6
Page
141
System.out.println("Invalid bSal....");
}
finally
{
s.close();
}
}
}
Assignment:
1.read stuName
2.stuRollNo
3.read branch
Note:
StuName =
StuRollNo =
StuBranch =
--------------------------------------------------------------------------------------
Dt : 29/7/2021
Diagram:(DException2)
142
Page
142
Assignment:(Solution)
1.read stuName
2.stuRollNo
3.read branch
Note:
StuName =
StuRollNo =
StuBranch =
DException3.java
package maccess;
import java.util.*;
@SuppressWarnings("serial")
public class DException3 extends Exception
{
public DException3(String msg) {
super(msg);
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try {
System.out.println("Enter the StuName:");
String stuName = s.nextLine();
System.out.println("Enter the StuRollNo:");
String stuRollNo = s.nextLine();
if(stuRollNo.length()!=10)//raise exception
{
DException3 ob1 = new DException3("Invalid
rollNo...");
//Object created with the message "invalid
rollNo..."
throw ob1;//throwing the object reference onto catch
block
}
System.out.println("Enter the branch:");
String br = s.nextLine();
switch(br)
{
143
case "CSE":
break;
Page
case "ECE":
143
break;
case "EEE":
break;
default://raise exception
DException3 ob2 = new DException3("InvalidBranch....");
//Object is created with the message "Invalid
Branch..."
throw ob2;//throwing the object reference onto catch
block
}//end of switch
System.out.println("StuName:"+stuName);
System.out.println("StuRollNO:"+stuRollNo);
System.out.println("StuBranch:"+br);
}//end of try
catch(DException3 ob)
{
System.out.println(ob.getMessage());
}
finally
{
s.close();
}
}
}
Note:
=>when we want to display individual messages,then we must pass message as parameter while
----------------------------------------------------------------------------------------------------------------------------------------------------------
Annotation
=>The tag based information which is added to the programming components like Class, Interface,Method and
Variable,is known as Annotation.
=>These annotations will give information to the compiler at compilation stage or will give information to the
execution controls while execution process.
Types of Annotation :
The following are some important annotations in CoreJava:
(a)SuppressWarnings
(b)Override
(a)SuppressWarnings:
=>This annotation will provide information to compiler to close the raised wranings.
(b)Override:
=>This annotation will provide information to compiler to check the method is overriding method or not.
144
=====================================================================================
Page
144
(b)Checked Exceptions:
=>The exceptions which are identified and raised by the compiler at compilation stage are known as Checked
Exceptions or Compiletime Exceptions.
Exp:
java.lang.InterruptedException
java.lang.ClassNotFoundException
java.io.IOException
...
Method Signature:
public static native void sleep(long) throws java.lang.InterruptedException;
syntax:
Thread.sleep(time);
Note:
=>'throws' keyword specify to ignore the exception in current method and raise at method call.
145
=>when the exception is raised at method call then it is identified by the compiler,because of this reason it is
known as CompileTime exception or Checked Exception.
Page
145
Exp application:
DException4.java
package test;
public class DException4 {
public static void main(String[] args) {
for(int i=1;i<=10;i++)
{
System.out.println("Value:"+i);
try {
Thread.sleep(5000);
}catch(InterruptedException ie) {ie.printStackTrace();}
}//end of loop
}
}
------------------------------------------------------------------------------
step-2 : declare 'throw' keywod in catch block and perform re-throwing process.
Exp application:
EmployeeDesignation.java
package test;
@SuppressWarnings("serial")
public class EmployeeDesignation extends Exception
{
public EmployeeDesignation() {}
public EmployeeDesignation(String msg) {
super(msg);
}
public void verify(String desg) throws EmployeeDesignation
{
try
{
switch(desg)
{
case "SE":
break;
case "ME":
break;
case "TE":
break;
default: //raise exception
146
throw ed;
146
}//end of switch
}//end of try
catch(EmployeeDesignation ed)
{
throw ed;//re-throwing process
}
}
}
DException5.java
package maccess;
import java.util.*;
import test.EmployeeDesignation;
@SuppressWarnings("serial")
super(msg);
try
if(empId.length()!=4)//raise exception
throw de;
};
147
int bSal = s.nextInt();
if(bSal<5000)//raise Exception
throw de;
System.out.println("EmpName:"+empName);
System.out.println("EmpId:"+empId);
System.out.println("EmpDesg:"+desg);
System.out.println("EmpBSal:"+bSal);
System.out.println("TotSal:"+totSal);
}//end of try
catch(DException5 de)
System.out.println(de.getMessage());
catch(EmployeeDesignation ed)
System.out.println(ed.getMessage());
finally
s.close();
---------------------------------------------------------------------------------------------------------------------------------------------------------
Assignment:
Dt : 2/8/2021
Assignment:(Solution)
148
CheckBranch.java
148
package test;
@SuppressWarnings("serial")
public CheckBranch() {}
super(msg);
try {
switch(br)
case "CSE":
break;
case "ECE":
break;
case "EEE":
break;
default://Exception raised
throw cb;
}//end of switch
}//end of try
catch(CheckBranch cb)
--------------------------------------------------------------------------------------------------------------------------------------------------
DException6.java
149
package maccess;
Page
import test.CheckBranch;
149
import java.util.*;
@SuppressWarnings("serial")
super(msg);
try {
String br = s.nextLine().toUpperCase();
cb.verify(br);
if(stuRollNo.length()!=10)//raise exception
System.out.println("StuName:"+stuName);
System.out.println("StuRollNO:"+stuRollNo);
System.out.println("StuBranch:"+br);
}//end of try
{
150
System.out.println(ob.getMessage());
Page
150
}//End of try-with-resource
=>The process of declaring 'throw' keyword in catch block and performing throwing process is known as re-
throwing process.
Exception Propagation
define Exception Propagation?
=>In Exception re-throwing process the exception is moved from one method to another method is known as
Exception Propagation.
=>'throw' keyword is used to throw the object reference onto catch block.
(ii)throws:
=>'throws' keyword specify ignore the exception in current method and raise at method call
=>catch
=>finally
=>throw
=>throws
-----------------------------------------------------------------------------------------------------------------------------------------------------------
syntax:
Page
151
{
//msg
----------------------------------------------------------------------------------------------------------------------------------------------------------
syntax:
try(resource1;resource2;...)
//statements
Exp:
try(Scanner s = new Scanner(System.in);)
//statements
Note:
=>In try-with-resource statement the resources are closed automatically at the end of
-----------------------------------------------------------------------------------------------------------------------------------------------------
syntax:
resource1;resource2;...
try(res1_ref_var;res2_ref_var;...)
//statements
Exp:
Scanner s = new Scanner(System.in);
try(s;)
152
//statements
Page
152
}
Exp Programm:
package maccess;
import test.CheckBranch;
import java.util.*;
@SuppressWarnings("serial")
super(msg);
try(s;)//Java9
try {
String br = s.nextLine().toUpperCase();
cb.verify(br);
if(stuRollNo.length()!=10)//raise exception
}
153
System.out.println("StuName:"+stuName);
System.out.println("StuRollNO:"+stuRollNo);
Page
153
System.out.println("StuBranch:"+br);
}//end of try
System.out.println(ob.getMessage());
}//End of try-with-resource
-----------------------------------------------------------------------------------------------------------------------------------------------------
define 'java.lang.NullPointerException'?
=>This 'java.lang.NullPointerException' is raised when we access the NonPrimitive datatype variable assigned
with null value.
DException7.java
package maccess;
public class DException7 {
public static void main(String[] args) {
String m = null;
int len = m.length();//NullPointerException is raised
System.out.println("String : "+m);
System.out.println("length : "+len);
}
}
======================================================================================
Assignment:
=====================================================================================
Polymorphism in Java:
=>The process in which the same programming having many forms is known as PolyMorphism.
Poly - Many
Morphism - Forms
(a)Dynamic PolyMorphism
154
(b)Static PolyMorphism
Page
154
(a)Dynamic PolyMorphism:
=>The process in which the same programming component having many forms at execution stage is known as
Dynamic PolyMorphism or Runtime PolyMorphism.
Exp:
Method Overriding
Note:
=>Through Method Overriding process we can provide the same method Signature with different
forms,which means different method bodies,because of this reason Method Overriding process comes under
Dynamic Polymorphism.
(b)Static PolyMorphism:
=>The process in which the same programming component having many forms at compilation
Exp:
Method Overloading
Note:
=>Through Method OverLoading process we can provide same method in different forms by changing its
Para_list or Para_type and these forms are identified by the compiler at compilation,because of this reason
Method Overloading comes under Static PolyMorphism.
add(int,int)
add(int,float)
add(int,int,int)
Example program
Display.java
package test;
public class Addition {
public void add(int x,int y) {
System.out.println("Sum1:"+(x+y));
}
public void add(int x,float y) {
System.out.println("Sum2:"+(x+y));
}
public void add(int x,int y,int z) {
155
System.out.println("Sum3:"+(x+y+z));;
}
Page
155
DPoly1.java
package maccess;
import test.Addition;
public class DPoly1 {
public static void main(String[] args) {
Addition ad = new Addition();
ad.add(1,2);
ad.add(1,2.3F);
ad.add(1,2, 3);;
}
}
------------------------------------------------------------------------------
2.private
3.final
1.static:
=>The following are the static programming components:
(a)static variables
(b)static methods
(c)static blocks
(d)static classes
(e)static Interfaces
(f)static AbstractClasses
2.private:
=>The following are the private programming components:
(a)private variables
(b)private methods
(c)private classes
(d)private Constructors
(a)private variables:
=>The variables which are declared with private keyword are known as private variables.
Rule:
=>private variables are accessed only inside the class,which means accessed by the methods of same class.
Note:
156
=>In realtime private variables are used in Bean classes and POJO classes.
Page
156
(b)private methods:
=>The methods which are declared with private keyword are known as private methods.
Rule:
=>Private methods are accessed by the NonPrivate methods of same class.
(c)private classes:
=>The classes which are declared with private keyword are known as private classes.
Rule:
=>These Private classes can be declared as only InnerClasses,which means OuterClasses cannot be private.
Exp program:
Display.java
package test;
public class Display {
private int a=10;
private static int b=20;
private void show1() {
System.out.println("===show1()===");
System.out.println("a:"+a);
System.out.println("b:"+b);
}//End of method
private static void show2() {
System.out.println("===show2()====");
//System.out.println("a:"+a);//Compilation Error
System.out.println("b:"+b);
}//End of method
private class SubClass1{
public void m1() {
System.out.println("====m1()====");
System.out.println("a:"+a);
System.out.println("b:"+b);
}
}//InnerClass
private static class SubClass2{
public void m2() {
System.out.println("====m2()====");
System.out.println("b:"+b);
}
}//InnerClass
public SubClass1 ob1 = new SubClass1();
public SubClass2 ob2 = new SubClass2();
public void dis() {
this.show1();
Display.show2();
ob1.m1();
ob2.m2();
157
}
}//OuterClass
Page
DPoly2.java
157
package maccess;
import test.Display;
public class DPoly2 {
public static void main(String[] args) {
Display d = new Display();
d.dis();
}
}
o/p:
===show1()===
a:10
b:20
===show2()====
b:20
====m1()====
a:10
b:20
====m2()====
b:20
----------------------------------------------------------------------------------
Dt : 4/8/2021
*imp
(d)private Constructors:
=>The Constructors which are declared with private keyword are known as private Constructors.
Rule:
=>Private Constructor is executed when the object is created inside the same class where the private constructor is
declared.
Note:
=>Using Private Constructor we can construct 'SingleTon class design pattern'.
=>The class which generates only one object inside the same class and the reference of object is accessed outside
the class is known as 'SingleTon class design pattern'.
(iii)static method
158
Page
158
(i)private Constructor:
=>Private constructor is executed when the object is created inside the same class and which also retrict the
object creation from externally.
(ii)private static reference variable:
=>private static reference variable will hold the reference of object created inside the same class.
(iii)static method:
=>we use static method to access the Object reference outside the class.
Exp program:
CTest.java
package test;
public class CTest {
private CTest() {}
private static CTest t = new CTest();//Constructor_Call
public static CTest getRef()
{
return t;
}
public void dis(int z) {
System.out.println("====dis()====");
System.out.println("The value z:"+z);
}
}
DPoly3.java
package maccess;
import test.CTest;
public class DPoly3 {
public static void main(String[] args) {
//CTest ob = new CTest();//Constructor call Compilation_Error
CTest ob = CTest.getRef();//Accessing the Object reference
ob.dis(123);
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>In realtime 'SingleTon class design pattern' is used in DAO(Data Access Object) layer of MVC(Model View
Controller).
-------------------------------------------------------------------------------------------------------------------------------------------------------
Based on Object Creation the 'SingleTon class design pattern' is categorized into two types:
(a)Early Instantiation process
=>In Early Instantiation process the object is created inside the static block.
Exp program:
Page
Test1.java
159
package test;
public class Test1 {
private Test1() {}
private static Test1 t = null;
static {
t = new Test1();//Constructor_Call
}
public static Test1 getRef()
{
return t;
}
public void dis(int z) {
System.out.println("====dis()====");
System.out.println("The value z:"+z);
}
}
DPoly4.java
package maccess;
import test.Test1;
public class DPoly4 {
public static void main(String[] args) {
//Test1 ob = new Test1();//Constructor call Compilation_Error
Test1 ob = Test1.getRef();//Accessing the Object reference
ob.dis(123);
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------
(b)Late Instantiation process:
=>In Late Instantiation process the object is created after after class loading.
=>In Late Instantiation process the object is created inside the method.
Exp program:
Test2.java
package test;
public class Test2 {
private Test2() {}
private static Test2 t = null;
public static Test2 getRef()
{
t = new Test2();//Constructor_Call
return t;
}
public void dis(int z) {
System.out.println("====dis()====");
System.out.println("The value z:"+z);
}
}
DPoly5.java
160
package maccess;
import test.Test2;
Page
160
public static void main(String[] args) {
//Test2 ob = new Test2();//Constructor call Compilation_Error
Test2 ob = Test2.getRef();//Accessing the Object reference
ob.dis(123);
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------
3.final:
The following are the final programming components:
(a)final variables
(b)final methods
(c)final classes
=>There is no concept of final blocks,final constructors,final Interfaces and final abstract classes.
(a)final variables:
=>The variables which are declared with final keyword are known as final variables.
Rule:
=>final variables must be initialized with an values and once initialized cannot be modified.
(b)final methods:
=>The methods which are declared with final keyword are known as final methods.
Rule:
=>final methods cannot be Overrided.(There is no Overriding process for final methods)
(c)final classes:
=>The classes which are declared with final keyword are known as final classes.
Rule:
=>final classes cannot be inherited.(There is no extention for final classes)
--------------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>Using final programming components we construct 'Immutable classes'.
---------------------------------------------------------------------------------------------------------------------------------------------
Rule-2 : The variables within the class must be private and final variables.
Rule-3 : The methods within the class must be only 'Getter methods'.
161
161
Note:
=>These Immutable classes will generate Immutable Objects.
Note:
=>In realtime Immutable objects are used in Banking domain applications to hold Transaction details.
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>Every variable in the class will have its own Getter method and Setter method
---------------------------------------------------------------------------------------------------------------------------------------------------------
Exp program:
TransLog.java
package test;
import java.util.Date;
public final class TransLog {
private final long accNo,bAccNo;
private final float amt;
private final Date d;
public TransLog(long accNo,long bAccNo,float amt,Date d) {
this.accNo=accNo;
this.bAccNo=bAccNo;
this.amt=amt;
this.d=d;
}
public final long getAccNo() {
return accNo;
}
public final long getbAccNo() {
return bAccNo;
}
public final float getAmt() {
return amt;
}
public final Date getD() {
return d;
}
}
DPoly6.java
package maccess;
import test.TransLog;
162
import java.util.Date;
162
public static void main(String[] args) {
//Immutable Object
System.out.println("====Transaction details====");
System.out.println("AccNo:"+ob.getAccNo());
System.out.println("BAccNo:"+ob.getbAccNo());
System.out.println("Amt Transferred:"+ob.getAmt());
System.out.println("Data&Time:"+ob.getD());
o/p:
====Transaction details====
AccNo:6123456
BAccNo:313131
Amt Transferred:12000.0
====================================================================================
Based on Security,the objects in Java Lang are categorized into two types:
(i)Mutable Objects
(ii)Immutable Objects
(i)Mutable Objects:
=>The Objects once created can be modified(changed) are known as Mutable Objects.
(ii)Immutable Objects:
=>The Objects once Created cannot be modified(changed) are known as Immutable Objects.
========================================================================================
faq:
========================================================================================
faq:
163
Page
163
Encapsulation process
=>The process of binding all the programming components into a single unit 'class' is known as Encapsulation
process.
Note:
=>Class is a Collection of Primitive DataType variables,NonPrimitive DataType variables, concrete
methods,blocks,Constructors,features,InnerClasses,InnerInterfaces,InnerAbstract Classes and Exception Handling
Components.(try,catch,finally,throw and throws)
Comparision Diagram:
========================================================================================
Abstraction process
=>The process in which only the essential details are displayed to the EndUser,is known as Abstraction
process.(Which means Non-Essential details are hided from the EndUser)
Note:
=>we use Interfaces and Abstract classes to achieve abstract process.
164
(The applications which are constructed using Interfaces and Abstract classes are abstraction process
applications)
Page
===========================================================================================
164
Type Casting in Java:
=>The process of converting one datatype value into another datatype value is known as TypeCasting process.
Note:
=>TypeCasting process is not applicable to convert Primitive datatypes to NonPrimitive datatypes and
NonPrimitive datatypes to Primitive datatypes.
Case-1 :
TypeCasting process on Primitive DataTypes can be done in two ways:
(a)Widening process
(b)Narrowing process
(a)Widening process:
=>The process of Converting Lower datatypes into Higher datatypes is known as Widening process.
=>This Widening process is done automatically,because of this reason it also known as Implicit TypeCasting
process.
(b)Narrowing process:
=>The process of Converting Higher datatype values into Lower datatype values is known as Narrowing process
=>This DownCasting process is done manually,because of this reason it is known as Explicit TypeCasting process.
Exp:
DTypeCast1.java
package maccess;
public class DTypeCast1 {
public static void main(String[] args) {
//Widening process
char ch1 = 'A';
int z = (int)ch1;//UpCasting Process
//Narrowing process
int k = 82;
char ch2 = (char)k;//DownCasting Process
System.out.println("Value at char A:"+z);
System.out.println("char at value 82:"+ch2);
}
}
Case-2 :
TypeCasting process is not applicable on NonPrimitive datatypes,but in inheritance process we can perform the
following:
165
(a)Generalization Process
Page
(b)Specialization Process
165
(a)Generalization Process:
=>The process in which one reference is created and the reference is binded with all the members of PClass and
only Overriding members from the CClass,is known as Generalization process.
Syntax
PClass ob = (PClass)new CClass();
Note:
=>Generalization process is also known as Widening process or UpCasting process or implicit TypeCasting
process.
(b)Specialization Process:
=>The process in which the CClass is constructed based on one feature of PClass,is known as Specialization
process.
Syntax
CClass ob = (CClass)new PClass();
Rule:
=>In Specialization process the PClass must be Built-in class or PreDefined class,if not it raises
'java.lang.ClassCastException'.
Note:
=>This Specialization process is also known as Narrowing process or DownCasting process or Explicit TypeCasting
process.
------------------------------------------------------------------------------------
Summary:
1.Widening process
2.Narrowing process
3.UpCasting process
4.DownCasting process
7.Genaralization process
8.Specialization process
9.'java.lang.ClassCastException'.
166
====================================================================================
Page
166
WrapperClasses
WrapperClasses in java:
=>The Built-in or PreDefined classes from java.lang package,which are used to make primitive datatypes
available in the form of Objects are known as WrapperClasses.
=>Every primitive datatype will have its own WrapperClass and in this process there are eight WrapperClasses.
List of WrapperClasses:
DataType WrapperClass
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Hierarchy of WrapperClasses:
Boxing process
=>The process of binding Primitive datatype values into WrapperClass objects is known as Boxing process.
Note:
=>we use 'Constructors' or 'valueOf()' method to perform Boxing process.
Case-1 :
Boxing process using Constructors
=>The following are the list of constructors from WrapperClasses:
167
WrapperClass Constructors
Page
Byte byte,String
167
Short short,String
Integer int,String
Long long,String
Float float,double,String
Double double,String
Character char
Boolean boolean
Integer WrapperClass:
=>Integer WrapperClass having two constructors,
Constructor Signatures:
public java.lang.Integer(int);
Note:
=>This 'java.lang.NumberFormatException' will be raised when we try to bind other than int data.
Exp program:
DWrapperClass1.java
package maccess;
public class DWrapperClass1 {
@SuppressWarnings("removal")
public static void main(String[] args) {
//Boxing process
Integer ob1 = new Integer(12);//Constructor_call with int
parameter
Integer ob2 = new Integer("13");//Constructor_call with int
parameter in the form of String
System.out.println("ob1:"+ob1.toString());
System.out.println("ob2:"+ob2.toString());
}
}
----------------------------------------------------------------------------------
168
Page
168
Diagram:
toString() method?
=>toString() method is a Built-in or PreDefined method used to display the data from the objects.
=>This toString() method is available in WrapperClasses,String classes,Collection classes, Map classes and Enum
class
Method Signature:
public java.lang.String toString();
Note:
=>This toString() method is executed automatically when we display object reference variable or Object
reference
--------------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>Like Integer WrapperClass Byte,Short,Long,Double and Boolean WrapperClasses also having
two constructors,
-------------------------------------------------------------------------------------------------------------------------------------------------------
Float WrapperClass:
=>Float WrapperClass having three Constructors,
Constructor Signatures:
public java.lang.Float(float);
public java.lang.Float(double);
169
Note:
Page
=>This 'java.lang.NumberFormatException' is raised when we try to bind other than float data.
169
Character WrapperClass:
=>Character WrapperClass having one constructor to bind char data.
Constructor Signature:
public java.lang.Character(char);
Exp program:
DWrapperClass2.java
package maccess;
public class DWrapperClass2 {
@SuppressWarnings("removal")
public static void main(String[] args) {
//Boxing process
Float ob1 = new Float(12.34F);
Float ob2 = new Float(123.56);
Float ob3 = new Float("234.56");
Character ob4 = new Character('A');
System.out.println("ob1:"+ob1.toString());
System.out.println("ob2:"+ob2.toString());
System.out.println("ob3:"+ob3.toString());
System.out.println("ob4:"+ob4.toString());
}
}
----------------------------------------------------------------------
Case-2:
Boxing process using valueOf() method
=>valueOf() is a static built-in method available in all WrapperClasses and used to perform Boxing process.
Exp program:
DWrapperClass3.java
package maccess;
public class DWrapperClass3 {
public static void main(String[] args) {
//Boxing Process
Integer ob1 = Integer.valueOf(12);
Float ob2 = Float.valueOf(12.34F);
Character ob3 = Character.valueOf('A');
Boolean ob4 = Boolean.valueOf(true);
System.out.println("ob1:"+ob1.toString());
System.out.println("ob2:"+ob2.toString());
System.out.println("ob3:"+ob3.toString());
System.out.println("ob4:"+ob4.toString());
170
}
}
Page
170
Note:
=>valueOf() method is a factory method because which hide the Object creation process from EndUser.
------------------------------------------------------------------------------------------------------------------------------------------------------
AutoBoxing process
=>The Boxing process which is performed automatically is known as AutoBoxing process
Exp program:
DWrapperClass4.java
package maccess;
public class DWrapperClass4 {
public static void main(String[] args) {
//AutoBoxing Process
Integer ob1 = 12;
Float ob2 = 12.34F;
Character ob3 = 'A';
Boolean ob4 = true;
System.out.println("ob1:"+ob1.toString());
System.out.println("ob2:"+ob2.toString());
System.out.println("ob3:"+ob3.toString());
System.out.println("ob4:"+ob4.toString());
Note:
variables.
------------------------------------------------------------------------------------
Dt : 9/8/2021
faq:
=>The process of taking Primitive datatype values out of WrapperClass objects is known as
UnBoxing process.
171
Page
171
public byte byteValue();
Exp program:
DWrapperClass5.java
package maccess;
public class DWrapperClass5 {
@SuppressWarnings("removal")
public static void main(String[] args) {
//Boxing Process
Integer ob1 = new Integer(12);
Float ob2 = new Float(13.45F);
Character ob3 = new Character('A');
Boolean ob4 = new Boolean(true);
//UnBoxing
int i = ob1.intValue();
float f = ob2.floatValue();
char ch = ob3.charValue();
boolean b = ob4.booleanValue();
System.out.println("i:"+i);
System.out.println("f:"+f);
System.out.println("ch:"+ch);
System.out.println("b:"+b);
}
}
---------------------------------------------------------------------------
faq:
172
Exp program:
DWrapperClass6.java
package maccess;
public class DWrapperClass6 {
public static void main(String[] args) {
//AutoBoxing Process
Integer ob1 = 12;
Float ob2 = 13.45F;
Character ob3 = 'A';
Boolean ob4 = true;
//AutoUnBoxing Process
int i = ob1;
float f = ob2;
char ch = ob3;
boolean b = ob4;
System.out.println("i:"+i);
System.out.println("f:"+f);
System.out.println("ch:"+ch);
System.out.println("b:"+b);
}
}
Note:
datatype variables.
--------------------------------------------------------------------------------------
Note:
=>WrapperClasses will provide the following parseXXXX() methods to convert String data
byte by = Byte.parseByte(s.nextLine());
short sh = Short.parseShort(s.nextLine());
int i = Integer.parseInt(s.nextLine());
long l = Long.parseLong(s.nextLine());
float f = Float.parseFloat(s.nextLine());
double d = Double.parseDouble(s.nextLine());
173
Page
Exp program:
173
DWrapperClass7.java
package maccess;
import java.util.*;
public class DWrapperClass7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
System.out.println("Enter the PhoneNo:");
long phoneNo =
Long.parseLong(s.nextLine());
System.out.println("Enter the UserName:");
String userName = s.nextLine();
System.out.println("PhoneNo:"+phoneNo);
System.out.println("UserName:"+userName);;
}//end of try
}
----------------------------------------------------------------------------------------------------------------------------------------------------------
why we have to make Primitive datatype variables available in the form of Objects?
=>The Frameworks like JCF and Hibernate will work only with Objects,because of this
FrameWorks:
...
-----------------------------------------------------------------------------------------------------------------------------------------------------
Note:
174
Strings in Java:
=>The Sequenced Collection of characters which are represented in double quotes is known
as String.
Exp:
"java","program",...
we use the followimg classes from 'java.lang' package to generate String objects:
1.String class
2.StringBuffer class
3.StringBuilder class
1.String class:
=>'String' class is from java.lang package and the objects generated from 'String' class
Hierarchy of 'String':
=>we use the following two syntaxes to create objects from 'String' class:
String s1 = "java";
175
175
String s2 = new String("program");
Exp program:
DString1.java
package maccess;
public class DString1 {
public static void main(String[] args) {
String s1 = "java";
String s2 = new String("program");
System.out.println("s1:"+s1.toString());
System.out.println("s2:"+s2.toString());;
}
}
-----------------------------------------------------------------------------------------------------------------------------------------
=>we use 'concat()' method or '+' symbol to perform String Concatenation process.
Exp program:
DString2.java
package maccess;
public class DString2 {
public static void main(String[] args) {
String s1 = "java";
String s2 = "program";
String s3 = "language";
String s4 = s1.concat(s2);
String s5 = s1+s3;
System.out.println("s4:"+s4);
System.out.println("s5:"+s5);
}
}
------------------------------------------------------------------------------
wt is the diff b/w 'String Literal process' and 'new operator process'?
=>In String Literal process,the execution control will check the 'String Constant pool' is any object having same
data,
=>If Available then without creating new object,the reference of existing object is used.
=>In new operator process,one reference is created part of Heap Area and the reference is binded with the
176
Diagram:
176
-----------------------------------------------------------------------------------
=>The String Comparision process can be done the following three ways:
Method Signature:
Note:
=>In realtime these methods are used in Authentication process.
Method Signature:
syntax:
int z = s1.compareTo(s2);
177
177
if z<0 then s1<s2
Note:
=>In realtime these methods are used in Sorting processes.
Exp program:
DString3.java
package maccess;
import java.util.Scanner;
public class DString3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
System.out.println("Enter the String1:");
String s1 = s.nextLine().trim();
System.out.println("Enter the String2:");
String s2 = s.nextLine().trim();
System.out.println("====equals()====");
boolean k = s1.equalsIgnoreCase(s2);
if(k) {
System.out.println("Strings are equal...");
}else{
System.out.println("Strings are Not-Equal...");
}
System.out.println("====compareTo()====");
int z = s1.compareToIgnoreCase(s2);
if(z==0) {
System.out.println("Strings are equal...");;
}else{
System.out.println("Strings are Not-Equal...");
};
}//end of try
}
}
Note:
=>'trim()' method is used to remove the spaces before and after the Strings.
-----------------------------------------------------------------------------
=>'is equal to'(==) operator will compare the references of an objects and which will
Exp program:
DString4.java
178
package maccess;
public class DString4 {
Page
178
String s1 = "java";
String s2 = "java";
String s3 = new String("java");
String s4 = new String("java");
System.out.println("====String Literal process====");
if(s1==s2) {
System.out.println("Strings are equal...");
}else {
System.out.println("Strings are Not-Equal...");
}
System.out.println("====new Operator process=====");
if(s3==s4) {
System.out.println("Strings are eqaul...");
}else {
System.out.println("Strings are Not-Equal...");
}
}
}
o/p:
Note:
=>'is equal to'(==) operator not preferable to compare NonPrimitive datatype variables,
because which compare the references of an objects and generate wrong results.
----------------------------------------------------------------------------------
Diagram:
179
Page
179
2.StringBuffer class:
=>StringBuffer is a class from java.lang package and the objects which are generated from StringBuffer class are
Mutable Objects.
public java.lang.StringBuffer(int);
public java.lang.StringBuffer(java.lang.String);
public java.lang.StringBuffer(java.lang.CharSequence);
=>In this syntax the StringBuffer object is created with default capacity 16 and the capacity increases
dynamically at runtime by doubling the capacity and adding 2.
16===>16+16+2===>34===>34+34+2===>70...
Note:
=>we can perform insert() operation based on index value and also we can perform reverse() operation on
StringBuffer objects,because StringBuffer objects are Mutable objects.
Exp program:
SBuffer1.java
package maccess;
public class SBuffer1 {
public static void main(String[] args) {
180
System.out.println("length:"+sb.length());
180
sb.append("java");
System.out.println("sb:"+sb.toString());
System.out.println("capacity:"+sb.capacity());
System.out.println("length:"+sb.length());
sb.append("language");
System.out.println("sb:"+sb.toString());
System.out.println("capacity:"+sb.capacity());
System.out.println("length:"+sb.length());
sb.insert(4,"program");
System.out.println("sb:"+sb.toString());
System.out.println("capacity:"+sb.capacity());
System.out.println("length:"+sb.length());
System.out.println("=====String Reverse=====");
sb.reverse();
System.out.println("sb:"+sb.toString());;
}
}
o/p:
default capacity:16
length:0
sb:java
capacity:16
length:4
sb:javalanguage
capacity:16
length:12
sb:javaprogramlanguage
capacity:34
length:19
=====String Reverse=====
sb:egaugnalmargorpavaj
---------------------------------------------------------------------------------------------------------------------------------------------------------
=>In this syntax the StringBuffer object is created with the capacity equal to the value passed as parameter
while Object creation.
Exp program:
181
SBuffer2.java
package maccess;
Page
181
public class SBuffer2 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(4);
System.out.println("default capacity:"+sb.capacity());
System.out.println("length:"+sb.length());
sb.append("NIT");
System.out.println("sb:"+sb.toString());
System.out.println("capacity:"+sb.capacity());
System.out.println("length:"+sb.length());
sb.append("HYD");
System.out.println("sb:"+sb.toString());
System.out.println("capacity:"+sb.capacity());
System.out.println("length:"+sb.length());
}
}
o/p:
default capacity:4
length:0
sb:NIT
capacity:4
length:3
sb:NITHYD
capacity:10
length:6
-------------------------------------------------------------------------------------
=>In this syntax sb2 is holding the reference of sb1,in this process the sb2 object is created with the capacity "16
+ length of sb1".
Exp program:
SBuffer4.java
package maccess;
public class SBuffer4 {
public static void main(String[] args) {
System.out.println("====sb1=====");
StringBuffer sb1 = new StringBuffer();
sb1.append("NITjava");
System.out.println("ab1:"+sb1.toString());
182
System.out.println("default capacity:"+sb1.capacity());
System.out.println("length:"+sb1.length());
System.out.println("====sb2====");
Page
182
StringBuffer sb2 = new StringBuffer(sb1);
sb2.append("program");
System.out.println("sb2:"+sb2.toString());
System.out.println("default capacity:"+sb2.capacity());
System.out.println("length:"+sb2.length());
}
}
o/p:
====sb1=====
ab1:NITjava
default capacity:16
length:7
====sb2====
sb2:NITjavaprogram
default capacity:23
length:14
syntax:
StringBuffer sb = new StringBuffer("NIT");
=>In this syntax the StringBuffer object is created with the capacity equal to the sum of '16 and length of String
passed as parameter'.
Exp program:
SBuffer3.java
package maccess;
public class SBuffer3 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("NITHYD");
System.out.println("sb:"+sb.toString());
System.out.println("default capacity:"+sb.capacity());
System.out.println("length:"+sb.length());
sb.append("javalanguageprogram");
System.out.println("sb:"+sb.toString());
System.out.println("capacity:"+sb.capacity());
System.out.println("length:"+sb.length());
}
183
}
o/p:
Page
183
sb:NITHYD
default capacity:22
length:6
sb:NITHYDjavalanguageprogram
capacity:46
length:25
----------------------------------------------------------------------------------------------------------------------------------------------------------
3.StringBuilder class:
=>StringBuilder class is from java.lang package and the objects generated from StringBuilder class are also
Mutable objects.
public java.lang.StringBuilder(int);
public java.lang.StringBuilder(java.lang.String);
public java.lang.StringBuilder(java.lang.CharSequence);
Note:
=>StringBuilder class is having the same behaviour like StringBuffer,but StringBuffer class is synchronized class
and StringBuilder class is Non-Synchronized class.
184
--------------------------------------------------------------------
Note:
StringBuffer - Synchronized and ThreadSafe class
used in Non-MultiThreading.
==========================================================================================
(b)StringJoiner class
(a)StringTokenizer class:
=>StringTokenizer class is from java.util package and which is used to break the givenString into pieces based on
delimiter.
syntax:
StringTokenizer st = new StringTokenizer(str,"delimiter");
Exp program:
185
Tokenizer.java
Page
package maccess;
185
import java.util.*;
public class Tokenizer {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
System.out.println("Enter the String:");
String str = s.nextLine().trim();
StringTokenizer st = new StringTokenizer(str," ");
System.out.println("No of Tokens:"+st.countTokens());
System.out.println("====Tokens====");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}//end of while
}//end of try
}
}
o/p:
No of Tokens:5
====Tokens====
java
is
good
programming
language
------------------------------------------------------------------------------
(b)StringJoiner class:
=>StringJoiner class is from java.util package introduced by Java8(2014) version and which is used to combine
the strings based on delimiter.
syntax:
StringJoiner sj = new StringJoiner("delimiter");
Exp program:
186
Joiner.java
package maccess;
Page
import java.util.*;
186
public class Joiner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
StringJoiner sj = new StringJoiner("/");
System.out.println("Enter the date:");
String date = s.nextLine();
sj.add(date);
System.out.println("Enter the Month:");
String month = s.nextLine();
sj.add(month);
System.out.println("Enter the Year:");
String year = s.nextLine();
sj.add(year);
System.out.println("DOB:"+sj.toString());
}//end of try
}
}
o/p:
22
01
1999
DOB:22/01/1999
==================================================================================
187
Page
187
Object Class:
=>java.lang.Object' class is the SuperClass or ParentClass of all the classes declared in the application.
Diagram:
2.toString()
3.clone()
4.equals()
5.wait()
6.notify()
7.notifyAll()
8.finalize()
9.getClass()
1.hashCode():
=>The unique numeric number which is generated while object creation is known as hashCode.
Method Signature:
public native int hashCode();
syntax:
int hc = obj.hashCode();
Note:
=>we display the hashCode and check the object is created or not.
2.toString():
=>toString() method is used to display the content from the object.
188
Method Signature:
Page
188
syntax:
String ms = obj.toString();
Note:
=>This toString() method is executed automatically when we display object reference or Object reference
variable.
3.clone():
=>The process of creating the duplicate copy of an object is known as Cloning process.
Method Signature:
protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException;
syntax:
Object o = obj.clone();
Note:
=>This
'java.lang.CloneNotSupportedException'
is raised at method_call.
step-2 : The user defined class must be declared with one user defined object return_type method
step-3 : Using user defined object return_type method call Built-in 'clone()' method
step-4 :Call User defined Object return_type method to start the cloning process.
Exp program:
Product.java
package test;
public class Product extends Object implements Cloneable //Step-1
{
public String pCode,pName;
public float pPrice;
public int pQty;
public Product(String pCode,String pName,float pPrice,int pQty) {
this.pCode=pCode;
this.pName=pName;
this.pPrice=pPrice;
this.pQty=pQty;
}
public String toString() {
return
"PCode:"+pCode+"\nPName:"+pName+"\nPPrice:"+pPrice+"\nPQty:"+pQty;
}
public Object cloning()//Step-2
189
{
Object o = null;
Page
try {
189
o = super.clone();//step-3
}catch(CloneNotSupportedException cnse) {cnse.printStackTrace();}
return o;
}
}
DemoClone.java
package maccess;
import test.Product;
public class DemoClone {
public static void main(String[] args) {
//Original Object
Product ob1 = new Product("A111","Mouse",1200.00F,12);
System.out.println("====Original Object(ob1)====");
System.out.println(ob1.toString());
System.out.println("hashCode of ob1:"+ob1.hashCode());
//Cloned Object
Product ob2 = (Product)ob1.cloning();//Step-4
DownCasting/Narrowing/Specialization
System.out.println("====Cloned Object(ob2)====");
System.out.println(ob2.toString());
System.out.println("hashCode of ob2:"+ob2.hashCode());
}
}
o/p:
====Original Object(ob1)====
PCode:A111
PName:Mouse
PPrice:1200.0
PQty:12
hashCode of ob1:123961122
====Cloned Object(ob2)====
PCode:A111
PName:Mouse
PPrice:1200.0
PQty:12
hashCode of ob2:1227229563
---------------------------------------------------------------------
Cloneable?
=>Cloneable is an interface from java.lang package and which specify the cloning process.
190
190
wt is the behaviour of Constructor in Cloning process?
=>Constructor is executed only for original object creation process,but not executed for Cloned objects or
duplicate objects.Because the constructor call is available in original object creation syntax.
-----------------------------------------------------------------------------
Note:
=>This Cloning process can be done in two ways:
------------------------------------------------------------------------------------
4.equals():
=>equals() method is used to compare two objects and generate boolean result.
Method Signature:
public boolean equals(java.lang.Object);
syntax:
boolean k = obj1.equals(obj2);
5.wait()
6.notify()
7.notifyAll():
=>These three methods are used to establish communication b/w threds.
191
(MultiThreading Chapter)
Page
191
8.finalize():
=>This finalize() method is used to check the object are eligible for garbage collection process or not.(Garbage
Collection process Chapater)
9.getClass():
=>This getClass() method is used to display the class name of an object.(JCF)
=====================================================================================
Arrays in Java:
=>Array is a sequenced collection of elements of same data type.(Similar data)
(or)
syntax:
Class_name arr_var[] = new Class_name[size];
Exp:
Exp program:
User.java
package test;
public class User {
public String uName;
public long phNo;
public User(String uName,long phNo) {
this.uName=uName;
this.phNo=phNo;
}
public String toString() {
return uName+"\t"+phNo;
}
192
}
Page
DArray1.java
192
package maccess;
import test.User;
public class DArray1 {
@SuppressWarnings("removal")
public static void main(String[] args) {
//WrapperClassArray
Integer a[] = new Integer[3];
a[0] = new Integer(12);
a[1] = new Integer(13);
a[2] = new Integer(14);
System.out.println("====WrapperClassArray====");
System.out.println("====Old for loop===");
for(int i=0;i<a.length;i++) {
System.out.println(a[i].toString()+" ");
}
System.out.println("\n====Extended for====");
for(Integer i : a) {
System.out.println(i.toString()+" ");
}
//StringClassArray
String str[] = new String[3];
str[0] = new String("NIT");
str[1] = new String("HYD");
str[2] = new String("java");
System.out.println("\n====StringClassArray====");
System.out.println("====Old for loop===");
for(int i=0;i<str.length;i++) {
System.out.println(str[i].toString()+" ");
}
System.out.println("\n====Extended for====");
for(String i : str) {
System.out.println(i.toString()+" ");
}
//UserDefinedClassArray
User u[] = new User[3];
u[0] = new User("Raj",9898981234L);
u[1] = new User("Alex",77788866612L);
u[2] = new User("Ram",56453412L);
System.out.println("\n====UserDefinedClassArray====");
System.out.println("====Old for loop===");
for(int i=0;i<u.length;i++) {
System.out.println(u[i].toString()+" ");
}
System.out.println("\n====Extended for====");
for(User i : u) {
System.out.println(i.toString()+" ");
}
//ObjectClassArray
Object o[] = new Object[3];
o[0] = new Integer(12);
o[1] = new String("NIT");
o[2] = new User("nit.v",7867561234L);
System.out.println("\n====ObjectClassArray====");
193
System.out.println(o[i].toString()+" ");
193
}
System.out.println("\n====Extended for====");
for(Object i : o) {
System.out.println(i.toString()+" ");
}
}
}
o/p:
====WrapperClassArray====
12
13
14
====Extended for====
12
13
14
====StringClassArray====
NIT
HYD
java
====Extended for====
NIT
HYD
java
====UserDefinedClassArray====
Raj 9898981234
Alex 77788866612
194
Ram 56453412
Page
194
====Extended for====
Raj 9898981234
Alex 77788866612
Ram 56453412
====ObjectClassArray====
12
NIT
nit.v 7867561234
====Extended for====
12
NIT
nit.v 7867561234
==============================================================================
Diagram:
----------------------------------------------------------------------------------------------------------------------------------------------------
'Extended for'
=>'Extended for' is a Auto-Retrieval loop introduced by Java5(2004) version and which retrieves the elements
from Array automatically.
syntax:
for(data_type var : Container_name)
{
195
//loop_block
Page
195
Advantage:
=>In 'Extended for' there is no initialization,Condition and Incre/Decre.
Note:
=>This 'Extended for' is also known as 'foreach loop' or 'Enhanced for loop'.
----------------------------------------------------------------------------------------------------------------------------------------------------
Object Array
=>The Array which is declared with java.lang.Object class is known as Object Array.
Note:
=>Object Array can hold Dis-Similar objects(Objects of different classes),because 'Object' class is the PClass of all
the classes.
--------------------------------------------------------------------------------------------------------------------------------------------------------
Exp:
2-D Arrays
3-D Arrays
4-D Arrays
...
Note:
=>In realtime Multi-D Arrays are less used when compared to 1-D Arrays,but using 2-D Arrays we can construct
'Jagged Arrays'.
Exp program:
DArray2.java
package maccess;
public class DArray2 {
public static void main(String[] args) {
Integer a1[] = {1,2,3};
Integer a2[] = {11,12,13,14};
Integer a3[] = {22,23,24,25,26};
Integer a[][] = {a1,a2,a3};//Jagged Array
System.out.println("=====Old For loop=====");
for(int i=0;i<a.length;i++) {
196
for(int j=0;j<a[i].length;j++) {
System.out.print(a[i][j]+" ");
}//InnerLoop
Page
System.out.println();
196
}//OuterLoop
System.out.println("\n====Extended for====");
for(Integer i[] : a) {
for(Integer j : i) {
System.out.print(j.toString()+" ");
}//InnerLoop
System.out.println();
}//OuterLoop
}
}
o/p:
123
11 12 13 14
22 23 24 25 26
====Extended for====
123
11 12 13 14
22 23 24 25 26
----------------------------------------------------------------------------------------------------------------------------------------------------------
Dis-Advantage of Arrays:
=>The Array size once defined cannot be modified at runtime or execution time,because of this reason arrays are
not preferable to hold dynamic data or runtime data.
Note:
197
-----------------------------------------------------------------------------------------------------------------------------------------------------------
197
Java Collection Framework(JCF):
define 'Collection<E>'?
=>'Collection<E>' is an interface from java.util package and which is root of Java Collection Framework.
1.Set<E>
2.List<E>
3.Queue<E>
Hierarchy of Collection<E>:
----------------------------------------------------------------------------------------------------------------------------------------------------
Framework
=>The structure which is ready constructed and available for application development is known as Framework.
Generic Types
=>The types which are ready to accept any type of data are known as Generic Types.
T - Type
E - Element
198
K - Key
Page
V - Value
198
The following are Generic programming components:
(a)Generic Variables
(b)Generic Methods
(c)Generic Classes
(d)Generic Interface
(a)Generic Variables:
=>The variables which are declared with generic types and ready to accept any type of data.
T a;
E k;
...
(b)Generic Methods:
=>The methods which are ready to accept any type of data as parameters are known as Generic Methods.
structure:
<T>return_type method_name(T)
//method_body
(c)Generic Classes:
=>The class object reference can hold any type of Object references is known as Generic class.
Structure:
class Class_name<T>
//members
(d)Generic Interface:
=>Generic Interfaces are implemented to generic classes.
Structure:
interface Interface_name<T>
//members
--------------------------------------------------------------------------------------
1.Set<E>:
=>Set<E> is an interface from java.util package and which organizes elements without
199
199
=>The following are some important methods from Set<E>:
=======================================================================================
2.List<E>:
=>List<E> is an interface from java.util package and which organizes elements with index values and can hold
duplicate elements.
200
public abstract java.util.Iterator<E> iterator();
DSet1.java
package maccess;
import java.util.*;
public class DSet1 {
@SuppressWarnings("removal")
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
Set<Integer> st=null;
System.out.println("=====Choice====");
System.out.println("1.HashSet\n2.LinkedHashSet\n3.TreeSet");
System.out.println("Enter the choice:");
int choice = s.nextInt();
switch(choice) {
case 1:
st = new HashSet<Integer>();
break;
case 2:
st = new LinkedHashSet<Integer>();
break;
case 3:
st = new TreeSet<Integer>();
break;
default:
System.out.println("Invalid choice....");
System.exit(0);
}//end of switch
st.add(new Integer(12));
st.add(new Integer(10));
st.add(new Integer(17));
st.add(new Integer(19));
st.add(new Integer(12));
System.out.println("====Display Set<E>====");
System.out.println(st.toString());
}//end of try
}
}
201
o/p:
=====Choice====
Page
1.HashSet
201
2.LinkedHashSet
3.TreeSet
====Display Set<E>====
-------------------------------------------------------------------------------
DSet2.java
package maccess;
import java.util.*;
public class DSet2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
Set<String> st=null;
System.out.println("=====Choice====");
System.out.println("1.HashSet\n2.LinkedHashSet\n3.TreeSet");
System.out.println("Enter the choice:");
int choice = s.nextInt();
switch(choice) {
case 1:
st = new HashSet<String>();
break;
case 2:
st = new LinkedHashSet<String>();
break;
case 3:
st = new TreeSet<String>();
break;
default:
System.out.println("Invalid choice....");
System.exit(0);
}//end of switch
st.add(new String("NIT"));
st.add(new String("Java"));
st.add(new String("Hyd"));
st.add(new String("ABC"));
st.add(new String("NIT"));
System.out.println("====Display Set<E>====");
System.out.println(st.toString());
}//end of try
}
}
o/p:
=====Choice====
1.HashSet
202
2.LinkedHashSet
Page
3.TreeSet
202
Enter the choice:
====Display Set<E>====
---------------------------------------------------------------------------------
Product.java
package maccess;
@SuppressWarnings("rawtypes")
public class Product implements Comparable//Step-1
{
public String pCode,pName;
public float pPrice;
public int pQty;
public Product(String pCode,String pName,float pPrice,int pQty) {
this.pCode=pCode;
this.pName=pName;
this.pPrice=pPrice;
this.pQty=pQty;
}
public String toString() {
return pCode+"\t"+pName+"\t"+pPrice+"\t"+pQty;
}
public int compareTo(Object o) //step-2
{
Product p = (Product)o;
int z = pCode.compareTo(p.pCode);//String Chapter
if(z==0) return 0;
else if(z>0) return 1;
else return -1;
}
}
DSet3.java
package maccess;
import java.util.*;
public class DSet3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
Set<Product> st=null;
System.out.println("=====Choice====");
System.out.println("1.HashSet\n2.LinkedHashSet\n3.TreeSet");
System.out.println("Enter the choice:");
int choice = s.nextInt();
switch(choice) {
case 1:
st = new HashSet<Product>();
203
break;
case 2:
st = new LinkedHashSet<Product>();
Page
break;
203
case 3:
st = new TreeSet<Product>();//Automatically calls sort()
method
break;
default:
System.out.println("Invalid choice....");
System.exit(0);
}//end of switch
st.add(new Product("A125","Mouse",234.45F,10));
st.add(new Product("A118","CDR",345.67F,11));
st.add(new Product("A112","FDisk",567.34F,9));
st.add(new Product("A117","KeyB",678.89F,10));
System.out.println("====Display Set<E>====");
for(Product p : st) {
System.out.println(p.toString());
}
}//end of try
}
}
o/p:
=====Choice====
1.HashSet
2.LinkedHashSet
3.TreeSet
====Display Set<E>====
--------------------------------------------------------------------------------
Note:
sorting process on User defined class objects using TreeSet<E>
=>To perform sorting process on User defined class objects using TreeSet<E>,we use use
Structure of 'Comparable<T>':
{
204
204
step-2 : The user defined class must construct body for abstract method and which is written with sorting logic.
step-3 : we use sort() method from 'java.util.Collections' class to perform sorting process
syntax:
Collections.sort(ref_var);
--------------------------------------------------------------------------------
Note:
=>This sort() method is called automatically for set<E>,but for List<E> we have to call manually.
Diagram:
-----------------------------------------------------------------------------------------
DList1.java
package maccess;
import java.util.*;
public class DList1 {
@SuppressWarnings("removal")
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
List<Integer> lt=null;
System.out.println("=====Choice====");
System.out.println("1.ArrayList\n2.LinkedList\n3.Vector");
System.out.println("Enter the choice:");
int choice = s.nextInt();
switch(choice) {
205
case 1:
lt = new ArrayList<Integer>();
break;
Page
case 2:
205
lt = new LinkedList<Integer>();
break;
case 3:
lt = new Vector<Integer>();
break;
default:
System.out.println("Invalid choice....");
System.exit(0);
}//end of switch
lt.add(new Integer(12));
lt.add(new Integer(10));
lt.add(new Integer(17));
lt.add(new Integer(19));
lt.add(new Integer(12));
System.out.println("====Display Set<E>====");
System.out.println(lt.toString());
System.out.println("====Sorted List<E>====");
Collections.sort(lt);//Sorting process
System.out.println(lt.toString());
}//end of try
}
}
o/p:
3=====Choice====
1.ArrayList
2.LinkedList
3.Vector
====Display Set<E>====
====Sorted List<E>====
-----------------------------------------------------------------------------------------------------------------------------------------------------------
(a)ArrayList<E>:
=>ArrayList<E> organizes elements in Sequence and which is NonSynchronized class.
Note:
=>when we perform add() or remove() operations on ArrayList<E>,then the reamining elements are distrubed and
elements move forward or backward.
=>In realtime ArrayList<E> is used in the application where we have less number of add() and remove()
operations.
(b)LinkedList<E>:
206
206
Node is divided in to three parts:
(i)Previous Node Address
(ii)Data Value
Note:
=>when we perform add() or remove() operations on LinkedList<E>,then the reamining elements are Not-
Distrubed.
=>In realtime LinkedList<E> is used in the applications where we have more number of add() and remove()
operations.
Exp program:
DList2.java
package maccess;
import java.util.*;
public class DList2 {
@SuppressWarnings("removal")
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(new Integer(12));
al.add(new Integer(11));
al.add(new Integer(16));
al.add(new Integer(14));
System.out.println("====ArrayList<E>====");
System.out.println(al.toString());
System.out.println("Index value of 16 : "+al.indexOf(16));
System.out.println("Value at index 1 : "+al.get(1));
al.set(2,500);
System.out.println(al.toString());
al.add(1,400);
System.out.println(al.toString());
o/p:
Page
====ArrayList<E>====
207
[12, 11, 16, 14]
Index value of 16 : 2
Value at index 1 : 11
====LinkedList<E>====
Index value of 11 : 1
Value at index 2 : 16
------------------------------------------------------------------------------------
(c)Vector<E>:
=>Vector<E> also organizes elements in Sequence,but which is Synchronized class.
208
public synchronized void removeElementAt(int);
Exp program:
DList3.java
package maccess;
import java.util.*;
public class DList3 {
@SuppressWarnings("removal")
public static void main(String[] args) {
Vector<Integer> v = new Vector<Integer>();
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
v.addElement(new Integer(12));
v.addElement(new Integer(11));
v.addElement(new Integer(10));
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
System.out.println(v.toString());
v.addElement(new Integer(17));
v.addElement(new Integer(18));
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
System.out.println(v.toString());
v.addElement(new Integer(13));
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
System.out.println(v.toString());
v.addElement(new Integer(14));
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
System.out.println(v.toString());
v.addElement(new Integer(8));
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
System.out.println(v.toString());
v.addElement(new Integer(7));
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
System.out.println(v.toString());
v.addElement(new Integer(3));
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
System.out.println(v.toString());
v.addElement(new Integer(2));
System.out.println("Capacity:"+v.capacity());
System.out.println("Size:"+v.size());
System.out.println(v.toString());
System.out.println("Ele at index value 2:"+v.elementAt(2));
v.setElementAt(500,2);
209
System.out.println(v.toString());
System.out.println("First Element:"+v.firstElement());
Page
System.out.println("Last Element:"+v.lastElement());
209
}
}
o/p:
Capacity:10
Size:0
Capacity:10
Size:3
Capacity:10
Size:5
Capacity:10
Size:6
Capacity:10
Size:7
Capacity:10
Size:8
Capacity:10
Size:9
Capacity:10
Size:10
Capacity:20
Size:11
First Element:12
210
Last Element:2
Page
---------------------------------------------------------------------------------------
210
Note:
=>Vector<E> is used in Connection pooling process.
=>The process of organizing multiple pre-initialized database connections is knonw as Connection pooling
process.
=>The default capacity of Vector<E> is 10 and which increases dynamically at runtime or execution time,by
doubling the capacity.
---------------------------------------------------------------------------------------
Stack<E>
=>Stack<E> is a class from java.util package and which is ChildClass of Vector<E>.
public E push(E);
Exp program:
DList4.java
package maccess;
import java.util.*;
public class DList4 {
@SuppressWarnings("removal")
public static void main(String[] args) {
Stack<Integer> st = new Stack<Integer>();
st.push(new Integer(12));
st.push(new Integer(13));
st.push(new Integer(14));
st.push(new Integer(15));
System.out.println(st.toString());
System.out.println("peek element:"+st.peek());
System.out.println("Position of ele 13:"+st.search(13));
st.pop();//deleting the element from top-of-the-stack
System.out.println(st.toString());
}
}
o/p:
peek element:15
211
Note:
=>search() method searches the ele from top-of-the-stack to Bottom-of-the-stack and displays the position of an
element in the Stack<E>.
-------------------------------------------------------------
-------------------------------------------------------------
Note:
=>In realtime Stack<E> and Queue<E> are
used part of Algirithmic design by Vendor
engineers.
-----------------------------------------------------------------------------------------
3.Queue<E>:
=>Queue<E> is a an interface from java.util package and which organizes elements based on the algorithm First-
In-First-Out.
Deque<E>
=>Deque<E> is also an interface extended from Queue<E> and in which the elements are organized on both
ends.(Double-ended-queue)
(b)ArrayDeque<E>
(c)LinkedList<E>
(a)PriorityQueue<E>:
=>PriorityQueue<E> will organize elements based on elements Priority.
=>In realtime PriorityQueue<E> is used to hold the threads executing based on priorities.
(b)ArrayDeque<E>:
=>ArrayDeque<E> organizes elements on both ends and elements are available in sequence.
(c)LinkedList<E>:
=>LinkedList<E> also organizes elements on both ends and available in NonSequence.
Exp program:
DemoQueue.java
212
package maccess;
import java.util.*;
Page
212
@SuppressWarnings("removal")
public static void main(String[] args) {
System.out.println("====PriorityQueue<E>=====");
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(new Integer(12));
pq.add(new Integer(11));
pq.add(new Integer(10));
pq.add(new Integer(14));
System.out.println(pq.toString());
System.out.println("====ArrayDeque<E>=====");
ArrayDeque<Integer> ad = new ArrayDeque<Integer>();
ad.add(new Integer(23));
ad.add(new Integer(24));
ad.add(new Integer(21));
ad.add(new Integer(25));
System.out.println(ad.toString());
ad.addFirst(new Integer(12));
ad.addLast(new Integer(56));
System.out.println(ad.toString());
System.out.println("====LinkedDeque<E>=====");
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(new Integer(23));
ll.add(new Integer(24));
ll.add(new Integer(2));
ll.add(new Integer(25));
System.out.println(ll.toString());
ll.addFirst(new Integer(12));
ll.addLast(new Integer(56));
System.out.println(ll.toString());
}
}
o/p:
====PriorityQueue<E>=====
====ArrayDeque<E>=====
====LinkedDeque<E>=====
--------------------------------------------------------------------------------------------------------------------------------------------------
Limitation of Collection<E>:
=>Collection<E> can not hold data from the DataBase by differentiating Primary-Key andNonPrimary-Key values.
Note:
213
===========================================================================================
Page
213
Map<K,V> in Java:
=>Map<K,V> is an interface from java.util package and which organizes elements in the form
of Key-Value pairs.
K - Key
V - Value
syntax:
214
214
DMap1.java
package maccess;
import java.util.*;
public class DempMap1 {
@SuppressWarnings("removal")
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try(s;){
Map<Integer,String> m = null;
System.out.println("====Choice====");
System.out.println("1.HashMap\n2.LinkedHashMap\n3.TreeMap\n4.Hashtable");
System.out.println("Enter the choice:");
int choice = s.nextInt();
switch(choice) {
case 1:
m = new HashMap<Integer,String>();
break;
case 2:
m = new LinkedHashMap<Integer,String>();
break;
case 3:
m = new TreeMap<Integer,String>();
break;
case 4:
m = new Hashtable<Integer,String>();
break;
default:
System.out.println("Invalid Choice...");
System.exit(0);
}//end of switch
m.put(new Integer(444), new String("Raj"));
m.put(new Integer(111), new String("Alex"));
m.put(new Integer(333), new String("Ram"));
m.put(new Integer(555), new String("ABC"));
m.put(new Integer(666), new String("PQR"));
System.out.println("====Display from Map<k,V>====");
for(Map.Entry<Integer, String> e : m.entrySet()) {
System.out.println(e.getKey()+" "+e.getValue());
}
}//end of try
}
}
o/p:
====Choice====
1.HashMap
2.LinkedHashMap
3.TreeMap
4.Hashtable
3
Page
215
111 Alex
333 Ram
444 Raj
555 ABC
666 PQR
------------------------------------------------------------------------------------------------------------------------------------------------------
Diagram:
-------------------------------------------------------------------------------------------------------------------------------------------------------
Hierarchy of Map<K,V>:
----------------------------------------------------------------------------------- ---------------------------------------------------------------------
216
Page
216
Enum<E>
=>'Enum<E>' is an abstract class from java.lang package and which hold elements,variables and methods.
syntax:
enum Enum_name
//elements
//variables
//methods
=>we use values() method to retrieve the data from Enum<E> objects.
Exp program:
Cars.java
package maccess;
public enum Cars {
Figo(800),Alto(300),Dezire(600);//Elements
public int price;
private Cars(int price) {
this.price=price;
}
public int getPrice() {
return price;
}
}
DemoEnum.java
package maccess;
public class DemoEnum {
public static void main(String[] args) {
for(Cars c : Cars.values())
{
System.out.println(c.toString()+"\t$"+c.getPrice());
}
}
}
Note:
=>The Constructors which are declared within the enum are automatically private constructorsbecause the objects
are created internally.
217
=====================================================================================
Summary:
(a)Class
(b)Interface
(b)Array/Collection<E>/Map<K,V>
(c)Enum<E>
=======================================================================================
2.WrapperClass objects
(a)Byte Object
(b)Short Object
(c)Integer Object
(d)Long Object
(e)Float Object
(f)Double Object
(g)Character Object
(h)Boolean object
3.String objects
(a)String objects
218
(b)StringBuffer Objects
(c)StringBuilder Objects
Page
218
4.Array objects
(a)WrapperClass Array
(b)String Array
(d)Object Array
5.Collection<E> objects
(a)Set<E>
(i)HashSet<E> object
(ii)LinkedHashSet<E> object
(iii)TreeSet<E> object
(b)List<E>
(i)ArrayList<E> object
(ii)LinkedList<E> object
(iii)Vector<E> object
=>(iv)Stack<E> object
(c)Queue<E>
(i)PriorityQueue<E> object
=>(d)Deque<E>
(ii)ArrayDeque<E> object
6.Map<K,V> objects
(a)HashMap<K,V> object
(b)LinkedHashMap<K,V> object
(c)TreeMap<K,V> object
(d)Hashtable object
7.Enum<E> object
----------------------------------------------------------------------------------
Input Stream
=>The Contineous flow of data into java program is known as Input Stream.
Output Stream
219
=>The Contineous flow of data out of java program is known as Output Stream.
Page
219
Streams in Java are categorized into two types:
1.Binary Stream(byte Stream)
2.Character Stream
=>Binary Stream or Byte Stream supports all the multimedia data formats like Audio,video, image,animation and
text.
(ii)DataOutputStream
(iii)FileInputStream
(iv)FileOutputStream
(i)DataInputStream:
(i)DataInputStream
=>'DataInputStream' class is from 'java.io' package and which is used to read binary
syntax:
DataInputStream dis = new DataInputStream(Source);
(ii)DataOutputStream:
=>'DataOutputStream' class is from 'java.io' package and which is used to send data out of Java program.
syntax:
DataOutputStream dos = new DataOutputStream(destination);
(iii)FileInputStream:
=>'FileInputStream' class is from 'java.io' package and which is used to find the file and open the file to read
binary stream.
syntax:
FileInputStream fis = new FileInputStream("fPath&fName");
(iv)FileOutputStream:
=>'FileOutputStream' class is from 'java.io' package and which is used to create new file and opens the file to
write binary Stream.
syntax:
FileOutputStream fos = new FileOutputStream("fPath&fName");
-------------------------------------------------------------------------------
Exp program1:
DemoFile1.java
220
package test;
import java.io.*;
Page
220
import java.util.*;
try(s;) {
if(f1.exists()) {
try(fos;fis;){
int ch;
while((ch=fis.read())!=-1) {
fos.write(ch);
}//end of loop
}else{
};
}catch(Exception e) {e.printStackTrace();}
o/p:
C:\dddd.jpeg
E:\images\AAAA.jpeg
--------------------------------------------------------------------------------------
221
Diagram:
Page
221
------------------------------------------------------------------------------------
2.Character Stream:
=>Th contineous flow of data in the form of 16-bits is known as Charcter Stream.
(ii)FileReader
(iii)FileWriter
(i)BufferedReader:
=>'BufferedReader' class is from java.io package and which is used to read character data into JavaProgram.
syntax:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
(ii)FileReader:
=>FileReader is a class from java.io package and which is used to find the file and open the file to read character
Stream.
Syntax:
FileReader fr = new FileReader("fPath&fName);
(iii)FileWriter:
=>FileWriter is a class from java.io package and which is used to create new file andopens the file to write
Character Stream.
syntax:
FileWriter fw = new FileWriter("fPath&fName");
--------------------------------------------------------------------------------------
Exp program:
222
DemoFile2.java
222
package test;
import java.io.*;
public class DemoFile2 {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the fPath&fName(destination)");
File f = new File(br.readLine());
FileWriter fw = new FileWriter(f);
char ch1;
System.out.println("Enter the data:(@ at end)");
while((ch1=(char)br.read())!='@') {
fw.write(ch1);
}//end of loop
System.out.println("Data recorded into file....");
fw.close();
System.out.println("====Display from file====");
FileReader fr = new FileReader(f);
int ch2;
while((ch2=fr.read())!=-1) {
System.out.print((char)ch2);
}//end of loop
fr.close();
br.close();
}catch(Exception e) {e.printStackTrace();}
}
}
o/p:
E:\images\Text.txt
java
program
language
task
thread
java
program
language
223
task
thread
Page
223
Dt : 25/8/2021
--------------------------------------------------------------------------------------------------------------------------------------------------------
Serialization process
=>The process of converting Object State into binary stream is known as Serialization process.
=>we use writeObject() method from 'java.io.ObjectOutputStream' class to perform Serialization process.
Method Signature:
public final void writeObject(java.lang.Object)throws java.io.IOException;
syntax:
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj_name);
DeSerialization process
=>The process of converting binary Stream into Object State is known as DeSerialization process.
Method Signature:
public final java.lang.Object readObject() throws java.io.IOException,
java.lang.ClassNotFoundException;
syntax:
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject();
Note:
224
=>To perform Serialization and DeSerialization,the class must be implemented from 'java.io.Serializable'
interface.
Page
Exp program:
224
TranLog.java
package test;
import java.io.*;
import java.util.*;
@SuppressWarnings("serial")
this.hAccNo=hAccNo;
this.bAccNo=bAccNo;
this.amt=amt;
this.dateTime=dateTime;
return "BAccNo:"+bAccNo+"\nHAccNo:"+hAccNo+"\nAmt:"+amt+"\nDate&Time:"+dateTime;
DemoSerialization.java
package test;
import java.io.*;
import java.util.*;
try {
oos.writeObject(ob1);
oos.close();
Page
}catch(Exception e) {e.printStackTrace();}
225
}
DemoDSerialization.java
package test;
import java.io.*;
public class DemoDSerialization {
public static void main(String[] args) {
try {
File f = new File("E:\\images\\ojbstore.txt");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
TransLog ob2 = (TransLog)ois.readObject();
System.out.println(ob2.toString());
ois.close();
}catch(Exception e) {e.printStackTrace();}
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------
Advantage of Serialization:
(i)we can store binary Stream in File Storage
----------------------------------------------------------------------------------------------------------------------------------------------------------
Note:
=>'Throwable' is implemented from 'Serializable' indicates Exception Handling components support Serialization
process.
226
227
Page
227
228
Page
228