0% found this document useful (0 votes)
3 views

JAVA NOTES

The document provides a comprehensive overview of Core and Advanced Java, detailing fundamental programming concepts and object-oriented features. It covers various topics such as Java versions, data types, control structures, exception handling, and the Java Collection Framework. Additionally, it discusses advanced technologies for web development and includes practical programming components necessary for constructing Java programs.

Uploaded by

voltagevibe440
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JAVA NOTES

The document provides a comprehensive overview of Core and Advanced Java, detailing fundamental programming concepts and object-oriented features. It covers various topics such as Java versions, data types, control structures, exception handling, and the Java Collection Framework. Additionally, it discusses advanced technologies for web development and includes practical programming components necessary for constructing Java programs.

Uploaded by

voltagevibe440
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 229

CORE JAVA

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

2.Advanced Java: _____________________________________________________________________________ 9


2.1 Advanced Java provides the following technologies to construct Web : ______________________________________ 9

wt is the diff b/w (i)Language (ii)Technology (iii)Framework _________________________________________ 9


define Program?(Syllabus) ____________________________________________________________________ 10
define programmer? _________________________________________________________________________ 10
wt is the diff b/w (i)Objective Code (ii)Byte Code ________________________________________________ 11
define High Level Language? ___________________________________________________________________ 12
define Translator? ___________________________________________________________________________ 12
Java Versions: ______________________________________________________________________________ 13
wt is the diff b/w (i)JDK (ii)JRE (iii)JDK: ________________________________________________________ 14
define Java Lib? ______________________________________________________________________________________ 14
Downloading,Installing JDK and Setting path: _____________________________________________________ 15
define Environment Variables? ________________________________________________________________ 16
These Environment variables are categorized into two types: _________________________________________________ 16

wt is the advantage of setting Java path? ________________________________________________________ 16

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.

Constructing first program: __________________________________________________ 16


wt is the diff b/w (i)print() (ii)println() _________________________________________________________ 17

JVM Architecture: _________________________________________________________ 18


Faq : define Object? _________________________________________________________________________ 21
Faq: define Method Frame? ___________________________________________________________________ 22

Naming Conventions in Java: ________________________________________________ 23


packages: __________________________________________________________________________________ 23
Classes&Interfaces:: _________________________________________________________________________ 24
Variables&Methods: _________________________________________________________________________ 24
1

Keywords: _________________________________________________________________________________ 24
Page

1
DataTypes in Java: _________________________________________________________ 24
1.Primitive DataTypes: _______________________________________________________________________ 24
2.NonPrimitive DataTypes: ____________________________________________________________________ 26
faq: why char 2 bytes in Java? ________________________________________________________________ 27

Operators of Java: _________________________________________________________ 28


1.Arithmetic operators:_______________________________________________________________________ 28
2.Relational operators: _______________________________________________________________________ 28
3.Logical Operators: _________________________________________________________________________ 28
4.Increment/Decrement Operators: ____________________________________________________________ 29

Control Structures in Java:___________________________________________________ 29


1.Selection Statements: ______________________________________________________________________ 30
2.Iterative Statements: _______________________________________________________________________ 30
3.Branching Statements: ______________________________________________________________________ 30

Object oriented programming(OOPS): _________________________________________ 31


(1)Class: ___________________________________________________________________________________ 31
define 'Scanner'? _____________________________________________________________________________________ 33
define 'System'? _____________________________________________________________________________________ 34
define 'import' statement? _____________________________________________________________________________ 37

Variables in Java: __________________________________________________________ 46


(1)Primitive DataType Variables: _______________________________________________________________ 46
(2)NonPrimitive DataType Variables: ____________________________________________________________ 46
Based on 'static' keyword the variables are categorized into two types: ________________________________ 46
(1)NonStatic variables: ________________________________________________________________________________ 46
(2)Static Variables: ___________________________________________________________________________________ 47

Methods in Java: __________________________________________________________ 47


(a)NonStatic methods(Instance methods): _______________________________________________________ 47
These Instance methods are categorized into two types: _____________________________________________________ 48

(b)Static methods: ___________________________________________________________________________ 48


These static methods are categorized into two types: _______________________________________________________ 48

define parameters? ________________________________________________________ 51


(i)Methods without parameters: _______________________________________________________________ 51
(ii)Methods with parameters: __________________________________________________________________ 52
wt is the diff b/w (i)Parameters (ii)Arguments __________________________________________________ 52

define return_type? ________________________________________________________ 52


(i)Non-Return_type methods:__________________________________________________________________ 52
(ii)Return_type methods: _____________________________________________________________________ 52

define switch-case statement? _______________________________________________ 56


2
Page

Behaviour: _________________________________________________________________________________ 56

2
define while loop? _________________________________________________________ 58
syntax: Flowchart: ________________________________________________________________ 58
__________________________________________________________________________________________ 58

define 'continue' statement? ________________________________________________ 58


define 'for' loop? __________________________________________________________ 61
syntax: ____________________________________________________________________________________ 61
Flowchart: _________________________________________________________________________________ 61

define Array? _____________________________________________________________ 63


define exit()? _____________________________________________________________ 68
define do-while loop? ______________________________________________________ 68
syntax: ____________________________________________________________________________________ 68
FlowChart: _________________________________________________________________________________ 68

Summary of Variables and Methods: __________________________________________ 69


Blocks in Java: ____________________________________________________________ 70
1.Static blocks: ______________________________________________________________________________ 70
2.NonStatic blocks(Instance blocks): ____________________________________________________________ 71
faq: wt is the diff b/w (i)Block (ii)Method ______________________________________________________ 72

Constructors in Java: _______________________________________________________ 72


Note: _____________________________________________________________________________________ 72
Structure of constructor:______________________________________________________________________ 72
Based on parameters the constructors are categorized into two types: ________________________________ 72
1.Constructors without parameters: ____________________________________________________________ 72
Faq: wt is the diff (i)Constructor (ii)Instance method ___________________________________________________ 73
Faq: wt is the diff b/w (i)Instance block (ii)Constructor ____________________________________________________ 73
Faq: wt is the diff b/w (i)static block (ii)Constructor ______________________________________________________ 73
faq: define default Constructor? ________________________________________________________________________ 74
faq: In wt situation default constructor is added? __________________________________________________________ 74
2.Constructors with parameters: _______________________________________________________________ 74
Advantage of Constructor: ____________________________________________________________________ 76
faq: define 'this' keyword?____________________________________________________________________ 76
faq: define 'static' constructor? _______________________________________________________________ 76

PACKAGES IN JAVA: ________________________________________________________ 76


1.Built-In packages: __________________________________________________________________________ 77
2.User defined packages: _____________________________________________________________________ 77
faq: define 'import' statement? ________________________________________________________________ 79
Access Modifiers? ___________________________________________________________________________ 80
3
Page

'static' import?______________________________________________________________________________ 81

3
define sqrt() method? ________________________________________________________________________ 81

RelationShip b/w classes: ___________________________________________________ 82


(a)References: ______________________________________________________________________________ 82
(b)Inheritance: ______________________________________________________________________________ 86
Inheritance Case-1 : NonStatic members from the ParentClass or SuperClass ____________________________________ 87
Inheritance Case-2 : Constructors from the ParentClass or SuperClass __________________________________________ 89
Inheritance Case-3 : Static members from the ParentClass or SuperClass ________________________________________ 91

OVERRIDING _______________________________________________________________________________ 92
define Method Overriding process? _____________________________________________________________________ 92

METHOD HIDING ____________________________________________________________________________ 94


Concept of super & this _______________________________________________________________________ 95
Concept of super() & this() ____________________________________________________________________ 96
can we use 'super' and 'this' keywords to access static members? ____________________________________ 97
METHOD OVERLOADING ______________________________________________________________________ 97
CONSTRUCTOR CHAINING PROCESS _____________________________________________________________ 98

Types of Inheritances: ______________________________________________________ 98


(a)Single Inheritance: ________________________________________________________________________ 99
(b)Multiple Inheritance: ______________________________________________________________________ 99

Interfaces in Java: ________________________________________________________ 102


define abstract method? _____________________________________________________________________________ 102
define Concrete methods? ____________________________________________________________________________ 102

Coding rules of Interface: ____________________________________________________________________ 103


Multiple Inheritance Models using Interfaces: ___________________________________________________ 108

AbstractClasses in Java:____________________________________________________ 111


InnerClasses: ____________________________________________________________ 114
1.Member InnerClasses: _____________________________________________________________________ 114
2.Local InnerClasses: ________________________________________________________________________ 116
Coding Rule: _______________________________________________________________________________________ 116
3.Anonymous InnerClasses: __________________________________________________________________ 117
define Generalization process? ________________________________________________________________________ 117
Note: _____________________________________________________________________________________________ 120
(a)Anonymous InnerClass as Class Extention: _____________________________________________________________ 120
(b)Anonymous InnerClass as Implementation class: ________________________________________________________ 121

InnerClass within the Interface: _______________________________________________________________ 123


InnerClass within the AbstractClass: ___________________________________________________________ 123
InnerInterface within the class: _______________________________________________________________ 123
InnerInterface within the Interface: ____________________________________________________________ 124
InnerInterface within the AbstractClass: ________________________________________________________ 124
InnerAbstractClass within the Class: ___________________________________________________________ 125
4

InnerAbstractClass within the Interface: ________________________________________________________ 125


Page

4
InnerAbstractClass within the AbstractClass:(Nested AbstractClass) __________________________________ 125
Comparision Diagram:_______________________________________________________________________ 135

Summary and Conclusion of Programming components:(Java Alphabets) ___________ 136


Exception Handling process: ________________________________________________ 137
define Exception? __________________________________________________________________________ 137
define Exception Handling process? ____________________________________________________________ 137
define 'Throwable' class? ____________________________________________________________________ 138
This 'Throwable' class is extended into the following SubClasses: _____________________________________________ 138

(a)Unchecked Exceptions: ____________________________________________________________________ 139


Note: ____________________________________________________________________________________ 144
Annotation ________________________________________________________________________________ 144
Types of Annotation : ________________________________________________________________________________ 144
(b)Checked Exceptions: ______________________________________________________________________ 145
(i)Built-in Checked Exceptions: _________________________________________________________________________ 145
(ii)User defined Checked Exceptions: ____________________________________________________________________ 146

Exception re-throwing process ________________________________________________________________ 151


Exception Propagation ______________________________________________________________________ 151
faq: wt is the diff b/w (i)throw (ii) throws _______________________________________________________ 151
wt are the components of Exception handling process? ____________________________________________ 151
Handling Multiple exceptions: ________________________________________________________________ 151
define try-with-resource statement? ___________________________________________________________ 152
define 'Enhanced try-with-resource statement'? _________________________________________________ 152
define 'java.lang.NullPointerException'? ________________________________________________________ 154

Polymorphism in Java: _____________________________________________________ 154


(a)Dynamic PolyMorphism: __________________________________________________________________ 155
(b)Static PolyMorphism: _____________________________________________________________________ 155
The following keywords are under the control of Compiler at Compilation Stage: _______________________ 156
The following components are used in constructing 'SingleTon class design pattern': _____________________________ 158

Encapsulation process _____________________________________________________ 164


Note: _____________________________________________________________________________________________ 164
Comparision Diagram: _______________________________________________________________________________ 164

Abstraction process _______________________________________________________ 164


Note: ____________________________________________________________________________________ 164

Type Casting in Java: ______________________________________________________ 165


Note: ____________________________________________________________________________________ 165
Case-1 :___________________________________________________________________________________ 165
Exp: ______________________________________________________________________________________________ 165

Case-2 :___________________________________________________________________________________ 165


5
Page

Summary:_________________________________________________________________________________ 166

5
WrapperClasses __________________________________________________________ 167
List of WrapperClasses: ______________________________________________________________________ 167
Hierarchy of WrapperClasses: _________________________________________________________________ 167
Boxing process _____________________________________________________________________________ 167
AutoBoxing process _________________________________________________________________________________ 171

Strings in Java: ___________________________________________________________ 175


1.String class: ______________________________________________________________________________ 175
2.StringBuffer class:_________________________________________________________________________ 180
Hierarchy of StringBuffer class: ________________________________________________________________________ 180
following are four constructors from 'StringBuffer' class: ___________________________________________________ 180

3.StringBuilder class: ________________________________________________________________________ 184


Hierarchy of StringBuilder class: _______________________________________________________________ 184
following are four constructors from 'StringBuilder' class: ___________________________________________________ 184
Note: _____________________________________________________________________________________________ 184
define 'synchronized class'? ___________________________________________________________________________ 184
define 'synchronized methods'?________________________________________________________________________ 184
wt is the behaviour of synchronized methods? ____________________________________________________________ 184

Note: ____________________________________________________________________________________ 185


There following are some classes realated to Strings: ______________________________________________ 185
(a)StringTokenizer class: ______________________________________________________________________________ 185

Object Class: _____________________________________________________________ 188


Diagram: _________________________________________________________________________________ 188
The following are some important methods of 'Object' class: _______________________________________ 188
Cloneable? ________________________________________________________________________________ 190
wt is the advantage of Cloning process? _________________________________________________________________ 191
4.equals(): ________________________________________________________________________________ 191
5.wait()___________________________________________________________________________________ 191
6.notify() _________________________________________________________________________________ 191
7.notifyAll():_______________________________________________________________________________ 191
8.finalize(): ________________________________________________________________________________ 192
9.getClass(): _______________________________________________________________________________ 192

Arrays in Java: ___________________________________________________________ 192


Arrays in Java are categorized into two types: ___________________________________________________ 192
'Extended for' ______________________________________________________________________________________ 195
Object Array _______________________________________________________________________________________ 196

2.Multi Dimensional Arrays: __________________________________________________________________ 196


Dis-Advantage of Arrays: ____________________________________________________________________ 197

Java Collection Framework(JCF):_____________________________________________ 198


define 'Collection<E>'? ______________________________________________________________________ 198
6

Hierarchy of Collection<E>: ___________________________________________________________________ 198


Page

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

3.Queue<E>: ______________________________________________________________________________ 212


Limitation of Collection<E>: __________________________________________________________________ 213

Map<K,V> in Java: ________________________________________________________ 214


The following are the implementation classes of Map<K,V>: ________________________________________ 214
Hierarchy of Map<K,V>: _____________________________________________________________________ 216

Enum<E> ________________________________________________________________ 217


syntax: ___________________________________________________________________________________ 217
Note: ____________________________________________________________________________________ 217

Summary: _______________________________________________________________ 218


IO Streams and files: ______________________________________________________ 219
Stream ___________________________________________________________________________________ 219
Input Stream ______________________________________________________________________________ 219
Output Stream _____________________________________________________________________________ 219
Streams in Java are categorized into two types: __________________________________________________ 220
1.Binary Stream(byte Stream): _________________________________________________________________________ 220
2.Character Stream: _________________________________________________________________________________ 222

Serialization process ______________________________________________________ 224


Method Signature: _________________________________________________________________________ 224
syntax: ___________________________________________________________________________________ 224
DeSerialization process ______________________________________________________________________ 224
Note: ____________________________________________________________________________________ 224
Advantage of Serialization: ___________________________________________________________________ 226
Note: ____________________________________________________________________________________ 226
7
Page

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

1.1CoreJava provides the following programming Concepts:


1.Object oriented programming
2.Exception Handling
3.Multi-Threading
4.Java Collection Framework(JCF)
5.IO Streams and Files
6.Networking
8
Page

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:

wt is the diff b/w (i)Language (ii)Technology


(iii)Framework
(i)Language:
=>Language provides the fundamental building blocks used in constructing programs.
9

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

wt is the diff b/w (i)Objective Code (ii)Byte Code


(i)Objective Code:
=>The compiled code which is generated from c and c++ programs is known as
Objective Code.
=>while Objective Code generation the operatingSystem(PlatForm) is participated becuase of this
reason Objective code is PlatForm dependent code.
DisAdvantage:
=>The Objective code which is generated from one PlatForm cannot be executed on other PlatForms.
Note:
=>c and c++ languages which are generating objective code are PlatForm dependent languages
11
Page

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 High Level Language?


=>The Language programs which are constructed from User understandable words is known as High
Level Language.
Exp: c,c++,Java
define Low Level Language?
=>The Language program codes which are not understandable by the users is known as Low Level
Language.
Exp:
Assembly Language
Machine Language

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:

1995 - Java Alpha&Beta


1996 - JDK 1.0
1997 - JDK 1.1
1998 - JDK 1.2
2000 - JDK 1.3
2002 - JDK 1.4
----------------------------
2004 - Java5
=>JDK 1.5
=>JRE 1.5
2006 - Java6
=>JDK 1.6
=>JRE 1.6
2011 - Java7
=>JDK 1.7
=>JRE 1.7
---------------------------------------------------------------------------------------------------------------------------------------
2014 - Java8
=>JDK 1.8
=>JRE 1.8
2017 - Java9
13
Page

=>JDK 1.9

13
=>JRE 1.9
2018 - Java10,Java11
2019 - Java12,Java13
2020 - Java14,Java15
2021 - Java16,Java17
=============================================================================
Dt : 4/6/2021

wt is the diff b/w (i)JDK (ii)JRE (iii)JDK:


=>JDK stands for 'Java Development Kit' and which is collection of JavaCompiler, JavaLib and JVM.
JavaCompiler - is used to perform compilation process and
translate Source Code into Byte Code.
JavaLib - will provide built-in 'classes and interfaces' used for
application development.
JVM - is used to execute Java ByteCode.

define Java Lib?


=>JavaLib is represented with the word 'java'.
=>JavaLib is collection of 'packages'.
=>'packages' are the collection of 'Classes and Interfaces'.
=>'Classes and 'Interfaces' are collection of 'Variables and
methods
=>The following are some important packages from 'JavaLib':
CoreJava:
java.lang - Language package
java.util - Utility package(JCF)
java.io - Stream and Files package.
java.net - Networking package
GUI:
java.awt - Abstract Window Toolkit package
javax.swing - Swing programming package
java.applet - Applet programming package
AdvJava:
java.sql - DataBase Connection package
14

javax.servlet - Servlet programming package


Page

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)

--------------------------------------------------------------------------------------------------------------------------------------------

Downloading,Installing JDK and Setting path:


step-1 : Find the System type or System Environment where the JDK is installed.
System type : 32-bit Operating System(Windows).
step-2 : Download JDK based on System type.
Note:
=>JDK is Platform dependent while downloading.
step-3 : Install JDK
Note:
=>After Installation process is successfull,then we can find one folder with name
'java' in ProgramFiles.
C:\Program Files\Java
step-4 : Set the path in Environment variables
RightClick on MyComputer->Properties->Advanced System Settings->
Environment Variables,click 'new' from System variables
Variable name : path
Variable value : C:\Program Files\Java\jdk1.8.0_251\bin;

step-5 : Click 'ok' for 3 times,then the path is setted.


----------------------------------------------------------------
Note:
=>Type the following commands in CommandPrompt and check whether they are working
or not:
15
Page

javac - for compilation process

15
java - Execution process
-------------------------------------------------------------------------
Dt : 5/6/2021
faq:

define Environment Variables?


=>The variables related to Operating System holding the information about the resources installed in
the ComputerSystem are known as Environmnent Variables.
These Environment variables are categorized into two types:
(i)User Variables
(ii)System Variables
(i)User Variables:
=>The information in User variables
can be used by only individual users.

(ii)System Variables:
=>The information in the System
variables can be used by all the users
of Computer System.

wt is the advantage of setting Java path?


=>when we have java path in Environment variables then the Java programs can be compiled and
executed from any location of Computer System.

Dt : 7/6/2021

Constructing first program:


Ex program:
Write a program(WAP) to add two numbers and display the result?

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[])'

wt is the diff b/w (i)print() (ii)println()


=>print() method is used to display the data in the same line.
=>println() method is used to display the data in different lines.
---------------------------------------------------------------------------------------------------------------------------
17
Page

17
JVM Architecture:

=>JVM stands for 'Java Virtual Machine' and which is used to execute JavaByteCode.

=>The following are the parts of JVM:


1.Class Loader SubSystem
2.Runtime Data Area
3.Execution Engine
1.Class Loader SubSystem:
=>The Class Loader SubSystem will load the ByteCode onto JVM,in this process it internally uses the
following:
(a)Loader
(b)Linker
(c)Initiate
(a)Loader:
=>The Loader will load the required files into current running program,in this process it internally uses
18

the following SubLoaders:


Page

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

(d)PC Register Area


Page

(e)Native Method Area

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.

Faq : define Object?


=>Object is a memory or storage created part of Heap Area related to a class holding the NonStatic
members of class.
Note:
=>After Object creation,the Object will have the following:
21
Page

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

Faq: define Method Frame?


=>The partition of JavaStackArea where the method is copied for execution is known as Method Frame.
Note:
=>After method execution completed,the method frame is destroyed automatically.
(c)Java Stack Area:
=>The memory block where the methods are executed is known as JavaStackArea.
=>main() method is copied onto JavaStackArea first and this main() method will call remaining()
methods for execution.
(d)PC Register Area:
=>Program Counter(PC) registers will record the status of method executions in JavaStackArea.
=>Every method will have its own PC-Register.
=>All these PC-registers will be opened in a separate memory block known as PC-Register Area.
(e)Native Method Area:
=>The pre-defined methods from JavaLib which are declared with 'native' keyword
are known as Native methods.
=>when these native methods are used part of program will be separated and loaded onto separate
memory block known as Native Method Area.
=>Native methods internally having c or C++ codes.
22

=>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

Naming Conventions in Java:


=>The rules or coding standards followed by the programmer in java to write programs are known as
Naming Conventions in Java.

packages:
23

=>The packages must be in lowercase.


Page

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

=>Primitive DataTypes are categorized into the following:

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

faq: why char 2 bytes in Java?


=>JavaLang use UniCode(Universal Code) representation and which is ready to accept all the language
codes in the world.

ASCII - American Standard code for Information InterChange


ISO 8859-1 for Western European Language
KOI-8 for Russian
GB18030 and BIG-5 for Chinese
-------------------------------------------------------------------------------
27

*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
==============================================================================

Control Structures in Java:


=>The Structures which are used to control the part of the program are known as Control Structures.
=>These Control Structures are categorized into three types:
1.Selection Statements
2.Iterative Statements
3.Branching Statements
29
Page

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

Scanner s = new Scanner(System.in);//Built-in class object


Page

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

(ii)out - for output data


Page

(iii)err - for error data

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

=>public static void main(String[] args)


35
Assignment(Solution):

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();
}
}

define 'import' statement?


=> "import" statement is used to load classes or interfaces from packages of JavaLib.
----------------------------------------------------------------------------------------------------------------------------------------
==============================================================================
Exp program:
wap to read two int values and perform arithmetic operation based on user choice?

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;

class SResult //SubClass


43

{
Page

43
int s1,s2,s3,s4,s5,s6;

void cal()

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((s1>=0 && s1<=34)||(s2>=0 && s2<=34)||(s3>=0 && s3<=34)

||(s4>=0 && s4<=34)||(s5>=0 && s5<=34)||(s6>=0 && s6<=34))

System.out.println("Result:Fail");

}//end of if

else

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");
44

}
Page

else

44
{

System.out.println("Result:Fail");

}//end of if

else

System.out.println("Invalid Marks...");

class StuMainClass2 //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();

}
45
Page

45
Variables in Java:
=>Variables are the data holders in the program.

=>Based on DataTypes in Java,the variables are categorized into two types:

(1)Primitive DataType Variables

(2)NonPrimitive DataType Variables

(1)Primitive DataType Variables:


=>The variables which are declared with Primitive datatypes are known as Primitive DataType variables.

Note:

=>Primitive DataType variables will hold values.

(2)NonPrimitive DataType Variables:


=>The variables which are declared with NonPrimitive datatypes or referential datatypes are known as
NonPrimitive datatype variables.

Note:

=>NonPrimitive DataType variables will hold object references.

Based on 'static' keyword the variables are categorized into


two types:
(1)NonStatic variables

(2)Static Variables

(1)NonStatic variables:
=>The variables which are declared without static keyword are known as NonStatic variables.

=>These NonStatic variables are categorized into two types:

(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:

=>There is no concept of declaring Static variables as Local variable.

(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.

=>Methods in Java are categorized into two types:

(a)NonStatic methods(Instance methods)

(b)Static methods

(a)NonStatic methods(Instance methods):


=>The methods which are declared without static keyword are known as NonStatic

methods or Instance methods.

=>These NonStatic methods or Instance methods will get the memory within the
47

object while object creation.


Page

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.

These Instance methods are categorized into two types:


(i)Built-In instance methods

(ii)User defined instance methods

(i)Built-In instance methods:


=>The instance methods which are available from JavaLib classes are known as

Built-in instance methods or PreDefined instance methods.

Exp:

'Scanner' class methods

(ii)User defined instance methods:


=>The instance methods which are defined by the programmer are known as User

defined instance methods.

(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.

Structure of static methods:


static return_type method_name(para_list)

//method_body

Coding rule:
=>Static methods can access static variables directly,but cannot access instace variables directly.
48

These static methods are categorized into two types:


Page

(i)Built-in static methods

48
(ii)User defined static methods

(i)Built-in static methods:


=>The static methods which are available from JavaLib classes are known as Built-in static methods or
PreDefined static methods.

(ii)User defined static methods:


=>The static methods which are defined by the programmer are known as user defined static methods.

----------------------------------------------------------------

Exp program:

class Display //SubClass

int a=20;//primitive datatype instance variable

static int k=10;//primitive datatype static variable

void m1()

a++;

k++;

int b=100;//primitive datatyoe Local variable

//static int z=20;//Compilation Error

System.out.println("====m1()====");

System.out.println("Instance variable a:"+a);

System.out.println("Local variable b:"+b);

System.out.println("Static variable k:"+k);

static void m2()

k++;

int c=200;//Local variable

System.out.println("====m2()====");

//System.out.println("Instance variable a:"+a);//Compilation Error

System.out.println("Local variable c:"+c);

System.out.println("Static variable k:"+k);

}
49

class MainClass2 //MainClass


Page

49
public static void main(String[] args)

Display d1 = new Display();//Object1

Display d2 = new Display();//Object2

d1.m1();//NonStatic method call

d2.m1();//NonStatic method call

Display.m2();//Static method call

o/p:

====m1()====

Instance variable a:21

Local variable b:100

Static variable k:11

====m1()====

Instance variable a:21

Local variable b:100

Static variable k:12

====m2()====

Local variable c:200

Static variable k:13

Execution flow of above program:

ClassFiles:

Display.class

MainClass2.class

-----------------------------------------------------------------------------------------------------------------------------------------------

*imp

Class generating multiple objects:

=>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:

=>The amt must be greater than zero and multiples of 100.

Classes:

WithDraw

=>amount

=>void wDraw()

=>If amount is less than 2000/- then perform transaction.

o/p:

Amt withDrawn : amount

Bal amt : 2000-amount

Deposit

=>amount

=>void deposit()

o/p:

Amt deposisted : amount

Bal amt : 2000+amount

BankMainClass

=>public static void main(String[] args)

=>input 'amt'

==============================================================================

define parameters?
=>Parameters are the variables which are used to transfer the data from one

method to another method.

=>Based on parameters the methods are categorized into two types:

(i)Methods without parameters

(ii)Methods with parameters


51

(i)Methods without parameters:


Page

=>The methods which are declared without parameters are known as 0-parameter

51
methods or Methods without parameters.

(ii)Methods with parameters:


=>The methods which are declared with parameters are known as parameterized

methods or Methods with parameters.

wt is the diff b/w (i)Parameters (ii)Arguments


=>Both are same can use the word interchangingly,

Parameters - Variables

Arguments - Values

------------------------------------------------------------------------------------------------------------------------------------------------------

define return_type?
=>The return_type specify the methods return the value after method execution

or not.

=>Based on return_type the methods are categorized into two types:

(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.

=>The returned value will come back to the method_call.

------------------------------------------------------------------------------------------------------------------------------------------------

Exp program:

wap to read empName,empDesg,empId and display the Same?

Note:

=>empDesg must be in,"SE" or "TE" or "ME" then read empId.


52

Classes:
Page

52
CheckDesignation

=>boolean k

=>boolean verify(desg)

MainClass3

=>public static void main(String[] args)

import java.util.Scanner;

class CheckDesignation //SubClass

boolean k=false;//Primitive datatype Instance variable

boolean verify(String desg)//Return_type Instance method with parameter

switch(desg)

case "SE":k=true;

break;

case "TE":k=true;

break;

case "ME":k=true;

break;

}//end of switch

return k;

class MainClass3 //MainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);

System.out.println("Enter the EmpName:");

String eName = s.nextLine();

System.out.println("Enter the EmpDesg");

String eDesg = s.nextLine();


53

CheckDesignation cd = new CheckDesignation();


Page

boolean p = cd.verify(eDesg);//Method_call with parameter passing

53
if(p)

System.out.println("Enter the EmpId:");

String eId = s.nextLine();

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

SubClasses are loaded based on their requirement in the object creation.

=>Parameters are categorized into two types:

(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

calculations are known as Formal parameters.

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

available options or cases

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:

=>The amt must be greater than zero and multiples of 100.

import java.util.*;

class WithDraw //SubClass

void wDraw(int amt)//Non-Return_type Instance method with parameter


56

{
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...");

class Deposit //SubClass

void deposit(int amt)//Non-Return_type Instance method with parameter

System.out.println("Amt Deposited:"+amt);

System.out.println("Balance Amount:"+(2000+amt));

System.out.println("Transaction completed...");

class BankMainClass //MainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);

System.out.println("Enter the amount:");

int amount = s.nextInt();

if(amount>0 && amount%100==0)

System.out.println("====Choice====");

System.out.println("1.WithDraw\n2.Deposit");
57

System.out.println("Enter the choice:");


Page

int choice = s.nextInt();

57
switch(choice)

case 1:

WithDraw wd = new WithDraw();

wd.wDraw(amount);//Method_call with parameter passing

break;

case 2:

Deposit dp = new Deposit();

dp.deposit(amount);//Method_call with parameter passing

break;

default:

System.out.println("Invalid choice...");

}//end of switch

}//end of if

else

System.out.println("Invalid amount....");

define while loop?


=>In while looping structure the condition is checked first,if the condition is true then the loop block is
executed.This process is repeated until the condition is false.

syntax: Flowchart:

while(condition)

//loop_block;

define 'continue' statement?


58

=>'continue' statement is used to skip the statements from the iteration,whichmeans the line declared after the
Page

'continue' statement will be skipped.

58
Note:

=>'continue' statement is declared with condition.

Modification of StuMainClass.java:

import java.util.Scanner;

class SResult //SubClass

void cal(boolean k,int totMarks)//NonReturn_type Instance method with paramter

float per = (float)totMarks/6;//TypeCasting

System.out.println("TotalMarks:"+totMarks);

System.out.println("Percentage:"+per);

if(k)

System.out.println("Result:Fail");

else 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
59

{
Page

System.out.println("Result:Fail");

59
}

class StuMainClass //MainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);

SResult sr = new SResult();

int i=1,totM=0;

boolean k=false;

while(i<=6)

System.out.println("Enter the marks of Sub"+i);

int sub = s.nextInt();

i++;

if(sub<0 || sub>100)//simple if

System.out.println("Invalid marks...");

i--;

continue;//will skip the statements from the iteration

if(sub>=0 && sub<=34)//simple if

k=true;

totM=totM+sub;

}//end of loop

sr.cal(k,totM);//Method_call with parameter passing

}
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:

step-1 : Initialization process

step-2 : Check the Condition

step-3 : In the condition is true,then execute loop block.

step-4 : Perform Increment/Decrement

Note:

=>Repeat the steps 2,3 and 4 until the contion is false

Note:

=>In realtime,'for' loop is used in 'Strings' and 'Arrays'.

=>In Strings the characters are organized based on index values.

=>In Arrays the elements are organized based on index values.

-----------------------------------------------------------------------------------------------------------------------------------------------------

Exp program:

wap to read a String and display the count of Vowels?

I/P : str="java program"

O/P : count=4

import java.util.Scanner;

class MainClass4 //MainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);


61

System.out.println("Enter the String:");


Page

61
String str = s.nextLine();

//str is NonPrimitive DataType local variable

int len = str.length();

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:

wap to read a String and display in reverse?

------------------------------------------------------------------------

Dt : 1/7/2021

Assingnment:(Solution)

wap to read a String and display in reverse?

MainClass5.java

import java.util.Scanner;

class MainClass5 //MainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);

System.out.println("Enter the String:");

String str = s.nextLine();

System.out.println("====Display String in reverse====");

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.

=>In JavaLang,Array is a sequenced collection of similer objects,which means

objects of same class.

syntax:

Class_name arr-var[] = new Class_name[size];

EXp program:

wat to read and display Product class objects using Array?

MainClass6.java

import java.util.Scanner;
63

class Product //SubClass


Page

63
{

String pCode,pName;

float pPrice;

int pQty;

void getProduct()

System.out.println(pCode+"\t"+pName+"\t"+pPrice+"\t"+pQty);

class MainClass6 //MainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);

System.out.println("Enter the number of Products:");

int n = s.nextInt();

s.nextLine();//to Overcome data skipping

Product p[] = new Product[n];

//Array created to hold Product class objects

System.out.println("Enter "+n+" product details:");

for(int i=0;i<n;i++)

Product ob = new Product();

System.out.println("Enter the pCode:");

ob.pCode = s.nextLine();

System.out.println("Enter the pName:");

ob.pName = s.nextLine();

System.out.println("Enter the pPrice:");

ob.pPrice = s.nextFloat();

System.out.println("Enter the pQty:");

ob.pQty = s.nextInt();

s.nextLine();//to OverCome data skipping


64

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:

Update StuMainClass.java to calculate result for Multiple Students using Array?

----------------------------------------------------------------------------

MainClass1.java(Modified)

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


65

{
Page

65
int sub(int x,int y)

return x-y;

class Multiplication //SubClass

int mul(int x,int y)

return x*y;

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:");


66

int v1 = s.nextInt();
Page

System.out.println("Enter the value2:");

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");

System.out.println("Enter the choice:");

int choice = s.nextInt();

switch(choice)

case 1:

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;

case 6:

System.exit(0);//Stop the program

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.

Method Signature of exit():

public static void exit(int);

syntax:

System.exit(0);

define do-while loop?


=>In do-while looping Structure the loop-block is executed first and then the condition is checked,this process is
repeated until the condition is false.

syntax:
do

//loo

while(condition);

FlowChart:

======================================================================
68
Page

68
Summary of Variables and Methods:
(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)

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.

=>Blocks in Java are categorized into two types:

1.Static blocks 2.NonStatic blocks(Instance blocks)

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

class Test1 //SubClass

static

System.out.println("=====SubClass static block====");

class DemoBlock1 //MainClass

public static void main(String[] args)

Test1 ob1 = new Test1();

Test1 ob2 = new Test1();

}
70

static
Page

70
System.out.println("=====MainClass static block====");

2.NonStatic blocks(Instance blocks):


=>The blocks which are declared without static keyword are known as NonStatic blocks or Instance blocks.

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

class Test2 //SubClass

System.out.println("====SubClass NonStatic block====");

class DemoBlock2 //MainClass

public static void main(String[] args)

Test2 ob1 = new Test2();

Test2 ob2 = new Test2();

DemoBlock2 db = new DemoBlock2();

System.out.println("====MainClass Instance block====");

}
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.

=>Blocks will have highest priority in execution when compared to methods.

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

Based on parameters the constructors are categorized into two


types:
1.Constructors without parameters
2.Constructors with parameters

1.Constructors without parameters:


=>The constructors which are declared without parameters are known as 0-parameter constructors or
Constructors without parameters.

Exp program:

DCon1.java

class CTest

CTest()
72
Page

72
System.out.println("====0-parameter Constructor====");

void dis()

System.out.println("====dis() method====");

class DCon1 //MainClass

public static void main(String[] args)

CTest ob = new CTest();//Constructor_call

ob.dis();//Method_call

Faq: wt is the diff (i)Constructor (ii)Instance method


=>Constructor is executed while object creation,but Instance method is executed after object creation.

Faq: wt is the diff b/w (i)Instance block (ii)Constructor


=>Instance block will have highest priority in execution when compared to Constructor because constructor
comes under method category.

Faq: wt is the diff b/w (i)static block (ii)Constructor


=>Static block and Constructor executes only once,but static block is executed while class loading and Constructor
executed while object creation.

Exp program:

DCon2.java

class CTest

static

System.out.println("====SubClass static block====");

{
73

System.out.println("====SubClass Instance block====");


Page

73
}

CTest()

System.out.println("====0-parameter Constructor====");

void dis()

System.out.println("====dis() method====");

class DCon2 //MainClass

public static void main(String[] args)

CTest ob = new CTest();//Constructor_call

ob.dis();//Method_call

faq: define default Constructor?


=>The Constructor without parameters which is added by the compiler at compilation stage is known as default
Constructor.

faq: In wt situation default constructor is added?


=>The compiler at compilation stage finds any class declared without constructorsthen default constructor is
added.

*imp

2.Constructors with parameters:


=>The Constructors which are declared with parameters are known as parameterized constructors or constructors
with parameters.

Exp program:

DCon4.java

import java.util.Scanner;

class UserDetails
74

{
Page

String fName,lName,addr,mId;

74
long phNo;

//Instance variables memory within the object

UserDetails(String fName,String lName,String addr,String mId,long phNo)

//Local variables memory within the method_frame

this.fName=fName;

this.lName=lName;

this.addr=addr;

this.mId=mId;

this.phNo=phNo;

/*This Constructor is used to load the data from Local variables to

Instance variables,in this process we have same names in Local

variables and Instance variable*/

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);

class DCon4 //MainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);

System.out.println("Enter the FirstName:");

String fN = s.nextLine();

System.out.println("Enter the LastName:");

String lN = s.nextLine();
75

System.out.println("Enter the Address:");


Page

String addr = s.nextLine();

75
System.out.println("Enter the MailId:");

String mId = s.nextLine();

System.out.println("Enter the PhoneNo:");

long pNo = s.nextLong();

UserDetails ud = new UserDetails(fN,lN,addr,mId,pNo);

//Constructor_call with parameters

ud.getUserDetails();

}}

Advantage of Constructor:
=>Constructors are used to initialize instance variables while object creation, which saves the execution time and
generates HighPerformance.

faq: define 'this' keyword?


="this" is a Built-in keyword acts like a NonPrimitive DataType variable and which is holding the object reference
of Current running class.

Note:

=>'this' keyword is used when we have same names in Local variables and Instancevariables.

----------------------------------------------------------------------------------------------------------------------------

faq: define 'static' constructor?


=>There is no concept of Static constructor in Java,because constructor means executed while object
creation.(Copilation error)

=============================================================================

PACKAGES IN JAVA:
=>Package is a collection of classes and Interfaces.

=>Packages in Java are categorized into two types.

1.Built-In packages

2.User defined packages


76
Page

76
1.Built-In packages:
=>The packages which are available from JavaLib are known as Built-in packages or PreDefined packages.

=>The following are some important packages from 'JavaLib':

CoreJava:

java.lang - Language package(default package)

java.util - Utility package(JCF)

java.io - Stream and Files package.

java.net - Networking package

GUI:

java.awt - Abstract Window Toolkit package

javax.swing - Swing programming package

java.applet - Applet programming package

AdvJava:

java.sql - DataBase Connection package

javax.servlet - Servlet programming package

javax.servlet.jsp - JSP Programming package

2.User defined packages:


=>The packages which are defined by the programmer are known as User defined packages.

=>we use 'package' keyword to define User defined packages.

syntax:

package package_name;

Note:

=>The Classes,Interfaces and its members which are declared within the package

must be 'public'.

Exp Application:

package p1;

public class Salary

public void cal(int bSal)


77

{
Page

77
if(bSal>=5000)

float totSal = bSal+(0.93F*bSal)+(0.63F*bSal);

System.out.println("BSal:"+bSal);

System.out.println("TotSal:"+totSal);

else

System.out.println("Invalid bSal...");

step1 : Save the program in ProjectFolder


as

Salary.java

step2 : Compile the program as

javac -d . Salary.java

Note:

(-d .) indicates create package and load


the class file as member of package.

package p2;

import java.util.Scanner;

import p1.Salary;

public class SalaryMainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);

Salary sl = new Salary();

System.out.println("Enter the bSal:");

sl.bSal = s.nextInt();

sl.cal();
78

}
Page

78
step1 : Save the program in ProjectFolder as SalaryMainClass.java

step2 : Compile the program as javac -d . SalaryMainClass.java

step3 : Execute the program as java p2.SalaryMainClass

---------------------------------------------------------------------

faq: define 'import' statement?


=>'import' statement is used to make class or interface available from one package to another package.

The importing process in Java can be done in three ways:


(i)Using 'import package_name.Class_name/Interface_name; '
=>In this importing process the required class or interface available to current running program.

=>This importing process also known as 'Explicit import process'.

Exp:

import java.util.Scanner;

import p1.Salary;

(ii)Using 'import package_name.*; '


=>In this importing process all the classes and Interfaces from the package are available to Current running
program.

=>This importing process also known as 'Implicit import process'.

Exp:

import java.util.*;

import java.lang.*;

import p1.*;

(iii)Using 'Fully Qualified names'.


=>The process of declaring classes and interfaces with package names part of program code is known as 'Fully
Qualified names'.

Exp:

java.util.Scanner s = new java.util.Scanner(System.in);

p1.Salary sl = new p1.Salary();

----------------------------------------------------------------------------------------------------------------------------------------------------------
79
Page

79
Access Modifiers?
=>Access modifiers specify the scope of programming components within the Project folder.

=>The following are some important access modifiers in Java:

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.

define sqrt() method?


=>sqrt() is a static built-in method from java.lang.Math class and which is used to find the sqrt of given number.

Method Signature:

public static double sqrt(double);

syntax:

double z = Math.sqrt(val);

DemoMainClass.java

package maccess;

import java.util.Scanner;

import static java.lang.Math.*;//Introduced by Java5 version(2004)

public class DemoMainClass

public static void main(String[] args)

Scanner s = new Scanner(System.in);

System.out.println("Enter the value:");

double v = s.nextDouble();

double z = sqrt(v);//Access directly without Class_name

System.out.println("Sqrt of "+v+" is "+z);

}
81
Page

81
RelationShip b/w classes:
=>The process of establishing communication b/w classes is known as relationshipb/w classes.

=>The RelationShip b/w classes are categorized into the following:

(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

classes,is known as References Concept.

(One object hoding reference of another object is known as references concept)

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;

public class EMainClass {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

Employee e = new Employee();

e.setEmployeeDetails(s);//Method_call with reference variable as parameter

e.getEmployeeDetails();

}
83

}
Page

83
Diagram:

----------------------------------------------------------------------------------------------------------------------------------------------------

Methods with reference variables as parameters and reference as retun_type:


=>we can also pass NonPrimitive datatypes as parameters to method and also canhave NonPrimitive datatypes
as return_type.

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;

public class BMainClass {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

System.out.println("Enter the BookCode:");

String bC = s.nextLine();

System.out.println("Enter the BookName:");

String bN = s.nextLine();
85

System.out.println("Enter the BookAuthor:");


Page

String bA = s.nextLine();

85
System.out.println("Enter the BookPrice:");

float bP = s.nextFloat();

System.out.println("Enter the BookQty:");

int bQ = s.nextInt();

//bC bN bA bP bQ are local variables

LoadBookData lbd = new LoadBookData();

BookData bd = lbd.load(bC, bN, bA, bP, bQ);//This method returns reference of BookData

Display d = new Display();

d.dis(bd);//Method_call with BookData reference

s.close();

===============================================================================================

(b)Inheritance:
=>The process of establishing
communication b/w two classes using
'extends'

keyword is known as Inheritance process.

(Linking two classes using 'extends'


keyword is known as Inheritance)

Diagram:
86
Page

86
syntax:
Class A

//members

class B extends A

//members

=>In Normal inheritance process we always create object for ChildClass.

syntax:

B ob = new B();

----------------------------------------------------------------------------------------------------------------------------------------------------

Inheritance Case-1 : NonStatic members from the ParentClass or SuperClass


=>In Inheritance process all the NonStatic members of ParentClass are available to CClass through 'extends'
keyword.

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;

public class Inheritance1 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

B ob = new B();//Normal Inheritance process

System.out.println("Enter the value of x:");

ob.x = s.nextInt();

System.out.println("Enter the value of y:");

ob.y = s.nextInt();

ob.m1();//PClass method_call

ob.m2();//CClass method_call

s.close();

O/P:

====PClass NonStatic Block====

====CClass NonStatic block====

Enter the value of x:

12

Enter the value of y:

13

====PClass m1()====
88

The value x:12


Page

88
====CClass m2()====

The value y:13

-------------------------------------------------------------------------------------------------------------------------------------------------------

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

Inheritance Case-2 : Constructors from the ParentClass or SuperClass


(i)0-parameter constructor from PClass or SuperClass
=>when we have 0-parameter constructor within the PClass,then the compiler will add super() to the CClass
Constructor and which is the PClass Constructor call.

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====

(ii)Parameterized Constructor from the PClass or SuperClass


=>when we have parameterized constructor within the PClass,then we must add super() to the CClass constructor
and which is the PClass Constructor call.

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;

public class Inheritance3 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

System.out.println("Enter the value x:");

int x = s.nextInt();

CClass ob = new CClass(x);//CClass Constructor_call


90

s.close();
Page

90
}

o/p:

Enter the value x:

123

====PClass Constructor====

The value x:123

=======================================================================

Inheritance Case-3 : Static members from the ParentClass or SuperClass


=>In Inheritance process all the static members of PClass are available to CClass through 'extends' and can be
accessed with the CClass_name.

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

public class Inheritance4 {

91
public static void main(String[] args) {

Scanner s = new Scanner(System.in);

System.out.println("Enter the value of x:");

CClass.x = s.nextInt();

System.out.println("Enter the value of y:");

CClass.y = s.nextInt();

CClass.m1();//PClass method_call

CClass.m2();//CClass method_call

s.close();

o/p:

Enter the value of x:

12

====PClass static block====

Enter the value of y:

13

====CClass static block====

====PClass m1()====

The value x:12

====CClass m2()====

The value y:13

OVERRIDING
faq:

define Method Overriding process?


=>The method with same method signature in PClass and CClass,then PClass method is replaced by CClass
method while object creation is known as Method Overriding process.

=>Same method Signature means,

Same return_type

Same method_name

Same para_list

Same para_type

Case-1 : Instance method Overriding process


92

=>we can perform Method Overriding process using Instance methods.


Page

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()====

The value x:123

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.

Case-3 : Static method Overriding process (No Concept of this overriding)


=>There is no concept of Static method Overriding process because the static methods are binded and available
within the classes.

-----------------------------------------------------------------------------------------------------------------------------------------------------

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.

=>Method Overriding process and Method Hiding process is available only in


94

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 variable a:10


95

CClass variable a:20


Page

====PClass m()====

95
The value x:123

====CClass m()====

The value y:124

Concept of super() & this()


wt is the diff b/w

(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

=>Constructor Overloading process is posible

=>Static method Overloading process is posible

Exp application:

Display.java

package test;
97

public class Display {


Page

//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);
}
}

CONSTRUCTOR CHAINING PROCESS


=>The process of calling the constructor from the constructor is known as Constructor Chaining process.

----------------------------------------------------------------------------------------------------------------------------------------------------------

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:

=>In realtime these Inheritances are categorized into two types:

(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

ambiguity state applications will generate wrong results.

=>In JavaLang,the Multiple Inheritance can be acheived using 'Interfaces'.

=================================================================================

Exp Progran:(Demonstrating Multi-Level 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 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.

define abstract method?


=>The methods which are declared without method_body are known abstract methods.

Structure of abstract method:


return_type method_name(para_list);

define Concrete methods?


=>The methods which are declared with method_body are known as Concrete methods.

Structure of Concrete method:


return_type method_name(para_list)

//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:

wap to demonstrate variables within the Interface?

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

public class Interface2 {

104
public static void main(String[] args) {

//IComparable ob = new IComparable();//Error

Scanner s = new Scanner(System.in);

System.out.println("Enter the value x:");

int x = s.nextInt();

System.out.println("Enter the value y:");

int y = s.nextInt();

System.out.println("====Choice====");

System.out.println("1.Greater\n2.Smaller");

System.out.println("Enter the Choice:");

int choice = s.nextInt();

switch(choice)

case 1:

Greater gt = new Greater();

System.out.println("Greater Value:"+gt.compareTo(x, y));

break;

case 2:

Smaller sm = new Smaller();

System.out.println("Smaller Value:"+sm.compareTo(x, y));

break;

default:

System.out.println("Invalid choice..");

}//End of switch

s.close(); 105
Page

105
}

Diagram:

Assignment:

Convert BankMainClass.java program in to packages and also use the Interface

Concept as follows:

Diagram:

----------------------------------------------------------------------------------------------------------------------------------------------------

Rule-9.There is no concept of declaring Blocks and Constructors within the Interface.

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

Multiple Inheritance Models using Interfaces:


Model-1 : Extracting the features from more than one interface into a class.

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;

public class IClass implements ITest3{


public void m1(int x){
System.out.println("x:"+x);
}
public void m2(int y){
System.out.println("y:"+y);
}
public void m3(int z){
System.out.println("z:"+z);
}
}
Interface6.java

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===");
}

public abstract void m2(int y);


public void dis2(){
System.out.println("===dis2()===");
System.out.println("The value b:"+b);
}
}
EClass.java

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===");
}

public void m2(int y){


System.out.println("===m2()===");
System.out.println("y:"+y);
}
}
AbstractClass1.java
112

package maccess;
import test.*;
Page

public class AbstractClass1 {

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()===

The value a:10

===dis2()===

The value b:20

=========================================================================

Comparision diagram:

113

=======================================================================
Page

113
InnerClasses:
=>The classes which are declared within the class are known as InnerClasses or Nested Classes

=>These InnerClasses are categorized into the following:

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.

=>These Member InnerClasses are categorized into two types:

(a)NonStatic member InnerClasses

(b)Static member InnerClasses

(a)NonStatic member InnerClasses:


=>The member InnerClasses which are declared without static keyword are known as NonStatic member
InnerClasses or Instance Member InnerClasses.

Coding Rules:
=>NonStatic member InnerClasses can be declared with only NonStatic members.

=>NonStatic member InnerClass object is created using OuterClass object.

syntax:
OuterClass.InnerClass obj_name=OuterClass_object.new InnerClass();

Exp:

SubClass1.SubClass2 ob4=ob.new SubClass2();

=>The methods of NonStatic member InnerClasses can access all the members of

outerClass directly.

(b)Static member InnerClasses:


=>The member InnerClasses which are declared with static keyword are known

as Static member InnerClasses.

Coding Rules:
=>static member InnerClasses can be declared with both static and NonStatic

members.

=>Static member InnerClass objects are created using OuterClass.

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();

public static class SubClass3{


public void m2(){
System.out.println("====Static member InnerClass m2()====");
System.out.println("a:"+a);
//System.out.println("b:"+b);//Compilation Error
}
public static void m3(){
System.out.println("====Static member InnerClass m3()====");
System.out.println("a:"+a);
//System.out.println("b:"+b);//Compilation Error
}
}//Static member InnerClass
public SubClass3 ob3 = new SubClass3();
}//OuterClass
InnerClass1.java(MainClass)

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.

=Local InnerClasses can be only NonStatic member InnerClasses.

(There is no concept of Static member InnerClasses)

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

public class InnerClass2 {


public static void main(String[] args) {
Page

SubClass11 ob = new SubClass11();//OuterClass object

116
ob.m1();
}
}

3.Anonymous InnerClasses:
=>The InnerClasses which are declared without name are known as Anonymous InnerClasses.

=>These Anonymous InnerClasses are categorized into the following:

(a)Anonymous InnerClass as Class Extention

(b)Anonymous InnerClass as Implementation class

Note:

=>"$" symbol in Java represents InnerClass or InnerInterface.

-----------------------------------------------------------------------------------------------------------------

define Generalization process?


(i)Using Classes:
=>In Generalization process using classes,one reference is created and the reference is binded with all the
members of PClass and only Overriding members from the

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

public void m2(int y) {

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:

Arithmetic ob = new Addition();

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:

Normal Inheritance process


119

====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'

(a)Anonymous InnerClass as Class Extention:


=>The process of declaring the CClass without name is known as 'Anonymous InnerClass as Class extention'.

syntax:
class PClass

//PClass_body

PClass ob = new PClass()

//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

-----------------------------------------------------------------------

(b)Anonymous InnerClass as Implementation class:


=>The process of declaring the implementation class without name is known as 'Anonymous InnerClass as
Implementation class'.

syntax:
interface Interface_name

//Interface_body

Interface_name ob = new Interface_name()

//Impl_Class_body

};

Exp Application:
121

Arithmetic.java
package test;
Page

public interface Arithmetic {


121
public abstract void process(int x,int y);
}
Anonymous2.java(MainClass)
package maccess;
import test.*;
public class Anonymous2 {
public static void main(String[] args) {
System.out.println("Generalization process");
Arithmetic ob2 = new 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);
}
};
ob2.process(23,20);
//ob2.dis(123);//Generalization process
}
}
o/P:

Generalization process

====process()====

x:23

y:20

Sum:43

-------------------------------------------------------------------------------------

Assignment1:

Update above application to perform arithmetic operation based on User choice.

(Using 'Anonymous InnerClass as implementation' concept)

Diagram:
122
Page

122
InnerClass within the Interface:
=>we can declare InnerClasses within the Interface and which are automatically static member InnerClasses.

InnerClass within the AbstractClass:


=>We can also declare InnerClasses within the abstract class and which can be static or NonStatic 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

----------------------------------------------------------------------------

InnerInterface within the class:


123

=>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)

InnerInterface within the AbstractClass:


=>we can also declare InnerInterface within the abstract class and which can be static or NonStatic member
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);
}
};

ITest.ITest2 ob2 = new ITest.ITest2() {


public void m2(int y) {
System.out.println("====m2()====");
System.out.println("y:"+y);
}
};
124

AClass.ITest3 ob3 = new AClass.ITest3() {


Page

public void m3(int z) {

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

------------------------------------------------------------------------------

InnerAbstractClass within the Class:


=>we can declare InnerAbstractClasses within the class and which can be static or NonStaticInnerAbstractClasses.

InnerAbstractClass within the Interface:


=>we can also declare InnerAbstractClasses within the Interface and which are automatically static member
InnerAbstractClasses.

InnerAbstractClass within the AbstractClass:(Nested


AbstractClass)
=>we can also declare InnerAbstractClasses within the AbstractClasses and which can be static or NonStatic.

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);
}
};

ITest.AClass2 ob2 = new ITest.AClass2() {


public void m2(int b) {
System.out.println("===m2()===");
System.out.println("b:"+b);
}
};

AClass.AClass3 ob3 = new AClass.AClass3() {


public void m3(int c) {
System.out.println("===m3()===");
System.out.println("c:"+c);
}
};

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.*;

public class BankTransaction1 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

int count=0;

xyz:

while(true) {

System.out.println("Enter the PinNo:");

int pinNo = s.nextInt();

CheckPinNo cpn = new CheckPinNo();

boolean k = cpn.verify(pinNo);

if(k) {

System.out.println("====Choice====");

System.out.println("1.WithDraw\n2.Deposit");

System.out.println("Enter the choice:");

int choice = s.nextInt();

switch(choice) {

case 1:

System.out.println("Enter the amt:");

int a1 = s.nextInt();

if(a1>0 && a1%100==0) {

WithDraw wd = new WithDraw();

wd.process(a1);

}else {

System.out.println("Invalid amt...");

break xyz;

case 2:
128

System.out.println("Enter the amt:");

int a2 = s.nextInt();
Page

128
if(a2>0 && a2%100==0) {

Deposit dp = new Deposit();

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) {

System.out.println("Sorry! Transaction blocked...");

break xyz;

}//End of loop

s.close();

==============================================================================

Assignment2:(Solution)

Update BankTransaction process using 'Anonymous InnerClass as ImplClass' concept.

(declare WithDraw and Deposit as Anonymous classes)

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.*;

public class BankTransaction2 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

int count=0;

xyz:

while(true) {

System.out.println("Enter the PinNo:");

int pinNo = s.nextInt();

CheckPinNo cpn = new CheckPinNo();

boolean k = cpn.verify(pinNo);

if(k) {

System.out.println("====Choice====");

System.out.println("1.WithDraw\n2.Deposit");

System.out.println("Enter the choice:");

int choice = s.nextInt();


130

switch(choice) {
Page

case 1:

130
System.out.println("Enter the amt:");

int a1 = s.nextInt();

if(a1>0 && a1%100==0) {

Transaction wd = new 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...");

};

wd.process(a1);

}else {

System.out.println("Invalid amt...");

break xyz;

case 2:

System.out.println("Enter the amt:");

int a2 = s.nextInt();

if(a2>0 && a2%100==0) {

Transaction dp = new Transaction()

public void process(int amt) {

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) {

System.out.println("Sorry! Transaction blocked...");

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

Update above application to perform arithmetic operation based on User choice.


Page

(Using 'Anonymous InnerClass as implementation' concept)

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.*;

public class DArithmetic {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

System.out.println("Enter the value x:");

int x = s.nextInt();

System.out.println("Enter the value y:");

int y = 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) {

case 1:

Arithmetic ad = new Arithmetic()

public void process(int x,int y)

System.out.println("Sum:"+(x+y));

};

ad.process(x, y);

break;

case 2:

Arithmetic sb = new Arithmetic()


133

{
Page

public void process(int x,int y)

133
{

System.out.println("Sub:"+(x-y));

};

sb.process(x, y);

break;

case 3:

Arithmetic ml = new Arithmetic()

public void process(int x,int y)

System.out.println("Mul:"+(x*y));

};

ml.process(x, y);

break;

case 4:

Arithmetic dv = new Arithmetic()

public void process(int x,int y)

System.out.println("Div:"+(float)x/y);

};

dv.process(x, y);

break;

case 5:

Arithmetic md = new Arithmetic()

public void process(int x,int y)

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
==============================================================================

Exception Handling process:

define Exception?
=>The disturbance which is occured from the application is known as Exception.

define Exception Handling process?


=>The process which is used to handle the exception is known as Exception Handling process.

The following blocks are used in exception handling process:


1.try block

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

the reference of object is thrown onto catch block.

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

Digram of Execption Handling

Note:

=>In realtime finally block will hold resource closing operations like IO Close,File Close,DB Close,N/W close,...

--------------------------------------------------------------------------------------------------------------------------------------------------------

define 'Throwable' class?


=>'Throwable' class is from java.lang package and which is root of exception handling process.

This 'Throwable' class is extended into the following SubClasses:


1.Error

2.Exception

Hierarchy of 'Throwable' class:


138
Page

138
1.Error:
=>The disturbance which is occured from the environment is known as error.

=>There is no concept of error handling process.

=>'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.

=>These UnChecked Exceptions are categorized into two types:

(i)Built-in UnChecked Exceptions

(ii)User defined UnChecked Exceptions

(i)Built-in UnChecked Exceptions:


=>The UnChecked Exceptions which are available from JavaLib are known as Built-in UnChecked 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:

faq: define getMessage() method?


=>getMessage() method is from java.lang.Throwable class and which is used to display the msg from the objects.

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();

------------------------------------------------------------------------------------

(ii)User defined UnChecked Exceptions:


=>The UnChecked exceptions which are defined and raised by the programmer are known as User defined
UnChecked Exceptions.

steps used to define User defined UnCheckedExceptions:


step-1 : The User defined class must be extended from 'java.lang.Exception' class.

step-2 : use try-catch blocks to hold exceptions_lines

step-3 : define the condition to raise exception

step-4 : If the condition is true then raise exception,which means create object for user

define class from where the exception raised.

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?

(raise exception when bSal is less than 5000)

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:

wap to read and display Student detials?

(Use exception handling process)

1.read stuName

2.stuRollNo

=>rollNo must be 10 digits,if not raise exception

3.read branch

=>branch must be in 'CSE' or 'ECE' or 'EEE',if not raise exception

Note:

=>if No exceptions then display the detials

StuName =

StuRollNo =

StuBranch =

--------------------------------------------------------------------------------------

Dt : 29/7/2021

Diagram:(DException2)

142
Page

142
Assignment:(Solution)

wap to read and display Student detials?

(Use exception handling process)

1.read stuName

2.stuRollNo

=>rollNo must be 10 digits,if not raise exception

3.read branch

=>branch must be in 'CSE' or 'ECE' or 'EEE',if not raise exception

Note:

=>if No exceptions then display the detials

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

object creation and the message is displayed using 'getMessage()' method.

----------------------------------------------------------------------------------------------------------------------------------------------------------

Annotation
=>The tag based information which is added to the programming components like Class, Interface,Method and
Variable,is known as Annotation.

=>These Annotations are represented using '@' symbol.

=>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.

=>These Checked Exceptions are categorized into two types:

(i)Built-in Checked Exceptions

(ii)User defined Checked Exceptions

(i)Built-in Checked Exceptions:


=>The Checked Exceptions which are available from JavaLib are known as Built-in Checked exceptions or Pre-
Defined Checked exceptions.

Exp:

java.lang.InterruptedException

java.lang.ClassNotFoundException

java.io.IOException

...

faq: define sleep() method?


=>sleep() method is a PreDefined method from java.lang.Thread class and which is used to stop the program
execution temporarly on some time.

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
}
}
------------------------------------------------------------------------------

(ii)User defined Checked Exceptions:


=>The checked exceptions which are defined and raised by the programmer are known asUser defined Checked
Exceptions.

Use the following two steps to raise checked exception:


step-1 : Add 'throws' keyword to the method signature to ignore the exception in current method and raise at
method_call

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

EmployeeDesignation ed = new EmployeeDesignation("Invalid


desg...");
Page

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")

public class DException5 extends Exception

public DException5(String msg)

super(msg);

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

try

System.out.println("Enter the EmpName:");

String empName = s.nextLine();

System.out.println("Enter the empId:");

String empId = s.nextLine();

if(empId.length()!=4)//raise exception

DException5 de = new DException5("Invalid empId...");

throw de;

};

System.out.println("Enter the EmpDesg:");

String desg = s.nextLine().toUpperCase();

EmployeeDesignation ob = new EmployeeDesignation();


147

ob.verify(desg);//Checked Exception is raised


Page

System.out.println("Enter the bSal:");

147
int bSal = s.nextInt();

if(bSal<5000)//raise Exception

DException5 de = new DException5("Invalid bSal...");

throw de;

System.out.println("EmpName:"+empName);

System.out.println("EmpId:"+empId);

System.out.println("EmpDesg:"+desg);

System.out.println("EmpBSal:"+bSal);

float totSal = bSal+(0.93F*bSal)+(0.63F*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:

Update DException3.java by adding SubClass 'CheckBranch' and raising Checked exception.

Dt : 2/8/2021

Assignment:(Solution)
148

Update DException3.java by adding SubClass 'CheckBranch' and raising Checked exception.


Page

CheckBranch.java

148
package test;

@SuppressWarnings("serial")

public class CheckBranch extends Exception

public CheckBranch() {}

public CheckBranch(String msg) {

super(msg);

public void verify(String br)throws CheckBranch

try {

switch(br)

case "CSE":

break;

case "ECE":

break;

case "EEE":

break;

default://Exception raised

CheckBranch cb = new CheckBranch("Invalid Branch...");

throw cb;

}//end of switch

}//end of try

catch(CheckBranch cb)

throw cb;//re-throwing process

--------------------------------------------------------------------------------------------------------------------------------------------------

DException6.java
149

package maccess;
Page

import test.CheckBranch;

149
import java.util.*;

@SuppressWarnings("serial")

public class DException6 extends Exception

public DException6(String msg) {

super(msg);

public static void main(String[] args) {

try(Scanner s = new Scanner(System.in);)//Java7

try {

System.out.println("Enter the StuName:");

String stuName = s.nextLine();

System.out.println("Enter the branch:");

String br = s.nextLine().toUpperCase();

CheckBranch cb = new CheckBranch();

cb.verify(br);

System.out.println("Enter the StuRollNo:");

String stuRollNo = s.nextLine();

if(stuRollNo.length()!=10)//raise exception

DException6 ob1 = new DException6("Invalid rollNo...");

//Object created with the message "invalid rollNo..."

throw ob1;//throwing the object reference onto catch block

System.out.println("StuName:"+stuName);

System.out.println("StuRollNO:"+stuRollNo);

System.out.println("StuBranch:"+br);

}//end of try

catch(CheckBranch | DException6 ob)//Java7

{
150

System.out.println(ob.getMessage());
Page

150
}//End of try-with-resource

Exception re-throwing process


define Exception re-throwing process?

=>The process of declaring 'throw' keyword in catch block and performing throwing process is known as re-
throwing process.

=>In Exception re-throwing process,the exception is moved to the method_call.

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.

faq: wt is the diff b/w (i)throw (ii) throws


(i)throw

=>'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

wt are the components of Exception handling process?


=>try

=>catch

=>finally

=>throw

=>throws

-----------------------------------------------------------------------------------------------------------------------------------------------------------

Handling Multiple exceptions:


=>There are two ways to handle Multiple Exceptions in Java:

(a)we use Multiple Catch blocks to hold Multiple Exceptions

(b)we use Single Catch block to hold Multiple Exceptions

(a)we use Multiple Catch blocks to hold Multiple Exceptions:


=>we declare Multiple catch blocks to hold Multiple exceptions.

(b)we use Single Catch block to hold Multiple Exceptions:


=>From Java7(2011) version onwards we can use Single catch block to hold Multiple Exceptions.
151

syntax:
Page

catch(Exception1 | Exception2 | Exception3 | ... ref_var)

151
{

//msg

----------------------------------------------------------------------------------------------------------------------------------------------------------

define try-with-resource statement?


=>try-with-resource statement introduced by Java7(2011) and in which the resources are declared with 'try'.

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

program and no need to use 'finally' block.

=>In try-with-resource statement the catch block is an optional block.

-----------------------------------------------------------------------------------------------------------------------------------------------------

define 'Enhanced try-with-resource statement'?


=>'Enhanced try-with-resource statement' introduced by Java9(2017) version and in which resources are declared
outside the try and resource reference variables are declared with try.

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")

public class DException6 extends Exception

public DException6(String msg) {

super(msg);

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

try(s;)//Java9

try {

System.out.println("Enter the StuName:");

String stuName = s.nextLine();

System.out.println("Enter the branch:");

String br = s.nextLine().toUpperCase();

CheckBranch cb = new CheckBranch();

cb.verify(br);

System.out.println("Enter the StuRollNo:");

String stuRollNo = s.nextLine();

if(stuRollNo.length()!=10)//raise exception

DException6 ob1 = new DException6("Invalid rollNo...");

//Object created with the message "invalid rollNo..."

throw ob1;//throwing the object reference onto catch block

}
153

System.out.println("StuName:"+stuName);

System.out.println("StuRollNO:"+stuRollNo);
Page

153
System.out.println("StuBranch:"+br);

}//end of try

catch(CheckBranch | DException6 ob)//Java7

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:

Convert StudentMainClass into Exception handling process?

=====================================================================================

Polymorphism in Java:
=>The process in which the same programming having many forms is known as PolyMorphism.

Poly - Many

Morphism - Forms

=>This PolyMorphism is categorized into two types:

(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

stage is known Static PolyMorphism or CompileTime PolyMorphism.

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);;
}
}
------------------------------------------------------------------------------

The following keywords are under the control of Compiler at


Compilation Stage:
1.static

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

=>There is no concept of static Constructor.

2.private:
=>The following are the private programming components:

(a)private variables

(b)private methods

(c)private classes

(d)private Constructors

=>There is no concept of private blocks,private Interfaces and Private abstract classes.

(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

(POJO - Plain Old Java Object)

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'.

SingleTon class design pattern'


define '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'.

The following components are used in constructing 'SingleTon class design


pattern':
(i)private Constructor

(ii)private static reference variable

(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

(b)Late Instantiation process

(a)Early Instantiation process:


=>In Early Instantiation process the object is created while class loading.
159

=>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

public class DPoly5 {

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.

=>final variables inside the class can be initialized using constructor.

(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'.

---------------------------------------------------------------------------------------------------------------------------------------------

define 'Immutable classes'?


=>The classes which are constructed using the following rules are known as Immutable classes:

Rule-1 : The Class must be 'final' class

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

Rule-4 : These 'Getter methods' must be final methods


Page

161
Note:
=>These Immutable classes will generate Immutable Objects.

define Immutable objects?


=>The Objects once created cannot be modified are known as Immutable objects.(Secured Objects)

Note:
=>In realtime Immutable objects are used in Banking domain applications to hold Transaction details.

-----------------------------------------------------------------------------------------------------------------------------------------------------------

define 'Getter methods'?


=>The methods which are used to get the data from the objects are known as 'Getter methods'.

define 'Setter methods'?


=>The methods which are used to set the data to the objects are knwn as 'Setter methods'.

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;

public class DPoly6 {


Page

162
public static void main(String[] args) {

TransLog ob = new TransLog(6123456L,313131L,12000F,new Date());

//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

Data&Time:Fri Aug 06 04:45:03 PDT 2021

====================================================================================

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:

define factory methods?


=>The methods which are used to access the object reference by hiding the object

creation process from EndUser are known as Factory methods.

========================================================================================

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)

=>AbstractClass is a Collection of Primitive DataType variables,NonPrimitive DataType variables,concrete


methods,abstract 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 also known as UpCasting 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 Narrowing process is also known as DownCasting 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.

=>This Generalization process can also be done using Interfaces.

=>we use the following syntax to acheive Generalization process:

Syntax
PClass ob = (PClass)new CClass();

Interface ob = (Interface)new IClass();

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.

=>This Specialization process is not applicable to Interfaces.

=>We use the following syntax to acheive 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

5.Implcit TypeCasting process

6.Explicit TypeCasting 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,

1 - to bind int data

2 - to bind int data in the form of String

Constructor Signatures:
public java.lang.Integer(int);

public java.lang.Integer(java.lang.String)throws java.lang.NumberFormatException;

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,

1 - to bind its data

2 - to bind its data in the form of String

-------------------------------------------------------------------------------------------------------------------------------------------------------

Float WrapperClass:
=>Float WrapperClass having three Constructors,

1 - to bind float data

2 - to bind double data

3 - to bind float data in the form of String

Constructor Signatures:
public java.lang.Float(float);

public java.lang.Float(double);
169

public java.lang.Float(java.lang.String) throw java.lang.NumberFormatException;

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

and this AutoBoxing process introduced by Java5(2004) version.

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:

=>AutoBoxing process means assigning Primitive datatype values to NonPrimitive datatype

variables.

------------------------------------------------------------------------------------

Dt : 9/8/2021

faq:

define UnBoxing process?

=>The process of taking Primitive datatype values out of WrapperClass objects is known as

UnBoxing process.
171
Page

=>we use the following methods to perform UnBoxing process:

171
public byte byteValue();

public short shortValue();

public int intValue();

public long longValue();

public float floatValue();

public double doubleValue();

public char charValue();

public boolean booleanValue();

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:

define AutoUnBoxing process?

=>The UnBoxing process which is performed automatically is known as AutoUnBoxing process


172

and which is also introduced by Java5(2004) version.


Page

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:

=>AutoUnBoxing process means assigning NonPrimitive datatype variables to primitive

datatype variables.

--------------------------------------------------------------------------------------

Note:

=>WrapperClasses will provide the following parseXXXX() methods to convert String data

to primitive datatype values.

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

reason we make Primitive DataTypes available in the form of Objects.

FrameWorks:

JCF(Java Collection Framework)

Hibernate with JPA

...

-----------------------------------------------------------------------------------------------------------------------------------------------------

Note:

=>All the WrapperClass objects by default Immutable objects.(Secured objects)


174
Page

174
Strings in Java:

=>The Sequenced Collection of characters which are represented in double quotes is known

as String.

Exp:

"java","program",...

=>The Characters in the String are organized based on index values.

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

are by default 'Immutable objects'.(Secured Objects)

=>'String' class is having 16 Constructors.

Hierarchy of 'String':

=>we use the following two syntaxes to create objects from 'String' class:

syntax-1 : using String Literal process

String s1 = "java";
175

syntax-2 : using new operator process


Page

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());;
}
}
-----------------------------------------------------------------------------------------------------------------------------------------

String Concatenation process


=>The process of combining multiple Strings into a Single String is known as String Concatenetion Process.

=>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);
}
}

------------------------------------------------------------------------------

'String Constant pool'


=>The separate partition of heap area where the String objects are created is known as 'String Constant pool'.

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 Not-Available then new Object is created

=>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

reference of Object created in 'String Constant pool'.


Page

Diagram:

176
-----------------------------------------------------------------------------------

String Comparision process


=>The process of comparing two strings is known as String Comparision process.

=>The String Comparision process can be done the following three ways:

(i)Using 'equals()' method

(ii)Using 'compareTo()' method

(iii)Using 'is equal to'(==) operator

(i)Using 'equals()' method:


=>'equals()' method is used to compare two strings and generate boolean result.

Method Signature:

public boolean equals(java.lang.Object);

public boolean equalsIgnoreCase(java.lang.String);

Note:
=>In realtime these methods are used in Authentication process.

(ii)Using 'compareTo()' method:


=>'compareTo()' method also used to compare two Strings and generate int result.

Method Signature:

public int compareTo(java.lang.String);

public int compareToIgnoreCase(java.lang.String);

syntax:

int z = s1.compareTo(s2);
177

if z==0 then Strings are equals

if z>0 then s1>s2


Page

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.

=>'IgnoreCase' specify to compare the Strings without considering the case.

-----------------------------------------------------------------------------

(iii)Using 'is equal to'(==) operator:

=>'is equal to'(==) operator will compare the references of an objects and which will

not compare the content of an objects.

Exp program:

DString4.java
178

package maccess;
public class DString4 {
Page

public static void main(String[] args) {

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:

====String Literal process====

Strings are equal...

====new Operator process=====

Strings are Not-Equal...

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.

=>we use append() method to add data to the StringBuffer objects.

Hierarchy of StringBuffer class:

following are four constructors from 'StringBuffer' class:


public java.lang.StringBuffer();

public java.lang.StringBuffer(int);

public java.lang.StringBuffer(java.lang.String);

public java.lang.StringBuffer(java.lang.CharSequence);

case-1 : using 'StringBuffer()'


syntax:

StringBuffer sb = new StringBuffer();

=>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

StringBuffer sb = new StringBuffer();


System.out.println("default capacity:"+sb.capacity());
Page

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

---------------------------------------------------------------------------------------------------------------------------------------------------------

case-2 : Using 'StringBuffer(int)'


syntax:
StringBuffer sb = new StringBuffer(4);

=>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

-------------------------------------------------------------------------------------

case-3 : Using 'StringBuffer(java.lang.String)'


case-4: using 'StringBuffer(java.lang.CharSequence)'
syntax:
StringBuffer sb1 = new StringBuffer();

StringBuffer sb2 = new StringBuffer(sb1);

=>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.

Hierarchy of StringBuilder class:

following are four constructors from 'StringBuilder' class:


public java.lang.StringBuilder();

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.

define 'synchronized class'?


=>The class which is declared with synchronized methods is known as 'synchronized class'.

define 'synchronized methods'?


=>The methods which are declared with 'synchronized' keyword are known as synchronized methods.
184

wt is the behaviour of synchronized methods?


=>These synchronized methods will be under 'synchronized lock' and the methods are available to one user at-a-
Page

ime or one thread at-a-time

184
--------------------------------------------------------------------

Note:
StringBuffer - Synchronized and ThreadSafe class

StringBuilder - Non-Synchronized and Non-ThreadSafe class.

=>StringBuffer class is used in MultiThreading applications and StringBuilder class is

used in Non-MultiThreading.

==========================================================================================

There following are some classes realated to Strings:


(a)StringTokenizer class

(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");

Some methods of StringTokenizer class:


public boolean hasMoreTokens();
=>This method is used to check the token(piece) is available or not,and returns Boolean result.

public java.lang.String nextToken();


=>This method is used to retrieve the token(piece).

public int countTokens();


=>This method is used to display the number of tokens.

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:

Enter the String:

java is good programming language

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");

some methods of StringJoiner:

public java.util.StringJoiner add(java.lang.CharSequence);


=>This method is used to add the data to the StringJoiner object.

public int length();


=>This method is used to find the length of StringJoiner object.

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:

Enter the date:

22

Enter the Month:

01

Enter the Year:

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:

The following are some important methods of 'Object' class:


1.hashCode()

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.

=>we use hashCode() method to dipslay the hashCodes.

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

public java.lang.String toString();

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.

=>we use 'clone()' method to perform 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.

The following steps are used to perform cloning process:


step-1 : The user defined class must be implemented from 'java.lang.Cloneable' interface.

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

=>Cloneable is an empty interface because which donot have any members.


Page

=>Cloneable interface is also known as Markable interface or Tagging interface.

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:

(a)Shallow Cloning process

(b)Deep cloning process

(a)Shallow Cloning process:


=>The process of duplicating OuterClass objects without duplicating reffered class objects,is known as Shallow
Cloning process.

(b)Deep cloning process:


=>The process of duplicating both OuterClass objects and reffered class objects,is known as Deep Cloning
process.

wt is the advantage of Cloning process?


=>Using Cloning process we can take the backup of an objects and which is used part of Protection and Security.

------------------------------------------------------------------------------------

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)

=>Array is a sequenced collection of objects of same class.(Similar object)

Arrays in Java are categorized into two types:


1.Single Dimensional Arrays

2.Multi Dimensional Arrays

1.Single Dimensional Arrays:


=>The Arrays which are represented in single dimension are known as Single Dimensional Arrays.

syntax:
Class_name arr_var[] = new Class_name[size];

Exp:

Integer a[] = new Integer[3];

String str[] = new String[3];

Test t[] = new Test[3];

Object o[] = new Object[3];

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("====Old for loop===");


for(int i=0;i<o.length;i++) {
Page

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====

====Old for loop===

12

13

14

====Extended for====

12

13

14

====StringClassArray====

====Old for loop===

NIT

HYD

java

====Extended for====

NIT

HYD

java

====UserDefinedClassArray====

====Old for loop===

Raj 9898981234

Alex 77788866612
194

Ram 56453412
Page

194
====Extended for====

Raj 9898981234

Alex 77788866612

Ram 56453412

====ObjectClassArray====

====Old for loop===

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'.

=>This 'Extended for' can also be used on Arrays,Collection,Map and Enum

----------------------------------------------------------------------------------------------------------------------------------------------------

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.

--------------------------------------------------------------------------------------------------------------------------------------------------------

2.Multi Dimensional Arrays:


=>The Arrays which are declared with multiple dimensions are known as Multi-D Arrays.

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'.

define 'Jagged Array'?


=>The Array which is holding Array Objects is known as 'Jagged Array'.

syntax of 2-D Array:


Class_name arr_var[][] = new Class_name[rows][cols];

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:

=====Old For loop=====

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

=>This Dis-Advantage of Arrays can be overcomed using 'Collection'.


Page

-----------------------------------------------------------------------------------------------------------------------------------------------------------

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.

This Collection<E> interface extended into the following Sub-Interfaces:

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

index values and cannot hold duplicate elements.


Page

199
=>The following are some important methods from Set<E>:

public abstract int size();

public abstract boolean isEmpty();

public abstract boolean contains(java.lang.Object);

public abstract java.lang.Object[] toArray();

public abstract boolean add(E);

public abstract boolean remove(java.lang.Object);

public abstract java.util.Iterator<E> iterator();

public java.util.Spliterator<E> spliterator();

The following are the implementattion classes of Set<E>:


(a)HashSet<E>
(b)LinkedHashSet<E>
(c)TreeSet<E>

=>HashSet<E> organizes elements without any order.

=>LinkedHashSet<E> organizes elements in insertion order.

=>TreeSet<E> organizes elements in ascending order automatically.

=======================================================================================

2.List<E>:
=>List<E> is an interface from java.util package and which organizes elements with index values and can hold
duplicate elements.

=>The following are some important methods of List<E>:

public abstract int size();

public abstract boolean isEmpty();

public abstract boolean contains(java.lang.Object);

public abstract java.lang.Object[] toArray();

public abstract boolean add(E);

public abstract boolean remove(java.lang.Object);

public abstract E get(int);

public abstract E set(int, E);

public abstract void add(int, E);

public abstract E remove(int);

public abstract int indexOf(java.lang.Object);


200

public abstract int lastIndexOf(java.lang.Object);


Page

200
public abstract java.util.Iterator<E> iterator();

public abstract java.util.ListIterator<E> listIterator();

public java.util.Spliterator<E> spliterator();

The following are the implementattion classes of List<E>:


(a)ArrayList<E>
(b)LinkedList<E>
(c)Vector<E>
=>Stack<E>
====================================================================================

Exp program1:Demonstraing Set<E> holding WrapperClass Integer objects.

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

Enter the choice:

====Display Set<E>====

[10, 12, 17, 19]

-------------------------------------------------------------------------------

Exp program2:Demonstraing Set<E> holding String class objects.

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>====

[ABC, Hyd, Java, NIT]

---------------------------------------------------------------------------------

Exp program3:Demonstraing Set<E> holding User defined class objects.

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

Enter the choice:

====Display Set<E>====

A112 FDisk 567.34 9

A117 KeyB 678.89 10

A118 CDR 345.67 11

A125 Mouse 234.45 10

--------------------------------------------------------------------------------

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

the following Steps:


step-1 : The User defined class must be implemented from 'java.lang.Comparable' interface.

Structure of 'Comparable<T>':

public interface java.lang.Comparable<T>

{
204

public abstract int compareTo(T);


Page

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

Method Signature of sort():


public static <T> void sort(List<T>);

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:

-----------------------------------------------------------------------------------------

Exp program:(Demonstrating List<E> holding Integer WrapperClass Objects)

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

Enter the choice:

====Display Set<E>====

[12, 10, 17, 19, 12]

====Sorted List<E>====

[10, 12, 12, 17, 19]

-----------------------------------------------------------------------------------------------------------------------------------------------------------

(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

=>LinkedList<E> organizes elemnts in NonSequence and which is also NonSynchronized class.


Page

=>In LinkedList<E> the elements are available in the form of nodes.

206
Node is divided in to three parts:
(i)Previous Node Address

(ii)Data Value

(iii)Next Node Address

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());

LinkedList<Integer> ll = new LinkedList<Integer>();


ll.add(new Integer(12));
ll.add(new Integer(11));
ll.add(new Integer(16));
ll.add(new Integer(14));
System.out.println("====LinkedList<E>====");
System.out.println(ll.toString());
System.out.println("Index value of 11 : "+ll.indexOf(11));
System.out.println("Value at index 2 : "+ll.get(2));
ll.set(3,700);
System.out.println(ll.toString());
ll.add(1,300);
System.out.println(ll.toString());
}
}
207

o/p:
Page

====ArrayList<E>====

207
[12, 11, 16, 14]

Index value of 16 : 2

Value at index 1 : 11

[12, 11, 500, 14]

[12, 400, 11, 500, 14]

====LinkedList<E>====

[12, 11, 16, 14]

Index value of 11 : 1

Value at index 2 : 16

[12, 11, 16, 700]

[12, 300, 11, 16, 700]

------------------------------------------------------------------------------------

(c)Vector<E>:
=>Vector<E> also organizes elements in Sequence,but which is Synchronized class.

=>The following are some important methods of Vector<E>:

public synchronized int capacity();

public synchronized int size();

public synchronized E elementAt(int);

public synchronized E firstElement();


208

public synchronized E lastElement();


Page

public synchronized void setElementAt(E, int);

208
public synchronized void removeElementAt(int);

public synchronized void insertElementAt(E, int);

public synchronized void addElement(E);

public synchronized boolean removeElement(java.lang.Object);

public java.util.Enumeration<E> elements();

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

[12, 11, 10]

Capacity:10

Size:5

[12, 11, 10, 17, 18]

Capacity:10

Size:6

[12, 11, 10, 17, 18, 13]

Capacity:10

Size:7

[12, 11, 10, 17, 18, 13, 14]

Capacity:10

Size:8

[12, 11, 10, 17, 18, 13, 14, 8]

Capacity:10

Size:9

[12, 11, 10, 17, 18, 13, 14, 8, 7]

Capacity:10

Size:10

[12, 11, 10, 17, 18, 13, 14, 8, 7, 3]

Capacity:20

Size:11

[12, 11, 10, 17, 18, 13, 14, 8, 7, 3, 2]

Ele at index value 2:10

[12, 11, 500, 17, 18, 13, 14, 8, 7, 3, 2]

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>.

=>The elements in Stack<E> are organized based on the algorithm First-In-Last-Out.

=>The following are some important methods of Stack<E>:

public E push(E);

public synchronized E pop();

public synchronized E peek();

public boolean empty();

public synchronized int search(java.lang.Object);

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:

[12, 13, 14, 15]

peek element:15

Position of ele 13:3


211

[12, 13, 14]


Page

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>.

-------------------------------------------------------------

Vendor : Product developer(designing


product)

=>Algorithmic design available

Service : Product User(Using product and


constructing application)

-------------------------------------------------------------

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)

The following are the implementations of Queue<E> and Deque<E>:


(a)PriorityQueue<E>

(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

public class DemoQueue {

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>=====

[10, 12, 11, 14]

====ArrayDeque<E>=====

[23, 24, 21, 25]

[12, 23, 24, 21, 25, 56]

====LinkedDeque<E>=====

[23, 24, 2, 25]

[12, 23, 24, 2, 25, 56]

--------------------------------------------------------------------------------------------------------------------------------------------------

Limitation of Collection<E>:
=>Collection<E> can not hold data from the DataBase by differentiating Primary-Key andNonPrimary-Key values.

Note:
213

=>This limitation can be overcomed using Map<K,V> in Java.

===========================================================================================
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

=>The following are some important methods of Map<K,V>:

public abstract int size();

public abstract boolean isEmpty();

public abstract boolean containsKey(java.lang.Object);

public abstract boolean containsValue(java.lang.Object);

public abstract V get(java.lang.Object);

public abstract V put(K, V);

public abstract V remove(java.lang.Object);

public abstract java.util.Set<K> keySet();

public abstract java.util.Collection<V> values();

public abstract java.util.Set<java.util.Map$Entry<K, V>> entrySet();

public void forEach(java.util.function.BiConsumer<? super K, ? super V>);

The following are the implementation classes of Map<K,V>:


(a)HashMap<K,V>
(b)LinkedHashMap<K,V>
(c)TreeMap<K,V>
(d)Hashtable<K,V>

=>HashMap<K,V> and Hashtable<K,V> oraganizes elements without any order.

=>LinkedHashMap<K,V> organizes elements in Insertion order.

=>TreeMap<K,V> organizes elements automatically in Ascending order based on Primary-Key(Key)

=>Hashtable<K,V> is Synchronized class and remaining classes are NonSynchronized classes.

Exp program:(Demonstrating Map<K,V> object)

(Map<K,V> holding empId(Integer) and empName(String))

syntax:
214

Map<Integer,String> m = new HashMap<Integer,String>();


Page

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

Enter the choice:


215

3
Page

====Display from Map<k,V>====

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.

=>we use 'enum' keyword to declare enums.

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.

=>Enum<E> is less used when compared to Classes and Interfaces.


217
Page

217
=====================================================================================

Summary:
(a)Class

(b)Interface

(b)Array/Collection<E>/Map<K,V>

(c)Enum<E>

=======================================================================================

Objects Genarated from CoreJava:

1.User Defined class Objects

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

(c)User defined Class 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

----------------------------------------------------------------------------------

IO Streams and files:


Stream
=>The contineous flow of data is known as Stream.

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

1.Binary Stream(byte Stream):


=>The contineous flow of data in the form of 8-bits is known as Binary Stream or Byte Stream.

=>Binary Stream or Byte Stream supports all the multimedia data formats like Audio,video, image,animation and
text.

The following are some important classes related to binary Stream:


(i)DataInputStream

(ii)DataOutputStream

(iii)FileInputStream

(iv)FileOutputStream

(i)DataInputStream:

(i)DataInputStream
=>'DataInputStream' class is from 'java.io' package and which is used to read binary

stream into JavaProgram.

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:

wap to copy the file from one location to another location?

DemoFile1.java
220

package test;

import java.io.*;
Page

220
import java.util.*;

public class DemoFile1 {

public static void main(String[] args) {

Scanner s= new Scanner(System.in);

try(s;) {

System.out.println("Enter the fPath&fName(Source)");

File f1 = new File(s.nextLine());

if(f1.exists()) {

FileInputStream fis = new FileInputStream(f1);

System.out.println("Enter the fPath&fName(Destination)");

File f2 = new File(s.nextLine());

FileOutputStream fos = new FileOutputStream(f2);

try(fos;fis;){

int ch;

while((ch=fis.read())!=-1) {

fos.write(ch);

}//end of loop

System.out.println("File copied Successfully...");

}//Try with resource

}else{

System.out.println("Invalid fPath or fName...");

};

}catch(Exception e) {e.printStackTrace();}

o/p:

Enter the fPath&fName(Source)

C:\dddd.jpeg

Enter the fPath&fName(Destination)

E:\images\AAAA.jpeg

File copied Success fully...

--------------------------------------------------------------------------------------
221

Diagram:
Page

221
------------------------------------------------------------------------------------

2.Character Stream:
=>Th contineous flow of data in the form of 16-bits is known as Charcter Stream.

=>Character Stream is preferable for text data.

The following are some important classes related to character Stream:


(i)BufferedReader

(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

wap to read data from console and write into a file?


Page

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:

Enter the fPath&fName(destination)

E:\images\Text.txt

Enter the data:(@ at end)

java

program

language

task

thread

Data recorded into file....

====Display from file====

java

program

language
223

task

thread
Page

223
Dt : 25/8/2021

Digram of above program:

--------------------------------------------------------------------------------------------------------------------------------------------------------

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.

=>we use readObject() method from 'java.io.ObjectInputStream' to perform 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")

public class TransLog implements Serializable{

public long hAccNo,bAccNo;

public float amt;

public Date dateTime;

public TransLog(long hAccNo,long bAccNo,float amt,Date dateTime) {

this.hAccNo=hAccNo;

this.bAccNo=bAccNo;

this.amt=amt;

this.dateTime=dateTime;

public String toString() {

return "BAccNo:"+bAccNo+"\nHAccNo:"+hAccNo+"\nAmt:"+amt+"\nDate&Time:"+dateTime;

DemoSerialization.java

package test;

import java.io.*;

import java.util.*;

public class DemoSerialization {

public static void main(String[] args) {

try {

TransLog ob1 = new TransLog(6123456L,313131L,22345.67F,new Date());

File f = new File("E:\\images\\ojbstore.txt");

FileOutputStream fos = new FileOutputStream(f);

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(ob1);

System.out.println("Object Stored Successfully...");


225

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

(ii)we can store binary Stream in DataBase Storage

(iii)we can send binary Stream through Network

----------------------------------------------------------------------------------------------------------------------------------------------------------

Note:
=>'Throwable' is implemented from 'Serializable' indicates Exception Handling components support Serialization
process.

=>All WrapperClass objects Support Serialization process.

=>String,StringBuffer and StringBuilder objects Support Serialization process.

=>All Collection<E> objects support Serialization process

=>All Map<K,V> objects support Serialization process

=>Enum<E> objects Support Serialization


226
Page

226
227
Page
227
228
Page
228

You might also like