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

Java Complete Reference (2023)

Uploaded by

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

Java Complete Reference (2023)

Uploaded by

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

OBJECT ORIENTED PROGRAMMING THROUGH JAVA (20A05302T)

Academic Year : 2023-24


Branch : AI&DS (II YEAR)

Lecturer Notes

ADITYA COLLEGE OF ENGINEERING


MADANAPALLI

S. No Contents Page No
1 Academic Calendar 2
2 Syllabus , OOPJ COs , PEOs and JNTUA Approved Textbooks and Reference 3-4
Text Books
3 Theory Syllabus 5-8
4 Laboratory Syllabus 8-9
5 Assignment Questions 287-288
6 Old Question Papers (JNTUA-R20) 289-292
Syllabus & OOPJ COs, PEOs and PSOs
Course Code Object Oriented Programming Through Java L T P C
20A05302T (Common to CSE, IT, CSE (AI), CSE (AI & ML) and AI& 3 0 0 3
DS)
Pre-requisite Fundamental Programming Semester III

Course Objectives:
 To understand object oriented concepts and problem solving techniques
 To obtain knowledge about the principles of inheritance and polymorphism
 To implement the concept of packages, interfaces, exception handling and concurrency
mechanism.
 To design the GUIs using applets and swing controls.
 To understand the Java Database Connectivity Architecture
Course Outcomes (CO):
After completion of the course, students will be able to
 Solve real-world problems using OOP techniques.
 Apply code reusability through inheritance, packages and interfaces
 Solve problems using java collection framework and I/O classes.
 Develop applications by using parallel streams for better performance.
 Develop applets for web applications.
 Build GUIs and handle events generated by user interactions.
 Use the JDBC API to access the database

UNIT - I Introduction 8Hrs


Introduction: Introduction to Object Oriented Programming, The History and Evolution of Java,
Introduction to Classes, Objects, Methods, Constructors, this keyword, Garbage Collection, Data Types,
Variables, Type Conversion and Casting, Arrays, Operators, Control Statements, Method Overloading,
Constructor Overloading, Parameter Passing, Recursion, String Class and String handling methods.
UNIT - II Inheritance, Packages, Interfaces 9Hrs
Inheritance: Basics, Using Super, Creating Multilevel hierarchy, Method overriding, Dynamic Method
Dispatch, Using Abstract classes, Using final with inheritance, Object class,
Packages: Basics, Finding packages and CLASSPATH, Access Protection, Importing packages.
Interfaces: Definition, Implementing Interfaces, Extending Interfaces, Nested Interfaces, Applying
Interfaces, Variables in Interfaces.
UNIT - III Exception handling, Stream based I/O (java.io) 9Hrs
Exception handling - Fundamentals, Exception types, Uncaught exceptions, using try and catch, multiple
catch clauses, nested try statements, throw, throws and finally, built-in exceptions, creating own exception
subclasses.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading console
Input and Writing Console Output, File class, Reading and Writing Files, Random access file operations,
The Console class, Serialization, Enumerations, Autoboxing, Generics.
UNIT - IV Multithreading, The Collections Framework (java.util) 8Hrs
Multithreading: The Java thread model, Creating threads, Thread priorities, Synchronizing threads,
Interthread communication.
The Collections Framework (java.util): Collections overview, Collection Interfaces, The
Collectionclasses- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque. Hashtable,
Properties, Stack, Vector, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner.
UNIT - V Applet, GUI Programming with Swings, Accessing Databases 8Hrs
with JDBC
Applet: Basics, Architecture, Applet Skeleton, requesting repainting, using the status window, passing
parameters to applets
GUI Programming with Swings – The origin and design philosophy of swing, components and containers,
layout managers, event handling, using a push button, jtextfield, jlabel and image icon, the swing buttons,
jtext field, jscrollpane, jlist, jcombobox, trees, jtable, An overview of jmenubar, jmenu and jmenuitem,
creating a main menu, showmessagedialog, showconfirmdialog, showinputdialog, showoptiondialog,
jdialog, create a modeless dialog.
Accessing Databases with JDBC:
Types of Drivers, JDBC Architecture, JDBC classes and Interfaces, Basic steps in developing JDBC
applications, Creating a new database and table with JDBC.
Textbooks:
1. Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India) Pvt. Ltd.
2. Java How to Program, 10th Edition, Paul Dietel, Harvey Dietel, Pearson Education.
Reference Books:
1. Understanding Object-Oriented Programming with Java, updated edition, T. Budd, Pearson
Education.
2. Core Java Volume – 1 Fundamentals, Cay S. Horstmann, Pearson Education.
3. Java Programming for core and advanced learners, Sagayaraj, Dennis, Karthik andGajalakshmi,
University Press
4. Introduction to Java programming, Y. Daniel Liang, Pearson Education.
5. Object Oriented Programming through Java, P. Radha Krishna, University Press.
6. Programming in Java, S. Malhotra, S. Chaudhary, 2nd edition, Oxford Univ. Press.
7. Java Programming and Object-oriented Application Development, R.A. Johnson,
Cengage Learning.
Online Learning Resources:
https://www.w3schools.com/java/java_oop.asp
http://peterindia.net/JavaFiles.html

COURSE OUTCOMES (CO) : At the end of the course, the student will be able to :

CO1: Solve real-world problems using OOP techniques.

CO2: Apply code reusability through inheritance, packages and interfaces

CO3: Solve problems using java collection framework and I/O classes.

CO4: Develop applications by using parallel streams for better performance and Develop applets for
web applications
CO5: Build GUIs and handle events generated by user interactions and Use the JDBC API to access
the database

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs):


PEO I: To inculcate the adaptability skills into the students for software design, software development or any
other allied fields of computing.
PEOII: To equip the graduates with the ability to analyze, design and synthesize data to create novel products.

PEO III: Ability to understand and analyze engineering issues in a broader perspective with ethical
responsibility towards sustainable development.

PEO IV: To empower the student with the qualities of effective communication, team work, continues learning
attitude, leadership needed for a successful computer professional.
Index

Unit-I

S.No Name of the Topic Page No Date


1.1 Introduction to Object Oriented Programming 10
1.2 The History and Evolution of Java 11-17
1.3 Introduction to Classes, Objects 17-18
1.4 Methods 19-23
1.5 Constructors 23-25
1.6 this keyword 26-28
1.7 Garbage Collection 29-30
1.8 Data Types 30-32
1.9 Variables 33-34
1.10 Type Conversion and Casting 34-35
1.11 Arrays 36-38
1.12 Operators 39-42
1.13 Control Statements 43-54
1.14 Method Overloading 54-55
1.15 Constructor Overloading 56-57
1.16 Parameter Passing 57-58
1.17 Recursion 59-60
1.18 String Class and String handling methods. 61-64

Unit-II

S.No Name of the Topic Page No Date


2.1 Inheritance Basics 65-72
2.2 Using Super 73-75
2.3 Creating Multilevel hierarchy Refer Inheritance
2.4 Method overriding 76-77
2.5 Dynamic MethodDispatch (Runtime Polymorphism) 78-80
2.6 Using Abstract classes 81-83
2.7 Using final with inheritance 84-85
2.8 Object class 86-89
2.9 Packages Basics 89-90

Object Oriented Programming Through Java Page 5


2.10 Finding packages and CLASSPATH 91
2.11 Access Protection 91-92
2.12 Importing packages 93-96
2.13 Interfaces 96
2.14 Implementing Interfaces 97
2.15 Extending Interfaces 98
2.16 Nested Interfaces 99
2.17 ApplyingInterfaces 99
2.18 Variables in Interfaces 100

Unit-III

S.No Name of the Topic Page No Date


3.1 Fundamentals 101-102
3.2 Exception types 102,106-108
3.3 Uncaught exceptions 103
3.4 using try and catch 108-109
3.5 multiple catch clauses 110
3.6 nested try statements 111-112
3.7 throw, throws and finally 113-119
3.8 built-in exceptions 106-108
3.9 creating own exceptionsubclasses. 119-120
3.10 The Stream classes 121-122
3.11 Byte streams and Character streams 123-125
3.12 Reading console Input and Writing Console Output, 126-128
3.13 File class 128-130
3.14 Reading and Writing Files 131-133
3.15 Random access file operations 134-135
3.16 The Console class 136-137
3.17 Serialization 137-139
3.18 Enumerations 140-141
3.19 Autoboxing 142-143
3.20 Generics. 144-145

Object Oriented Programming Through Java Page 6


Unit-IV

S.No Name of the Topic Page No Date


4.1 The Java thread model 148-149
4.2 Creating threads 149-152
4.3 Thread priorities 152-154
4.4 Synchronizing threads 154-157
4.5 Interthread communication 157-160
4.6 Collections overview 160
4.7 Collection Interfaces 161
The Collection classes
4.8 Array List 162-163
4.9 Linked List 164
4.10 Hash Set 165
4.11 Tree Set 166
4.12 Priority Queue 167
4.13 Array Deque 168
4.14 HashTable 169
4.15 Properties 170
4.16 Stack 171
4.17 Vector 172
4.18 StringTokenizer 173
4.19 BitSet 173-174
4.20 Date 175
4.21 Calendar 175-176
4.22 Random 176-177
4.23 Formatter 177-178
4.24 Scanner 179

Object Oriented Programming Through Java Page 7


Unit-V

S.No Name of the Topic Page No Date


5.1 Applet Basics 180
5.2 Applet Architecture 181
5.3 Applet Skeleton 181-183
5.4 requesting repainting 183
5.5 using the status window 184
5.6 passing parameters to applets 185
5.7 The origin and design philosophy of swing 186
5.8 components and containers 186-187
5.9 layout managers 187-189
5.10 event handling using a push button 190-191
5.11 jtextfield, jlabel and image icon 192-194
5.12 the swing buttons, jscrollpane, jlist, jcombobox, trees, 195-202
5.13 An overview of jmenubar, jmenu and jmenuitem 203
5.14 creating a main menu 203-205
5.15 showmessagedialog, showconfirmdialog, 205-209
showinputdialog, showoptiondialog, jdialog
5.16 create a modeless dialog. 210
5.17 Types of Drivers 211
5.18 JDBC Architecture 213-214
5.19 JDBC classes and Interfaces 214-215
5.20 Basic steps in developing JDBC applications 215-216
5.21 Creating a new database and table with JDBC 216-219

Laboratory Syllabus
S. Exp Name of the experiment Page Date signature
no no No
1 I a) Installation of Java software, Use Eclipse IDE with the various 220-
menus. 221
Write a java program to find prime numbers between 1 to n.
I b) Write a Java program that prints all real solutions to the quadratic 222
equation ax2+bx+c=0
I c) Write a Java application to generate Electricity bills 224
I d) Write a Java program to multiply two given matrices 228
2 II a) Write Java program on use of inheritance, preventing inheritance 230
using final, abstract classes
II b) Write Java program on dynamic binding, differentiating method 233
overloading and overriding
II c) Develop a java application to implement currency converter 235

Object Oriented Programming Through Java Page 8


3 III Write Java program that inputs 5 numbers, each between 10 and 100 239
a) inclusive (duplicates not allowed)
III Write a Java Program to create an abstract class 241
b)
III Write a Java program to read the time intervals 243
c)
4 IV Write a Java program to implement user defined exception handling 246
5 V a) Write a Java program that creates a user interface to perform integer 248
division
V Write a Java program that creates three threads 250
b)
6 VI Write a java program to split a given text file into n parts 252
a)
VI Write a Java program that reads a file name from the user 254
b)
7 VI Write a java program that displays the number of characters, lines 256
a) and words in a text file
VI Write a java program that reads a file and displays the file on the 257
b) screen with line number before each line
8 VIII Write a Java program that correctly implements the producer- 259
a) consumer problem
VIII Develop a Java application for stack operations 261
b)
VIII Develop a Java application to perform Addition, Division, 263
c) Multiplication and subtraction
9 IX Develop a Java application for the blinking eyes and mouth should 265
a) open while blinking
IX Develop a Java application that simulates a traffic signals 267
b)
10 X Develop a Java application to implement the opening of a door 269
a)
X Develop a Java application by using JtextField to read decimal values 271
b) and converting a decimalnumber into a binary number
11 XI Develop a Java application that handles all mouse events 274
a)
XI Develop a Java application to demonstrate the key event handlers 276
b)
12 XII Develop a Java application to find the maximum value using generics 277
a)
XII Develop a Java application that works as a simple calculator 279
b)
13 XIII A Java application to establish a JDBC connection 284

Object Oriented Programming Through Java Page 9


Java Introduction

 Java is a high level, object-oriented and a secure and stable programming language but it is not a pure
object-oriented language because it supports primitive data types like int, char etc.
 Java is a platform-independent language because it has runtime environment i.e JRE and API.
Here platform means a hardware or software environment in which an application runs.
Java codes are compiled into byte code or machine-independent code.
 This byte code is run on JVM (Java Virtual Machine).
 Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java.
 Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and
his team changed the name from Oak to Java.

HISTORY OF JAVA

 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
 Originally designed for small, embedded systems in electronic appliances like set-top boxes.
 Firstly, it was called "Greentalk" by James Gosling.After that, it was called Oak
 Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc.
 In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
 Java is an island of Indonesia where first coffee was produced (called java coffee).
 Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.

Object Oriented Programming Through Java Page 10


Java Version History & Evolution

1) JDK Alpha and Beta (1995)


2) JDK 1.0 (23rd Jan 1996)
3) JDK 1.1 (19th Feb 1997)
4) J2SE 1.2 (8th Dec 1998)
5) J2SE 1.3 (8th May 2000)
6) J2SE 1.4 (6th Feb 2002)
7) J2SE 5.0 (30th Sep 2004)
8) Java SE 6 (11th Dec 2006)
9) Java SE 7 (28th July 2011)
10) Java SE 8 (18th Mar 2014)
11) Java SE 9 (21st Sep 2017)
12) Java SE 10 (20th Mar 2018)
13) Java SE 11 (September 2018)
14) Java SE 12 (March 2019)
15) Java SE 13 (September 2019)
16) Java SE 14 (Mar 2020)
17) Java SE 15 (September 2020)
18) Java SE 16 (Mar 2021)
19) Java SE 17 (September 2021)
20) Java SE 18 ( March 2022)
21) Java SE 19 (September 2022)
22) Java SE 20 ( March 2023)
Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version is release
in March month and an odd version released in September month.

Application of Java
 Java is not only used in softwares but is also widely used in designing hardware
 There are more than 930 million JRE downloads each year and 3 billion mobile phones run java.
Following are some other usage of Java :
1. Developing Desktop Applications
2. Web Applications like Linkedin.com, Snapdeal.com etc
3. Mobile Operating System like Android
4. Robotics and games etc.

Object Oriented Programming Through Java Page 11


Types of Java Application

Following are different types of applications that we can develop using Java:

1. Standalone Applications

The standalone application is also known as Java GUI Applications or Desktop Applications which uses
some standard GUI components such as AWT(Abstract Windowing Toolkit), swing and JavaFX and this
component are deployed to the desktop.
These components have buttons, menu, tables, GUI widget toolkit, 3D graphics etc.

Example: Media player, antivirus, Paint, POS (point of sale) Billing software, etc.

2. Web Applications

Web Applications are the client-server software application which is run by the client.
Servlets, JSP, Spring, hibernate etc. are used for the development of a client-server application.
eCommerce application is also developed in java using eCommerce platform

Example: e-mail, e-commerce website, bank website etc.

3. Enterprise Application

Enterprise application is middleware applications.


To use software and hardware systems technologies and services across the enterprises.
It is designed for the corporate area such as banking business systems.

Example: e-commerce, accounting, banking information systems etc.

4. Mobile Application

For mobile applications, Java uses ME or J2ME framework.


This framework are the cross platform that runs applications across phones and smart phones.
Java provides a platform for application development in Android too.

Example: WhatsApp , Twitter .. etc

Object Oriented Programming Through Java Page 12


Java Platforms / Editions
What is a Platform?

Platform is a hardware or software environment in which a program runs.


Java has its own run time environment known as JRE(Java Run-time Environment) and Java Virtual
Machine(JVM) which converts Java code to machine code.
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io,
java.net, java.util, java.sql, java.math etc.
It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream,
Networking, AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise applications.
It is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
Features of Java or Buzz words
The features of java are :
1) Simple
 Java is easy to learn and its syntax is quite simple, clean and easy to understand.
 The confusing concepts of C++ are either left out in Java or they have been re-implemented in a cleaner
way.
2) Object Oriented
 In java, everything is an object which has some data and behaviour.
Following are some basic concept of OOP's.
Objects , Classes , Inheritance , Polymorphism , Abstraction and Encapsulation
3) Robust
 Java makes an effort to eliminate error level codes by focusing mainly on compile time error checking
and runtime errors checking.
 But the main areas which Java improved were Memory Management and mishandled Exceptions by
introducing automatic Garbage Collector and Exception Handling.

Object Oriented Programming Through Java Page 13


4) Platform Independent
 Unlike other programming languages such as C, C++ etc which are compiled into platform specific
machines. Java is guaranteed to be write-once, run-anywhere language (WORA).
 On compilation Java program is compiled into bytecode.
 This bytecode is platform independent and can be run on any machine, plus this bytecode format also
provide security. Any machine with Java Runtime Environment can run Java Programs.

5) Secure
 When it comes to security, Java is always the first choice.
 With java secure features it enable us to develop virus free, temper free system.
6) Multi Threading
 Java multithreading feature makes it possible to write program that can do many tasks simultaneously.
 Benefit of multithreading is that it utilizes same memory and other resources to execute multiple threads
at the same time, like While typing, grammatical errors are checked along.
7) Portable
 Java Byte code can be carried to any platform and no implementation dependent features.
 Everything related to storage is predefined, example: size of primitive data types
8) High Performance
 Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
 But, Java enables high performance with the use of just-in-time compiler.
9) Distributed
 Java is also a distributed language. Programs can be designed to run on computer networks.
 Java has a special class library for communicating using TCP/IP protocols.
 Creating network connections is very much easy in Java as compared to C/C++.
10. Dynamic
 Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.
 Java supports dynamic compilation and automatic memory management (garbage collection).

Object Oriented Programming Through Java Page 14


Java Terminology
JVM (Java Virtual Machine)
 It is a software and that provides runtime environment in which java bytecode can be executed.
 It not physically exists and JVMs are not same for all hardware and software, for example for window
OS JVM is different and for Linux JVM is different.
 JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is
platform independent .
Operation of JVM
JVM mainly performs following operations.
 Allocating sufficient memory space for the class properties.
 Provides runtime environment in which java bytecode can be executed
 Converting byte code instruction into machine level instruction.
JVM is separately available for every Operating System while installing java software so that JVM is
platform dependent.
Note: Java is platform Independent but JVM is platform dependent because every Operating system have
different-different JVM which is install along with JDK Software.
What is Java Bytecode?
 As soon as a java program is compiled, java bytecode is generated. In more suitable terms, java
bytecode is the machine code in the form of a .class file.
How does it works?
 When we write a program in Java, firstly, the compiler compiles that program and a bytecode is
generated for that piece of code.
 When we wish to run this .class file on any other platform, we can do so. After the first compilation, the
bytecode generated is now run by the Java Virtual Machine and not the processor in consideration.
 This essentially means that we only need to have basic java installation on any platforms that we want to
run our code on.
 Resources required to run the bytecode are made available by the Java Virtual Machine, which calls the
processor to allocate the required resources.
Java Development Kit(JDK):
 As the name suggests, it is a complete Java development kit that includes everything including compiler,
Java Runtime Environment (JRE), java debuggers, java docs, etc.
 For the program to execute in java, we need to install JDK on our computer in order to create, compile
and run the java program.
Java Runtime Environment (JRE):
For running the java program, a computer needs JRE.

Object Oriented Programming Through Java Page 15


OOP Concepts in Java
The object-oriented programming paradigm has the following core concepts.
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#, Python, etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit (object / class).
In programming, data is defined as variables and code is defined as methods. In OOP, every object is associated
with its data and code. The java programming language uses the class concept to implement encapsulation.
Inheritance
 Inheritance is the process of acquiring properties and behaviors from one object to another object or one
class to another class.
 In the inheritance concept, the class which provides properties is called as parent class or base class or
super class and the class which receives the properties is called as child class or derived class or sub
class.
 In the inheritance, the properties and behaviors of base class extended to its derived class, but the base
class never receive properties or behaviors from its derived class.
 Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Polymorphism
Polymorphism is the process of defining same method with different implementation. That means
creating multiple methods with different behaviors.
 The java uses method overloading and method overriding to implement polymorphism.
 Method overloading - multiple methods with same name but different parameters.
 Method overriding - multiple methods with same name and same parameters but different method body
Abstraction
Abstraction is hiding the internal details and showing only essential functionality.
In the abstraction concept, we do not show the actual implementation to the end user, instead we provide only
essential things.
For example, if we want to drive a car, we does not need to know about the internal functionality like how
wheel system works? how brake system works? how music system works? etc.

Object Oriented Programming Through Java Page 16


Java Scanner Class
 Scanner class belongs to java.util package.
 Java Scanner class allows the user to take input from the console(screen).
 It is used to read the input of primitive types like int, double, long, short, float, and byte.
Syntax
Scanner scan = new Scanner(System.in);
 The above statement creates a constructor of the Scanner class having System.in as an argument.
 It means it is going to read from the standard input stream of the program.
 The java.util package should be import while using Scanner class.
Methods of Java Scanner Class
Java Scanner class provides the following methods to read different primitives types:
Method Description

int nextInt() It is used to scan the next token of the input as an integer.

float nextFloat() It is used to scan the next token of the input as a float.

double nextDouble() It is used to scan the next token of the input as a double.

byte nextByte() It is used to scan the next token of the input as a byte.

String nextLine() Advances this scanner past the current line.

boolean nextBoolean() It is used to scan the next token of the input into a boolean value.

long nextLong() It is used to scan the next token of the input as a long.

short nextShort() It is used to scan the next token of the input as a Short.

BigInteger nextBigInteger() It is used to scan the next token of the input as a BigInteger.

BigDecimal nextBigDecimal() It is used to scan the next token of the input as a BigDecimal.

CLASS & OBJECT


Class:
Class is a blue print which is containing only list of variables and methods. When we declare a class no
memory is allocated. A class in java contains:
 Data Members
 Methods
 Constructors
 Blocks
 Class and Interface

Object Oriented Programming Through Java Page 17


Syntax
class Class_Name
{
data members;
methods;
}
Object:
 Object is a instance (allocating memory) of class and object has state and behaviors.
 The objectName must begin with an alphabet, and a Lower-case letter is preferred.
 We can create any no.Of objects for any class
An Object in java has three characteristics:
State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID.
Syntax
<ClassName> <objectName> = new <ClassName>( );

Simple Example
class Ex1
{
int a;
public static void main(String args[])
{
Ex1 e = new Ex1();
e.a = 10;
System.out.println(" number= "+e.a);
}
}
Output: number=10
Difference between Class and Object

Class Object

Class is a container which collection of variables


1 object is a instance of class
and methods.

No memory is allocated at the time of Sufficient memory space will be allocated for all
2
declaration the variables of class at the time of declaration.

One class definition should exist only once in the


3 For one class multiple objects can be created.
program.

Object Oriented Programming Through Java Page 18


Java Methods
Definition:

 A method is a block of statements which are used to perform a specific task .


 Method gets executes only when it is called.
 Every method in java must be declared inside a class.
 The major advantage of methods is code re-usability (define the code once, and use it many times).

Method Declaration

It has six components that are known as method header

Method Signature:
Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Return Type:
Return type is a data type that the method returns.
It may have a primitive data type, object, collection, void, etc.
If the method does not return anything, we use void keyword.
Method Name:
It is a unique name that is used to define the name of a method.
Parameter List:
It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name.
If the method has no parameter, left the parentheses blank.
Method Body:
It is a part of the method declaration.
It contains all the actions to be performed. It is enclosed within the pair of curly braces.

Object Oriented Programming Through Java Page 19


Types of Methods
There are two types of methods in Java:
 Predefined Method

 User-defined Method

Predefined Methods
 As the name gives it, predefined methods in Java are the ones that the Java class libraries already define.
 This means that they can be called and used anywhere in our program without defining them.
 There are many predefined methods, such as length(), sqrt(), max(), and print(), and each of them is
defined inside their respective classes.

Output:
The Square root is : 5
Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.print("The maximum number is: " + Math.max(9,7)); // using max() method of Math class

}
}
Output: The maximum number is: 9

Object Oriented Programming Through Java Page 20


User-defined Method
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. The calling of a method in a program is simple.
When we call or invoke(call) a user-defined method, the program control transfer to the called method.
Syntax
<Objectname>.methodname(actualarguments);

//Example1
class A
{
int a,b,c;
void sum()
{
a=10;
b=20;
c=a+b;
System.out.println(" c= "+c);
}
}
class B
{
public static void main(String ars[])
{
A e = new A();
e.sum();
}
}
Output: c=30
Methods in Java can also be classified into the following types:
 Static Method

 Instance Method

 Abstract Method

 Factory Method

 Native method

Object Oriented Programming Through Java Page 21


Static Method
 We can create a static method by using the keyword static before the method name.
 The static method is that we can call it without creating an object by using <class name>.<methodname>
Example of static method
Display.java
public class Display
{
public static void main(String[] args)
{
show();
}

static void show()


{
System.out.println("It is an example of static method.");
}
}

Output: It is an example of a static method.


Instance Method
 The method of the class is known as an instance method. It is a non-static method defined in the class.
 Before calling the instance method, it is necessary to create an object of its class.
InstanceMethodExample.java
public class InstanceMethodExample
{
public static void main(String [] args)
{
InstanceMethodExample obj = new InstanceMethodExample(); //Creating an object of the class
System.out.println("The sum is: "+obj.add(12, 13)); //invoking instance method
}

public int add(int a, int b) //user-defined method because we have not used static keyword
{
s = a+b; //returning the sum
return s;
}
}
Output: The sum is: 25

Object Oriented Programming Through Java Page 22


Abstract Method

 The method that does not has method body is known as abstract method.
 In other words, without an implementation is known as abstract method.
 It always declares in the abstract class. It means the class itself must be abstract if it has abstract
method.
 To create an abstract method, we use the keyword abstract.
Syntax
abstract void method_name();
Factory method
It is a method that returns an object to the class to which it belongs. All static methods are factory methods.
NumberFormat obj = NumberFormat.getNumberInstance();
Native method
 A native method in Java is used to merge the efficiency and functions of C and C++ in the Java
program.
 When the Java compiler did not implement or support some function, then, in that case, to increase the
performance of the Java application, the native methods are used.

Syntax: public / protected / private] native [return-type] methodName ();

Constructors
 Constructor is a special type of method and Constructor name must be same as its class name
 Constructor is used to initialize the object.
 constructor is invoked (called) automatically when we create the object creation.
 It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
 Constructor name must be same as its class name
 Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
 Default constructor (no-arg constructor)
 Parameterized constructor

Object Oriented Programming Through Java Page 23


Default Constructor
 A constructor is said to be default constructor if and only if it never take any parameters.
 If any class does not contain at least one user defined constructor than the system will create a default
constructor at the time of compilation it is known as system defined default constructor.
Syntax
class className
{
className () // Call default constructor
{
Block of statements; // Initialization
}
}
Note:
System defined default constructor is created by java compiler and does not have any statement in the body
part. This constructor will be executed every time whenever an object is created if that class does not contain
any user defined constructor.
Example :
//TestDemo.java
class Test
{
int a, b;
Test ()
{
System.out.println("I am from default Constructor...");
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
}
class TestDemo
{
public static void main(String [] args)
{
Test t1=new Test ();
}
}
Output:
I am from default Constructor...
Value of a: 10
Value of b: 20

Object Oriented Programming Through Java Page 24


parameterized constructor
 If any constructor contain list of variable in its signature is known as paremetrized constructor.
 A parameterized constructor is one which takes some parameters.
Syntax
class ClassName
{
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}
Syntax
ClassName objref = new ClassName(value1, value2, .... );
Example
class Test
{
int a, b;
Test(int n1, int n2)
{
System.out.println("I am from Parameterized Constructor...");
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
}
class TestDemo1
{
public static void main(String k [])
{
Test t1=new Test(10, 20);
Test t2=new Test(4,5);
}
}
Output:
I am from Parameterized Constructor...
Value of a = 10
Value of b = 20
I am from Parameterized Constructor...
Value of a = 4
Value of b = 5

Object Oriented Programming Through Java Page 25


this keyword in Java

In Java, this is a reference variable that refers to the current object.


Usage of Java this keyword
Here is given the 3 usage of java this keyword.
1. To refer current class instance variable
2. To invoke current class method
3. To invoke current class constructor
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Note: If parameters (formal arguments) and instance variables are same. So, we are using this keyword to
distinguish local variable and instance variable.
Example:
class Robo
{
int x,y,total;
void add(int x,int y)
{
this.x=x;
this.y=y;
total=x+y;
System.out.println("sum="+total);
}
}
class Mrobo
{
public static void main(String args[])
{
Robo r = new Robo();
r.add(20,30);
}
}
Note:
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword
like in the following program:

Object Oriented Programming Through Java Page 26


2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword.
If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.

class A
{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m(); //same as this.m()
this.m();
}
}
class TestThis4
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}
Output:
hello n
hello m

3) this() : to invoke current class constructor

 The this() constructor call can be used to invoke the current class constructor.
 It is used to reuse the constructor. In other words, it is used for constructor chaining.
 Rule: Call to this() must be the first statement in constructor.

Object Oriented Programming Through Java Page 27


Calling default constructor from parameterized constructor:
class A
{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5
{
public static void main(String args[])
{
A a=new A(10);
}
}
Output:
hello a
10
Calling parameterized constructor from default constructor:

class A
{
A()
{
this(5);
System.out.println("hello a");
}
A(int x)
{
System.out.println(x);
}
}
class TestThis6
{
public static void main(String args[])
{
A a=new A();
}
}
Output:
5
hello a

Object Oriented Programming Through Java Page 28


Java Garbage Collection
 Garbage Collection is process of reclaiming unused memory automatically at runtime.
 garbage means unreferenced objects , it is a way to destroy the unused objects.
Advantages
 It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
 By nulling the reference

 By assigning a reference to another …etc

1) By nulling a reference:
Employee e = new Employee();
e = null;
2) By assigning a reference to another:

Employee e1 = new Employee();


Employee e2 = new Employee();
e1=e2; //now the first object referred by e1 is available for garbage collection
finalize() method
 The finalize() method is invoked each time before the object is garbage collected.
 This method can be used to perform cleanup processing.
 This method is defined in Object class as protected void finalize(){}
Note:
The Garbage collector of JVM collects only those objects that are created by new keyword.
So if you have created any object without new, you can use finalize method to destroying remaining objects.
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
public static void gc(){}
Note:
Garbage collection is performed by a daemon thread called Garbage Collector(GC).
This thread calls the finalize() method before object is garbage collected.

Object Oriented Programming Through Java Page 29


public class TestGarbage1
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1 = new TestGarbage1();
TestGarbage1 s2 = new TestGarbage1();
s1 = null;
s2 = null;
System.gc();
}
}
Output: object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.
DATATYPES
In java, there are two types of data types
 primitive data types
 non-primitive data types

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte

Object Oriented Programming Through Java Page 30


float 0.0f 4 byte
double 0.0d 8 byte
byte
 byte data type is a 8-bit signed two's complement integer
 Minimum value is : -128 (-2^7)
 Maximum value is : 127 (inclusive)(2^7 -1)
 Default value is : 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an int
Syntax :
byte Variable_Name = Value;
short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is : -32,768 (-2^15)
 Maximum value is : 32,767(inclusive) (2^15 -1)
 Default value is : 0
 Short data type can also be used to save memory. A short is 2 times smaller than an int
Syntax : short Variable_Name = Value;
int
 Int data type is a 32-bit signed two's complement integer
 Minimum value is : -2,147,483,648.(-2^31)
 Maximum value is : 2,147,483,647(inclusive).(2^31 -1)
 Default value is : 0
 int is generally used as the default data type for integral values unless there is a concern
about memory
Syntax :
int Variable_Name = Value;
long
 Long data type is a 64-bit signed two's complement integer
 Minimum value is : -9,223,372,036,854,775,808.(-2^63)
 Maximum value is : 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 Default value is : 0L
 This type is used when a wider range than int is needed
Syntax :
long Variable_Name = Value_L;
float
 float data type is a single-precision 32-bit IEEE 754 floating point
 Default value is : 0.0f
 Float data type is never used for precise values such as currency
 Float is mainly used to save memory in large arrays of floating point numbers
Syntax :
float Variable_Name = (float) Value;
double
 double data type is a double-precision 64-bit IEEE 754 floating point
 Default value is : 0.0d
 Double data type should never be used for precise values such as currency
 This data type is generally used as the default data type for decimal values. generally the
default choice
Syntax :
double Variable_Name = Value;

Object Oriented Programming Through Java Page 31


boolean
 boolean data type represents one bit of information
 There are only two possible values : true and false
 This data type is used for simple flags that track true/false conditions
 Default value is : false
Syntax :
boolean Variable_Name = Value (true/false);
char
 char data type is a single 16-bit Unicode character
 Minimum value is : '\u0000' (or 0)
 Maximum value is : '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character
Note:
It is because java uses Unicode system not ASCII code system.
The \u0000 is the lowest range of Unicode system. Unicode is a 16-bit character encoding standard.
Syntax :
char Variable_Name = Value;
Example:
public class Main2
{
public static void main(String[] args)
{
int myNum = 5; // integer (whole number)
float myFloatNum = 5.99f; // floating point number
char myLetter = 'D'; // character
boolean myBool = true; // boolean
String myText = "Hello"; // String
System.out.print(" "+myNum);
System.out. print(" "+myFloatNum);
System.out. print(" "+myLetter);
System.out. print(" "+myBool);
System.out. print(" '"+myText);
}
}
Output:
D:\ACEM\java23batch\cse_a>javac main2.java

D:\ACEM\java23batch\cse_a>java Main2
5 5.99 D true 'Hello

Object Oriented Programming Through Java Page 32


VARIABLES
 Variable is a name of memory location.
 A variable is a container which holds the value while the Java program is executed.
 It is a combination of "vary + able" which means its value can be changed.
Example:
int data=50;//Here data is variable
Types of Variable
There are three types of variables in java

Local Variable
A variable that is declared inside the method is called local variable.
//local Variable Example

class LocalVariable
{
public static void main(String args[])
{
int a=10;
System.out.println(a);
}
}

Instance Variable

A variable that is declared inside the class but outside the method is called instance variable . It is not
declared as static.
//Instance variable Example
class InstanceVariable
{
int a=10;

public static void main(String args[])


{
InstanceVariable d = new InstanceVariable();
System.out.println(d.a);
}
}

Object Oriented Programming Through Java Page 33


Static variable
A variable that is declared as static is called static variable. It cannot be local.
//Static variable Example
class StaticVariable
{
static int a = 1;
public static void main(String args[])
{
System.out.println(a);
}
}
Type Casting and Type Conversion
Type casting
Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
There are two types of type casting:
 Widening Type Casting(Type Conversion)
 Narrowing Type Casting(Type Casting)
Widening Type Casting
 Converting a lower data type into a higher one is called widening type casting.
 It is also known as implicit conversion or casting down.
 It is done automatically. It is safe because there is no chance to lose data.
It takes place when:
 Both data types must be compatible with each other.

 The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done automatically.
Also, the char and Boolean data types are not compatible with each other.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
long y = x; //automatically converts the integer type into long type
float z = y; //automatically converts the long type into float type

System.out.println("Before conversion, int value "+x);


System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Object Oriented Programming Through Java Page 34
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0

Narrowing Type Casting

 Converting a higher data type into a lower one is called narrowing type casting.
 It is also known as explicit conversion or casting up and it is done manually by the programmer.
 If we do not perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.

NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
long l = (long)d; //converting double data type into long data type
int I = (int)l; //converting long data type into int data type

System.out.println("Before conversion: "+d);


System.out.println("After conversion into long type: "+l); //fractional part lost
System.out.println("After conversion into int type: "+i); //fractional part lost

}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

Object Oriented Programming Through Java Page 35


Java Arrays

 An array is a collection of similar data values with a single name.


 An array can also be defined as, a special type of variable that holds multiple values of the same data
type at a time.
 In java, arrays are objects and they are created dynamically using new operator.
 Every array in java is organized using index values and index value of an array starts with '0' and ends
with 'size-1'.
 We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
 One Dimensional Array
 Multi Dimensional Array
One Dimensional Array
Creating an array
In the java programming language, an array must be created using new operator and with a specific size.
The size must be an integer value but not a byte, short, or long.
Syntax
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Example 1
public class ArrayExample
{
public static void main(String[] args)
{
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 =" + list[0]);
System.out.println("Length of the array = " + list.length);
}
}
Output:
Value at index 0 =10
Length of the array =5

Object Oriented Programming Through Java Page 36


Note: it need not specify the size of the array , the size is automatically decided based on the number of values
that are initialized.
Example int list[ ] = {10,20,30,40,50};

Looping through an array


An entire array is accessed using either simple for statement or for-each statement.
Example
import java.util.Scanner;
public class ArrayExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int size, sum = 0;

System.out.print("Enter the size of the list: ");


size = read.nextInt();

short list[] = new short[size];

System.out.println("Enter any " + size + " numbers: ");

for(int i = 0; i < size; i++) // Simple for statement


list[i] = read.nextShort();

for(int i : list) // for-each statement


sum = sum + i;

System.out.println("Sum of all elements: " + sum);


}
}
Output:
Enter the size of the list: 3
Enter any 3 numbers:
12 15 17
Sum of all elements: 44

Object Oriented Programming Through Java Page 37


Multidimensional Array
We can create 2-dimensional, 3-dimensional, or any dimensional array (arrays are arrays of arrays).
To create multidimensional array variable, specify each additional index using another set of square brackets.
Syntax

data_type array_name[ ][ ] = new data_type[rows][columns];


(or)
data_type[ ][ ] array_name = new data_type[rows][columns];

 When we create a two-dimensional array, it created with a separate index for rows and columns.
 The individual element is accessed using the respective row index followed by the column index.
Syntax

data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};

When an array is initialized at the time of declaration, it need not specify the size of the array and use of the
new operator. Here, the size is automatically decided based on the number of values that are initialized.
Example

int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};

Example:
class TwoDimwntinalArrays
{
public static void main(String[] args)
{

int[][] arr = {
{ 1, 2 },
{ 3, 4 }
};

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


{
for (int j = 0; j < 2; j++)
{
System.out.println("arr[" + i + "][" + j + "] = " + arr[i][j]);
}
}
}
OUTPUT:
arr[0][0] = 1
arr[0][1] = 2
arr[1][0] = 3
arr[1][1] = 4

Object Oriented Programming Through Java Page 38


Operators in Java

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.

Operator Type Category Precedence

Unary Postfix expr++ expr--

Prefix ++expr --expr +expr -expr

Arithmetic Multiplicative  / %

Additive + -

Shift Shift << >>


Relational Comparison < > <= >=

Equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||
Ternary Ternary ?:
Assignment Assignment = += -= *= /= %=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:
 incrementing/decrementing a value by one
 negating an expression
 inverting the value of a Boolean

Object Oriented Programming Through Java Page 39


Java Unary Operator Example: ++ and --

public class OperatorExample


{
public static void main(String args[])
{
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}
}
Output:
10
12
12
10
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as
basic mathematical operations.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%b); //0
}
}
Output:
15
5
50
2
0

Object Oriented Programming Through Java Page 40


Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of
times.
public class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}
}
Output:
40
80
80
240

Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.

Java Right Shift Operator Example


public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
Output:
2
5
2
Object Oriented Programming Through Java Page 41
Java AND Operator Example: Logical && and Bitwise &

 The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
 The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c); //false && true = false
System.out.println(a<b&a<c); //false & true = false
}
}
Output:
false
false
Java Ternary Operator
 Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min = (a<b) ? a : b;
System.out.println(min);
}
}
Output:
2
Object Oriented Programming Through Java Page 42
java Control Statements | Control Flow in Java
 In java, the control statements are the statements which will tell us that in which order the instructions
are getting executed.
 The control statements are used to control the order of execution according to our requirements.

Types of Control Statements


In java, the control statements are classified as follows.
 Selection Control Statements ( Decision Making Statements )
 Iterative Control Statements ( Looping Statements )
 Jump Statements
Selection Control Statements or Decision-Making statements:
 As the name suggests, decision-making statements decide which statement to execute
 when Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided.
 There are two types of decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition.
The control of the program is diverted depending upon the specific condition.
The condition of the If statement gives a Boolean value, either true or false. In Java,
there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Object Oriented Programming Through Java Page 43


Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition)
{
//code to be executed
}
Example: //Java Program to demonstrate the use of if statement.
public class IfExample
{
public static void main(String[] args)
{
int age=20;
if(age>18) //checking the age
{
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
Java if-else Statement

The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}

Object Oriented Programming Through Java Page 44


Example: //It is a program of odd and even number.
public class IfElseExample
{
public static void main(String[] args)
{
int number=13;

if(number%2==0) //Check if the number is divisible by 2 or not


{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
Output: odd number
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
else
{
//code to be executed if all the conditions are false
}

Object Oriented Programming Through Java Page 45


//Program to check POSITIVE, NEGATIVE or ZERO:
public class PositiveNegativeExample
{
public static void main(String[] args)
{
int number=-13;
if(number>0)
{
System.out.println("POSITIVE");
}
else
if(number<0)
{
System.out.println("NEGATIVE");
}
else
{
System.out.println("ZERO");
}
}
}

Output:
NEGATIVE

Java Nested if statement

The nested if statement represents the if block within another if block.


Here, the inner if block condition executes only when outer if block condition is true.
Syntax:

if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

Object Oriented Programming Through Java Page 46


Example: //Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample
{
public static void main(String[] args)
{
//Creating two variables for age and weight
int age=20;
int weight=80;
if(age>=18) //applying condition on age and weight
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
}
}
}
Output:
You are eligible to donate blood
Java Switch Statement
 The Java switch statement executes one statement from multiple conditions.
 It is like if-else-if ladder statement.
 The switch statement works with byte, short, int, long, enum types, String and some wrapper types like
Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
Points to Remember
 There can be one or N number of case values for a switch expression.
 The case value must be of switch expression type only. The case value must be literal or constant. It
doesn't allow variables.
 The case values must be unique. In case of duplicate value, it renders compile-time error.
 The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and
string.
 Each case statement can have a break statement which is optional. When control reaches to the break
statement, it jumps the control after the switch expression. If a break statement is not found, it
executes the next case.
 The case value can have a default label which is optional.

Object Oriented Programming Through Java Page 47


Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

SwitchExample.java
public class SwitchExample
{
public static void main(String[] args)
{
int number=20; //Declaring a variable for switch expression
switch(number) //Switch expression
{
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
case 30:
System.out.println("30");
break;
default:
System.out.println("Not in 10, 20 or 30");
}
}
}
Output: 20

Object Oriented Programming Through Java Page 48


Loop Statements or Iterative Statements
 In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true.
 However, loop statements are used to execute the set of instructions in a repeated order.
 The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. 
1. for loop
2. while loop
3. do-while loop
Java Simple for Loop
A simple for loop is the same as C/C++.

We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}
ForExample.java ///which prints table of 1
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
System.out.print(i);
}
}
}
Output: 1 2 3 4 5

Object Oriented Programming Through Java Page 49


Java Nested for Loop
If we have a for loop inside the another loop, it is known as nested for loop.
The inner loop executes completely whenever outer loop executes.
NestedForExample.java
public class NestedForExample
{
public static void main(String[] args)
{
for(int i=1;i<=3;i++) //loop of i
{
for(int j=1;j<=3;j++) //loop of j
{
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
Output:
11
12
13
21
22
23
31
32
33
Java for-each Loop
 It is easier to use than simple for loop because we don't need to increment value and use subscript
notation.
 It works on the basis of elements and not the index. It returns element one by one in the defined variable.
Syntax:
for(data_type variable : array_name)
{
//code to be executed
}

Object Oriented Programming Through Java Page 50


ForEachExample.java //Java For-each loop example which prints the elements of the array

public class ForEachExample


{
public static void main(String[] args)
{
int arr[]={12,23,44,56,78}; //Declaring an array
for(int i:arr) //Printing array using for-each loop
{
System.out.print(i);
}
}
}
Output:
12 23 44 56 78
Java While Loop
 The while loop is used to iterate a part of the program repeatedly until the specified condition is true.
 As soon as the Boolean condition becomes false, the loop automatically stops.
 If the number of iteration is not fixed, it is recommended to use the while loop.
Syntax:
while (condition)
{
//code to be executed
Increment / decrement statement
}
Example:
Unlike the for loop, we separately need to initialize and increment the variable used in the condition
(here, i). Otherwise, the loop will execute infinitely.
WhileExample.java
public class WhileExample
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
System.out.print(i);
i++;
}
}
}
Output: 1 2 3 4 5

Object Oriented Programming Through Java Page 51


Java do-while Loop
 The do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true.
 If the number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use a do-while loop.
 Java do-while loop is called an exit control loop.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
Note: The do block is executed at least once, even if the condition is false.
Example:
Unlike the for loop, we separately need to initialize and increment the variable used in the condition
(here, i). Otherwise, the loop will execute infinitely.
DoWhileExample.java //In the below example, we print integer values from 1 to 10.
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.print(i);
i++;
}while(i<=5);
}
}
Output:
1 2 3 4 5

Object Oriented Programming Through Java Page 52


Jump Statements or Unconditional Control Statements

 Jump statements are used to transfer the control of the program to the specific statements.
 In other words, jump statements transfer the execution control to the other part of the program.
 There are two types of jump statements in Java, i.e., break and continue.
Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
break;
BreakExample.java //Java Program to demonstrate the use of break statement inside the for loop.
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++) //using for loop
{
if(i==5) //breaking the loop
{
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java Continue Statement
 The continue statement is used in loop control structure when you need to jump to the next iteration of
the loop immediately.
 The Java continue statement is used to continue the loop.
 It continues the current flow of the program and skips the remaining code at the specified condition.
 In case of an inner loop, it continues the inner loop only.
 We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
continue;

Object Oriented Programming Through Java Page 53


ContinueExample.java //Java Program to demonstrate the use of continue statement inside the for loop.
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5 || i==7 || i==3)
{
continue; //it will skip the rest statement
}
System.out.println(i);
}
}
}
Output:
1
2
4
6
8
9
10
As you can see in the above output, 5 is not printed on the console. It is because the loop is continued when it
reaches to 5.
METHODS OVERLOADING
 class have multiple methods with same name but difference in parameters is called method overloading.
 If we have to perform only one operation, having same name of the methods increases the readability of
the program.
Syntax
class class_Name
{
returntype method(datatype1 variable1)
{
...........
...........
}
returntype method(datatype1 variable1, datatype2 variable2)
{
...........
...........
}
returntype method(datatype2 variable2)
{
...........
...........
}
}

Object Oriented Programming Through Java Page 54


Different ways to overload the method
There are two ways to overload the method in java a) By changing number of arguments or parameters
b) By changing the data type
Example By changing number of arguments
class Addition
{
void sum(int a, int b) // addition of two numbers
{
System.out.println(a+b);
}
void sum(int a, int b, int c) addition of three numbers
{
System.out.println(a+b+c);
}

public static void main(String args[])


{
Addition obj = new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}
Output
30
60
Example By changing the data type
In this example, we have created two overloaded methods that differs in data type.
The first sum method receives two integer arguments and second sum method receives two float arguments.
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}

public static void main(String args[])


{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}
Output
30
25.25

Object Oriented Programming Through Java Page 55


CONSTRUCTOR OVERLOADING

 Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.
 The compiler differentiates these constructors by taking the number of parameters, and their type.
 In other words whenever same constructor is existing multiple times in the same class with different
number of parameters or order of parameters or type of parameters is known asConstructor overloading.
Syntax
class ClassName
{
ClassName()
{
..........
}
ClassName(datatype1 value1)
{
.......
}
ClassName(datatype1 value1, datatype2 value2)
{
.......
}
ClassName(datatype2 variable2)
{
.......
}
}

Example
class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i, String n, int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}

Object Oriented Programming Through Java Page 56


public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output
111 Karan 0
222 Aryan 25
Parameter Passing Techniques in Java
 There are different ways in which parameter data can be passed into and out of methods and functions
 Let us assume that a function B() is called from another function A().
 In this case A is called the “caller function” and B is called the “called function function”.
 The arguments which A sends to B are called actual arguments and the parameters of B are
called formal arguments.
Pass by Value:
In the pass by value concept, the method is called by passing a value. So, it is called pass by value. It
does not affect the original parameter.

Example: // Call by Value


class CallByValue
{
public static void Example(int x, int y) // Function to change the value of the parameters
{
x++;
y++;
}
}

public class Main


{
public static void main(String[] args)
{
int a = 10;
int b = 20;

CallByValue object = new CallByValue();


System.out.println("Value of a: " + a + " & b: " + b);
object.Example(a, b); // Passing variables in the class function
System.out.println("Value of a: "+ a + " & b: " + b); // Displaying values after calling the function
}
}
Output:
Value of a: 10 & b: 20
Value of a: 10 & b: 20

Object Oriented Programming Through Java Page 57


Pass by Reference:

 In the pass by reference concept, the method is called using a reference of the actual parameter.
So, it is called pass by reference.
 It forwards the unique identifier of the object to the method.
 If we made changes to the parameter's instance member, it would affect the original value.

Note: Java does not support pass by reference concept.


Example:
class CallByReference
{
int a, b;

CallByReference(int x, int y) // Function to assign the value to the class variables


{
a = x;
b = y;
}
void ChangeValue(CallByReference obj) // Changing the values of class variables
{
obj.a += 10;
obj.b += 20;
}
}
public class B
{
public static void main(String[] args)
{
CallByReference object = new CallByReference(10, 20);
System.out.println("Value of a: " + object.a+ " & b: "+ object.b);
object.ChangeValue(object);// Changing values in class function
System.out.println("Value of a: " + object.a + " & b: "+ object.b); // print values after calling
}
}
Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40

Please note that when we pass a reference, a new reference variable to the same object is created.
So we can only change members of the object whose reference is passed.
We cannot change the reference to refer to some other object as the received reference is a copy of the original
reference.

Object Oriented Programming Through Java Page 58


Recursion

The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.

What is the difference between direct and indirect recursion?

A function fun is called direct recursive if it calls the same function fun.
A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun
directly or indirectly.
Direct recursion:

void directRecFun()
{
// Some code....

directRecFun();

// Some code...
}
Indirect recursion:

void indirectRecFun1()
{
// Some code...

indirectRecFun2();

// Some code...
}

void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}

Syntax:

returntype methodname()
{
//code to be executed
methodname();//calling same method
}

Object Oriented Programming Through Java Page 59


Java Recursion Example : Factorial Number
public class RecursionExample3
{
static int factorial(int n)
{
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args)
{
System.out.println("Factorial of 3 is: "+factorial(3));
}
}
Output: Factorial of 3 is: 6

Working of above program:


factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6

Java Recursion Example : Fibonacci Series


public class RecursionExample4
{
static int n1=0,n2=1,n3=0;
static void printFibo(int count)
{
if(count>0)
{
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibo(count-1);
}
}
public static void main(String[] args)
{
int count=15;
System.out.print(n1+" "+n2); //printing 0 and 1
printFibo(count-2); //n-2 because 2 numbers are already printed
}
}
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Object Oriented Programming Through Java Page 60


String
What is a Java String?
 In Java, a string is an object that represents a sequence of characters or char values.
 The java.lang.String class is used to create a Java string object. .
 In java, string is an immutable object, which means it is constant, and can cannot be changed.
Creating a String
There are two ways to create a String in Java a)String literal
b)Using new keyword
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
String str1 = "Welcome";
String str2 = "Welcome";
The problem with this approach:
If the object already exist in the memory it does not create a new Object rather it assigns the same old object to
the new instance, that means even though we have two string instances above(str1 and str2) compiler only
created on string object (having the value “Welcome”) and assigned the same to both the instances.
For example there are 10 string instances that have same value, it means that in memory there is only one object
having the value and all the 10 string instances would be pointing to the same object.
Solution:
What if we want to have two different object with the same string? For that we would need to create
strings using new keyword.
Using New Keyword
As we saw above that when we tried to assign the same string object to two different literals, compiler only
created one object and made both of the literals to point the same object.
To overcome that approach we can create strings like below, here compiler creates two different object in
memory having the same string.
String str1 = new String("Welcome");
String str2 = new String("Welcome");
A Simple Java String Example
public class Main
{
public static void main(String args[])
{
char[] c={'j','a','v','a'};
String s1=new String(c);
String s2="java";
System.out.println(s1);
System.out.println(s2);
}
}
Output: java
Java

Object Oriented Programming Through Java Page 61


Immutable String in Java
 In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable.
 Once String object is created its data or state can't be changed but a new String object is created.
 Let's try to understand the concept of immutability by the example given below:
Testimmutablestring.java
class Testimmutablestring
{
public static void main(String args[])
{
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:
Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created
with Sachin Tendulkar. That is why String is known as immutable.

As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin"
not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
Testimmutablestring1.java
class Testimmutablestring1
{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not modified.

Object Oriented Programming Through Java Page 62


Java String Methods
The String class has a set of built-in methods that you can use on strings.
Method Description Return
Type

charAt() Returns the character at the specified index (position) Char

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence of characters Boolean

endsWith() Checks whether a string ends with the specified character(s) Boolean

equals() Compares two strings. Returns true if the strings are equal, and false if not Boolean

equalsIgnoreCase() Compares two strings, ignoring case considerations Boolean

indexOf() Returns the position of the first found occurrence of specified characters Int

isEmpty() Checks whether a string is empty or not Boolean

lastIndexOf() Returns the position of the last found occurrence of specified characters Int

length() Returns the length of a specified string Int

startsWith() Checks whether a string starts with specified characters Boolean

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String

Object Oriented Programming Through Java Page 63


public class TestDemo1
{
public static void main(String args[])
{

String sample = "ACEM.edu";


String s1="string";
String s2="string";
String s3="RING";
String s4="swing";
String s5="stringa";

System.out.println(s3.charAt(2)); //N
System.out.println(s1.compareTo(s2)); //0 because both are equal
System.out.println(s1.compareTo(s4)); //-3 because "s" is 1x greater than "r"
System.out.println(s5.compareTo(s1)); // 1
System.out.println(s1.equals(s2)); //true because both are equal
System.out.println(s1.length()); // 6
System.out.println( s4.replace("w","p")); //sping
System.out.println(s3.toLowerCase()); //ring
System.out.println(s1.concat(s2)); // stringstring
}
}
/* output
N
0
-3
1
true
6
sping
ring
stringstring */

Object Oriented Programming Through Java Page 64


INHERITANCE
Definition:
 Getting properties from one class to another class is called inheritance
 When a Class extends another class it inherits all non-private members including fields and methods.
 Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as
Super class(Parent) and Sub class(child) in Java language.
 Inheritance defines is-a relationship between a Super class and its Sub class
 extends or implements keywords are used to describe inheritance in Java.
Example:
class Vehicle.
{
......
}
class Car extends Vehicle
{
. ........ //extends the property of vehicle class.
}
On above example
Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle.
Purpose of Inheritance
To promote code reuse.
To use Polymorphism.
Types of inheritance in java (On the basis of class, there can be three types of inheritance in java)
single,
multilevel and
hierarchical.

Object Oriented Programming Through Java Page 65


SINGLE INHERITANCE

 When one class extends another class(Only one class) then we call it as Single inheritance.
 The below diagram represents single inheritance in java where Class B extends only one class Class A.
 Here Class B will be the Sub class and Class A will be one and only Super class.

Single Inheritance Example

class A
{
public void dispA()
{
System.out.println(" disp() method of Class A ");
}
}

public class B extends A


{
public void dispB()
{
System.out.println(" disp() method of Class B ");
}
public static void main(String args[])
{
B b = new B(); //Assigning ClassB object to ClassB reference
b.dispA(); //call dispA() method of ClassA
b.dispB(); //call dispB() method of ClassB
}
}

Output :

disp() method of ClassA


disp() method of ClassB
Note: One and only one public class is allowed in one java file (same file)
Like two , three or fours public classes not allowed in the same java file

Object Oriented Programming Through Java Page 66


MULTILEVEL INHERITANCE
 In Multilevel Inheritance a derived class will be inheriting a parent class and as well as the derived
class act as the parent class to other class.
 In the below diagram, ClassB inherits the property of ClassA and ClassB act as a parent for ClassC.
 In Short ClassA parent for ClassB and ClassB parent for ClassC.

MultiLevel Inheritance Example

class A
{
public void dispA()
{
System.out.println(" disp() method of ClassA ");
}
}

class B extends A
{
public void dispB()
{
System.out.println(" disp() method of ClassB ");
}
}
public class C extends B
{
public void dispC()
{
System.out.println(" disp() method of ClassC ");
}

Object Oriented Programming Through Java Page 67


public static void main(String args[])
{
C c = new C(); //Assigning ClassC object to ClassC reference
c.dispA(); //call dispA() method of ClassA
c.dispB(); //call dispB() method of ClassB
c.dispC(); //call dispC() method of ClassC
}
}
Output :
disp() method of ClassA
disp() method of ClassB
disp() method of ClassC

HIERARCHICAL INHERITANCE
 In Hierarchical inheritance one parent class will be inherited by many sub classes.
 As per the below example ClassA will be inherited by ClassB, ClassC and ClassD.
 ClassA will be acting as a parent class for ClassB, ClassC and ClassD.

Hierarchical Inheritance Example


class A
{
public void dispA()
{
System.out.println(" disp() method of ClassA ");
}
}
class B extends A
{
public void dispB()
{
System.out.println(" disp() method of ClassB ");
}
}

Object Oriented Programming Through Java Page 68


class C extends A
{
public void dispC()
{
System.out.println(" disp() method of ClassC ");
}
}

class HierarchicalInheritanceTest
{
public static void main(String args[])
{
B b = new B();
b.dispB();
b.dispA();

C c = new C(); //Assigning ClassC object to ClassC reference


c.dispC(); //call dispC() method of ClassC
c.dispA(); //call dispA() method of ClassA
}
}
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA

Note:

Multiple inheritance is not supported in java through class but multiple and hybrid inheritance is supported
through interface only. When a class extends multiple classes i.e. known as multiple inheritance.

Object Oriented Programming Through Java Page 69


Why multiple inheritance is not supported in java?
To reduce the complexity and simplify of the language, multiple inheritance is not supported in java.
 Consider a scenario where A, B, and C are three classes.
 The C class inherits A and B classes.
 If A and B classes have the same method and you call it from child class object, there will be ambiguity
(doubt) to call the method of A or B class.
 Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error.
Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
 Multiple inheritance is not supported in the case of class because of ambiguity.
 However, it is supported in case of an interface because there is no ambiguity.
 It is because its implementation is provided by the implementation class.
MULTIPLE INHERITANCE
Multiple Inheritance is nothing but one class extending morethan one class.

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple
inheritance

interface Printable
{
public void print();
}
interface Showable
{
public void show();
}

Object Oriented Programming Through Java Page 70


class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:

Hello
Welcome

HYBRID INHERITANCE

 Hybrid Inheritance is the combination of both Single and Multiple Inheritance.


 Hybrid inheritance is also not directly supported in Java only through interface we can achieve this.
 As you can ClassA will be acting as the Parent class for ClassB & ClassC and ClassB & ClassC will be
acting asParent for ClassD.

Object Oriented Programming Through Java Page 71


Example
interface A
{
public void methodA();
}
interface B extends A
{
public void methodB();
}
interface C extends A
{
public void methodC();
}
class D implements B, C
{
public void methodA()
{
System.out.println("MethodA");
}
public void methodB()
{
System.out.println("MethodB");
}
public void methodC()
{
System.out.println("MethodC");
}
public static void main(String args[])
{
D obj1 = new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
}
}
Output:
MethodA
MethodB
MethodC

Object Oriented Programming Through Java Page 72


SUPER KEYWORD
 super keyword in java is a reference variable that is used to refer parent class object.
 super is an implicit keyword create by JVM and supply each and every java program
Uses of super at three levels
At variable level
At method level
At constructor level
Need of super keyword:
 Whenever the derived class is inherits the base class features, there is a possibility that base class
features are similar to derived class features and JVM will gets an ambiguity.
 In order to differentiate between base class features and derived class features must be preceded by
super keyword.
Syntax
super.baseclass feature

Super at variable level:


 In both base and derived class variables are same to differentiate those variables super keyword is used.
 If we are not writing super keyword before the base class data member name than it will be referred as
current class data member name and base class data member are hidden in the context of derived class.
Example
class Employee
{
float salary=10000;
}

class HR extends Employee


{
float salary=20000;
void display()
{
System.out.println(" Salary: "+salary); //print current class salary
System.out.println(" Salary: "+super.salary); //print base class salary
}
}

Object Oriented Programming Through Java Page 73


class Svariable
{
public static void main(String[] args)
{
HR obj = new HR();
obj.display();
}
}
Output
Salary: 20000.0
Salary: 10000.0
Super at method level
 The super keyword can also be used to invoke or call parent class method.
 In other word super keyword use when base class method name and derived class method name have
same name. (It should also be used in case of method overriding)
Example
class Student
{
void message()
{
System.out.println(" Good Morning Sir ");
}
}
class Faculty extends Student
{
void message()
{
System.out.println(" Good Morning Students ");
}
void display()
{
message(); //will invoke or call current class message() method
super.message(); //will invoke or call parent class message() method
}
public static void main(String args[])
{
Facultys = new Faculty();
s.display();
}
}
Output
Good Morning Students
Good Morning Sir

Object Oriented Programming Through Java Page 74


Super at constructor level
 The super keyword can also be used to invoke or call the parent class(base class) constructor.
 Super() It is used for calling super class default constructor from the context of derived class
constructors.
Example
class Employee
{
Employee()
{
System.out.println(" Employee class Constructor ");
}
}

class HR extends Employee


{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}

class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}

Output
Employee class Constructor
HR class Constructor

Object Oriented Programming Through Java Page 75


Method Overriding in Java
Definition: If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding.
Usage:
 Method overriding is used to provide our own implementation of a method which is already provided by
its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).

class Vehicle
{
void run()
{
System.out.println(" Vehicle is running ");
}
}

class Bike extends Vehicle


{
public static void main(String args[])
{
Bike obj = new Bike();
obj.run();
}
}
Output:
Vehicle is running

Problem is that I have to provide my own implementation for run() method in subclass that is why we use
method overriding.
The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there
is method overriding.

Object Oriented Programming Through Java Page 76


Example:
class Vehicle
{
void run() //defining a method
{
System.out.println(" Vehicle is running ");
}
}

class Bike2 extends Vehicle


{
void run() //defining the same method as in the parent class
{
System.out.println(" Bike is running safely ");
}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}
}
Output:
Bike is running safely
Difference between method overloading and method overriding in java

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already provided by
its super class.

2) Method overloading is performed within Method overriding occurs in two classesthat have IS-A
class. (inheritance) relationship.

3) In method overloading, parameter must be In case of method overriding, parameter must be same.
different.

4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.

5) In java, method overloading can't be Return type must be same or covariant in method
performed by changing return type of the overriding.

Object Oriented Programming Through Java Page 77


Polymorphism in Java
 Polymorphism in Java is a concept by which we can perform a single action in different ways.
 Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms, So polymorphism means many forms.
 There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism.
 We can perform polymorphism in java by method - overloading and method overriding.
 If you overload a static method in Java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.
Runtime Polymorphism in Java or Dynamic Method Dispatch

 Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time.
 In this process, an overridden method is called through the reference variable of a superclass.
 The determination of the method to be called is based on the object being referred to by the reference
variable.
Let's first understand the upcasting before Runtime Polymorphism.

Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.

class A
{
}
class B extends A
{
}
A a=new B(); //upcasting

For upcasting, we can use the reference variable of class type or an interface type.

Object Oriented Programming Through Java Page 78


Example:
interface I
{
}
class A
{
}
class B extends A implements I
{
}
Here, the relationship of B class would be:
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.
Example of Java Runtime Polymorphism
class Bike
{
void run()
{
System.out.println(" running ");
}
}
class Splendor extends Bike
{
void run()
{
System.out.println(" running safely with 60km ");
}
public static void main(String args[])
{
Bike b = new Splendor(); //upcasting
b.run();
}
}
Output:
running safely with 60km.

Object Oriented Programming Through Java Page 79


Explanation:
 In this example, we are creating two classes Bike and Splendor.
 Splendor class extends Bike class and overrides its run() method.
 We are calling the run method by the reference variable of Parent class.
 Since it refers to the subclass object and subclass method overrides the Parent class method, the subclass
method is invoked at runtime.
 Since method call is determined by the JVM not compiler, it is known as runtime polymorphism.

Java Runtime Polymorphism Example: Shape


class Shape
{
void draw()
{
System.out.println("drawing...");
}
}

class Rectangle extends Shape


{
void draw()
{
System.out.println(" drawing rectangle... ");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println(" drawing circle... ");
}
}

class Triangle extends Shape


{
void draw()
{
System.out.println(" drawing triangle... ");
}
}

Object Oriented Programming Through Java Page 80


class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;

s=new Rectangle();
s.draw();

s=new Circle();
s.draw();

s=new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...

Java Runtime Polymorphism with Data Member


A method is overridden, not the data members, so runtime polymorphism can't be achieved by data members.

Abstraction in Java
 Abstraction is a process of hiding the implementation details and showing only functionality to the user.
 Another way, it shows only essential things to the user and hides the internal details.
 Abstraction lets you focus on what the object does instead of how it does it.
Example: Sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
There are two ways to achieve abstraction in java
 Abstract class (0 to 100%)
 Interface (100%)

Object Oriented Programming Through Java Page 81


Abstract class in Java
 A class which is declared as abstract using abstract keyword is known as an abstract class.
 It cannot be instantiated (object creation not allowed for abstract class directly).
 An abstract class can have a data member, abstract method, non-abstract method(method body), static
methods , final methods ,constructors, and even main() method.
 If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.
 If there is an abstract method in a class, that class must be abstract.
 A method which is declared as abstract and does not have implementation is called as an abstract
method.
Example: class A {
abstract void run();
}
Output: compile time error

abstract class A //abstract class


{
abstract void run(); //abstract method no method body and abstract
}
Example:
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Output: running safely
Explanation: In the above example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.

Object Oriented Programming Through Java Page 82


Example 2:
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw() //In real scenario, implementation is provided by others i.e. unknown by end user
{
System.out.println(" drawing rectangle ");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println(" drawing circle ");
}
}

class TestAbstraction1
{
public static void main(String args[])
{
Shape s = new Circle1();
s.draw();
}
}
Output:
drawing circle

Object Oriented Programming Through Java Page 83


Final Keyword In Java
 The final keyword in java is used to restrict the user.
 The java final keyword can be used in many context.
 final can be used for variables or methods or classes
Java final variable
If you make any variable as final, you cannot change the value of final variable (It will be constant).
Example:
class Bike9
{
final int speedlimit = 90; //final variable
void run()
{
speedlimit = 400;
}
public static void main(String args[])
{
Bike9 obj = new Bike9();
obj.run();
}
}
Output: Compile Time Error

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
Java final method

If you make any method as final, you cannot override it.

Example :
class Bike
{
final void run()
{
System.out.println("running");
}
}

Object Oriented Programming Through Java Page 84


class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda = new Honda();
honda.run();
}
}
Output: Compile Time Error

Java final class


If you make any class as final, you cannot extend it.
Example
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda = new Honda1();
honda.run();
}
}
Output: Compile Time Error

Object Oriented Programming Through Java Page 85


Object class in Java
 Object class is present in java.lang package.
 If a Class does not extend any other class then it is direct child class of Object and if extends other
class then it is an indirectly derived.
 Therefore the Object class methods are available to all Java classes, So, Object class acts as a root
class inheritance hierarchy in any Java Program.
Methods of Object class

The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() Returns the class object of “this” object and used to get actual runtime class of
the object. It can also be used to get metadata of this class.

public int hashCode() Returns the hashcode number for this object. For every object, JVM generates a
unique number which is hashcode. It returns distinct integers for distinct objects.

public boolean equals(Object compares the given object to this object.


obj)
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long causes the current thread to wait for the specified milliseconds, until another
timeout)throws thread notifies (invokes notify() or notifyAll() method).

public final void wait(long causes the current thread to wait for the specified milliseconds and nanoseconds,
timeout,int nanos)throws until another thread notifies (invokes notify() or notifyAll() method).
InterruptedException

public final void wait()throws causes the current thread to wait, until another thread notifies (invokes notify() or
InterruptedException notifyAll() method).

protected void finalize()throws is invoked by the garbage collector before object is being garbage collected.
Throwable

Object Oriented Programming Through Java Page 86


getClass() :
The java.lang.Object.getClass() method returns the runtime class of an object.
Example:
public class ObjectgetClassExample
{
public static void main(String[] args)
{
Object obj1 = new String("Facebook");
ObjectgetClassExample obj2 = new ObjectgetClassExample();
System.out.println(" Class of Object obj1 is : " + obj1.getClass());
System.out.println(" Class of Object obj2 is : " + obj2.getClass());
}
}
Output
Class of Object obj1 is : class java.lang.String
Class of Object obj2 is : class ObjectgetClassExample
hashCode() Method
The hashCode() method returns the hash code for the Method class object.
Example:
public class ObjectgetClassExample
{
public static void main(String[] args)
{
Object obj1 = new String("Facebook");
ObjectgetClassExample obj2 = new ObjectgetClassExample();
System.out.println("obj1 hashcode = " + obj1.hashCode());
System.out.println("obj2 hashcode = " + obj2.hashCode());
}
}
Output
obj1 hashcode = 561774310
obj2 hashcode = 1284693
Java equals()
 The java equals() is a method of lang.Object class, and it is used to compare two objects.
 To compare two objects that whether they are the same, it compares the values of both the objects
 By default, two objects will be the same only if stored in the same memory location.

Object Oriented Programming Through Java Page 87


Example:
public class ObjectgetClassExample
{
public static void main(String[] args)
{
String a = "Andhra";
String b = "Andhra";
String c="pradesh";

if(a.equals(b))
{
System.out.println(" a and b are equal " );
}
if(!a.equals(c))
{
System.out.println(" a and b are not equal " );
}
}
}
Output:
a and b are equal
a and b are not equal
toString() Method
 If you want to represent any object as a string, toString() method comes into existence.
 The toString() method returns the String representation of the object.
 If you print any object, Java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output it can be the state of an object etc.
Advantage of Java toString() method
By overriding the toString() method ,we can return values of the object, so we don't need to write much code.
class Student
{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{
this.rollno = rollno;
this.name = name;
this.city = city;
}

Object Oriented Programming Through Java Page 88


public String toString() //overriding the toString() method
{
return rollno+" "+name+" "+city;
}

public static void main(String args[])


{
Student s1 = new Student(101,"Raj","mumbai");
Student s2 = new Student(102,"Vijay","chennai");
Student s3 = new Student(103,"Sai","Bangalore");

System.out.println(s1); //compiler writes here s1.toString()


System.out.println(s2); //compiler writes here s2.toString()
System.out.println(s3); //compiler writes here s2.toString()
}
}
Output
101 Raj mumbai
102 Vijay chennai
103 Sai Bangalore
Packages
 In java, a package is a container of classes, interfaces, and sub-packages.
 We may think of it as a folder in a file directory.
 We use the packages to organize project-related classes, interfaces, and sub-packages into a bundle.
 In java, the packages have divided into two types.
Built-in Packages
User-defined Packages
Built-in Packages
 The built-in packages are the packages from java API. The Java API is a library of pre-defined classes,
interfaces, and sub-packages. The built-in packages were included in the JDK.
 There are many built-in packages in java, few of them are as java, lang, io, util, awt, net, sql, etc.

Object Oriented Programming Through Java Page 89


User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their own packages.
Advantage of Java Package
 Java package is used to categorize the classes and interfaces so that they can be easily maintained.
 Java package provides access protection.
Definig a Package in java
We use the package keyword to create or define a package .
Syntax : package packageName;
 The package statement must be the first statement in the program.
 The package name must be a single word (spaces not allowed).
 The package name must use Camel case notation (lower case).

Note: To compile and run the program we should follow the following format
To Compile: javac -d . directory.javafilename
The -d switch specifies the destination where to put the generated class file.
To Run: java packagename.filename

Example (code to create a user-defined package myPackage)


package myPackage;
public class DefiningPackage
{
public static void main(String[] args)
{
System.out.println(" This class belongs to myPackage ");
}
}
Compile: javac -d . DefiningPackage.java
The above command creates a directory with the package name myPackage, and
the DefiningPackage.class is saved into it.
Run : java myPackage.DefiningPackage
Note: When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically.

Object Oriented Programming Through Java Page 90


Permanent java classpath setting:
 Firstly, Right Click on “This PC”.
 Click Properties.
 Click “Advanced System Settings”.
 Click “Environment Variables”.
 In the “User Variable Section”, click the “New” button.
 Enter Variable name :classpath [Don’t give space between class path] Variable
value:<directory_location>(for example in my F:\workspace\bin)
 Click OK->OK->OK.
 Close all windows, open a new command prompt, and run the java command
Access protection in java packages
 In java, the access modifiers define the accessibility(visibility) of the class and its members.
 Java has four access modifiers, and they are default, private, protected, and public.
 The class acts as a container of data and methods. So, the access modifier decides the
accessibility of class members across the different packages.

 The public members can be accessed everywhere.


 The private members can be accessed only inside the same class.
 The protected members are accessible to every child class (same package or other packages).
 The default members are accessible within the same package but not outside the package.
Example
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

Object Oriented Programming Through Java Page 91


void showData()
{
System.out.println(" Inside ParentClass ");
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" c = " + c);
System.out.println(" d = " + d);
}
}
class ChildClass extends ParentClass
{
void accessData()
{
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}

Object Oriented Programming Through Java Page 92


importing Packages in java
 In java, the import keyword used to import built-in and user-defined packages.
 When a package has imported, we can refer to all the classes of that package using their name directly.
 The import statement must be after the package statement, and before any other statement.
 Using an import statement, we may import a specific class or all the classes from a package.
 Using one import statement, we may import only one package or a class.
 A program may contain any number of import statements.
access package from another package
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name.
1) Using packagename.*
 If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
 The import keyword is used to make the classes and interface of another package accessible to the
current package.
Example (//save by A.java )

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack; (//save by B.java )
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello

Object Oriented Programming Through Java Page 93


Example
package myPackage;
import java.util.Scanner;
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
}
}
In the above code, the class ImportingExample belongs to myPackage package, and it also importing a class
called Scanner from java.utilpackage.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example (//save by A.java )
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

package mypack; (//save by B.java )


import pack.A;

class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello

Object Oriented Programming Through Java Page 94


Example
package myPackage;
import java.util.*;
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
Random rand = new Random();
int num = rand.nextInt(100);
System.out.println("Randomly generated number " + num);
}
}
In the above code, the class ImportingExample belongs to myPackage package, and it also importing all the
classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from the java.util package.
3) Using fully qualified name
 If you use fully qualified name then only declared class of this package will be accessible.
 Now there is no need to import. But you need to use fully qualified name every time when you
are accessing the class or interface.
 It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example (//save by A.java )
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack; (//save by B.java )
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output: Hello

Object Oriented Programming Through Java Page 95


Note: If you import a package, subpackages will not be imported.
 Subpackage(Package inside the package is called the subpackage.)
 If you import a package, all the classes and interface of that package will be imported excluding the
classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
 We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-
package.
Example :
import java.util.*;
The above import statement util is a sub-package of java package. It imports all the classes of util package only,
but not classes of java package.
Interfaces
 In java, an interface is similar to a class, but it contains public abstract methods and public static final
variables only.
 We may think of an interface as a completely abstract class. None of the methods in the interface has an
implementation, and all the variables in the interface are constants.
Purpose:
The interface in java enables java to support multiple-inheritance.
The interface in Java is another mechanism to achieve abstraction (100% abstraction)
Points to Rember:
 The class that implements an interface must provide code for all the methods defined in the interface,
otherwise, it must be defined as an abstract class.
 The class uses a keyword implements to implement an interface.
 A class can implement any number of interfaces.
 We can not instantiate (object creation) an interface.
 All the members of an interface are public by default.
 An interface can extend multiple interfaces.
Understanding relationship between classes and interfaces
A class extends another class, an interface extends another interface but a class implements an interface.

Object Oriented Programming Through Java Page 96


Declaring Interfaces
Defining an interface is similar to that of a class. We use the keyword interface to define an interface.
Syntax
interface InterfaceName
{
members declaration;
}
Example
interface Emp
{
void learn(String str);
void work();
}
Implementing Interfaces
Syntax
class className implements InterfaceName
{
...
body-of-the-class
}
Example
interface Emp
{
void learn(String str);
void work();
}
class Programmer implements Emp
{
public void learn(String str)
{
System.out.println(" Learn using " + str);
}
public void work()
{
System.out.println("Develop applications");
}
}

public class EmpTest


{
public static void main(String[] args)
{
Programmer trainee = new Programmer();
trainee.learn("coding");
trainee.work();
}
}
Output
Learn using coding
Develop applications
Object Oriented Programming Through Java Page 97
Extending Interfaces

One interface can extends another interface like as shown below.


Syntax
interface InterfaceName1
{
members declaration;
}
interface InterfaceName2 extends InterfaceName1
{
members declaration;
}
Example:
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}

class A7 implements Showable


{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome

Object Oriented Programming Through Java Page 98


Nested interfaces
 The interface that defined inside another interface is known as nested interface (inner interface).
 The nested interface declared within an interface is public by default.
 The nested interface declared within a class can be with any access modifier.
 Every nested interface is static by default.
Note:
 We can only access the nested interface by using outer interface or outer class name followed by
dot( . ), followed by the nested interface name.
Example
interface OuterInterface
{
void outerMethod();
interface InnerInterface
{
void innerMethod();
}
}
class OnlyOuter implements OuterInterface
{
public void outerMethod()
{
System.out.println("This is OuterInterface method");
}
}
class OnlyInner implements OuterInterface.InnerInterface
{
public void innerMethod()
{
System.out.println("This is InnerInterface method");
}
}
public class NestedInterfaceExample
{
public static void main(String[] args)
{
OnlyOuter obj_1 = new OnlyOuter();
OnlyInner obj_2 = new OnlyInner();

obj_1.outerMethod();
obj_2.innerMethod();
}
}
Output:
This is OuterInterface method
This is InnerInterface method

Object Oriented Programming Through Java Page 99


Variables in Java Interfaces
 The variables defined in an interface can not be modified by the class that implements the interface, but
it may use as it defined in the interface.
 The variable in an interface is public, static, and final by default.
 If any variable in an interface is defined without public, static, and final keywords then, the compiler
automatically adds the same.
 Every variable of an interface must be initialized in the interface itself.
 The class that implements an interface can not modify the interface variable, but it may use as it defined
in the interface.
Example
interface SampleInterface
{
int UPPER_LIMIT = 100;
//int LOWER_LIMIT; // Error - must be initialised
}
public class InterfaceVariablesExample implements SampleInterface
{
public static void main(String[] args)
{
System.out.println("UPPER LIMIT = " + UPPER_LIMIT);
// UPPER_LIMIT = 150; // Can not be modified
}
}
Output:
UPPER LIMIT = 100

Object Oriented Programming Through Java Page 100


Exceptions:

 An exception is a problem or an abnormal condition that arises during the program execution (at run
time).
 In other words an exception is a run time error.
 When an Exception occurs the normal flow of the program is interrupts the flow and the program
terminates abnormally, therefore these exceptions are to be handled.

An exception can occur for many different reasons, including the following:

 A user has entered invalid data.


 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.

Errors
No matter how good a program we write it may cause the following types of errors.

1. Syntax Errors or 2. Logical Errors or 3. Runtime Errors

Syntax Errors:
It is an error which occurs when the rules of language are violated .
If we are not following the rules, those cause the error. It can be easily detected and corrected by compilers.

Eg: Statement missing semicolon; , Missing/expected „ }‟ , Un-defined symbol varname etc.

Logical Error:
It is an error caused due to manual mistake in the logical expressions. These errors cannot be detected by the
compiler.
Eg. Current_balance = old_balance*cash_deposit
Runtime Error:
It is an Error, which occurs after executing the program at runtime.
Eg. Divide by zero.
File not found
No disc in the drive etc.
Exception Handling

 Exception Handling is the technique to handle runtime malfunctions.


 We need to handle such exceptions to prevent unexpected termination of program.
 The term exception means exceptional condition, it is a problem that may arise during the execution of
program.
 A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need
to be opened cannot be found, resource exhaustion etc.

Object Oriented Programming Through Java Page 101


Usage:
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally interrupts the normal flow of the application; that is why we need to handle exceptions.
Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;//exception occurs
4. statement 4;
5. statement 5;
Suppose there are 5 statements in a Java program and an exception occurs at statement 3;
the rest of the code will not be executed, i.e., statements 4 to 5 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed. That is why
we use exception handling in Java
Types of Exception in Java
Bugs or errors that we don't want and restrict our program's normal execution of code are referred to
as exceptions.
In this section, we will focus on the types of exceptions in Java and the differences between the two.
Exceptions can be categorized into two ways:
1. Built-in Exceptions
 Checked Exception

 Unchecked Exception

2. User-Defined Exceptions

Object Oriented Programming Through Java Page 102


3.8 Built-in Exceptions (checked & Unchecked exceptions)
 Exception that are already available in Java libraries are referred to as built-in exception.
 These exceptions are able to define the error situation so that we can understand the reason of getting
this error. It can be categorized into two broad categories, i.e., checked exceptions and unchecked
 All the built-in exception classes in Java were defined a package java.lang.

The hierarchy of Java Exception classes


Checked Exceptions
 Checked exceptions are called compile-time exceptions because these exceptions are checked at
compile-time by the compiler.
 The compiler ensures whether the programmer handles the exception or not.
 The programmer must to handle the exception; otherwise, the system has shown a compilation error.
Some list of checked exceptions
S. No. Exception Class with Description
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class
cannot be found in the classpath
2 FileNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular file specified file cannot be
found in that location.
3 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.
4 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile time, a
NoSuchMethodException occurs during reflection when we try to access a method that does not exist.

Object Oriented Programming Through Java Page 103


CheckedExceptionExample.java

import java.io.*;
import java.util.Scanner;

class CheckedDemo
{
public static void main(String args[])
{
FileInputStream mydata = new FileInputStream("G:/soft wares/names.txt");
Scanner myReader = new Scanner(mydata);
while (myReader.hasNextLine())
{
String data = myReader.nextLine();
System.out.println(data);
}
}
}
Output:
In the above code, we are trying to read the names.txt file and display its data or content on the screen.
D:\ACEM\II CSE Bsection>javac CheckedDemo.java
CheckedDemo.java:9: error: unreported exception FileNotFoundException; must be caught or declared
to be thrown
FileInputStream mydata = new FileInputStream("G:/soft wares/names.txt");
^
1 error
How to resolve the error?

There are basically two ways through which we can solve these errors.

 The exceptions occur in the main method. We can get clear from these compilation errors by declaring
the exception in the main method using the throws . We only declare the IOException, not
FileNotFoundException, because of the child-parent relationship.

 The IOException class is the parent class of FileNotFoundException, so this exception will
automatically cover by IOException. We will declare the exception in the following way:

Object Oriented Programming Through Java Page 104


Example:
import java.io.*;
import java.util.Scanner;

class CheckedDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream mydata = new FileInputStream("G:/soft wares/names.txt");
Scanner myReader = new Scanner(mydata);
while (myReader.hasNextLine())
{
String data = myReader.nextLine();
System.out.println(data);
}
}
}
Output:
D:\ACEM\II CSE Bsection>javac CheckedDemo.java
D:\ACEM\II CSE Bsection>java CheckedDemo
raja
ram
raghavan

2) We can also handle these exception using try-catch However, the way which we have used above is not
correct. We have to a give meaningful message for each exception type.
By doing that it would be easy to understand the error. We will use the try-catch block in the following way:
Exception.java
import java.io.*;
import java.util.Scanner;
class CheckedDemo
{
public static void main(String args[])
{
try
{
FileInputStream mydata = new FileInputStream("G:/soft wares/names.txt");
Scanner myReader = new Scanner(mydata);
while (myReader.hasNextLine())
{
String data = myReader.nextLine();
System.out.println(data);
}
}

Object Oriented Programming Through Java Page 105


catch(FileNotFoundException e)
{
System.out.println(" no file found ");
}
}
}
Output:
D:\ACEM\II CSE Bsection>javac CheckedDemo.java
D:\ACEM\II CSE Bsection>java CheckedDemo
raja
ram
raghavan
Note:
If the file is not found in the specified location it will generate the following error
File Not Found

and 3.8 Unchecked Exceptions (uncaught Exceptions)


 The unchecked exceptions are just opposite to the checked exceptions.
 The compiler will not check these exceptions at compile time.
 Usually, it occurs when the user provides bad data during the interaction with the program.
 The RuntimeException class is able to resolve all the unchecked exceptions because of the child-parent
relationship.
S. Example
No. Exception Class with Description

1 ArithmeticException int a = 30, b = 0;


It handles the arithmetic exceptions like dividion by zero int c = a/b;

2 ArrayIndexOutOfBoundsException int a[] = new int[5];


It handles the situations like an array has been accessed with an a[6] = 9;
illegal index like ( index is either negative or greater than or
equal to the size of the array).

3 ArrayStoreException Double[] a = new Double[2];


It handles the situations like when an attempt has been made to
store the wrong type of object into an array of objects a[0] = new Integer(4);

4 ClassCastException Object o = new Object();


It handles the situation when we try to improperly cast a class String s = (String)o;
from one type to another.

5 IndexOutOfBoundsException int ar[] = { 1, 2, 3, 4, 5 };


It is thrown when attempting to access an invalid index within a System.out.println(ar[9]);
collection, such as an array, vector , string , and so forth.

Object Oriented Programming Through Java Page 106


S. Example
No. Exception Class with Description

6 NegativeArraySizeException int ar[] = new int[-9];


It is thrown if an applet tries to create an array with negative
size.

7 NullPointerException String s =null;


it is thrown when program attempts to use an object reference s.length();
that has the null value.

8 NumberFormatException String s = "aditya ";


It is thrown when we try to convert a string into a numeric Integer i = Integer.parseInt(s);
value such as float or integer, but the format of the input string
is not appropriate or illegal.

9 StringIndexOutOfBounds String s = "aditya ";


It is thrown by the methods of the String class, in order to s.charAt[8];
indicate that an index is either negative, or greater than the size
of the string itself.

UncheckedExceptionExample1.java
class UncheckedExceptionExample1
{
public static void main(String args[])
{
int positive = 35;
int zero = 0;
int result = positive/zero; //Give Unchecked Exception here.
System.out.println(result);
}
}
Output:
D:\sasi>javac UncheckedExceptionExample1.java
D:\sasi>java UncheckedExceptionExample1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at UncheckedExceptionExample1.main(UncheckedExceptionExample1.java:6)

Object Oriented Programming Through Java Page 107


Difference Between Checked and Unchecked Exception(uncaught Exception)

S.No Checked Exception Unchecked Exception

1. These exceptions are checked at compile time. These exceptions are just opposite to the checked
These exceptions are handled at compile time exceptions. These exceptions are not checked and
too. handled at compile time.

2. These exceptions are direct subclasses of They are the direct subclasses of the
Exception RuntimeException class.

3. The code gives a compilation error in the case The code compiles without any error because the
when a method throws a checked exception. The exceptions escape the notice of the compiler. These
compiler is not able to handle the exception on its exceptions are the results of user-created errors in
own. programming logic.

4. Common checked exceptions include Common unchecked exceptions include


IOException, DataAccessException, ArithmeticException, InvalidClassException,
InterruptedException, etc. NullPointerException, etc.

5. These exceptions are propagated using the throws These are automatically propagated.
keyword

6. It is required to provide the try-catch and try- In the case of unchecked exception it is not
finally block to handle the checked exception. mandatory.

try-catch block
 In java, the try and catch, both are the keywords used for exception handling.
 The keyword try is used to define a block of code that will be tests the occurrence of an exception.
 The keyword catch is used to define a block of code that handles the exception occurred in the
respective try block.
 Both try and catch are used as a pair. Every try block must have one or more catch blocks.
 We can not use try without at least one catch, and catch alone can be used (catch without try is not
allowed).
Syntax
try
{
code to be tested
}
catch(ExceptionType object)
{
code for handling the exception
}

Object Oriented Programming Through Java Page 108


Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
Example 1 (TryCatchExample1.java)
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all the code below the
exception won't be executed.
Solution by exception handling ( the above problem by a java try-catch block)
Example 2 (TryCatchExample2.java)
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data = 50/0; //may throw exception
}
catch(ArithmeticException e) //handling the exception
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code

Object Oriented Programming Through Java Page 109


Multi-catch block
 A try block can be followed by one or more catch blocks.
 Each catch block must contain a different exception handler. So, if you have to perform different tasks at
the occurrence of different exceptions, use java multi-catch block.
Points to remember
 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException
must come before catch for Exception. 
Flowchart of Multi-catch Block

Example 1 MultipleCatchBlock1.java
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[] = new int[5];
a[5] = 30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Object Oriented Programming Through Java Page 110
Java Nested try block
 In Java, using a try block inside another try block is permitted. It is called as nested try block.
 Every statement that we enter a statement in try block, context of that exception is pushed onto the stack.
 For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).

Use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
statement 1;
statement 2;
try //try catch block within another try block
{
statement 3;
statement 4;
}
catch(Exception e1)
{
//exception message
}
}
catch(Exception e2) //catch block of parent (outer) try block
{
//exception message
}

Object Oriented Programming Through Java Page 111


Java Nested try Example (NestedTryBlock.java)
public class NestedTryBlock
{
public static void main(String args[])
{
try //outer try block
{
try //inner try block 1
{
System.out.println("going to divide by 0");
int b = 39/0;
}
catch(ArithmeticException e) //catch block of inner try block 1
{
System.out.println(e);
}
try //inner try block 2
{
int a[] = new int[5];
a[5] = 4;
}
catch(ArrayIndexOutOfBoundsException e) //catch block of inner try block 2
{
System.out.println(e);
}
System.out.println("other statement");
}
catch(Exception e) //catch block of outer try block
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
D:\ACEM\II CSE Bsection>javac NestedTryBlock.java
D:\ACEM\II CSE Bsection>java NestedTryBlock
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..
Explanation:
 When any try block does not have a catch block for a particular exception, then the catch block of the
outer (parent) try block are checked for that exception, and if it matches, the catch block of outer try
block is executed.
 If none of the catch block specified in the code is unable to handle the exception, then the Java runtime
system will handle the exception. Then it displays the system generated message for that exception.

Object Oriented Programming Through Java Page 112


throw , throws and finally keywords
Java throw keyword
 The Java throw keyword is used to throw an exception explicitly.
 We specify the exception object which is to be thrown. The Exception has some message with it that
provides the error description. These exceptions may be related to user inputs, server, etc.
 We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to
throw a custom(user defined) exception.
 We can also define our own set of conditions and throw an exception explicitly using throw keyword.
syntax
throw new exception_class("error message");
Example
throw new IOException("sorry device error");
 Where the Instance(object) must be of type Throwable or subclass of Throwable.
 For example, Exception is the sub class of Throwable and the user-defined exceptions usually
extends the Exception class.
Example 1: Throwing Unchecked Exception
public class TestThrow1
{
public static void validate(int age) //function to check if person is eligible to vote or not
{
if(age<18)
{
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else
{
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[])
{
validate(13); //calling the function
System.out.println("rest of the code...");
}
}
Output:
D:\sasi>javac TestThrow1.java
D:\sasi>java TestThrow1
Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to vote
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception or declare in throws
clause.
If we throw a checked exception using throw keyword, it is must to handle the exception using catch
block or the method must declare it using throws declaration.
Object Oriented Programming Through Java Page 113
Java throws keyword
 The Java throws keyword is used to declare an exception.
 Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers' fault that he is not checking the code before
it being used.
Syntax:
return_type method_name() throws exception_class_name
{
//method code
}
Which exception should be declared?

Ans: Checked exception only, because unchecked exception is under our control so we can correct our code.
error is beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
 Now Checked Exception can be propagated (forwarded in call stack).
 It provides information to the caller of the method about the exception.
Java throws Example

import java.io.IOException;
class Testthrows1
{
void m() throws IOException
{
throw new IOException("device error"); //checked exception
}
void n() throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
Object Oriented Programming Through Java Page 114
public static void main(String args[])
{
Testthrows1 obj = new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Rules:
If we are calling a method that declares an exception, we must either caught or declare the exception.
1. Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the method.

Difference between throw and throws in Java

S.no Differences Throw Throws

1. Definition throw keyword is used throw an Java throws keyword is used in the method
exception explicitly from inside the signature.
function .

2. Type of Using throw keyword, we can only Using throws keyword, we can declare both
exception propagate unchecked exception i.e., the checked and unchecked exceptions. However,
checked exception cannot be propagated the throws keyword can be used to propagate
using throw only. checked exceptions only.

3. Syntax The throw keyword is followed by an The throws keyword is followed by class
instance of Exception to be thrown. names of Exceptions to be thrown.

4. Declaration throw is used within the method. throws is used with the method signature.

Java throw and throws Example (TestThrowAndThrows.java)


public class TestThrowAndThrows
{
// defining a user-defined method which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println(" Inside the method() ");
throw new ArithmeticException(" throwing ArithmeticException ");
}

Object Oriented Programming Through Java Page 115


public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
Output:
D:\sasi>javac TestThrowAndThrows.java
D:\sasi>java TestThrowAndThrows
Inside the method()
caught in main() method

Java finally block


Java finally block is a block used to execute important code such as closing the connection, etc.
Flowchart of finally block

Note:
If you don't handle the exception, before terminating the program, JVM executes finally block (if any).
Why use Java finally block?
 finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.

 The important statements to be printed can be placed in the finally block.

Uses:
Case 1: When an exception does not occur
Case 2: When an exception occurs but not handled by the catch block
Case 3: When an exception occurs and is handled by the catch block

Object Oriented Programming Through Java Page 116


Case 1: When an exception does not occur (TestFinallyBlock.java)
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
D:\sasi>javac TestFinallyBlock.java
D:\sasi>java TestFinallyBlock
5
finally block is always executed
rest of the code...
Case 2: When an exception occurs but not handled by the catch block

The code throws an exception however the catch block cannot handle it.
Even though, the finally block is executed after the try block and then the program terminates abnormally.

TestFinallyBlock1.java
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}

Object Oriented Programming Through Java Page 117


finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
D:\ACEM\II CSE Bsection>javac TestFinallyBlock.java
D:\ACEM\II CSE Bsection>java TestFinallyBlock
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero

Case 3: When an exception occurs and is handled by the catch block

Example where the Java code throws an exception and the catch block handles the exception.
Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.

class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(" Exception handled ");
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
D:\ACEM\II CSE Bsection>javac TestFinallyBlock.java
D:\ACEM\II CSE Bsection>java TestFinallyBlock
Exception handled
finally block is always executed
rest of the code...
Note:
For each try block there can be zero or more catch blocks, but only one finally block.
The finally block will not be executed if the program exits ( by calling System.exit())

Object Oriented Programming Through Java Page 118


Difference between final, finally and finalize

Sr. no. Key Final Finally Finalize

1. Definition final is the keyword and finally is the block in Java finalize is the method in Java
access modifier which is Exception Handling to which is used to perform
used to apply restrictions on execute the important code clean up processing just
a class, method or variable. whether the exception occurs before object is garbage
or not. collected.

2. Applicable Final keyword is used with Finally block is always finalize() method is used with
to the classes, methods and related to the try and catch the objects.
variables. block in exception handling.

3. Execution Final method is executed Finally block is executed as finalize method is executed
only when we call it. soon as the try-catch block is just before the object is
executed.. destroyed.

Java Custom Exception or Creating our own Exceptions or User-defined Exception

 In Java, we can create our own exceptions that are derived classes of the Exception class.
 User Defined Exception or custom exception is creating your own exception class and throws that
exception using ‘throw’ keyword. This can be done by extending the class Exception class that belongs
to java.lang package.
 Basically, Java custom exceptions are used to customize the exception according to user need.
 Using the custom exception, we can have your own exception and message.
Example 1:
 In the following code, constructor of InvalidAgeException takes a string as an argument.
 This string is passed to constructor of parent class Exception using the super() method.
 Also the constructor of Exception class can be called without using a parameter and calling super()
method is not mandatory.
TestCustomException1.java
class InvalidAgeException extends Exception // class representing custom exception
{
public InvalidAgeException (String str)
{
super(str); // calling the constructor of parent Exception
}
}

Object Oriented Programming Through Java Page 119


public class TestCustomException1 // class that uses custom exception InvalidAgeException
{
static void validate (int age) throws InvalidAgeException // method to check the age
{
if(age < 18)
{
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote");
}
else
{
System.out.println("welcome to vote");
}
}
public static void main(String args[])
{
try
{
validate(13); // calling the method
}

catch (InvalidAgeException ex)


{
System.out.println("Caught the exception");
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}

Output:

D:\ACEM\II CSE Bsection>javac TestCustomException1.java


D:\ACEM\II CSE Bsection>java TestCustomException1
Caught the exception
Exception occured: InvalidAgeException: age is not valid to vote
rest of the code...

Object Oriented Programming Through Java Page 120


Throwable class
 The Throwable class is the super class of every error and exception in the Java language.
 Only objects that are one of the subclasses this class are thrown by any “Java Virtual Machine” or
may be thrown by the Java throw statement..
Example:
import java.io.IOException;
class Testthrows2
{
public static void main(String args[])
{
try
{
int a = 10/0;
}
catch(Throwable t)
{
System.out.println(t.toString()); //This method returns a short description of current throwable.
System.out.println(t.getMessage()); //Returns the detail message string of current throwable.
t.printStackTrace(); //Prints the current throwable and its backtrace to the standard error stream.
}
}
}
Output:
D:\ACEM\II AI DS>java Testthrows2
java.lang.ArithmeticException: / by zero
/ by zero
java.lang.ArithmeticException: / by zero
at Testthrows2.main(Testthrows2.java:8)
Stream in java

 In java, the IO operations are performed using the concept of streams.


 Generally, a stream means a continuous flow of data.
 In java, a stream is a logical container of data that allows us to read from and write to it.
 The stream-based IO operations are faster than normal IO operations.
 The Stream is defined in the java.io package.

Object Oriented Programming Through Java Page 121


To understand the functionality of java streams, look at the following picture.

 The stream-based IO operations are performed using two separate streams input stream and output
stream.
 The input stream is used for input operations, and the output stream is used for output operations.
 The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to the console.
 System.out: standard output stream for console output operations.
 System.in: standard input stream for console input operations.
 System.err: standard error stream for console error output operations.
The Java streams support many different kinds of data, including simple bytes, primitive data types,
localized characters, and objects.
Java provides two types of streams, and they are as follows.
 Byte Stream
 Character Stream
The below picture shows how streams are categorized, and various built-in classes used by the java IO system.

Both character and byte streams essentially provides a convenient and efficient way to handle data streams

Object Oriented Programming Through Java Page 122


Byte Stream in java
 In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of data.
 In Java 1.0 version all IO operations were byte oriented, there was no other stream (character stream).
 The java byte stream is defined by two abstract classes, InputStream and OutputStream.
 The InputStream class used for byte stream based input operations, and the OutputStream class used for
byte stream based output operations.
 The InputStream and OutputStream classes have several concrete classes to perform various IO
operations based on the byte stream.
The following picture shows the classes used for byte stream operations.

InputStream class
The InputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
S.No. Method with Description
1 int available()
It returns the number of bytes that can be read from the input stream.
2 int read()
It reads the next byte from the input stream.
3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.

Object Oriented Programming Through Java Page 123


OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
S.No. Method with Description
1 void write(int n)
It writes byte(contained in an int) to the output stream.
2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void close()
It closes the output stream and also frees any resources connected with this output stream.

Character Stream in java


 In java, when the IO stream manages 16-bit Unicode characters, it is called a character stream.
 The unicode set is basically a type of character set where each character corresponds to a specific
numeric value within the given character set, and every programming language has a character set.
 The character stream is a 16 bits carrier. The character stream allows us to transmit 16 bits of data.
 The character stream was introduced in Java 1.1 version. The character stream
 The java character stream is defined by two abstract classes, Reader and Writer.
 The Reader class used for character stream based input operations, and the Writer class used for
character stream based output operations.
 The Reader and Writer classes have several concrete classes to perform various IO operations based on
the character stream.
The following picture shows the classes used for character stream operations.

Object Oriented Programming Through Java Page 124


Reader class

The Reader class has defined as an abstract class, and it has the following methods which have implemented by
its concrete classes.
S.No. Method with Description
1 int read()
It reads the next character from the input stream.
2 String readLine()
It reads a line of text. A line is considered to be terminated by any one of a line feed ('\n')
a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
3 boolean ready()
It tells whether the stream is ready to be read.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.

Writer class
The Writer class has defined as an abstract class, and it has the following methods which have implemented by
its concrete classes.
S.No. Method with Description
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
2 void write(char[] cbuf)
It writes a whole array(cbuf) to the output stream.
3 void write(int c)
It writes single character.
4 void write(String str)
It writes a string.
5 void write(String str, int off, int len)
It writes a portion of a string.
6 Writer append(char c)
It appends the specified character to the writer.
7 Writer append(CharSequence csq)
It appends the specified character sequence to the writer
8 Writer append(CharSequence csq, int start, int end)
It appends a subsequence of the specified character sequence to the writer.
9 void close()
It closes the output stream and also frees any resources connected with this output stream.

Object Oriented Programming Through Java Page 125


Console IO Operations in Java

Reading console input in java


There are three ways to read console input. Using these 3 ways we can read input data from the console.
 Using BufferedReader class
 Using Scanner class
1. Reading console input using BufferedReader class in java
 Reading input data using the BufferedReader class is the traditional technique.
 This way of the reading method is used by wrapping the System.in (standard input stream) in
an InputStreamReader which is wrapped in a BufferedReader, we can read input from the console.
 The BufferedReader class has defined in the java.io package.
Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FirstCode
{
public static void main(String args[]) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println(" Enter your favorite subject ");
String word = reader.readLine();
System.out.println(word);
}
}
Input and Output D:\ACEM\II AI DS>javac FirstCode.java
D:\ACEM\II AI DS>java FirstCode
Enter your favorite subject
Maths
Maths

2. Reading console input using Scanner class in java


 Reading input data using the Scanner class is the most commonly used method.
 This way of the reading method is used by wrapping the System.in (standard input stream) which is
wrapped in a Scanner, we can read input from the console.
 The Scanner class has defined in the java.util package.

Object Oriented Programming Through Java Page 126


Example
import java.util.Scanner;
public class ReadingDemo
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String name = "";
System.out.print(" Please enter your name : ");
name = in.next();
System.out.println("Hello, " + name);
}
}
Output:
D:\ACEM\II AI DS>javac ReadingDemo.java
D:\ACEM\II AI DS>java ReadingDemo
Please enter your name : Aditya
Hello, Aditya

Writing console output in java

In java, there are two methods to write console output. Using the 2 following methods, we can write output
data to the console.
 Using print() and println() methods
 Using write() method


1. Writing console output using print() and println() methods


 There are two ways to write at the console. Both ways belong to class PrintStream(Character-based
class ).
 print and println methods: Here, the methods are defined by class Printstream and is referenced by
System.out. These methods are widely used.

Object Oriented Programming Through Java Page 127


public class WritingToConsole
{
public static void main(String args[])
{
System.out.println(" ***** I am System.out.print. I print the passed string ***** ");
for(int i=1;i<=5;i++)
{
System.out.print(i);
}
System.out.println();
System.out.println("I am System.out.println. I print the passed string and end with a new line");
for(int i=1;i<=3;i++)
{
System.out.println(i);
}
}
}
Output
D:\ACEM\II AI DS>javac WritingToConsole.java
D:\ACEM\II AI DS>java WritingToConsole
***** I am System.out.print. I print the passed string *****
12345
I am System.out.println. It print the passed string and end with a new line
1
2
3

File class in Java

 The File is a built-in class in Java.


 In java, the File class has been defined in the java.io package.
 The File class represents a reference to a file or directory.
 The File class has various methods to perform operations like creating a file or directory, reading from a
file, updating file content, and deleting a file or directory.

Object Oriented Programming Through Java Page 128


The File class in java has the following constructors.
S.No. Constructor with Description
1 File(String pathname)
It creates a new File instance by converting the given pathname string into an abstract pathname. If the
given string is the empty string, then the result is the empty abstract pathname.
2 File(String parent, String child)
It Creates a new File instance from a parent abstract pathname and a child pathname string. If parent is
null then the new File instance is created as if by invoking the single-argument File constructor on the
given child pathname string.
3 File(File parent, String child)
It creates a new File instance from a parent abstract pathname and a child pathname string. If parent is
null then the new File instance is created as if by invoking the single-argument File constructor on the
given child pathname string.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract pathname.

The File class in java has the following methods.


S.No. Methods with Description
1 String getName()
It returns the name of the file or directory that referenced by the current File object.
2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not name a parent directory.
3 String getPath()
It returns the path of curent File.
4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.
5 String getAbsolutePath()
It returns the current file or directory path from the root.
6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.
7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.
8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.
9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.
10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the application; false otherwise.

Object Oriented Programming Through Java Page 129


Example:
import java.io.File;
public class FileClassTest
{
public static void main(String args[])
{
File f = new File("D:\\ACEM\\II AI DS\\datFile.txt");
System.out.println("Executable File : " + f.canExecute());
System.out.println("Name of the file : " + f.getName());
System.out.println("Path of the file : " + f.getAbsolutePath());
System.out.println("Parent name : " + f.getParent());
System.out.println("Write mode : " + f.canWrite());
System.out.println("Read mode : " + f.canRead());
System.out.println("Existance : " + f.exists());
System.out.println("Last Modified : " + f.lastModified());
System.out.println("Length : " + f.length());
}
}
Input & Output
C:\Raja\>javac FileClassTest.java
C:\Raja\>java FileClassTest
Executable File : true
Name of the file : textfile.txt
Path of the file : C:\Raja\textfile.txt
Parent name : C:\Raja\
Write mode : true
Read mode : true
Existance : true
Last Modified : 1641629987284
Length : 35

Object Oriented Programming Through Java Page 130


File Reading & Writing in Java
In java, there are multiple ways to read data from a file and to write data to a file.
The most commonly used ways are as follows.
Using Byte Stream (FileInputStream and FileOutputStream)
Using Character Stream (FileReader and FileWriter)
File Handling using Byte Stream
In java, we can use a byte stream to handle files. The byte stream has the following built-in classes to
perform various operations on a file.
 FileInputStream - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the byte stream. The FileInputStream class provides a method read() to read data
from a file byte by byte.
 FileOutputStream - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the byte stream. The FileOutputStream class provides a method write() to write
data to a file byte by byte.
Example program that reads data from a file and writes the same to another file using FileInoutStream and
FileOutputStream classes.

Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileReadingTest
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("D:\\ACEM\\II AI DS\\Input-File.txt");
out = new FileOutputStream("D:\\ACEM\\II AI DS\\Output-File.txt");
int c;

while ((c = in.read()) != -1)


{
out.write(c);
}
System.out.println(" Reading and Writing has been success ");
}

Object Oriented Programming Through Java Page 131


catch(Exception e)
{
System.out.println(e);
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
Output:
D:\ACEM\II AI DS>javac FileReadingTest.java
D:\ACEM\II AI DS>java FileReadingTest

Reading and Writing has been success

Note: The above program will read data from one file and writes data to another file by creating new file

File Handling using Character Stream

In java, we can use a character stream to handle files. The character stream has the following built-in classes to
perform various operations on a file.
 FileReader - It is a built-in class in java that allows reading data from a file. This class has implemented
based on the character stream. The FileReader class provides a method read() to read data from a file
character by character.
 FileWriter - It is a built-in class in java that allows writing data to a file. This class has implemented
based on the character stream. The FileWriter class provides a method write() to write data to a file
character by character.
Example program that reads data from a file and writes the same to another file using FIleReader and FileWriter
classes.

Object Oriented Programming Through Java Page 132


Example

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadingTest1
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

try
{
in = new FileReader("D:\\ACEM\\II AI DS\\Input-File1.txt");
out = new FileWriter("D:\\ACEM\\II AI DS\\Output-File1.txt");
int c;

while ((c = in.read()) != -1)


{
out.write(c);
}
System.out.println("Reading and Writing has been success ");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
Output:
D:\ACEM\II AI DS>javac FileReadingTest1.java
D:\ACEM\II AI DS>java FileReadingTest1
Reading and Writing has been success

Object Oriented Programming Through Java Page 133


RandomAccessFile in Java

 The java.io package has a built-in class RandomAccessFile that enables a file to be accessed randomly.
 The RandomAccessFile class has several methods used to move the cursor position in a file.
 A random access file behaves like a large array of bytes stored in a file.
RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.

S.No. Constructor with Description


1 RandomAccessFile(File fileName, String mode)
It creates a random access file stream to read from, and optionally to write to, the file specified
by the File argument.
2 RandomAccessFile(String fileName, String mode)
It creates a random access file stream to read from, and optionally to write to, a file with the
specified fileName.

Access Modes
Using the RandomAccessFile, a file may created in th following modes.
 r - Creates the file with read mode; Calling write methods will result in an IOException.
 rw - Creates the file with read and write mode.
 rwd - Creates the file with read and write mode - synchronously. All updates to file content is written to
the disk synchronously.
 rws - Creates the file with read and write mode - synchronously. All updates to file content or meta data
is written to the disk synchronously.
RandomAccessFile methods

S.No. Methods with Description


1 int read()
It reads byte of data from a file. The byte is returned as an integer in the range 0-255.
2 int read(byte[] b)
It reads byte of data from file upto b.length, -1 if end of file is reached.
3 int read(byte[] b, int offset, int len)
It reads bytes initialising from offset position upto b.length from the buffer.
4 boolean readBoolean()
It reads a boolean value from from the file.
5 byte readByte()
It reads signed eight-bit value from file.
6 char readChar()
It reads a character value from file.
7 double readDouble()
It reads a double value from file.
8 float readFloat()
It reads a float value from file.

Object Oriented Programming Through Java Page 134


Example
import java.io.*;
public class RandomAccessFileDemo
{
public static void main(String[] args)
{
try
{
double d = 1.5;
float f = 14.56f;
RandomAccessFile ref = new RandomAccessFile("D:\\ACEM\\II AI DS\\random.txt", "rw");
ref.writeUTF("Hello, Good Morning!");

ref.seek(0); // File Pointer at index position - 0


System.out.println("Use of read() method : " +ref.read());

ref.seek(0);
byte[] b = {1, 2, 3};
System.out.println("Use of .read(byte[] b) : " +ref.read(b)); // Use of .read(byte[] b) method :

System.out.println("Use of readBoolean() : " +ref.readBoolean()); // readBoolean() method :


System.out.println("Use of readByte() : " +ref.readByte()); // readByte() method :
System.out.println("Use of readFloat() : " +ref.readFloat());
System.out.println("Use of readDouble() : " +ref.readDouble());
}
catch (IOException ex)
{
System.out.println("Something went Wrong");
ex.printStackTrace();
}
}
}
Output
D:\ACEM\II AI DS>javac RandomAccessFileDemo.java
D:\ACEM\II AI DS>java RandomAccessFileDemo
Use of read() method : 0
Use of .read(byte[] b) : 3
Use of readBoolean() : true
Use of readByte() : 108
Use of readFloat() : 1.1565666E27
Use of readDouble() : 1.3057638631517625E36

Object Oriented Programming Through Java Page 135


Console class in Java

 In java, the java.io package has a built-in class Console used to read from and write to the console, if
one exists.
 The Console class implements the Flushable interface.
 In java, most the input functionalities of Console class available through System.in, and the output
functionalities available through System.out.
Console class Constructors
The Console class does not have any constructor.
We can obtain the Console class object by calling System.console()
Console class methods

S.No. Methods with Description


1 void flush( )
It causes buffered output to be written physically to the console.
2 String readLine( )
It reads a string value from the keyboard, the input is terminated on pressing enter key.
3 Console format(String str, Object ....args)
It writes the given string to the console.
4 PrintWriter writer( )
It returns a reference to a Writer connected to the console.
Example
import java.io.Console;
public class ReadingDemo1
{
public static void main(String[] args)
{
String name;
Console con = System.console();
if(con != null)
{
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name);
}
else
{
System.out.println("Console not available.");
}
}
}
Output: D:\ACEM\II AI DS>javac ReadingDemo1.java
D:\ACEM\II AI DS>java ReadingDemo1
Please enter your name : raju
Hello,raju

Object Oriented Programming Through Java Page 136


Example
import java.io.*;
public class WritingDemo
{
public static void main(String[] args)
{
int[] list = new int[5];
for(int i = 0; i < 5; i++)
{
list[i] = i + 65;
}
for(int i : list)
{
System.out.write(i);
System.out.write('\n');
}
}
}
Output: D:\ACEM\II AI DS>javac WritingDemo.java
D:\ACEM\II AI DS>java WritingDemo
A
B
C
D
E
Serialization and Deserialization
 In java, the Serialization is the process of converting an object into a byte stream so that it can be stored
on to a file, or memory, or a database for future access.
 The deserialization is reverse of serialization.
 The deserialization is the process of reconstructing the object from the serialized state.
 Using serialization and deserialization, we can transfer the Object Code from one Java Virtual machine
to another.
Serialization in Java
 In a java programming language, the Serialization is achieved with the help of interface Serializable.
 The class whose object needs to be serialized must implement the Serializable interface.
 We use the ObjectOutputStream class to write a serialized object to write to a destination.
 The ObjectOutputStream class provides a method writeObject() to serializing an object.
steps to serialize an object

Step 1 - Define the class whose object needs to be serialized; it must implement Serializable interface.
Step 2 - Create a file reference with file path using FileOutputStream class.
Step 3 - Create reference to ObjectOutputStream object with file reference.
Step 4 - Use writeObject(object) method by passing the object that wants to be serialized.
Step 5 - Close the FileOutputStream and ObjectOutputStream.

Object Oriented Programming Through Java Page 137


Example

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable
{
int id;
String name;

public Student(int id, String name)


{
this.id = id;
this.name = name;
}
}

public class SerializationExample


{
public static void main(String[] args)
{
try
{
Student s1 = new Student(211,"ravi");
FileOutputStream fout = new FileOutputStream("f.txt"); //Creating stream and writing the obj
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
out.close();
System.out.println("success");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output
D:\ACEM\II AI DS>javac SerializationExample.java
D:\ACEM\II AI DS>java SerializationExample
success

Object Oriented Programming Through Java Page 138


Deserialization in Java
 In a java programming language, the Deserialization is achieved with the help of
class ObjectInputStream.
 This class provides a method readObject() to deserializing an object.
Steps to serialize an object.

 Step 1 - Create a file reference with file path in which serialized object is available using

FileInputStream class.
 Step 2 - Create reference to ObjectInputStream object with file reference.

 Step 3 - Use readObject() method to access serialized object, and typecaste it to destination type.

 Step 4 - Close the FileInputStream and ObjectInputStream.

Example (deserializing an object)


import java.io.*;
public class DeserializationExample
{
public static void main(String[] args) throws Exception
{
try
{
FileInputStream fis = new FileInputStream("f.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Student stud2 = (Student) ois.readObject();
System.out.println(" The object has been deserialized. ");
fis.close();
ois.close();
System.out.println("Name = " + stud2.id);
System.out.println("Department = " + stud2.name);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output: D:\ACEM\II AI DS>javac DeserializationExample.java
D:\ACEM\II AI DS>java DeserializationExample
The object has been deserialized.
Name = 211
Department = ravi

Object Oriented Programming Through Java Page 139


Enum in Java

 An enum is a special "class" that represents a group of constants (unchangeable variables, like final
variables).
 This concept enables the java enum to have constructors, methods, and instance variables.
 All the constants of an enum are public, static, and final.
 As they are static, we can access directly using enum name.
 The main objective of enum is to define our own data types in Java, and they are said to be enumeration
data types.
Creating enum in Java
 In java, an enum can be defined outside a class, inside a class, but not inside a method.
 To create an enum, use the enum keyword , and separate the constants with a comma.
 Note that they should be in uppercase letters:
 Access enum constants with the dot syntax
 Enum is short for "enumerations", which means "specifically listed".
 Every constant of an enum is defined as an object and enum does not allow to create an object of it.
 As an enum represents a class, it can have methods, constructors. It also gets a few extra methods from
the Enum class, and one of them is the values() method.
Enum using values() method
The enum type has a values() method, which returns an array of all enum constants. This method is
useful when you want to loop through the constants of an enum:
Example
enum WeekDay
{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class EnumerationExample
{
public static void main(String[] args)
{
WeekDay day = WeekDay.FRIDAY;
System.out.println(" Today is " + day);
System.out.println("\n All WeekDays: ");
for(WeekDay d : WeekDay.values())
{
System.out.println(d);
}
}
}

Object Oriented Programming Through Java Page 140


Output:
Today is FRIDAY

All WeekDays:
MONDAY
TUESDAY
WEDNESSDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
Java Enum ordinal() Method
The ordinal() method of Enum class returns the ordinal of this enumeration constant.
This method is designed to be used by sophisticated enum-based data structures, like EnumSet and EnumMap.
Syntax
public final int ordinal()
Return Value
The ordinal() method returns this enumeration constant's ordinal.
Example
public class Enum_ordinalMethodExample1
{
enum Colours
{
Red,Green,Brown,Yellow;
}
public static void main(String[] args)
{
Colours Red = Colours.Red;
Colours Green = Colours.Green;
Colours Brown = Colours.Brown;
Colours Yellow = Colours.Yellow;
System.out.println(" Red ordinal = "+Red.ordinal());
System.out.println(" Green Ordinal = "+Green.ordinal());
System.out.println(" Brown Ordinal = "+Brown.ordinal());
System.out.println(" Yellow Ordinal = "+Yellow.ordinal());
}
}
Output:
Red ordinal = 0
Green Ordinal = 1
Brown Ordinal = 2
Yellow Ordinal = 3
Object Oriented Programming Through Java Page 141
Autoboxing and Unboxing in Java
 All the primitive data types have defined using the class concept, these classes known as wrapper
classes.
 In java, every primitive type has its corresponding wrapper class.
 All the wrapper classes in Java were defined in the java.lang package.
 The following table shows the primitive type and its corresponding wrapper class.

S.No. Primitive Type Wrapper class

1 byte Byte

2 short Short

3 int Interger

4 long Long

5 float Float

6 double Double

7 char Character

8 boolean Boolean

The Java 1.5 version introduced a concept that converts primitive type to corresponding wrapper type and
reverses of it.
Autoboxing in Java

 In java, the process of converting a primitive type value into its corresponding wrapper class object is
called autoboxing or simply boxing.
 For example, converting an int value to an Integer class object.
 The compiler automatically performs the autoboxing when a primitive type value has assigned to an
object of the corresponding wrapper class.
 We can also perform autoboxing manually using the method valueOf( ), which is provided by every
wrapper class.

Object Oriented Programming Through Java Page 142


Example - Autoboxing
import java.lang.*;
public class AutoBoxingExample
{
public static void main(String[] args)
{
int num = 100; // Auto boxing : primitive to Wrapper
Integer i = num;
Integer j = Integer.valueOf(num);
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}
Output:
D:\SASI\sasijava>javac AutoBoxingExample.java
D:\SASI\sasijava>java AutoBoxingExample
num = 100, i = 100, j = 100
Auto un-boxing in Java
 In java, the process of converting an object of a wrapper class type to a primitive type value is called
auto un-boxing or simply unboxing.
 For example, converting an Integer object to an int value.
 The compiler automatically performs the auto un-boxing when a wrapper class object has assigned to a
primitive type.
 We can also perform auto un-boxing manually using the method intValue( ), which is provided by
Integer wrapper class. Similarly every wrapper class has a method for auto un-boxing.
Example - Auto unboxing
import java.lang.*;
public class AutoUnboxingExample
{
public static void main(String[] args)
{
Integer num = 200; // Auto un-boxing : Wrapper to primitive
int i = num;
int j = num.intValue();
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}
Output:
D:\SASI\sasijava>javac AutoUnboxingExample.java
D:\SASI\sasijava>java AutoUnboxingExample
num = 200, i = 200, j = 200

Object Oriented Programming Through Java Page 143


Generics in Java
 The java generics is a language feature that allows creating methods and class which can handle any
type of data values.
 Most of the collection framework classes are generic classes.
 The java generics allows only non-primitive type, it does not support primitive types like int, float, etc.
 Generics provide us compile time safety which helps the programmer to catch the invalid type at
compile time.
 There are two reasons why we need generics .They are Type Safety and Type Casting
The java generics feature was introduced in Java 1.5 version. In java, generics used angular brackets “< >”.
In java, the generics feature implemented using the following Generic Method or Generic Class
Generic methods
 The java generics allows creating generic methods which can work with a different type of data values.
 Using a generic method, we can create a single method that can be called with arguments of different
types.
 Based on the types of the arguments passed to the generic method, the compiler handles each method
call appropriately.
Example - Generic method
public class GenericMethodTest
{
public static < E > void printArray( E[] inputArray)
{
for(E element : inputArray)
{
System.out.printf("%s",element);
}
System.out.println();
}
public static void main(String args[])
{
Integer[] intArray = {1,2,3,4,5};
Character[] charArray = {'h','e','l','l','o'};
System.out.println(" Array inter contains ");
printArray(intArray);
System.out.println(" Array character contains ");
printArray(charArray);
}
}

Object Oriented Programming Through Java Page 144


Output:
D:\SASI\sasijava>javac GenericMethodTest.java
D:\SASI\sasijava>java GenericMethodTest
Array inter contains
12345
Array character contains
Hello

In the above example code, the method printArray ( ) is a generic method that allows a different type of
parameter values for every function call.
Generic Class
In java, a class can be defined as a generic class that allows creating a class that can work with different types.
A generic class declaration looks like a non-generic class declaration, except that the class name is followed by
a type parameter section.
Example - Generic class
public class GenericClass <T1,T2>
{
public void display(T1 var1,T2 var2)
{
System.out.println("Name:"+var1+", ID:"+var2);
}

public static void main(String args[])


{
GenericClass<String,Integer> obj1 = new GenericClass<String,Integer>();
GenericClass<Integer,Integer> obj2 = new GenericClass<Integer,Integer>();
obj1.display("Mounica",101);
obj2.display(100,101);
}
}
Output:
D:\SASI\sasijava>javac GenericClass.java
D:\SASI\sasijava>java GenericClass
Name:Mounica, ID:101
Name:100, ID:101

Object Oriented Programming Through Java Page 145


Multithreading in java

 The java programming language allows us to create a program that contains one or more parts that can
run simultaneously at the same time. This type of program is known as a multithreading program.
 Each part of this program is called a thread. Every thread defines a separate path of execution in java.

A thread is explained in different ways, and a few of them are as specified below.

 A thread is a light weight process. (or) A thread is a subpart of a process that can run individually.
 In java, multiple threads can run at a time, which enables the java to write multitasking programs.

 The multithreading is a specialized form of multitasking.


 All modern operating systems support multitasking.
There are two types of multitasking, and they are as follows.
 Process-based multitasking
 Thread-based multitasking

It is important to know the difference between process-based and thread-based multitasking.

Process-based multitasking Thread-based multitasking


It allows the computer to run two or more It allows the computer to run two or more
programs concurrently threads concurrently
In this process is the smallest unit. In this thread is the smallest unit.

Process is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

Process requires separate address space for each. Threads share same address space.

Process never gain access over idle time of CPU. Thread gain access over idle time of CPU.

Inter process communication is expensive. Inter thread communication is not expensive.

Object Oriented Programming Through Java Page 146


Thread class
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.

The Thread class has the following consructors.


 Thread( )
 Thread( String threadName )
 Thread( Runnable objectName )
 Thread( Runnable objectName, String threadName )

The Thread class contains the following methods.

Method Description Return Value

run( ) Defines actual task of the thread. void

start( ) It moves there thread from Ready state to Running state by calling Void
run( ) method.

setName(String) Assigns a name to the thread. Void

getName( ) Returns the name of the thread. String

setPriority(int) Assigns priority to the thread. Void

getPriority( ) Returns the priority of the thread. Int

getId( ) Returns the ID of the thread. Long

activeCount() Returns total number of thread under active. Int

currentThread( ) Returns the reference of the thread that currently in running state. Void

sleep( long ) moves the thread to blocked state till the specified number of milliseconds. Void

isAlive( ) Tests if the thread is alive. Boolean

yield( ) Tells to the scheduler that the current thread is willing to yield its current use Void
of a processor.

join( ) Waits for the thread to end. Void

Object Oriented Programming Through Java Page 147


 The Thread class in java also contains methods like stop( ), destroy( ), suspend( ), and resume( ). But
they are deprecated.
 Other thread methods are
isDaemon(): tests if the thread is a daemon thread.
getId(): returns the id of the thread.
interrupt(): interrupts the thread.
isInterrupted(): tests if the thread has been interrupted.
Note: Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or
because a better alternative exists.

The Java thread model


 In java, a thread goes through different states throughout its execution. These stages are called thread
life cycle states or phases.
 A thread may in any of the states like new, ready or runnable, running, blocked or wait, and dead or
terminated state.
The life cycle of a thread in java is shown in the following figure.

New
When a thread object is created using new, then the thread is said to be in the New state.
This state is also known as Born state.
Example
Thread t1 = new Thread();

Object Oriented Programming Through Java Page 148


Runnable / Ready

When a thread calls start( ) method, then the thread is said to be in the Runnable state.
This state is also known as a Ready state.
Example
t1.start( );

Running
When a thread calls run( ) method, then the thread is said to be Running.
The run( ) method of a thread called automatically by the start( ) method.

Blocked / Waiting

A thread in the Running state may move into the blocked state due to various reasons like sleep( ) method
called, wait( ) method called, suspend( ) method called, and join( ) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons like sleep time
completed, waiting time completed, notify( ) or notifyAll( ) method called, resume( ) method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait();
suspend();
notify();
notifyAll();
resume();

Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution completed or the stop( )
method called. The dead state is also known as the terminated state.
Creating Threads
 In java, a thread is a lightweight process.
 Every java program executes by a thread called the main thread. When a java program gets executed, the
main thread created automatically. All other threads called from the main thread.
The java programming language provides two methods to create threads listed below.
 Using Thread class (by extending Thread class)

 Using Runnable interface (by implementing Runnable interface)

Object Oriented Programming Through Java Page 149


Extending Thread class
 The java contains a built-in class Thread inside the java.lang package.
 The Thread class contains all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.
 Step-1: Create a class as a child of Thread class. That means, create a class that extends Thread class.

 Step-2: Override the run( ) method with the code that is to be executed by the thread. The run( ) method

must be public while overriding.


 Step-3: Create the object of the newly created class in the main( ) method.

 Step-4: Call the start( ) method on the object created in the above step.

Example
class SampleThread extends Thread
{
public void run()
{
for(int i= 1; i<=4; i++)
{
try
{
System.out.println("i = " + i);
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

public class ThreadCreate


{
public static void main(String[] args)
{
SampleThread s1 = new SampleThread();
SampleThread s2 = new SampleThread();
Thread t1=new Thread(s1);
Thread t2=new Thread(s2);
System.out.println("Thread about to start...");
t1.start();
t2.start();
}
}

Object Oriented Programming Through Java Page 150


Output:
D:\ACEM\II CSE Bsection>javac ThreadCreate.java
D:\ACEM\II CSE Bsection>java ThreadCreate
Thread about to start...
i=1
i=1
i=2
i=2
i=3
i=3
i=4
i=4
Implementng Runnable interface
 The java contains a built-in interface Runnable inside the java.lang package.
 The Runnable interface implemented by the Thread class that contains all the methods that are related to
the threads.
To create a thread using Runnable interface, follow the step given below.
 Step-1: Create a class that implements Runnable interface.

 Step-2: Override the run( ) method with the code that is to be executed by the thread. The run( ) method

must be public while overriding.


 Step-3: Create the object of the newly created class in the main( ) method.

 Step-4: Create the Thread class object by passing above created object as parameter to the Thread class

constructor.
 Step-5: Call the start( ) method on the Thread class object created in the above step.
Example
class SampleThread implements Runnable
{
public void run()
{
for(int i= 1; i<=4; i++)
{
try
{
System.out.println("i = " + i);
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

Object Oriented Programming Through Java Page 151


public class ThreadCreate1
{
public static void main(String[] args)
{
SampleThread s1 = new SampleThread();
SampleThread s2 = new SampleThread();
Thread t1=new Thread(s1);
Thread t2=new Thread(s2);
System.out.println("Thread about to start...");
t1.start();
t2.start();
}
}
Output:
D:\ACEM\II CSE Bsection>javac ThreadCreate1.java
D:\ACEM\II CSE Bsection>java ThreadCreate1
Thread about to start...
i=1
i=1
i=2
i=2
i=3
i=3
i=4
Thread priorities

 In a java programming language, every thread has a property called priority.


 Most of the scheduling algorithms use the thread priority to schedule the execution sequence.
 In java, the thread priority range from 1 to 10.
 Priority 1 is considered as the lowest priority, and priority 10 is considered as the highest priority.
 The thread with more priority allocates the processor first.
 Thread class provides two methods setPriority(int),and getPriority( ) to handle thread priorities.

 The Thread class also contains three constants that are used to set the thread priority, and they are
MAX_PRIORITY - It has the value 10 and indicates highest priority.
NORM_PRIORITY - It has the value 5 and indicates normal priority.
MIN_PRIORITY - It has the value 1 and indicates lowest priority.

The default priority of any thread is 5 (i.e. NORM_PRIORITY).

Object Oriented Programming Through Java Page 152


setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread.
It takes an integer range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.
Example
threadObject.setPriority(4); or threadObject.setPriority(MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not takes
any argument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.
Example
String threadName = threadObject.getPriority();
Example
class SampleThread extends Thread
{
public void run()
{
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " + Thread.currentThread().getName());
}
}
public class PriorotyThreds
{
public static void main(String[] args)
{
SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);
threadObject1.start();
threadObject2.start();
}
}

Object Oriented Programming Through Java Page 153


Output:
D:\ACEM\II CSE Bsection>javac PriorotyThreds.java
D:\ACEM\II CSE Bsection>java PriorotyThreds
Inside SampleThread
Inside SampleThread
Current Thread: second
Current Thread:first
Note:In java, it is not guaranteed that threads execute according to their priority because it depends on JVM
specification that which scheduling it chooses.
Synchronizing threads
 The java programming language supports multithreading.
 The problem of shared resources occurs when two or more threads get execute at the same time.
 In such a situation, we need some way to ensure that the shared resource will be accessed by only one
thread at a time, and this is performed by using the concept called synchronization.

The synchronization is the process of allowing only one thread to access a shared resource at a time.

In java, the synchronization is achieved using the following concepts.


 Mutual Exclusion
 Inter thread communication
Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while they
accessing the shared resource.
In java, mutual exclusion is achieved using the following concepts.
Synchronized method
Synchronized block
Synchronized method

When a method created using a synchronized keyword, it allows only one object to access it at a time.
 When an object calls a synchronized method, it put a lock on that method so that other objects or thread
that are trying to call the same method must wait, until the lock is released.
 Once the lock is released on the shared resource, one of the threads among the waiting threads will be
allocated to the shared resource.

Object Oriented Programming Through Java Page 154


 In the above image, initially the thread-1 is accessing the synchronized method and other threads
(thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
 When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.
Example
class Table
{
synchronized void printTable(int n) // Here, method is synchronized.
{
for(int i = 1; i <= 5; i++)
{
System.out.println(n * i);
try
{
Thread.sleep(400);
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
}
}
class Thread1 extends Thread
{
Table t; // Declaration of variable t of class type Table.
Thread1(Table t) // Declare one parameterized constructor and pass variable t as a parameter.
{
this.t = t;
}
public void run()
{
t.printTable(2);
}
}

Object Oriented Programming Through Java Page 155


class Thread2 extends Thread
{
Table t;

Thread2(Table t)
{
this.t = t;
}

public void run()


{
t.printTable(10);
}
}
public class SynchronizedMethod
{
public static void main(String[] args)
{
Table obj = new Table(); // Create an object of class Table.
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
t1.start();
t2.start();
}
}
Output:
D:\ACEM\II CSE Bsection>javac SynchronizedMethod.java
D:\ACEM\II CSE Bsection>java SynchronizedMethod
2
4
6
8
10
10
20
30
40
50

Object Oriented Programming Through Java Page 156


Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of lines in a method.
For example, let's consider a method with 20 lines of code where we want to synchronize only a sequence of
five lines code, we use the synchronized block.
Syntax
synchronized(object)
{ ...
block code
...
}
Note: The complete code of a method may be written inside the synchronized block, where it works similarly to
the synchronized method.
Interthread communication
 Inter thread communication is the concept where two or more threads communicate to solve the problem
of polling.
 In java, polling is the situation to check some condition repeatedly, to take appropriate action, once the
condition is true. That means, in inter-thread communication, a thread waits until a condition becomes
true such that other threads can execute its task.
 The inter-thread communication allows the synchronized threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.

Method Description

void wait( ) It makes the current thread to pause its execution until other thread in the same monitor calls notify( )

void notify( ) It wakes up the thread that called wait( ) on the same object.

void notifyAll() It wakes up all the threads that called wait( ) on the same object.

calling notify( ) or notifyAll( ) does not actually give up a lock on a resource.

Let's look at an example problem of producer and consumer.

The producer produces the item and the consumer consumes the same. But here, the consumer can not consume
until the producer produces the item, and producer can not produce until the consumer consumes the item that
already been produced.
So here, the consumer has to wait until the producer produces the item, and the producer also needs to wait until
the consumer consumes the same. Here we use the inter-thread communication to implement the producer and
consumer problem.

Object Oriented Programming Through Java Page 157


Example
import java.util.LinkedList;

class ProducerConsumer
{
LinkedList<Integer> list = new LinkedList<>();
public void produce() throws InterruptedException
{
int value=0;
while(true)
{
synchronized(this)
{
while(list.size()>0)
wait();

System.out.println("producer data "+value);


list.add(value);

value++;
notify();
}
}
}

public void consume() throws InterruptedException


{
while(true)
{
synchronized(this)
{
while(list.size() ==0)
wait();

int value=list.removeFirst();

System.out.println("Consumer data "+value);


notify();

Thread.sleep(2000);
}
}
}
}

Object Oriented Programming Through Java Page 158


class ExeLogics
{

public static void main(String args[])throws InterruptedException


{
ProducerConsumer pc = new ProducerConsumer();

Thread t1 = new Thread(new Runnable()


{
public void run()
{
try
{
pc.produce();
}
catch(Exception e)
{
System.out.println(e);
}
}
});

Thread t2 = new Thread(new Runnable()


{
public void run()
{
try
{
pc.consume();
}
catch(Exception e)
{
System.out.println(e);
}
}
});

t1.start();
t2.start();

t1.join();
t2.join();
}
}

Object Oriented Programming Through Java Page 159


Output

D:\ACEM\II AI DS>javac ExeLogics.java


D:\ACEM\II AI DS>java ExeLogics

producer data 0
Consumer data 0
producer data 1
Consumer data 1
producer data 2
Consumer data 2
producer data 3
Consumer data 3
Note: while running this program press CTRL+C to break the execution

Java Collection Framework Overview


 Java collection framework is a collection of interfaces and classes used to storing and processing a group
of individual objects as a single unit.
 The java collection framework holds several classes that provide a large number of methods to store and
process a group of objects.
These classes make the programmer task super easy and fast.
 Java collection framework was introduced in java 1.2 version.
 Java collection framework has the following hierarchy.

 Before the collection framework in java (before java 1.2 version), there was a set of classes
like Array, Vector, Stack, HashTable. These classes are known as legacy classes.
 The java collection framework contains List, Queue, Set, and Map as top-level interfaces.
 The List, Queue, and Set stores single value as its element, whereas Map stores a pair of a key and value

Object Oriented Programming Through Java Page 160


Java Collection Interface
 The Collection interface is the root interface for most of the interfaces and classes of collection
framework.
 The Collection interface is available inside the java.util package.
 It defines the methods that are commonly used by almost all the collections.
 The Collection interface extends Iterable interface.
 The Collection interface defines the following methods.

Object Oriented Programming Through Java Page 161


The Collection classes
ArrayList class
The ArrayList class is a part of java collection framework and It is available inside the java.util package.
 The ArrayList class extends AbstractList class and implements List interface.
 The elements of ArrayList are organized as an array internally. The default size of an ArrayList is 10.
 The ArrayList class is used to create a dynamic array that can grow or shrunk as needed.
 ArrayList is is a child class of AbstractList implements List, Serializable, Cloneable, RandomAccess.

 The ArrayList allows to store duplicate data values.


 The ArrayList allows to access elements randomly using index-based accessing.
 The ArrayList maintains the order of insertion.
ArrayList class declaration
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable,
Serializable
ArrayList class constructors
The ArrayList class has the following constructors.
 ArrayList( ) - Creates an empty ArrayList.

 ArrayList(Collection c) - Creates an ArrayList with given collection of elements.

 ArrayList(int size) - Creates an empty ArrayList with given size (capacity).

Operations on ArrayList

The ArrayList class allow us to perform several operations like adding, accessing, deleting, updating, etc.
Adding Items
The ArrayList class has the following methods to add items.
 boolean add(E element) - Appends given element to the ArrayList.

 boolean addAll(Collection c) - Appends given collection of elements to the ArrayList.

 void add(int index, E element) - Inserts the given element at specified index.

Accessing Items
The ArrayList class has the following methods to access items.
 E get(int index) - Returns element at specified index from the ArrayList.

 ArrayList subList(int startIndex, int lastIndex) - Returns an ArrayList that contains elements from

specified startIndex to lastIndex-1 from the invoking ArrayList.


Updating Items
The ArrayList class has the following methods to update or change items.
 E set(int index, E newElement) - Replace the element at specified index with new Element in the

invoking ArrayList.

Object Oriented Programming Through Java Page 162


Removing Items
The ArrayList class has the following methods to remove items.
 E remove(int index) - Removes the element at specified index in the invoking ArrayList.

 boolean remove(Object element) - Removes the first occurrence of the given element from the invoking

ArrayList.
 boolean removeAll(Collection c) - Removes the given collection of elements from the invoking

ArrayList.
 void retainAll(Collection c) - Removes all the elements except the given collection of elements from the

invoking ArrayList..
 void clear( ) - Removes all the elements from the ArrayList.

Example
import java.util.ArrayList;
class JavaExample1
{
public static void main(String args[])
{
ArrayList<String> arrList=new ArrayList<>();

//adding few elements

arrList.add("Cricket"); //list: ["Cricket"]


arrList.add("Hockey"); //list: ["Cricket", "Hockey"]
arrList.add(0, "BasketBall"); //list: ["BasketBall", "Cricket", "Hockey"]

System.out.println("ArrayList Elements: ");

/* Traversing ArrayList using enhanced for loop


for(String str:arrList)
System.out.println(str); */
for(int i=0;i<arrList.size();i++)
{
System.out.println(arrList(i));
}
}
}
Output:
D:\ACEM\II AI DS>javac JavaExample1.java
D:\ACEM\II AI DS>java JavaExample1
ArrayList Elements:
BasketBall
Cricket
Hockey

Object Oriented Programming Through Java Page 163


Linked List
 The LinkedList class is a part of java collection framework. It is available inside the java.util package.
 The LinkedList class extends AbstractSequentialList class and implements List and Deque interface.
 The elements of LinkedList are organized as the elements of linked list data structure.
 The LinkedList class is used to create a dynamic list of elements that can grow or shrunk as needed.
 The LinkedList is a child class of AbstractSequentialList
 The LinkedList implements interfaces like List, Deque, Cloneable, and Serializable.
 The LinkedList allows to store duplicate data values.
 The LinkedList maintains the order of insertion.
LinkedList class declaration

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>,


Cloneable, Serializable
Example
import java.util.LinkedList;
import java.util.Iterator;
public class JavaExample2
{
public static void main(String args[])
{
LinkedList<String> linkList=new LinkedList<>();

linkList.add("Apple"); //["Apple"]
linkList.add("Orange"); //["Apple", "Orange"]

//inserting element at first position


linkList.add(0, "Banana"); //["Banana", "Apple", "Orange"]

System.out.println("LinkedList elements: ");

//iterating LinkedList using iterator


Iterator<String> it=linkList.iterator();

while(it.hasNext())
{
System.out.println(it.next());
}
}
}
Output:
D:\ACEM\II AI DS>javac JavaExample2.java
D:\ACEM\II AI DS>java JavaExample2
LinkedList elements:
Banana
Apple
Orange
Object Oriented Programming Through Java Page 164
Hash Set
 The HashSet class extends AbstractSet class and implements Set interface.
 The elements of HashSet are organized using a mechanism called hashing.
 The HashSet is used to create hash table for storing set of elements.
 The HashSet class is used to create a collection that uses a hash table for storing set of elements.
 The HashSet does not allows to store duplicate data values, but null values are allowed.
 The HashSet does not maintains the order of insertion.
 The HashSet initial capacity is 16 elements.
 The HashSet is best suitable for search operations.
HashSet class declaration
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
Program:
import java.util.HashSet;
import java.util.Iterator;
public class JavaExample3
{
public static void main(String args[])
{
HashSet<String> set=new HashSet<>();

set.add("honey cake");
set.add("stawberry");
set.add("vennela cake");
set.add("ice cake");

Iterator<String> it=set.iterator();

while(it.hasNext())
{
System.out.println(it.next());
}
}
}
Output:

D:\ACEM\II AI DS>javac JavaExample3.java


D:\ACEM\II AI DS>java JavaExample3
ice cake
stawberry
honey cake
vennela cake

Object Oriented Programming Through Java Page 165


Tree Set
 The TreeSet class is a part of java collection framework. It is available inside the java.util package.
 The TreeSet class extends AbstractSet class and implements NavigableSet, Cloneable, and Serializable
interfaces.
 The elements of TreeSet are organized using a echanism called tree.
 The TreeSet class internally uses a TreeMap to store elements. The elements in a TreeSet are sorted
according to their natural ordering.
 The TreeSet does not allows to store duplicate data values, but null values are allowed.
 The elements in a TreeSet are sorted according to their natural ordering.
 The TreeSet initial capacity is 16 elements and it is best suitable for search operations.
TreeSet class declaration
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
Example:
import java.util.TreeSet;
import java.util.Iterator;
public class JavaExample4
{
public static void main(String args[])
{
TreeSet<String> set=new TreeSet<>();
set.add("airtel");
set.add("idea");
set.add("jio");
set.add("voda phone");
Iterator<String> it=set.iterator();

while(it.hasNext())
{
System.out.println(it.next());
}
}
}
Output:
D:\ACEM\II AI DS>javac JavaExample4.java
D:\ACEM\II AI DS>java JavaExample4
airtel
idea
jio
voda phone

Object Oriented Programming Through Java Page 166


Priority Queue
 The PriorityQueue classand ,.it is available inside the java.util package.
 The PriorityQueue class extends AbstractQueue class and implements Serializable interface.
 The elements of PriorityQueue are organized as the elements of queue , but it does not follow FIFO.
 The PriorityQueue elements are organized based on the priority heap and maintains the order of
insertion
 The PriorityQueue class is used to create a dynamic queue of elements that can grow or shrunk as
needed.
 The PriorityQueue is a child class of AbstractQueue and implements Serializable interface
 The PriorityQueue allows to store duplicate data values, but not null values.
PriorityQueue class declaration

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable


Example
import java.util.*;
public class PriorityQueueExample1
{
public static void main(String[] args)
{
PriorityQueue queue = new PriorityQueue();
PriorityQueue anotherQueue = new PriorityQueue();

queue.add(10);
queue.add(20);
queue.add(15);

System.out.println("\nQueue is " + queue);


anotherQueue.addAll(queue);

System.out.println("\n anotherQueue is " + anotherQueue);


anotherQueue.offer(25);

System.out.println("\nanotherQueue is " + anotherQueue);


}
}
Output:
D:\sasi>javac PriorityQueueExample1.java
D:\sasi>java PriorityQueueExample1
Queue is [10, 20, 15]
anotherQueue is [10, 20, 15]
anotherQueue is [10, 20, 15, 25]

Object Oriented Programming Through Java Page 167


Array Deque
 The ArrayDeque class is a part of java collection framework. It is available inside the java.util package.
 The ArrayDeque class extends AbstractCollection class and implements Deque, Cloneable,
and Serializable interfaces.
 The elements of ArrayDeque are organized as the elements of double ended queue data structure.
 The ArrayDeque is a special kind of array that grows and allows users to add or remove an element from
both the sides of the queue.
 The ArrayDeque class is used to create a dynamic double ended queue of elements that can grow or
shrunk as needed.
 The ArrayDeque is a child class of AbstractCollection
 The ArrayDeque implements interfaces like Deque, Cloneable, and Serializable.
 The ArrayDeque allows to store duplicate data values, but not null values.
 The ArrayDeque maintains the order of insertion.
 The ArrayDeque allows to add and remove elements at both the ends.
 The ArrayDeque is faster than LinkedList and Stack.
ArrayDeque class declaration
public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable

Example:
import java.util.Deque;
import java.util.ArrayDeque;
public class TestJavaCollection6
{
public static void main(String[] args)
{
//Creating Deque and adding elements

Deque<String> deque = new ArrayDeque<String>();

deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");

//Traversing elements

for (String str : deque)


{
System.out.println(str);
}
}
}
Output:
D:\ACEM\II AI DS>javac TestJavaCollection6.java
D:\ACEM\II AI DS>java TestJavaCollection6
Gautam
Karan
Ajay

Object Oriented Programming Through Java Page 168


Hashtable
 In java, the package java.util contains a class called Hashtable which works like a HashMap but it is
synchronized.
 The Hashtable is a concrete class of Dictionary.
 It is used to store and manage elements in the form of a pair of key and value.
 The Hashtable stores data as a pair of key and value. In the Hashtable, each key associates with a value.
 Any non-null object can be used as a key or as a value. We can use the key to retrieve the value back
when needed.
 The Hashtable class is no longer in use, it is obsolete. The alternate class is HashMap.
 The Hashtable class is a concrete class of Dictionary.
 The Hashtable class is synchronized.
 The Hashtable does no allow null key or value and Hashtable has the initial default capacity 11.
Example:
import java.util.Hashtable;
import java.util.Map;
class Hashtable1
{
public static void main(String args[])
{
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
D:\ACEM\II AI DS>javac Hashtable1.java
D:\ACEM\II AI DS>java Hashtable1
103 Rahul
102 Ravi
101 Vijay
100 Amit

Object Oriented Programming Through Java Page 169


Properties
 In java, the package java.util contains a class called Properties which is a child class of Hashtable
class.
 It implements interfaces like Map, Cloneable, and Serializable.
 The Properties class used to store configuration values managed as key, value pairs. In each pair, both
key and value are String values. We can use the key to retrieve the value back when needed.
 The Properties class provides methods to get data from the properties file and store data into the
properties file. It can also be used to get the properties of a system.
 The Properties class is child class of Hashtable class.
 The Properties class implements Map, Cloneable, and Serializable interfaces.
 The Properties class used to store configuration values.
 The Properties class stores the data as key, value pairs.
 In Properties class both key and value are String data type.
 Using Properties class, we can load key, value pairs into a Properties object from a stream.
 Using Properties class, we can save the Properties object to a stream.
Example: db.properties (save in separate notepad)
user=system
password=oracle
Program:
import java.util.*;
import java.io.*;
public class TestProperties
{
public static void main(String[] args)throws Exception
{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output:
D:\ACEM\II AI DS>javac TestProperties.java
D:\ACEM\II AI DS>java TestProperties
system
oracle

Object Oriented Programming Through Java Page 170


Stack
 In java, the package java.util contains a class called Stack which is a child class of Vector class.
 It implements the standard principle Last-In-First-Out of stack data structure.
The Stack has push method for insertion and pop method for deletion. It also has other utility methods.
In Stack, the elements are added to the top of the stack and removed from the top of the stack.
Example
import java.util.*;
public class StackClassExample
{
public static void main(String[] args)
{
Stack stack = new Stack();
Random num = new Random();
for(int i = 0; i < 5; i++)
stack.push(num.nextInt(100));

System.out.println("Stack elements => " + stack);


System.out.println("Top element is " + stack.peek());
System.out.println("Removed element is " + stack.pop());
System.out.println("Element 50 availability => " + stack.search(50));
System.out.println("Stack is empty? - " + stack.isEmpty());
}
}
Output:
D:\SASI\sasijava>javac StackClassExample.java
Note: StackClassExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

D:\SASI\sasijava>java StackClassExample
Stack elements => [14, 42, 15, 14, 19]
Top element is 19
Removed element is 19
Element 50 availability => -1
Stack is empty? – false

Object Oriented Programming Through Java Page 171


Vector
 In java, the package java.util contains a class called Vector which implements the List interface.
 The Vector is similar to an ArrayList. Like ArrayList Vector also maintains the insertion order. But
Vector is synchronized, due to this reason, it is rarely used in the non-thread application. It also lead to
poor performance.
 The Vector is a class in the java.util package.
 The Vector implements List interface.
 The Vector is a legacy class.
 The Vector is synchronized.
Example:
import java.util.*;
public class VectorExample
{
public static void main(String args[])
{

Vector<String> vec = new Vector<String>();

//Adding elements using add() method of List

vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");

//Adding elements using addElement() method of Vector

vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");

System.out.println("Elements are: "+vec);


}
}
Output:
D:\ACEM\II AI DS>javac VectorExample.java

D:\ACEM\II AI DS>java VectorExample

Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Object Oriented Programming Through Java Page 172


String Tokenizer
 The StringTokenizer is a built-in class in java used to break a string into tokens. The StringTokenizer
class is available inside the java.util package.
 The StringTokenizer class object internally maintains a current position within the string to be
tokenized.
 A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
Example:
import java.util.StringTokenizer;

public class StringTokenizerExample


{

public static void main(String args[])


{
StringTokenizer st = new StringTokenizer("my name is sachin"," ");

while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
D:\ACEM\II AI DS>javac StringTokenizerExample.java
D:\ACEM\II AI DS>java StringTokenizerExample
my
name
is
sachin
Bit Set
 The BitSet is a built-in class in java used to create a dynamic array of bits represented by boolean
values. The BitSet class is available inside the java.util package.
 The BitSet array can increase in size as needed. This feature makes the BitSet similar to a Vector of bits.
 The bit values can be accessed by non-negative integers as an index.
 The size of the array is flexible and can grow to accommodate additional bit as needed.
 The default value of the BitSet is boolean false with a representation as 0 (off).
 BitSet uses 1 bit of memory per each boolean value.

Object Oriented Programming Through Java Page 173


Example:
import java.util.BitSet;
public class BitSetAndExample1
{
public static void main(String[] args)
{
// create 2 bitsets

BitSet bitset1 = new BitSet();


BitSet bitset2 = new BitSet();

// assign values to bitset1


bitset1.set(0);
bitset1.set(1);
bitset1.set(2);
bitset1.set(3);
bitset1.set(4);

// assign values to bitset2


bitset2.set(2);
bitset2.set(4);
bitset2.set(6);
bitset2.set(8);
bitset2.set(10);

// print the sets


System.out.println("bitset1: " + bitset1);
System.out.println("bitset2: " + bitset2);

// perform and operation between two bitsets

bitset1.and(bitset2);

// print the new bitset1

System.out.println("result bitset: " + bitset1);


}
}
Output:
D:\ACEM\II AI DS>javac BitSetAndExample1.java
D:\ACEM\II AI DS>java BitSetAndExample1
bitset1: {0, 1, 2, 3, 4}
bitset2: {2, 4, 6, 8, 10}
result bitset: {2, 4}

Object Oriented Programming Through Java Page 174


Date
 The Date is a built-in class in java used to work with date and time in java. The Date class is available
inside the java.util package. The Date class represents the date and time with millisecond precision.
 The Date class implements Serializable, Cloneable and Comparable interface.
 Most of the constructors and methods of Date class has been deprecated after Calendar class introduced.
Example:
import java.time.LocalDate;
public class LocalDateExample1
{
public static void main(String[] args)
{
LocalDate date = LocalDate.now();
LocalDate yesterday = date.minusDays(1);
LocalDate tomorrow = yesterday.plusDays(2);

System.out.println("Today date: "+date);


System.out.println("Yesterday date: "+yesterday);
System.out.println("Tomorrow date: "+tomorrow);
}
}
Output:
D:\ACEM\II AI DS>javac LocalDateExample1.java
D:\ACEM\II AI DS>java LocalDateExample1
Today date: 2022-12-25
Yesterday date: 2022-12-24
Tomorrow date: 2022-12-26
Calendar

 The Calendar is a built-in abstract class in java used to convert date between a specific instant in time
and a set of calendar fields such as MONTH, YEAR, HOUR, etc.
 The Calendar class is available inside the java.util package.
 The Calendar class implements Serializable, Cloneable and Comparable interface.
 As the Calendar class is an abstract class, we can not create an object using it.
 We will use the static method Calendar.getInstance() to instantiate and implement a sub-class.

Object Oriented Programming Through Java Page 175


Example:
import java.util.Calendar;
public class CalendarExample1
{
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());

calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());

calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());

calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
Output:
D:\ACEM\II AI DS>javac CalendarExample1.java
D:\ACEM\II AI DS>java CalendarExample1
The current date is : Sun Dec 25 22:08:47 IST 2022
15 days ago: Sat Dec 10 22:08:47 IST 2022
4 months later: Mon Apr 10 22:08:47 IST 2023
2 years later: Thu Apr 10 22:08:47 IST 2025
Random
The Random is a built-in class in java used to generate a stream of pseudo-random numbers in java
programming. The Random class is available inside the java.util package.
The Random class implements Serializable, Cloneable and Comparable interface.
 The Random class is a part of java.util package.
 The Random class provides several methods to generate random numbers of type integer, double, long,
float etc.
 The Random class is thread-safe.
 Random number generation algorithm works on the seed value. If not provided, seed value is created
from system nano time.

Object Oriented Programming Through Java Page 176


Example:
import java.util.Random;
public class JavaRandomExample
{
public static void main(String[] args)
{
Random random = new Random();

//return the next pseudorandom integer value


System.out.println("Random Integer value : "+random.nextInt());

// setting seed

long seed =20;


random.setSeed(seed);

//value after setting seed


System.out.println("Seed value : "+random.nextInt());

//return the next pseudorandom long value

Long val = random.nextLong();


System.out.println("Random Long value : "+val);
}

}
Output:
D:\ACEM\II AI DS>javac JavaRandomExample.java
D:\ACEM\II AI DS>java JavaRandomExample
Random Integer value : -1652727993
Seed value : -1150867590
Random Long value : -7322354119883315205

Formatter class
 The Formatter is a built-in class in java used for layout justification and alignment, common formats
for numeric, string, and date/time data, and locale-specific output in java programming.
 The Formatter class is defined as final class inside the java.util package.
 The Formatter class implements Cloneable and Flushable interface.
 The Formatter class in java has the following constructors.

Object Oriented Programming Through Java Page 177


Example:
import java.util.Formatter;
public class FomatterExample
{
public static void main(String args[]) throws Exception
{
int num[] = {10, 21, 13, 4, 15, 6, 27, 8, 19};

Formatter fmt = new Formatter();

fmt.format("%15s %15s %15s\n", "Number", "Square", "Cube");

for (int n : num)


{
fmt.format("%14s %14s %17s\n", n, (n*n), (n*n*n));
}
System.out.println(fmt);
}
}
Output:
D:\ACEM\II AI DS>javac FomatterExample.java
D:\ACEM\II AI DS>java FomatterExample
Number Square Cube
10 100 1000
21 441 9261
13 169 2197
4 16 64
15 225 3375
6 36 216
27 729 19683
8 64 512
19 361 6859

Object Oriented Programming Through Java Page 178


Scanner
The Scanner is a built-in class in java used for read the input from the user in java programming.
The Scanner class is defined inside the java.util package and implements Iterator interface.
 The Scanner class provides the easiest way to read input in a Java program.
 The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter is
whitespace.

Example:
import java.util.*;
public class ScannerClassExample1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = in.next();
System.out.println("Name: " + name);

System.out.print("Enter your age: ");


int i = in.nextInt();
System.out.println("Age: " + i);

System.out.print("Enter your salary: ");


double d = in.nextDouble();
System.out.println("Salary: " + d);

in.close();
}
}
Output:
D:\ACEM\II AI DS>javac ScannerClassExample1.java
D:\ACEM\II AI DS>java ScannerClassExample1
Enter your name: Aditya
Name: Aditya
Enter your age: 32
Age: 32
Enter your salary: 35000
Salary: 35000.0

Object Oriented Programming Through Java Page 179


Applet Basics
 A Java applet is a special kind of Java program that a browser enabled with Java technology.
 An applet is typically embedded inside a web page and runs in the context of a browser.
 An applet must be a subclass of the java.applet.Applet class.
 The Applet class provides the standard interface between the applet and the browser environment.
 Applet contains several methods that give you detailed control over the execution of your applet.
Advantage of Applet
 There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
 Plugin is required at client browser to execute applet.
Applet Basics:
 All applets are subclasses of Applet. Thus, all applets must import java.applet.
 Applets must also import java.awt. AWT stands for the Abstract Window Toolkit.
 Execution of an applet does not begin at main( ), since it does not have main() method. Output to your
applet’s window is not performed by System.out.println( ). Rather, it is handled with various AWT
methods, such as drawString( ), which outputs a string to a specified X,Y location. Input is also
handled differently than in an application.
 Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet
will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML
file.
 To view and test an applet more conveniently, simply include a comment at the head of your Java
source code file that contains the APPLET tag.
Here is an example of such a comment:
/*
<applet code = "MyApplet.class" width = 200 height = 60>
</applet>
*/

This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels
wide and 60 pixels high.

The Applet Class:

 Applet extends the AWT class Panel.


 In turn, Panel extends Container, which extends Component ,These classes provide support for
Java’s window-based, graphical interface.

Object Oriented Programming Through Java Page 180


Applet Architecture:
 An applet is a window-based program. As such, its architecture is different from the so-called normal,
console-based programs .
 First, applets are event driven. it is important to understand in a general way how the event- driven
architecture impacts the design of an applet.
 Here is how the process works. An applet waits until an event occurs.
 The AWT notifies the applet about an event by calling an event handler that has been provided by the
applet. Once this happens, the applet must take appropriate action and then quickly return control to the
AWT.

APPLET SKELETON or Life Cycle of an Applet


Most applets override these four methods. These four methods forms Applet lifecycle.
 init() : init() is the first method to be called. This is where variables are initialized.

This method is called only once during the runtime of applet.


 start() : start() method is called after init(). It is called to restart an applet after it has been stopped.

 stop() : stop() method is called to suspend thread that does not need to run when applet is not visible.

 destroy() : destroy() method is called when your applet needs to be removed completely from memory. 

 public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.
Note:
Four methods—init( ), start( ), stop( ), and destroy( )—are defined by Applet.
Another, paint( ), is defined by the AWT Component class.

Object Oriented Programming Through Java Page 181


Applet Skeleton
import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
}
public void destroy()
{
//perform shutdown activity
}
public void paint(Graphics g)
{
//display the content of window
}
}
How To Run an Applet Programe:
There are two ways to run an applet.
Executing an applet within a Java compatible web browser or using appletviewer

<APPLET CODE = "name of the applet class file"


HEIGHT = maximum height of applet in pixels
WIDTH = maximum width of applet in pixels
ALIGN = alignment (LEFT, RIGHT,MIDDLE, TOP, BOTTOM)>
</APPLET>
Using an applet viewer to run applet(demonstrates you to run SimpleApplet.java):
Compiling: javac programname.java
Run: AppletViewer programname.java
Example Program:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}

Object Oriented Programming Through Java Page 182


Invoking an Applet - HelloWorldApplet.html

<html>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
</applet>
</html>
OUTPUT:

javac HelloWorldApplet.java
appletviewer HelloWorldApplet.html

Requesting Repainting:

 Whenever applet needs to update the information displayed in its window, it simply calls repaint( ).
 The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call to
your applet’s update( ) method, which, in its default implementation, calls paint( ).
Syntax:
void repaint( )

This version causes the entire window to be repainted.


The following version specifies a region that will be repainted:

void repaint(int left, int top, int width, int height)

 Here, the coordinates of the upper-left corner of the region are specified by left and top, and the width
and height of the region are passed in width and height.
 These dimensions are specified in pixels. You save time by specifying a region to repaint.

The other two versions of repaint():

void repaint(long maxDelay)


void repaint(long maxDelay, int x, int y, int width, int height)

Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( ) is called.

Object Oriented Programming Through Java Page 183


Using the Status Window

 In addition to displaying information in its window, an applet can also output a message to the
status window of the browser or applet viewer on which it is running.
 To do so, call showStatus( ) with the string that you want displayed.
 It is used to give the user feedback about what is occurring in the applet ,suggest options

import java.awt.*;
import java.applet.*;
public class StatusWindow extends Applet
{
public void init()
{
setBackground(Color.cyan);
}

public void paint(Graphics g)


{
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}

/*
<applet code="StatusWindow.class" width=300 height=300>
</applet>
*/

Output:

Object Oriented Programming Through Java Page 184


Passing Parameters to Applets:

 The APPLET tag in HTML allows you to pass parameters to your applet.
 To retrieve a parameter, use the getParameter( ) method.
 It returns the value of the specified parameter in the form of a String object.
ParamDemo.java
import java.awt.*;
import java.applet.*;

public class ParamDemo extends Applet


{
String fontname = null, fontsize = null;
public void init()
{
setBackground(Color.gray);
setForeground(Color.pink);
}
public void start()
{
fontname = getParameter("fontName");
fontsize = getParameter("fontSize");
repaint();
}
public void paint(Graphics g)
{
g.drawString("Name of font :"+fontname,10,10);
g.drawString("Size of font:"+fontsize,10,30);
}
}
/*
<applet code = "ParamDemo.class" width = 300 height=300>
<param name = fontName value = verdana>
<param name = fontSize value = 14>
</applet>
*/
Output:

Object Oriented Programming Through Java Page 185


The origin and design philosophy of swing

 Swing in Java is a lightweight GUI toolkit which has a wide variety of components for building
optimized window based applications.
 It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written
in java. It is platform independent unlike AWT and has lightweight components.
 It is easier to build applications since we already have GUI components like button, checkbox etc.
Difference Between AWT and Swing

AWT SWING
Platform Dependent Platform Independent
Lesser Components More powerful components
Does not support pluggable look and feel Supports pluggable look and feel
Heavyweight Lightweight
components and containers
Component
 A component is an independent visual control and Java Swing Framework contains a large set of these
components which provide rich functionalities and allow high level of customization.
 They all are derived from JComponent class. All these components are lightweight components.
 This class provides some common functionality like pluggable look and feel, support for accessibility,
drag and drop, layout, etc.
Container Class
 Any class which has other components in it is called as a container class.
For building GUI applications at least one container class is necessary.
Following are the three types of container classes:
1. Panel – It is used to organize components on to a window
2. Frame – A fully functioning window with icons and titles
3. Dialog – It is like a pop up window but not fully functional like the frame

 A container holds a group of components.


 It provides a space where a component can be managed and displayed. Containers are of two types:
1. Top level Containers
 It inherits Component and Container of AWT.

 It cannot be contained within other containers.

 Heavyweight.

 Example: JFrame, JDialog, JApplet

Object Oriented Programming Through Java Page 186


2. Lightweight Containers
 It inherits JComponent class.

 It is a general purpose container.

 It can be used to organize related components together.

 Example: JPanel

Java Swing Class Hierarchy

Explanation:
 All the components in swing like JButton, JComboBox, JList, JLabel are inherited from the JComponent
class which can be added to the container classes.
 Containers are the windows like frame and dialog boxes.
 Methods like setLayout override the default layout in each container.
layout managers
Java LayoutManagers
 The LayoutManagers are used to arrange components in a particular manner.
 The LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
 LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.GridBagLayout

Object Oriented Programming Through Java Page 187


Types of LayoutManager
There are 4 layout managers in Java
BorderLayout:
 It arranges all the components along the edges or the middle of the container i.e. top, bottom, right and
left edges of the area.
 The components added to the top or bottom gets its preferred height, but its width will be the width of
the container and also the components added to the left or right gets its preferred width, but its height
will be the remaining height of the container.

.
Constructors of BorderLayout class:
1. BorderLayout(): creates a border layout but with no gaps between the components.
2. BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.
FlowLayout:
 It arranges the components in a container like the words on a page and
 It fills the top line from left to right and top to bottom.
 The components are arranged in the order as they are added i.e. first components appears at top left, if
the container is not wide enough to display all the components, it is wrapped around the line.
 Vertical and horizontal gap between components can be controlled. The components can be left, center
or right aligned.

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical
gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.

Object Oriented Programming Through Java Page 188


GridLayout:
 It arranges all the components in a grid of equally sized cells, adding them from the left to right and top
to bottom.
 Only one component can be placed in a cell and each region of the grid will have the same size.
 When the container is resized, all cells are automatically resized.
 The order of placing the components in a cell is determined as they were added.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and
columns along with given horizontal and vertical gaps.
GridBagLayout:
 It is a powerful layout which arranges all the components in a grid of cells and maintains the aspect
ration of the object whenever the container is resized.
 In this layout, cells may be different in size. It assigns a consistent horizontal and vertical gap among
components.
 It allows us to specify a default alignment for components within the columns or rows.

Constructor
1. GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.

Object Oriented Programming Through Java Page 189


Event Handling in Java

An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, key press through keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Event Handling

It is a mechanism to control the events and to decide what should happen after an event occur. To handle
the events, Java follows the Delegation Event model.
Different interfaces consists of different methods which are specified below.

Listener Interface Methods

ActionListener actionPerformed()

KeyListener keyTyped() , keyPressed() , keyReleased()

MouseListener mousePressed() , mouseClicked() ,mouseEntered()


mouseExited() ,mouseReleased()

MouseMotionListener mouseMoved() , mouseDragged()

MouseWheelListener mouseWheelMoved()

Example:
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label b;

MouseListenerExample()
{
addMouseListener(this);

b = new Label();
b.setBounds(20,50,100,20);

add(b);

setSize(300,300);
Object Oriented Programming Through Java Page 190
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
b.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
b.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
b.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
b.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
b.setText("Mouse Released");
}

public static void main(String[] args)


{
new MouseListenerExample();
}
}
Output:

Object Oriented Programming Through Java Page 191


jtextfield, jlabel and image icon
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
JTextField class declaration
public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:
Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.
Commonly used Methods:
Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive action events
from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent source, or null
if no Action is set.
Java JLabel
The object of JLabel class is a component for placing text in a container.
It is used to display a single line of read only text and It inherits JComponent class.
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f = new JFrame("TextField Example");
JTextField t1,t2;

t1 = new JTextField("Welcome .");


t1.setBounds(50,100, 200,30);

t2 = new JTextField("Aditya college");


t2.setBounds(50,150, 200,30);

f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Object Oriented Programming Through Java Page 192


Output:

JLabel class declaration


public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

Commonly used Methods:


Methods Description

String getText() it returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis.
Example:
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f = new JFrame("Label Example");
JLabel l1,l2;

l1 = new JLabel("First Label.");


l1.setBounds(50,50, 100,30);

l2 = new JLabel("Second Label.");


Object Oriented Programming Through Java Page 193
l2.setBounds(50,100, 100,30);

f.add(l1);
f.add(l2);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

ImageIcon
The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
Class Declaration
public class ImageIcon extends Object implements Icon, Serializable, AccessibleField
Class Constructors

Sr.No. Constructor & Description

ImageIcon()
1
Creates an uninitialized image icon.

ImageIcon(byte[] imageData)
2 Creates an ImageIcon from an array of bytes which were read from an image file containing a supported
image format, such as GIF, JPEG

Object Oriented Programming Through Java Page 194


swing buttons
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.
JTextField class declaration
public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.
Commonly used Methods:

Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive action events
from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent source, or null
if no Action is set.
Example:

import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f = new JFrame("TextField Example");
JTextField t1,t2;

t1 = new JTextField("Welcome .");


t1.setBounds(50,100, 200,30);

t2 = new JTextField("Aditya college");


t2.setBounds(50,150, 200,30);

f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Object Oriented Programming Through Java Page 195


Output:

Java JScrollPane
 A JscrollPane is used to make scrollable view of a component.
 When screen size is limited, we use a scroll pane to display a large component or a component whose
size can change dynamically.

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class JScrollPaneExample


{
private static final long serialVersionUID = 1L;
private static void createAndShowGUI()
{
final JFrame frame = new JFrame("Scroll Pane Example"); //create a setup window

// Display the window.


frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout()); // set flow layout for the frame
JTextArea textArea = new JTextArea(20,20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

frame.getContentPane().add(scrollableTextArea);
}

Object Oriented Programming Through Java Page 196


public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Output:

Java JList
The object of JList class represents a list of text items.
The list of text items can be set up so that the user can choose either one item or multiple items.
JList class declaration
public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified array.

Object Oriented Programming Through Java Page 197


Commonly used Methods:

Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be notified each


listener) time a change to the selection occurs.

int getSelectedIndex() It is used to return the smallest selected cell index.


Example:
import javax.swing.*;
public class ListExample
{
ListExample()
{
JFrame f = new JFrame();

DefaultListModel<String> l1 = new DefaultListModel<>();

l1.addElement("mango ");
l1.addElement("apple");
l1.addElement("banana");
l1.addElement("orange");

JList<String> list = new JList<>(l1);


list.setBounds(100,100, 75,75);

f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Output:

Object Oriented Programming Through Java Page 198


Java JComboBox
The object of Choice class is used to show popup menu of choices.
JComboBox class declaration
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionList
ener, Accessible
Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

Example:
import javax.swing.*;
public class ComboBoxExample
{
JFrame f;

ComboBoxExample()
{
f =new JFrame("ComboBox Example");
String country[] = { "India","Aus","U.S.A","England","Newzealand" };
JComboBox cb = new JComboBox(country);
cb.setBounds(50, 50,90,20);

f.add(cb);

f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args)
{
new ComboBoxExample();
}
}

Object Oriented Programming Through Java Page 199


Output:

JTree

The JTree class is used to display the tree structured data or hierarchical data.
It has a 'root node' at the top most which is a parent for all nodes in the tree.

JTree class declaration


public class JTree extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] value) Creates a JTree with every element of the specified array as the child of a new root node.

JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which displays the root node.

Example:

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class TreeExample


{
JFrame f;

TreeExample()
{
f = new JFrame();
DefaultMutableTreeNode style = new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color = new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font = new DefaultMutableTreeNode("font");

style.add(color);
style.add(font);

DefaultMutableTreeNode red = new DefaultMutableTreeNode("red");

Object Oriented Programming Through Java Page 200


DefaultMutableTreeNode blue = new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black = new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green = new DefaultMutableTreeNode("green");

color.add(red);
color.add(blue);
color.add(black);
color.add(green);

JTree jt=new JTree(style);

f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args)
{
new TreeExample();
}
}

Output:

Object Oriented Programming Through Java Page 201


Java JTable

The JTable class is used to display data in tabular form. It is composed of rows and columns.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Example:

import javax.swing.*;
public class TableExample
{
JFrame f;
TableExample()
{
f = new JFrame();
String data[][] = {
{"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}
};

String column[] = {"ID","NAME","SALARY"};

JTable jt = new JTable(data,column);

jt.setBounds(30,40,200,300);

JScrollPane sp = new JScrollPane(jt);


f.add(sp);

f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new TableExample();
}
}

Object Oriented Programming Through Java Page 202


Output:

An overview of jmenubar, jmenu and jmenuitem

Java JMenuBar, JMenu and JMenuItem

 The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
 The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
inherits the JMenuItem class.
 The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong
to the JMenuItem or any of its subclass.
JMenuBar class declaration
public class JMenuBar extends JComponent implements MenuElement, Accessible
JMenu class declaration
public class JMenu extends JMenuItem implements MenuElement, Accessible
JMenuItem class declaration
public class JMenuItem extends AbstractButton implements Accessible, MenuElement
Creating a main menu
Create a Main Menu
 Constructing the main menu requires several steps.
 First, create the JMenuBar object that will hold the menus. Next, construct each menu that will be in the
menu bar.
 In general, a menu is constructed by first creating a JMenu object and then adding JMenuItems to it.
 After the menus have been created, add them to the menu bar.
 The menu bar, itself, must then be added to the frame by calling setJMenuBar( ).
 Finally, for each menu item, you must add an action listener that handles the action event fired when the
menu item is selected.

Object Oriented Programming Through Java Page 203


Example of creating Edit menu for Notepad:
import javax.swing.*;
import java.awt.event.*;
public class MenuExample implements ActionListener
{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
MenuExample()
{
f = new JFrame();
cut = new JMenuItem("cut");
copy = new JMenuItem("copy");
paste = new JMenuItem("paste");
selectAll = new JMenuItem("selectAll");

cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);

selectAll.addActionListener(this);

mb = new JMenuBar();
file = new JMenu("File");
edit = new JMenu("Edit");
help = new JMenu("Help");

edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(selectAll);

mb.add(file);
mb.add(edit);
mb.add(help);

ta = new JTextArea();
ta.setBounds(5,5,360,320);

f.add(mb);
f.add(ta);

f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}

Object Oriented Programming Through Java Page 204


public void actionPerformed(ActionEvent e)
{
if(e.getSource() = = cut)
ta.cut();
if(e.getSource() = = paste)
ta.paste();
if(e.getSource() = = copy)
ta.copy();
if(e.getSource() = = selectAll)
ta.selectAll();
}
public static void main(String[] args)
{
new MenuExample();
}
}

Output:

showmessagedialog, showconfirmdialog, showinputdialog, showoptiondialog, jdialog

Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm
dialog box and input dialog box.
These dialog boxes are used to display information or get input from the user.
The JOptionPane class inherits JComponent class.
JOptionPane class declaration
public class JOptionPane extends JComponent implements Accessible

Object Oriented Programming Through Java Page 205


Common Constructors of JOptionPane class

Constructor Description

JOptionPane() It is used to create a JOptionPane with a test message.

JOptionPane(Object message) It is used to create an instance of JOptionPane to display a message.

Common Methods of JOptionPane class


Methods Description

JDialog createDialog(String title) It is used to create and return a new parentless JDialog with the
specified title.

static void showMessageDialog(Component It is used to create an information-message dialog titled


parentComponent, Object message) "Message".

Example:
import javax.swing.*;
public class OptionPaneExample
{
JFrame f;
OptionPaneExample()
{
f = new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Aditya Engineering college students");
}
public static void main(String[] args)
{
new OptionPaneExample();
}
}
Output:

Object Oriented Programming Through Java Page 206


Java JOptionPane Example: showConfirmDialog()
import javax.swing.*;
import java.awt.event.*;
public class OptionPaneExample12 extends WindowAdapter
{
JFrame f;
OptionPaneExample12()
{
f = new JFrame();
f.addWindowListener(this);
f.setSize(300, 300);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
}
public void windowClosing(WindowEvent e)
{
int a = JOptionPane.showConfirmDialog(f,"Are you sure?");
if(a == JOptionPane.YES_OPTION)
{
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args)
{
new OptionPaneExample12();
}
}
Output: ( when we click on close button it will display options)

Object Oriented Programming Through Java Page 207


Java JOptionPane Example: showInputDialog()
import javax.swing.*;
public class OptionPaneExample111
{
JFrame f;
OptionPaneExample111()
{
f = new JFrame();
String name = JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args)
{
new OptionPaneExample111();
}
}
Output:

showOptionDialog
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class ShowOptionDialogExample
{
public static void main(String[] args)
{
Object[] options = {"java","python"};
int n = JOptionPane.showOptionDialog(null, "A Message", "A Title",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.DEFAULT_OPTION,
null,
options,
options[1] );
System.out.println(n);

JFrame metric = new JFrame("Metric");


metric.setBounds(0, 0, 320, 240);

JFrame imperial = new JFrame("Imperial");

Object Oriented Programming Through Java Page 208


imperial.setBounds(0, 0, 320, 240);
if(n==0)
{
metric.setVisible(true);
}
else
if(n==1)
{
imperial.setVisible(true);
}
else
{
System.out.println("no option choosen");
}
}
}
Output:

Java JDialog
The JDialog control represents a top level window with a border and a title used to take some form of
input from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer
Commonly used Constructors:

Constructor Description

JDialog() It is used to create a modeless dialog without a title and without a specified Frame owner.

JDialog(Frame It is used to create a modeless dialog with specified Frame as its owner and an empty title.
owner)

Object Oriented Programming Through Java Page 209


Create a modeless dialog
import java.awt.Cursor;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class SwingDemos
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(new Dimension(600, 400));
JDialog dialog = new JDialog(frame, "New",ModalityType.MODELESS);
dialog.setSize(300, 300);

frame.add(new JButton(new AbstractAction("Click to generate")


{
public void actionPerformed(ActionEvent e)
{
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
dialog.setVisible(true);
}
}));
frame.setVisible(true);
}
}
Output:

Object Oriented Programming Through Java Page 210


JDBC
Introduction:
 Java DataBase Connectivity, commonly known as JDBC, is an API for Java programming language that
defines how a client may access a database.
 JDBC API uses JDBC driver written in Java. JDBC is platform independent.
What is API (Application Programming Interface)?
 API is a document that contains description of all features of a product or software.
 It represents classes and interfaces that software programs can follow to communicate with each other.
JDBC Driver (Types of JDBC drivers)
 A JDBC driver is a software component enabling a java application to interact with a database.
 JDBC requires drivers for each database.
 The JDBC driver gives out the connection to the database and implements the protocol for transferring
the query and result between client and database. .
There are four types of driver
1. JDBC-ODBC Bridge Driver (Type 1)
2. Native API Driver (Type 2/Partially Java Driver)
3. Network Protocol Driver (Type 3/Fully Java Driver)
4. Thin Driver (Type 4/Fully Java Driver)
1. JDBC-ODBC Bridge Driver (Type 1)
 Uses ODBC bridge driver to connect to database.
 Converts JDBC methods call into function call.
 ODBC drivers need to be installed on client machine
 This driver is platform dependent

Advantages : Easy to connect and directly connected to database


Disadvantage
 Does not support the complete java command set and are limited by the functionality of the ODBC
driver
 Needs to be installed on client machine and slow, as compared to other drivers.

Object Oriented Programming Through Java Page 211


2. Native API Driver (Type 2/Partially Java Driver)
 It uses client side libraries of the database so must be installed on client machines.
 The driver converts the JDBC method call into native call.
 Vendor client libraries need to be installed on client machine and It is not written entirely in java.

Advantage
 Better performance as compared to Type 1 driver.
Disadvantage
 Driver is platform dependent.
 The vendor client library needs to be installed.
 Native driver needs to be installed on each machine.
3. Network Protocol Driver (Type 3/Fully Java Driver)
 Uses middleware that convert JDBC call directly or indirectly into vendor specific database protocol.
 Fully written in Java.
 Database specific coding to be done in middle tier.

Advantage :
No client side library is required.
Disadvantage
 Network support is required on client machine.
 Database specific coding is done in middleware.

Object Oriented Programming Through Java Page 212


4. Thin Driver (Type 4/Fully Java Driver)
 Converts JDBC calls directly into vendor specific database protocol.
 Fully written in Java , User needs different drivers for each database and
 Performance is good.

Advantage
 Performance is good as compared to other drivers.
 No software is required for client or server side.
Disadvantage
 Different types of drivers required for different database.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access.
Two tier architecture
 In the two-tier model, a Java applet or application talks directly to the data source.
 This requires a JDBC driver that can communicate with the particular data source being accessed.
 A user's commands are delivered to the database or other data source, and the results of those statements
are sent back to the user.
 The data source may be located on another machine to which the user is connected via a network.
 This is referred to as a client/server configuration, with the user's machine as the client, and the machine
housing the data source as the server.

Object Oriented Programming Through Java Page 213


Three tier architecture
 In the three-tier model, commands are sent to a "middle tier" of services, which then sends the
commands to the data source.
 The data source processes the commands and sends the results back to the middle tier, which then sends
them to the user.
 Advantage is that it simplifies the deployment of applications.
 Finally, in many cases, the three-tier architecture can provide performance advantages.

JDBC CLASSES & INTERFACES

The JDBC API is comprised of two Java packages: java.sql and javax.sql.
The following are core JDBC classes, interfaces, and exceptions in the java.sql package:
DriverManager
 The DriverManager class (java.sql.DriverManager) is one of main components of JDBC.
DriverManager manages database drivers, load database specific drivers and select the most
appropriate database specific driver from the previously loaded drivers when a new connection is
established.
Connection
 Connection interface provides a standard abstraction to access the session established with a database
server.
 JDBC driver provider should implement the connection interface. We can obtain a Connection object
using the getConnection() method of the DriverManager as:
Connection con = DriverManager.getConnection(url, username, password);

Object Oriented Programming Through Java Page 214


Statement
 The Statement interface provides a standard abstraction to execute SQL statements and return the results
using the ResultSet objects.
Statement st = con.createStatement();
PreparedStatement
 PreparedStatement is a sub interface of the Statement interface.
 PreparedStatements are pre-compiled and hence their execution is much faster than that of Statements.
PreparedStatement ps1 = con.prepareStatement("insert into employeeList values (?,?)");
ps1.setString(1, "Heartin4");
ps1.setInt(2, 7);
ps1.executeUpdate();
CallableStatement
 CallableStatement extends the capabilities of a PreparedStatement to include methods that are only
appropriate for stored procedure calls; and hence CallableStatement is used to execute SQL stored
procedures.
 Whereas PreparedStatement gives methods for dealing with IN parameters, CallableStatement provides
methods to deal with OUT parameters as well.
ResultSet
This interface represents a table of data representing a database result set, which is usually generated
by executing a statement that queries the database.

Basic steps in developing JDBC applications


Steps to connect a Java Application to Database
 Register the Driver
 Create a Connection
 Create SQL Statement
 Execute SQL Statement
 Closing the connection
Register the Driver
Class.forName() is used to load the driver class explicitly.
Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Create a Connection
getConnection() method of DriverManager class is used to create a connection.

Object Oriented Programming Through Java Page 215


Syntax
getConnection(String url, String username, String password)
Example establish connection with Oracle Driver
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username","password");

Create SQL Statement


createStatement() method is invoked on current Connection object to create a SQL Statement.
Syntax
public Statement createStatement() throws SQLException
Example to create a SQL statement
Statement s = con.createStatement();
Execute SQL Statement
executeQuery() method of Statement interface is used to execute SQL statements.
Syntax
public ResultSet executeQuery(String query) throws SQLException
Example to execute a SQL statement
ResultSet rs = s.executeQuery("select * from user");
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
Closing the connection
After executing SQL statement you need to close the connection and release the session.
The close()method of Connection interface is used to close the connection.
Syntax
public void close() throws SQLException
Example of closing a connection
con.close();

Creating a new database and table with JDBC

Example 1:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

Object Oriented Programming Through Java Page 216


public class TestApplication99
{
static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE";
static final String USER = "system";
static final String PASS = "acem";

public static void main(String[] args)


{
try
{
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();

String sql = "CREATE TABLE Results(" +


"name char(15) , "+
"htno int ,"+
" marks1 int ,"+
" marks2 int ,"+
" marks3 int)";

stmt.executeUpdate(sql);

System.out.println("Created table in given database...");

}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Output
Created table in given database...
Example 2:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class Insert99
{
static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE";
static final String USER = "system";
static final String PASS = "acem";

Object Oriented Programming Through Java Page 217


public static void main(String[] args)
{
try
{
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

Statement stmt = conn.createStatement();

PreparedStatement ps = conn.prepareStatement("insert into results values(?,?,?,?,?)");

ps.setString(1, "charan");//1 specifies the first parameter in the query


ps.setInt(2,2001);
ps.setInt(3,88);
ps.setInt(4,99);
ps.setInt(5,95);

int i = ps.executeUpdate();

System.out.println(i+" records inserted");


conn.close(); // closing connection
}
catch (SQLException e)
{
System.out.println(e);
}
}
}
Output:
successfully inserted

Example 3:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class GettingResults


{
static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE";
static final String USER = "system";
static final String PASS = "acem";

Object Oriented Programming Through Java Page 218


public static void main(String[] args)
{
try
{
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();

PreparedStatement ps = null;
String qry = "select * from results";

ps = conn.prepareStatement(qry);

ResultSet rs = ps.executeQuery(qry);

while (rs.next())
{
String name = rs.getString("name");
int htno = rs.getInt("htno");
int marks1 = rs.getInt("marks1");
int marks2 = rs.getInt("marks2");
int marks3 = rs.getInt("marks3");

System.out.println("stu name : " + name);


System.out.println("studtno : " + htno);
System.out.println("sub1 : " + marks1);
System.out.println("sub2 : " + marks2);
System.out.println("sub3 : " + marks3);
}

conn.close(); // closing connection


}

catch (SQLException e)
{
System.out.println(e);
}
}
}
Output:
D:\ACEM\II AI DS>javac GettingResults.java
D:\ACEM\II AI DS>java GettingResults
stu name : charan
studtno : 2001
sub1 : 88
sub2 : 99
sub3 : 95
Object Oriented Programming Through Java Page 219
Object Oriented Programming Through Java Lab -- (20A05302P)
Week 1
A)
Installation of Java software, study of any Integrated development environment, Use Eclipse or Netbeans
platform and acquaint with the various menus.

Create a test project, add a test class and runit.

See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like renaming
variables, methods and classes. Try debug step by step with java program to find prime numbers between 1 to n.

1) Installation of Java software

Step 1 - Download JDK for windows using below link

Downloading Java JDK 19.0.0.0 (64-bit) from FileHorse.com

Step -2 Install by clicking on executable file

Step-3 After installation set the path to environment variables

C:\Program Files (x86)\Java\jdk1.8.0_60\bin;

Steps to install Eclipse IDE:

1. Download and install JDK(it is a pre-requisite essential step)


2. Go to eclipse website and download choosing the version as operating system and bits requirement.
3. Open the downloaded file extension and follow the standard software installation process.
4. Choose package as per developer language needs.
5. A new window will be relaunch and if not relaunch eclipse.
6. Go to the new project and create classes inside which java applications(or programs) are good to go.

Aim : Program to find all Prime Numbers between 1 to N

Description:

 Prime number in Java: Prime number is a number that is greater than 1 and divided by 1 or itself only.
 In other words, prime numbers can't be divided by other numbers than itself or 1.
 For example 2, 3, 5, 7, 11, 13, 17 .... are the prime numbers.

Algorithm:

 Get the upper limit from the user and store it in the variable “N”
 Start the loop from 2 to N, for each iteration increment the loop by 1
 In the checkPrime() method, we have used a boolean flag. It will be set to false when the number is less
than 1 or if the number is divisible by number/2.
 Validate the boolean returned by the checkPrime() and print the number if the boolean returned
is true.

Object Oriented Programming Through Java Page 220


Program:

import java.util.Scanner;

public class PrimeNumbersPrint


{

public static void main(String arg[])


{
int i,j,count;

Scanner sc=new Scanner(System.in);

System.out.print("Enter n value : ");


int n=sc.nextInt();

System.out.println("Prime numbers between 1 to "+n);

for(j=2;j<=n;j++)
{
count=0;

for(i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
System.out.print(j+" ");
}
}
}
Output:
D:\ACEM\java23batch\cse_a>java PrimeNumbersPrint
Enter n value : 20
Prime numbers between 1 to 20
2 3 5 7 11 13 17 19

Object Oriented Programming Through Java Page 221


B)
Aim: A Java program that prints all real solutions to the quadratic equation ax2+bx+c=0.
Read in a,b, c and use the quadratic formula.
Description:

 The standard form of a quadratic equation is ax2+bx+c=0. It is also known as the second-degree
equation.
 In the equation ax2+bx+c=0, a, b, and c are unknown values and a cannot be 0. x is an unknown
variable.
 The formula to find the roots of the quadratic equation is known as the quadratic formula.

 A quadratic equation has two roots and the roots depend on the discriminant.
 In the above formula, (b2-4ac) is called discriminant (d).

 The value of d may be positive, negative, or zero.


If d is positive (d>0), the root will be:
If the value of d is positive, both roots are real and different. It means there are two real solutions.

If d is zero (d=0), the root will be:


If the value of d is zero, both roots are real and the same. It means we get one real solution.

If d is negative (d<0), the root will be:


If the value of d is negative, both roots are distinct and imaginary or complex.
It means that there are two complex solutions.

Algorithm :
Step 1: Start
Step 2: Read a, b, c
Step 3: initialize d<-(b*b)-(4*a*c)
Step 4: initialize r<- b/2*a
Step 5: if d>0 go to Step 6, else go to Step 8
Step 6: r1=r+(sqrt(d)/2*a) and r2=r-(sqrt(d)/2*a)
Step 7: prints roots are real and distinct, first root r1 second root r2

Object Oriented Programming Through Java Page 222


Step 8: if d=0 go to Step 9, else go to Step 10
Step 9: print roots are real and equal, -r
Step 10: d=-d
Step 11: im=sqrt(d)/2*a
Step 12: print roots are imaginary, first root is r+i im, and the second root is r-i im
Step 13: Stop
Program:
import java.util.Scanner;

public class QuadraticEquationExample


{
public static void main(String[] Strings)
{
double a,b,c,d;
Scanner input = new Scanner(System.in);

System.out.print("Enter the value of a: ");


a = input.nextDouble();

System.out.print("Enter the value of b: ");


b = input.nextDouble();

System.out.print("Enter the value of c: ");


c = input.nextDouble();

d= b * b - 4 * a * c;

if (d> 0.0)
{
double r1 = (-b + Math.pow(d, 0.5)) / (2 * a);
double r2 = (-b - Math.pow(d, 0.5)) / (2 * a);
System.out.println("The roots are " + r1 + " and " + r2);
}
else
if (d == 0)
{
double r1 = -b / (2 * a);
System.out.println("The root is " + r1);
}
else
{
System.out.println("Roots are not real.");
}
}
}

Object Oriented Programming Through Java Page 223


Output:
E:\AI>java QuadraticEquationExample

Enter the value of a: 1


Enter the value of b: 2
Enter the value of c: 3
Roots are not real.

E:\AI>java QuadraticEquationExample

Enter the value of a: 1


Enter the value of b: 5
Enter the value of c: 2
The roots are -0.4384471871911697 and -4.561552812808831
C)
Aim: Develop a Java application to generate Electricity bills.

Create a class with the following members:


Consumer no , consumer name, previous month reading, current month reading, type of EB connection (i.e
domestic or commercial).

If the type of the EB connection is domestic, calculate the amount to be paid as follows:

 First 100 units - Rs. 1 per unit


 101-200 units - Rs. 2.50 per unit
 201 -500 units - Rs. 4 per unit
 > 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:

 First 100 units - Rs. 2 per unit


 101-200 units - Rs. 4.50 per unit
 201 -500 units - Rs. 6 per unit
 > 501 units - Rs. 7 per unit

Description:

Step 1: Declare all variables as per our requirement


Step 2: Read all variables data
Step 3: Calculate bill amount based on commercial or domestic
Step 4: Display bill amount

Object Oriented Programming Through Java Page 224


Program:

import java.util.*;

public class ComputeElectricityBill


{
int consumerno;
String consumername;
int prev_reading;
int curr_reading;
String Ebconn;
double bill;

void readData()
{
Scanner scan = new Scanner(System.in);

System.out.println(" Enter consumer number ");


consumerno = scan.nextInt();

System.out.println(" Enter consumer name ");


consumername = scan.next();

System.out.println(" Enter previous reading ");


prev_reading = scan.nextInt();

System.out.println(" Enter current reading ");


curr_reading = scan.nextInt();

System.out.println(" Enter the type of connection ");


Ebconn = scan.next();
}

void caluclate_bill_amount()
{
if(Ebconn.equals("domestic"))
{
int units;

units=curr_reading-prev_reading;

if(units<=100)
{
bill=units*1;

Object Oriented Programming Through Java Page 225


}
else
if(units>=101 && units<=200)
{
bill=units*2.50;
}
else
if(units>=201 && units<=500)
{
bill=units*4;
}
else
if(units>=501)
{
bill=units*6;
}

}
else
{
int units;

units=curr_reading-prev_reading;

if(units<=100)
{
bill=units*2;
}
else
if(units>=101 && units<=200)
{
bill=units*4.50;
}
else
if(units>=201 && units<=500)
{
bill=units*6;
}
else
if(units>=501)
{
bill=units*7;
}

Object Oriented Programming Through Java Page 226


}

void displayData()
{
System.out.println(" consumer number = "+consumerno);
System.out.println(" consumer name = "+consumername);
System.out.println(" previous reading = "+prev_reading);
System.out.println(" current reading = "+curr_reading);
System.out.println(" Type of connection = "+ Ebconn);
System.out.println(" Bill amount = "+bill);
}

public static void main(String[] args)


{
ComputeElectricityBill b = new ComputeElectricityBill();
b.readData();
b.caluclate_bill_amount();
b.displayData();
}
}
Output:
E:\AI>java ComputeElectricityBill

Enter consumer number


102
Enter consumer name
mass
Enter previous reading
100
Enter current reading
300
Enter the type of connection
Commertial
consumer number = 102
consumer name = mass
previous reading = 100
current reading = 300
Type of connection = Commertial
Bill amount = 900.0

Object Oriented Programming Through Java Page 227


D)
Aim: Write a Java program to multiply two given matrices
Description:
 We can multiply two matrices in java using binary * operator and executing another loop.
 A matrix is also known as array of arrays. We can add, subtract and multiply matrices.
 In case of matrix multiplication, one row element of first matrix is multiplied by all columns of second
matrix.

Algorithm:
Step 1: Declare two matrices and assign values and declare third matrix to store product
Step 2: Multiply two matrices and display output
Step 3: use inner loops to multiply matrices like below
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;

for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" "); //printing matrix element
}
System.out.println(); //new line
}

Object Oriented Programming Through Java Page 228


Program :

public class MatrixMultiplicationExample


{

public static void main(String args[])


{
//creating two matrices

int a[][] = { {1,1,1},{2,2,2},{3,3,3} };


int b[][] = { {1,1,1},{2,2,2},{3,3,3} };

int c[][] = new int[3][3]; //3x3 matrix to store multiplication

//multiplying and printing multiplication of 2 matrices

for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;

for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" "); //printing matrix element
}
System.out.println(); //new line
}
}
}

Output :

E:\AI>javac MatrixMultiplicationExample.java

E:\AI>java MatrixMultiplicationExample

666
12 12 12
18 18 18

Object Oriented Programming Through Java Page 229


Week 2:
A) Write Java program on use of inheritance, preventing inheritance using final,
abstract classes.
Aim : Java program on use of inheritance
Description :
 Inheritance is defined as a mechanism where the sub or child class inherits the properties and
characteristics of the super class or other derived classes.
 It also supports additional features of extracting properties from the child class and using it into
other derived classes."
Procedure:
 Define a class (parent class ) and write some properties
 Define one more class (child class) write some methods and inherit properties from parent class
 Create an object for child class and access the both classes properties with child class object
Program:

class MathOperations
{
public void addition(int x, int y)
{
System.out.println(" The sum of the given numbers ="+(x+y));
}

public void substraction(int x, int y)


{
System.out.println(" The difference of the given numbers ="+(x-y));
}
}
class MoreOperations extends MathOperations
{
public void multiplication(int x, int y)
{
System.out.println(" The sum of the given numbers ="+(x*y));
}

Object Oriented Programming Through Java Page 230


public static void main(String[] args)
{
int a=40,b=20;
MoreOperations m = new MoreOperations();
m.addition(a,b);
m.substraction(a,b);
m.multiplication(a,b);
}
}
Output:
The sum of the given numbers =60
The difference of the given numbers =20
The product of the given numbers =800

b) preventing inheritance using final


Aim: preventing inheritance using final and abstract classes
Description:
 The class declared as final is called final class. Note that the final class cannot be inherited.
 There are two uses of the final class i.e. to prevent inheritance and to make classes immutable.
Procedure:
 Develop one class with final modifier
 Develop more class and extends from base class
Program:
final class Demo1
{
// variables, methods, and fields
}

class Demo2 extends Demo1 // The following class is illegal


{
// COMPILE-ERROR! Can't subclass A
}
Output:
D:\>javac Demo2.java
Demo2.java:6: error: cannot inherit from final Demo1
class Demo2 extends Demo1 // The following class is illegal

Object Oriented Programming Through Java Page 231


C) Aim: preventing inheritance using abstract classes

Description:

 An abstract class can also have methods that are neither abstract nor final, just regular methods.
 There may be "final" methods in "abstract" class. But, any "abstract" method in the class can't be
declared final. It will give "illegal combination of modifiers: abstract and final" error.
public abstract final void show(); // illegal combination of modifiers: abstract and final

Program:

abstract class Demo1 //ABSTRACT CLASS


{
public final void show() // FINAL METHOD
{
System.out.println("Yes");
}
}
class Demo2 extends Demo1 //INHERTING ABSTRACT CLASS
{
public void show() //OVERRIDING THE FINAL METHOD
{
System.out.println("Success overriding");
}
public static void main (String[] args)
{
Demo2 id = new Demo2(); //OBJECT OF SUBCLASS
id.show(); //CALLING FINAL METHOD
}
}
Output:

D:\>javac Demo2.java

Demo2.java:19: error: show() in Demo2 cannot override show() in Demo1

public void show() //OVERRIDING THE FINAL METHOD

overridden method is final

1 error

Object Oriented Programming Through Java Page 232


B)Write Java program on dynamic binding, differentiating method overloading and overriding.
Aim: Java program on dynamic binding, differentiating method overloading and overriding.
Description:

The key difference between overloading and overriding in Java is that the Overloading is the ability to
create multiple methods of the same name with different implementations and Overriding is to
provide an implementation for a subclass method that already exists in the superclass.

Procedure:
 we have created two methods, first sum() method performs addition of two numbers and second sum
method performs addition of three numbers.
 Create an object for that class and call both sum methods using period (.) operator

Example By changing number of arguments


class Addition
{
void sum(int a, int b) // addition of two numbers
{
System.out.println(a+b);
}
void sum(int a, int b, int c) addition of three numbers
{
System.out.println(a+b+c);
}

public static void main(String args[])


{
Addition obj = new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}

Output
30
60

Method overriding :

Description:

 If a subclass provides the specific implementation of the method that has been declared by one of its
parent class, it is known as method overriding.
 Method overriding is used to provide the specific implementation of a method which is already provided
by its superclass.

Object Oriented Programming Through Java Page 233


Rules of overriding:
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
Procedure:
Create a class (base class) and define a method
Create one more class (derived) and extend using base class
Redefine method in derived class as per our own requirement
Define a main method , and create an object for derived class and class the method

Program:
class Demo1
{
public void show(int a, int b , int c)
{
System.out.println("sum ="+(a+b+c));
}
}

class Demo2 extends Demo1


{
public void show(int a,int b,int c) //OVERRIDING THE SUM METHOD
{
int d=40;
System.out.println("sum ="+(a+b+c+d));
}
public static void main (String[] args)
{
Demo2 id = new Demo2(); //OBJECT OF SUBCLASS
id.show(10,20,30); //CALLING METHOD
}
}
Output:
sum =100

Object Oriented Programming Through Java Page 234


c) Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen)
using Interfaces

Description:
INR is currency of INDIA
EURO is currency of European union
YEN is currency of Japan
Procedure:

 Declare methods in interface


 Define those methods in class
 Create a menu in do-while loop
 Use choice in switch to use this method
Program:

import java.util.*;

interface converter
{
void dollar_rupee();
void rupee_dollar();
void euro_rupee();
void rupee_euro();
void yen_rupee();
void rupee_yen();

}
public class currency implements converter
{
double inr,usd;
double euro,yen;

Scanner in=new Scanner(System.in);

public void dollar_rupee()


{
System.out.println("Enter dollars to convert into Rupees:");
usd=in.nextInt();

inr=usd*67;
System.out.println("Dollar ="+usd+"equal to INR="+inr);
}

Object Oriented Programming Through Java Page 235


public void rupee_dollar()
{
System.out.println("Enter Rupee to convert into Dollars:");
inr=in.nextInt();

usd=inr/67;
System.out.println("Rupee ="+inr+"equal to Dollars="+usd);
}

public void euro_rupee()


{
System.out.println("Enter euro to convert into Rupees:");
euro=in.nextInt();

inr=euro*79.50;
System.out.println("Euro ="+euro +"equal to INR="+inr);
}

public void rupee_euro()


{
System.out.println("Enter Rupees to convert into Euro:");
inr=in.nextInt();

euro=(inr/79.50);
System.out.println("Rupee ="+inr +"equal to Euro="+euro);
}

public void yen_rupee()


{
System.out.println("Enter yen to convert into Rupees:");
yen=in.nextInt();

inr=yen*0.61;
System.out.println("YEN="+yen +"equal to INR="+inr);
}

public void rupee_yen()


{
System.out.println("Enter Rupees to convert into Yen:");
inr=in.nextInt();

yen=(inr/0.61);
System.out.println("INR="+inr +"equal to YEN"+yen);
}

public static void main(String args[])


{

int ch;
currency c = new currency();

Object Oriented Programming Through Java Page 236


do
{
System.out.println("1.dollar to rupee ");
System.out.println("2.rupee to dollar ");
System.out.println("3.Euro to rupee ");
System.out.println("4..rupee to Euro ");
System.out.println("5.Yen to rupee ");
System.out.println("6.Rupee to Yen ");

Scanner in=new Scanner(System.in);

System.out.println("Enter 0 to quit and 1 to continue ");


ch=in.nextInt();

switch(ch)
{
case 1:
{
c.dollar_rupee();
break;
}
case 2:
{
c.rupee_dollar();
break;
}
case 3:
{
c.euro_rupee();
break;
}
case 4:
{
c.rupee_euro();
break;
}
case 5:
{
c.yen_rupee();
break;
}
case 6:
{
c.rupee_yen();

Object Oriented Programming Through Java Page 237


break;
}
default:
System.exit(0);
} //switch close
}while(ch==1); //do-while close
} // main close
} //class close
Output:

D:\>java currency
1. dollar to rupee
2. rupee to dollar
3. Euro to rupee
4. .rupee to Euro
5. Yen to rupee
6. Rupee to Yen
Enter 0 to quit and 1 to continue
1
Enter dollars to convert into Rupees:
30
Dollar =30.0equal to INR=2010.0
1. dollar to rupee
2. rupee to dollar
3. Euro to rupee
4. .rupee to Euro
5. Yen to rupee
6. Rupee to Yen
Enter 0 to quit and 1 to continue
2
Enter Rupee to convert into Dollars:
10
Rupee =10.0equal to Dollars=0.14925373134328357

Object Oriented Programming Through Java Page 238


Week 3:
C) Aim: Write Java program that inputs 5 numbers, each between 10 and 100 inclusive. As each number
is read, display it only if it’s not a duplicate of any number already read display the complete set
of unique values input after the user enters each new value
Description :
The main two conditions of these programs are
 A number once read should not be read again.
 The number we read should be in the range of 10 and 100.
Procedure:
 If the number lies between 10 and 100, Compare the recently read number with all the previously read
numbers,
 if any number matches then declare that it a duplicate and ask the user to enter another number.
 Else declare that the number is not in the range of 10 and 100 and read another number.
Program:
import java.io.*;
import java.util.*;

public class Arrays2


{
public static void main(String ar[])
{
int temp,i,flag=0;
int a[]=new int[10];
Scanner s=new Scanner(System.in);
System.out.println("Enter values : ");
for( i=0;i<5;)
{
temp=s.nextInt();
flag=0;
if(temp>10 && temp<100)
{
for(int j=0;j<i;j++)
if(a[j]==temp)
flag=1;

Object Oriented Programming Through Java Page 239


if(flag==0)
{
a[i]=temp;
i++;
}
else
System.out.println("Number already entered. Enter another value : ");
}
else
System.out.println("Number not in range. Enter another values : ");
}

System.out.println("Numbers in the array are : ");


for(int j=0;j<5;j++)
System.out.println(a[j]);
}
}
Output:
D:\ACEM>java Arrays2
Enter values :
56
89
43
43
Number already entered. Enter another value :
95
76
Numbers in the array are :
56
89
43
95
76

Object Oriented Programming Through Java Page 240


b) Aim: Write a Java Program to create an abstract class named Shape that contains two integers and an
empty method named print Area(). Provide three classes named Rectangle, Triangle and Circle
suchthat each one of the classes extends the class Shape. Each one of the classes contains
only the method print Area () that prints the area of the given shape.
Description:
A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
Procedure:
 Define a class with name Shape declare two integers and assign values
 Define three more classes like Rectangle, Triangle and Circle suchthat each one of the classes extends
the Shape class
 Override print_area() method and calculate area
 Write one more class create objects for three classes and call with that object names

Program:
abstract class Shape
{
int a=3,b=4;
abstract public void print_area();
}
class Rectangle extends Shape
{
public double area_rect;
public void print_area()
{
area_rect=a*b;
System.out.println("The area of rectangle is:"+area_rect);
}
}
class Triangle extends Shape
{
double area_tri;
public void print_area()
{
area_tri= 0.5*a*b;
System.out.println("The area of triangle is:"+area_tri);
}
}

Object Oriented Programming Through Java Page 241


class Circle extends Shape
{
double area_circle;

public void print_area()


{
area_circle=3.14*a*a;
System.out.println("The area of circle is:"+area_circle);
}
}
public class AreaCode
{

public static void main(String[] args)


{

Rectangle r=new Rectangle();


r.print_area();

Triangle t=new Triangle();


t.print_area();

Circle r1=new Circle();


r1.print_area();

Output:

D:\ACEM>javac AreaCode.java
D:\ACEM>java AreaCode
The area of rectangle is:12.0
The area of triangle is:6.0
The area of circle is:28.259999999999998

Object Oriented Programming Through Java Page 242


C) Aim:
Write a Java program to read the time intervals (HH:MM) and to compare system time if the system
Time between your time intervals print correct time and exit else try again to repute the same thing.
By using StringToknizer class.

Description:

 Initially take the input interval of time in hours, minutes, and seconds.
 The system time can be read as using the object of the class GregorianCalendar.
 This GregorianCalendar class contains a method by name get which returns a required value from the
hour, minutes, and seconds of the system time.
 Calendar class contains variables hour, minute, second which gives the system time through the object
of the class GregorianCalendar
Program:
import java.util.*;
import java.text.*;

class Tokenizer
{
static int[] cal(String y)
{
String a,b,x=":";
int i[] = {0,0};

StringTokenizer st=new StringTokenizer(y,x);


a=(String) st.nextElement();
b=(String) st.nextElement();

i[0]=Integer.parseInt(a);
i[1]=Integer.parseInt(b);
return i;
}
}

Object Oriented Programming Through Java Page 243


public class GetCurrentDateTime
{
public static void main(String[] args)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Calendar cal = Calendar.getInstance();
String y =dateFormat.format(cal.getTime());

while(true)
{
String x,t1,a,b;
int minute,hour;
int HH[]={0,0},MM[]={0,0};
t1=dateFormat.format(cal.getTime());
int time1[]=Tokenizer.cal(t1);
hour=time1[0];
minute=time1[1];
System.out.println("Enter the time intervels in HH:MM fommat");
Scanner z = new Scanner(System.in);
String t2=z.next();
String t3=z.next();

int time2[]=Tokenizer.cal(t2);
HH[0]=time2[0];
MM[0]=time2[1];

int time3[]=Tokenizer.cal(t3);
HH[1]=time3[0];
MM[1]=time3[1];

if(HH[0]>HH[1])
{
int t=HH[0];
HH[0]=HH[1];
HH[1]=t;

Object Oriented Programming Through Java Page 244


}
if(HH[0]==HH[1] && MM[0]>MM[1])
{
int t=MM[0];
MM[0]=MM[1];
MM[1]=t;
}

if((hour>=HH[0] && hour<HH[1]) || (hour==HH[0] && hour==HH[1]) && (minute>=MM[0] &&


minute<=MM[1]))
{
System.out.println("Current time is "+hour+" : "+minute);
break;
}
else
{
System.out.println("Try again");
}
}
}
}
Output:
D:\ACEM>java GetCurrentDateTime

Enter the time intervels in HH:MM fommat

2:15

3:46

Try again

Enter the time intervels in HH:MM fommat

3:46

7:13

Current time is 6 : 23

Object Oriented Programming Through Java Page 245


Week 4.
Aim: To Write a Java program to implement user defined exception handling
Description:
 Java user-defined exception is a custom exception created and throws that exception using a keyword
‘throw’.
 It is done by extending a class ‘Exception’. An exception is a problem that arises during the execution of
the program.
Procedure:
 Create a class that extends the Exception class.
 Create a constructor which receives the string as an argument.
 Get the Amount as input from the user.
 If the amount is negative, the exception will be generated.
 Using the exception handling mechanism, the thrown exception is handled by the catch block.
 After the exception is handled, the string “withdraw amount is never negative“ will be displayed.
 If the amount is greater than 0, the message “Please collect the cash “ will be displayed
Program:
import java.util.Scanner;

class InvalidAmountException extends Exception // class representing user defined exception


{
public InvalidAmountException(String msg)
{
super(msg); // calling the constructor of parent Exception
}
}
// class that uses user defined exception InvalidAmountException
public class DefineUserDefinedException
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println(" Enter amount to withdraw ");
int amount = s.nextInt();
try
{
if(amount<0) // throw an object of user defined exception
{
throw new InvalidAmountException("withdraw amount is never negative");
}

Object Oriented Programming Through Java Page 246


else
{
System.out.println(" Please collect cash ");
}

}
catch (InvalidAmountException ex)
{
System.out.println("Caught the exception");
// printing the message from InvalidAmountException object
System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


} //main close
} //class close
Output:
D:\ACEM\II CSE Bsection>javac DefineUserDefinedException.java
D:\ACEM\II CSE Bsection>java DefineUserDefinedException
Enter amount to withdraw
200
Please collect cash
rest of the code...
D:\ACEM\II CSE Bsection>java DefineUserDefinedException
Enter amount to withdraw
-99
Caught the exception
Exception occured: InvalidAmountException: withdraw amount is never negative
rest of the code...

Object Oriented Programming Through Java Page 247


5 A) Aim :
Write a Java program that creates a user interface to perform integer division.
The user enters two numbers in the text fields, Num1 and Num2.
The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked.
If Num1 and Num2 were not integers, the program would throw a Number Format Exception.
If Num2 were zero, the program would throwan Arithmetic Exception Display the exception in a message
dialog box
Description:
 The AWT supports a rich assortment of graphics methods.
 All graphics are drawn relative to a window. this can the main window of an applet, a child window of
an applet, or a stand alone application window.
 The origin of each window is at the top-left corner and is 0,0cordinates are specified in pixels.
 All output to a window takes place through a graphics context.
Program:

import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.awt.event.*;

public class Division extends Applet implements ActionListener


{

TextField t1,t2,t3;
Button b;
Label L1,L2,L3,L4;
String s;
Division e;

public void init()


{
e=this;
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);

L1=new Label("enter num1");


L2=new Label("enter num2");
L3=new Label("Result is");
L4=new Label("Division of 2 numbers");

b=new Button("Divide");

Object Oriented Programming Through Java Page 248


add(L4);
add(L1);
add(t1);
add(L2);
add(t2);
add(L3);
add(t3);
add(b);

b.addActionListener(this);

public void actionPerformed(ActionEvent ae)


{
try
{
int num1=Integer.parseInt(t1.getText());
int num2=Integer.parseInt(t2.getText());
s=""+(num1/num2);

t3.setText(s);
}
catch(ArithmeticException a)
{

JOptionPane.showMessageDialog(null,"Divide by zero");

}
catch(NumberFormatException b)
{

JOptionPane.showMessageDialog(null,"NumberFormateException");
}
}
}

Open notepad type below code and save with file name.html and open with appletviewer.html

<html>

<applet code="Division.class" height=200 width=320>

</applet>
</html>

Object Oriented Programming Through Java Page 249


Output:

5 b) Aim:
Write a Java program that creates three threads. First thread displays Good Morning for every one second, the
second thread displays Hello for every two seconds and the third thread displays Welcome for every three
seconds.
Description:
 The first thread displays Good Morning every one second, the second thread displays Hello every two
seconds and the third thread displays Welcome every three seconds.
 The technique used to implement threads here is by extending the Thread class.
 While executing a thread, if any interrupt occurs then there arises a java exception.
 In such cases, to handle these exceptions thread statements are kept in try-catch blocks.
Program:
class A extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}

Object Oriented Programming Through Java Page 250


class B extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
sleep(2000);
System.out.println("hello");
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
class C extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();

t1.start();
t2.start();
t3.start();
}
}

Object Oriented Programming Through Java Page 251


Output : D:\ACEM\II CSE Bsection>javac MultiThreadDemo.java
D:\ACEM\II CSE Bsection>java MultiThreadDemo
good morning
good morning
hello
welcome
good morning
hello
good morning
good morning
welcome
hello
hello
welcome
hello
welcome
welcome */

Week 6:
a) Aim: To write a java program to split a given text file into n parts. Name each part as the name of theoriginal
file followed by .part where n is the sequence number of the part file.
Description:
BufferedReader br = new BufferedReader(new FileReader(inputfile));
String strLine;

for (int j=1;j<=nof;j++)


{
FileWriter fw= new FileWriter("File"+j+".txt"); // Destination File Location

for (int i=1;i<=nol;i++)


{
strLine = br.readLine();

if (strLine!= null)
{
strLine=strLine+"\r\n";
fw.write(strLine);
}
}
}
Procedure:
 Declare variables inputfile as String type nol as double type
 Take File data type and file as object pass inputfile to File constructor
 Create Scanner class object
 Declare count variable and assign to zero
 Count no. if lines using while loop ,hasNextLine() and nextLine() methods and print no.of lines
 Find equals parts of file using double temp = (count/nol);
 Declare temp1 variable and do typecasting
 Find split files using BufferedReader
Object Oriented Programming Through Java Page 252
Program:
import java.io.*;
import java.util.Scanner;

public class SplitFiles


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

String inputfile = "test.txt"; // Source File Name.

double nol = 5.0; // No. of lines to be split and saved in each output file

File file = new File(inputfile);

Scanner scanner = new Scanner(file);

int count = 0;

while (scanner.hasNextLine())
{
scanner.nextLine();
count++;
}

System.out.println("Lines in the file: " + count); // Displays no. of lines in the input file
double temp = (count/nol);

int temp1 = (int)temp;


int nof = 0;

if( temp1 == temp)


{
nof = temp1;
}
else
{
nof = temp1+1;
}
System.out.println("No. of files to be generated :"+nof);

// Actual splitting of file into smaller files

BufferedReader br = new BufferedReader(new FileReader(inputfile));

String strLine;

Object Oriented Programming Through Java Page 253


for (int j=1;j<=nof;j++)
{

FileWriter fw = new FileWriter("File"+j+".txt"); // Destination File Location

for (int i=1;i<=nol;i++)


{
strLine = br.readLine();

if (strLine != null)
{
strLine = strLine+"\r\n";
fw.write(strLine);
}
}

fw.close();
}
br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

Output:
D:\ACEM\II CSE Bsection>javac SplitFiles1.java
D:\ACEM\II CSE Bsection>java SplitFiles1
Lines in the file: 11
No. of files to be generated :3
File1,File2,File3
B) Aim: Write a Java program that reads a file name from the user, displays information about whether the
file exists, whether the file is readable, or writable and the length of the file in bytes.
Description:
A file is a named location that can be used to store related information.
For example, main.java is a Java file that contains information about the Java program.
Procedure:
 Create a class FileDemo. Get the file name from the user .
 Use the file functions and display the information about the file.
 getName() displays the name of the file.
 getPath() diplays the path name of the file.

Object Oriented Programming Through Java Page 254


 exists() – Checks whether the file exists or not.
 canRead()-This method is basically a check if the file can be read.
 canWrite()-verifies whether the application can write to the file.
 isDirectory() – displays whether it is a directory or not.
 isFile() – displays whether it is a file or not.
 length()- displays the size of the file.
Program:
import java.io.*;
import java.util.*;
class FileDemo
{
public static void main(String args[])
{
String filename;
Scanner s = new Scanner(System.in);
System.out.println("Enter the file name ");
filename = s.nextLine();
File f1 = new File(filename);

System.out.println(" FILE INFORMATION ");


System.out.println(" ***************** ");
System.out.println(" NAME OF THE FILE "+f1.getName());
System.out.println(" PATH OF THE FILE "+f1.getPath());

if(f1.exists())
System.out.println(" THE FILE EXISTS ");
else
System.out.println(" THE FILE DOES NOT EXISTS ");

if(f1.canRead())
System.out.println(" THE FILE CAN BE READ ");
else
System.out.println(" THE FILE CANNOT BE READ ");

if(f1.canWrite())
System.out.println(" WRITE OPERATION IS PERMITTED ");
else
System.out.println(" WRITE OPERATION IS NOT PERMITTED ");

System.out.println(" LENGTH OF THE FILE "+f1.length()+" bytes ");

}
}
Object Oriented Programming Through Java Page 255
Output:
D:\ACEM\II CSE Bsection>javac FileDemo.java
D:\ACEM\II CSE Bsection>java FileDemo
Enter the file name
Test.txt
FILE INFORMATION
*****************
NAME OF THE FILE Test.txt
PATH OF THE FILE Test.txt
THE FILE EXISTS
THE FILE CAN BE READ
WRITE OPERATION IS PERMITTED
LENGTH OF THE FILE 102 bytes

Week 7

Aim: Write a java program that displays the number of characters, lines and words in a text file.
Description:
File(String pathname):
This function is present under the java.io.File package.
It creates a new File instance by converting the given pathname string into an abstract pathname.
FileInputStream(File file) :
This function is present under the java.io.FileInputStream package.
It creates a FileInputStream by opening a connection to an actual file named by the File object file in
the file system.
InputStreamReader(InputStream in):
This function is present under the java.io.InputStreamReader package.
It creates an InputStreamReader that uses the default charset.
BufferedReader(Reader in):
This function is present under the java.io.BufferedReader package.
It creates a buffering character-input stream that uses a default-sized input buffer.
Program:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

Object Oriented Programming Through Java Page 256


public class CountLinnesWordsChars
{
public static void main(String[] args) throws IOException
{
File file = new File("D:\\ACEM\\II CSE JAVA LAB\\smilejava.txt");
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String line;
int lines=0;
int wordCount = 0;
int characterCount = 0;

while ((line = bufferedReader.readLine()) != null)


{
lines++;
characterCount += line.length();
String words[] = line.split("\\s+");
wordCount += words.length;
}

System.out.println("Total word count = "+ wordCount);


System.out.println("Total number of lines = "+ lines);
System.out.println("Total number of characters = "+ characterCount);
}
}
Output:
D:\ACEM\II CSE Bsection>javac CountLinnesWordsChars.java
D:\ACEM\II CSE Bsection>java CountLinnesWordsChars
Total word count = 6
Total number of lines = 6
Total number of characters = 26

b) Aim : Write a java program that reads a file and displays the file on the screen with line number beforeeach line.
Description:
 import java packages
 Create class ReadFileForLine
 Create main function
 public static void main( String[] args)throws IOException and write rest of the code

Object Oriented Programming Through Java Page 257


Program:
import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

class ReadFileForLine
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String file_name = input.nextLine();
File f = new File(file_name);

int i;
boolean wrong=true;
while(wrong)
{
try
{
FileReader finp = new FileReader(f);
LineNumberReader linereader = new LineNumberReader(finp);

while((i=linereader.read())!=-1)
{
System.out.print("Line #: "+(linereader.getLineNumber()+1));
System.out.println((char)i+linereader.readLine());
}
wrong=false;
}
catch(FileNotFoundException e)
{
System.out.println("File does not exist, ");
System.out.print("Enter another file name:");
file_name = input.nextLine();
f = new File(file_name);
}
catch(IOException e)
{
System.out.println("Cannot Read file:");
}
}
}
}
Object Oriented Programming Through Java Page 258
Output:
D:\ACEM\II CSE Bsection>javac ReadFileForLine.java
D:\ACEM\II CSE Bsection>java ReadFileForLine
Enter the name of the file: smilejava.txt
Line #: 1hello
Line #: 2keep
Line #: 3smiling
Line #: 4java
Line #: 5is
Line #: 6easy

Week 8
a) Aim:

Write a Java program that correctly implements the producer-consumer problem using the
concept of inter thread communication.
Description:
 The producer produces the item and the consumer consumes the same. But here, the consumer can not
consume until the producer produces the item, and producer can not produce until the consumer
consumes the item that already been produced.
 So here, the consumer has to wait until the producer produces the item, and the producer also needs to
wait until the consumer consumes the same.
Program:
import java.util.LinkedList;
public class ProduceConsumer
{
public static void main(String[] args) throws InterruptedException
{
final PC pc = new PC(); // Object of a class that has both produce() and consume() methods

Thread t1 = new Thread(new Runnable() // Create producer thread


{
public void run()
{
try
{
pc.produce();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});

Object Oriented Programming Through Java Page 259


Thread t2 = new Thread(new Runnable() // Create consumer thread
{
public void run()
{
try
{
pc.consume();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
t1.join(); // t1 finishes before t2
t2.join();
}
static class PC // This class has a list, producer (adds items to list and consumer (removes items)
{
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;

public void produce() throws InterruptedException // Function called by producer thread


{
int value = 0;
while (true)
{
synchronized (this) // producer thread waits while list is full
{
while (list.size() == capacity)
wait();

System.out.println("Producer produced-"+ value);

list.add(value++); // to insert the jobs in the list


notify(); //notifies the consumer thread that now it can start consuming
Thread.sleep(1000); // makes the working of program easier to understand
}
}
}

Object Oriented Programming Through Java Page 260


public void consume() throws InterruptedException // Function called by consumer thread
{
while (true)
{
synchronized (this) // consumer thread waits while list is empty
{
while (list.size() == 0)
wait();
int val = list.removeFirst(); // to retrieve the first job in the list
System.out.println("Consumer consumed-"+ val);
notify(); // Wake up producer thread and sleep
Thread.sleep(1000);
}
}
}
}
}
Output:
D:\ACEM\II CSE Bsection>javac ProduceConsumer.java
D:\ACEM\II CSE Bsection>java ProduceConsumer
Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2
Producer produced-3
Consumer consumed-2
Consumer consumed-3
Producer produced-4
Producer produced-5

b) Aim: Develop a Java application for stack operation using Buttons and JOptionPane input and
Message dialog box.
Description:
 This dialogbox defined in JOptionPane class in Java is used when you wish to get some input from the
user.
 Like if you want user to enter his bank account number to display his transaction details you can use
showInputDialog to prompt user.
 After entering the value in the textbox when user presses OK button the input gets stored in a string
variable on left hand variable of the assignment operator.

Object Oriented Programming Through Java Page 261


Program:
import java.util.Stack;
import javax.swing.JOptionPane;
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
Stack<Integer> stk= new Stack<>();
boolean result = stk.empty(); // checking stack is empty or not
JOptionPane.showMessageDialog(null,result,"Result", JOptionPane.PLAIN_MESSAGE);

// pushing elements into stack


stk.push(Integer.parseInt(JOptionPane.showInputDialog("Number1=")));
stk.push(Integer.parseInt(JOptionPane.showInputDialog("Number2=")));
stk.push(Integer.parseInt(JOptionPane.showInputDialog("Number3=")));
stk.push(Integer.parseInt(JOptionPane.showInputDialog("Number4=")));
//prints elements of the stack
JOptionPane.showMessageDialog(null,stk,"Result", JOptionPane.PLAIN_MESSAGE);
result = stk.empty();
JOptionPane.showMessageDialog(null,result,"Result", JOptionPane.PLAIN_MESSAGE);
}
}
Output:

Object Oriented Programming Through Java Page 262


b) Aim:
Develop a Java application to perform Addition, Division, Multiplication and subtraction usingthe
JOptionPane dialog Box and Textfields
Description:
 This dialogbox defined in JOptionPane class in Java is used when you wish to get some input from the
user.
 Like if you want user to enter his bank account number to display his transaction details you can use
showInputDialog to prompt user.
 After entering the value in the textbox when user presses OK button the input gets stored in a string
variable on left hand variable of the assignment operator.
 We can perform mathematical operations using operators and use showMessageDialog to display output

Object Oriented Programming Through Java Page 263


Program:
import javax.swing.JOptionPane;
public class Calculator
{
public static void main(String args[])
{
int num1;
int num2;
int sum;
int sub;
int mul;
int div;
String Res;

num1=Integer.parseInt(JOptionPane.showInputDialog("Number1="));
num2=Integer.parseInt(JOptionPane.showInputDialog("Number2="));

sum=num1+num2;
sub=num1-num2;
mul=num1*num2;
div=num1/num2;

Res="The Sum of "+num1+" and "+num2+" is " +sum ;


Res=Res +"\n The DIfference of "+num1+" and "+num2+" is " +sub;
Res=Res +"\n The Product of "+num1+" and "+num2+" is " +mul;
Res=Res +"\n The Division of "+num1+" by "+num2+" is " +div;
JOptionPane.showMessageDialog(null,Res,"Result", JOptionPane.PLAIN_MESSAGE);
}
}
Output:

Object Oriented Programming Through Java Page 264


9)a) Aim: Develop a Java application for the blinking eyes and mouth should open while blinking.

Description:
 we can use Applet concepts for blinking eyes
 we can use paint() method and drawstring() methods
 we draw symbols like rectangle, oval like many for many operations in this code
Program:
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;

public class A extends Applet


{
private static final long serialVersionUID = -1152278362796573663L;

public class MyCanvas extends Canvas


{
private static final long serialVersionUID = -4372759074220420333L;
private int flag = 0;
public void paint(Graphics g)
{
draw();
}

public void draw()


{
Graphics g = this.getGraphics();
g.setColor(Color.BLACK);
super.paint(g);
if (flag == 0)
{
System.out.println(flag);
g.drawOval(40, 40, 120, 150);// face
g.drawRect(57, 75, 30, 5);// left eye shut
g.drawRect(110, 75, 30, 20);// right eye
g.drawOval(85, 100, 30, 30);// nose
g.fillArc(60, 125, 80, 40, 180, 180);// mouth
g.drawOval(25, 92, 15, 30);// left ear
g.drawOval(160, 92, 15, 30);// right ear
flag = 1;
}

Object Oriented Programming Through Java Page 265


else
{
System.out.println(flag);
g.drawOval(40, 40, 120, 150);// face
g.drawOval(57, 75, 30, 20);// left eye
g.drawOval(110, 75, 30, 20);// right eye
g.fillOval(68, 81, 10, 10);// left pupil
g.fillOval(121, 81, 10, 10);// right pupil
g.drawOval(85, 100, 30, 30);// nose
g.fillArc(60, 125, 80, 40, 180, 180);// mouth
g.drawOval(25, 92, 15, 30);// left ear
g.drawOval(160, 92, 15, 30);// right ear
flag = 0;
}

try
{
Thread.sleep(900);
}
catch (Exception e)
{
System.out.println("killed while sleeping");
}
this.repaint(100);
}
}
public void init()
{
this.C = new MyCanvas();
this.setLayout(new BorderLayout());
this.add(C, BorderLayout.CENTER);
C.setBackground(Color.GRAY);
}
private MyCanvas C;
}
/* <applet code = "A.class" width=200 height=200>
</applet>
*/

Object Oriented Programming Through Java Page 266


Output:

9 b) Aim: Develop a Java application that simulates a traffic light.


The program lets the user select one ofthe three lights: Red, Yellow or Green with radio buttons. On selecting a
button an appropriate message with ―STOP‖ or ―READY‖ or ‖GO‖ should appear above the buttons in the
selected color.Initially, there is no message shown
Description:
We can use different classes related to Applets and its methods
Write init() method to write code
Program:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class TrafficLightsExample extends Applet implements ItemListener


{
CheckboxGroup grp = new CheckboxGroup();
Checkbox redLight, yellowLight, greenLight;
Label msg;
public void init()
{
redLight = new Checkbox("Red", grp, false);
yellowLight = new Checkbox("Yellow", grp, false);
greenLight = new Checkbox("Green", grp, false);

msg = new Label("");

Object Oriented Programming Through Java Page 267


redLight.addItemListener(this);
yellowLight.addItemListener(this);
greenLight.addItemListener(this);

add(redLight);
add(yellowLight);
add(greenLight);

add(msg);
msg.setFont(new Font("Serif", Font.BOLD, 20));
}

public void itemStateChanged(ItemEvent ie)


{
redLight.setForeground(Color.BLACK);
yellowLight.setForeground(Color.BLACK);
greenLight.setForeground(Color.BLACK);

if(redLight.getState() == true)
{
redLight.setForeground(Color.RED);
msg.setForeground(Color.RED);
msg.setText("STOP");
}
else
if(yellowLight.getState() == true)
{
yellowLight.setForeground(Color.YELLOW);
msg.setForeground(Color.YELLOW);
msg.setText("READY");
}
else
{
greenLight.setForeground(Color.GREEN);
msg.setForeground(Color.GREEN);
msg.setText("GO");
}
}
}

Object Oriented Programming Through Java Page 268


/*
<applet code = "TrafficLightsExample.class" width = 1000 height = 500>
</applet> */
Output:

10 a) Aim: Develop a Java application to implement the opening of a door while opening man should
present before hut and closing man should disappear
Description:
 Use awt for applet classes
 Use animation classes
 ImageIcon for image in the below code
Program:

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Animation extends JFrame implements ActionListener
{

ImageIcon ii1, ii2;

Container c;

JButton b1,b2;

JLabel lb1;

Object Oriented Programming Through Java Page 269


Animation()
{
c = getContentPane();

c.setLayout(null);

ii1 = new ImageIcon("house0.jpg");

ii2 = new ImageIcon("house1.jpg");

lb1 = new JLabel(ii1);

lb1.setBounds(50,10,500,500);

b1 = new JButton("Open");

b2 = new JButton("Close");

b1.addActionListener(this);

b2.addActionListener(this);

b1.setBounds(650,240,70,40);

b2.setBounds(650,320,70,40);

c.add(lb1);

c.add(b1);

c.add(b2);
}

public void actionPerformed(ActionEvent ae)


{
String str = ae.getActionCommand();
if( str.equals("Open") )

lb1.setIcon(ii2);

else

lb1.setIcon(ii1);

Object Oriented Programming Through Java Page 270


public static void main(String args[])
{
Animation ob = new Animation();
ob.setTitle("Animation");

ob.setSize(800,600);

ob.setVisible(true);

ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Output:

10 b) Aim: Develop a Java application by using JtextField to read decimal values and converting a decimal
number into a binary number then print the binary value in another JtextField.
Description:

Binary to decimal conversion is done to convert a number given in the binary system to its
equivalent in the decimal number system.
A number system is a format to represent numbers in a certain way.
Binary Number System – The binary number system is used in computers and electronic systems to
represent data, and it consists of only two digits which are 0 and 1.
Input: 33 Output: 100001

Object Oriented Programming Through Java Page 271


Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class Rottenapplet extends JApplet implements ActionListener
{
JPanel mainpanel=new JPanel(new GridLayout (3,1));

JPanel p1=new JPanel(new FlowLayout(0));


JPanel p2=new JPanel(new FlowLayout (0));
JPanel p3=new JPanel(new FlowLayout ());

JTextField q1=new JTextField (10);


JTextField q2=new JTextField (10);

JButton clickbutton = new JButton("convert");

public void init()


{
getContentPane().add(mainpanel);
mainpanel.add(p1);
mainpanel.add(p2);
mainpanel.add(p3);

p1.add(new JLabel("Insert Decimal:"));

p1.add(q1);
p2.add(clickbutton);
p3.add(new JLabel("Decimal to Binary:"));
p3.add(q2);

clickbutton.addActionListener(this);
}

Object Oriented Programming Through Java Page 272


public void actionPerformed(ActionEvent x)
{
if(x.getSource()==clickbutton)
{
int counter,dec,user;
user=Integer.valueOf(q1.getText()).intValue();

String[]conversion=new String[8];
String[]complete=new String[4];
counter=0;
complete[0]="";

do
{
dec=user%2;
conversion[counter]=String.valueOf(dec);
complete[0]=conversion[counter]+complete[0];
user=user/2;
counter=counter+1;
}

while(user !=0);
q2.setText(String.valueOf(complete[user]));
}
}
}
/*
<applet code="Rottenapplet.class" height=300 width=300>
</applet> */
Output:

Object Oriented Programming Through Java Page 273


11 a) Aim: Develop a Java application that handles all mouse events and shows the event name at the centerof the
window when a mouse event is fired. Use adapter classes
Description:
 click: click event occurs when mouse is clicked on the register element. ...
 mouseup: mouseup event occurs when button of the mouse is released over an element. ...
 mousedown: mousedown event occurs when button of the mouse is pressed over an element. ...
 mousemove: mousemove event occurs when button of the mouse move over an element. ...
 mouseover: mouseover event occurs when the mouse cursor moves onto the element. ...
Program:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MouseDemo extends Applet implements MouseListener, MouseMotionListener


{
int mx=0;
int my=0;

String msg="";

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mx=20;
my=40;
msg="Mouse Clicked";
repaint();
}

public void mousePressed(MouseEvent me)


{
mx=30;
my=60;
msg="Mouse Pressed";
repaint();
}

public void mouseReleased(MouseEvent me)


{
mx=30;
my=60;

Object Oriented Programming Through Java Page 274


msg="Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent me)


{
mx=40;
my=80;
msg="Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent me)


{
mx=40;
my=80;
msg="Mouse Exited";
repaint();
}

public void mouseDragged(MouseEvent me)


{
mx=me.getX();
my=me.getY();
showStatus("Currently mouse dragged"+mx+" "+my);
repaint();
}

public void mouseMoved(MouseEvent me)


{
mx=me.getX();
my=me.getY();
showStatus("Currently mouse is at"+mx+" "+my);
repaint();
}

public void paint(Graphics g)


{
g.drawString("Handling Mouse Events",30,20);
g.drawString(msg,60,40);
}
}
/*
<applet code="MouseDemo.class" width=300 height=300>
</applet> */

Object Oriented Programming Through Java Page 275


Output:

11 b) Aim: Develop a Java application to demonstrate the key event handlers


Description:
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through keyboard or page scrolling, etc.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class TestKey extends Applet implements KeyListener
{
String msg="";

public void init()


{
addKeyListener(this);
}

public void keyPressed(KeyEvent k)


{
showStatus("KeyPressed");
}

public void keyReleased(KeyEvent k)


{
showStatus("KeyRealesed");
}
Object Oriented Programming Through Java Page 276
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg, 20, 40);
}
}
/*
<applet code="TestKey.class" width=300 height=100>
</applet> */
Output:

12 A) Aim: Develop a Java application to find the maximum value from the given type of elements using a
generic function
Description:
1. Create a class Myclass to implement generic class and generic methods.
2. Get the set of the values belonging to specific data type.
3. Create the objects of the class to hold integer,character and double values.
4. Create the method to compare the values and find the maximum value stored in the array.
5. Invoke the method with integer, character or double values . The output will be displayed based on the
data type passed to the method.

Object Oriented Programming Through Java Page 277


Program:

class MyClass<T extends Comparable<T>>


{
T[] vals;

MyClass(T[] o)
{
vals = o;
}

public T min()
{
T v = vals[0];

for(int i=1; i < vals.length; i++)


if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}

public T max()
{
T v = vals[0];
for(int i=1; i < vals.length;i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
}
}

class MaxMinUseGeneric
{
public static void main(String args[])
{
int i;

Integer inums[] = {10,2,5,4,6,1};


Character chs[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};

MyClass<Integer> iob = new MyClass<Integer>(inums);


MyClass<Character> cob = new MyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);

Object Oriented Programming Through Java Page 278


System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
System.out.println("Max value in chs: " + dob.max());
System.out.println("Min value in chs: " + dob.min());
}
}
Output:
D:\ACEM\II CSE JAVA LAB\lab 9-13>javac MaxMinUseGeneric.java
D:\ACEM\II CSE JAVA LAB\lab 9-13>java MaxMinUseGeneric

Max value in inums: 10


Min value in inums: 1
Max value in chs: v
Min value in chs: a
Max value in chs: 88.3
Min value in chs: 10.4

12 b) Aim: Develop a Java application that works as a simple calculator. Use a grid layout to arrange buttonsfor the
digits and for the +, -,*, % operations. Add a text field to display the result
Description:
GridLayout is one of the Layout managers.
A layout manager automatically arranges your controls with in a window by using some type of algorithm.
Grid Layout lays out component in a two dimensional grid.
When you instantiate a GridLayout,you define the number of rows and columns
Program:

import javax.swing.*;
import java.awt.*;
import
java.awt.event.*;
public class Calculator extends JApplet
{
public void init()
{
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}

Object Oriented Programming Through Java Page 279


class CalculatorPanel extends JPanel implements ActionListener
{

JButton n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;

static JTextField result=new JTextField("0",45);


static String lastCommand=null;
JOptionPane p=new JOptionPane();
double preRes=0,secVal=0,res;

private static void assign(String no)


{

if((result.getText()).equals("0"))

result.setText(no);

else if(lastCommand=="=")
{
result.setText(no);
lastCommand=null;
}
else
result.setText(result.getText()+no);
}

public CalculatorPanel()
{
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);

JPanel panel=new JPanel();


panel.setLayout(new GridLayout(4,4));

n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);

n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);

n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);

Object Oriented Programming Through Java Page 280


div=new JButton("/");
panel.add(div);
div.addActionListener(this);

n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);

n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);

n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);

mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);

n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);

n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);

n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);

minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);

dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);

n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);

equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);

Object Oriented Programming Through Java Page 281


plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);

add(panel,BorderLayout.CENTER);

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource()==n1)
assign("1");
else if(ae.getSource()==n2)
assign("2");
else if(ae.getSource()==n3)

assign("3");

else if(ae.getSource()==n4)
assign("4");
else if(ae.getSource()==n5)
assign("5");
else if(ae.getSource()==n6)

assign("6");
else if(ae.getSource()==n7)
assign("7");
else if(ae.getSource()==n8)

assign("8");
else if(ae.getSource()==n9)

assign("9");
else if(ae.getSource()==n0)
assign("0");
else if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}

Object Oriented Programming Through Java Page 282


else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="-";
result.setText("0");
}

else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";

result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else
if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}
else
if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="+";
result.setText("0");
}
}
}
Object Oriented Programming Through Java Page 283
/*
<applet code="Calculator.class" height=300 width=200>
</applet>
*/

Output:

13 Aim: . Develop a Java application to establish a JDBC connection, create a table student with propertiesname,
register number, mark1, mark2, mark3. Insert the values into the table by using java and display the information
of the students at front end.

Description:
Steps For Connectivity Between Java Program and Database
1. Import the Packages
2. Load the drivers using the forName() method
3. Register the drivers using DriverManager
4. Establish a connection using the Connection class object
5. Create a statement
6. Execute the query
7. Close the connections

Program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;

Object Oriented Programming Through Java Page 284


import java.sql.ResultSet;

public class TestApplication99


{
static final String url = "jdbc:oracle:thin:@localhost:1521:XE";
static final String user = "system";
static final String pwd = "acem";

public static void main(String[] args)


{
try
{
Connection conn = DriverManager.getConnection(url,user,pwd);
Statement stmt = conn.createStatement();

String sql = "CREATE TABLE SemOne(" +


"name char(15) , "+
"htno int ,"+
" marks1 int ,"+
" marks2 int ,"+
" marks3 int)";

stmt.executeUpdate(sql);

System.out.println("Created table in given database...");


//insertion o record
PreparedStatement ps = conn.prepareStatement("insert into SemOne values(?,?,?,?,?)");
ps.setString(1, "charan");//1 specifies the first parameter in the query
ps.setInt(2,2001);
ps.setInt(3,88);
ps.setInt(4,99);
ps.setInt(5,95);
int i = ps.executeUpdate();
System.out.println(i+" records inserted");

//selecting records from database


PreparedStatement ps1 = null;
String qry = "select * from SemOne";

ps1 = conn.prepareStatement(qry);

ResultSet rs = ps1.executeQuery(qry);

Object Oriented Programming Through Java Page 285


while (rs.next())
{
String name = rs.getString("name");
int htno = rs.getInt("htno");
int marks1 = rs.getInt("marks1");
int marks2 = rs.getInt("marks2");
int marks3 = rs.getInt("marks3");

System.out.println("stu name : " + name);


System.out.println("studtno : " + htno);
System.out.println("sub1 : " + marks1);
System.out.println("sub2 : " + marks2);
System.out.println("sub3 : " + marks3);
}

}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Output:

D:\ACEM\II CSE JAVA LAB\lab 9-13>javac TestApplication99.java


D:\ACEM\II CSE JAVA LAB\lab 9-13>java TestApplication99

Created table in given database...

1 records inserted

stu name : charan


studtno : 2001
sub1 : 88
sub2 : 99
sub3 : 95

Object Oriented Programming Through Java Page 286


Object Oriented Programming Through Java Page 287
Unit-III (Assignement Questions)
1) Explain exception handling using try-catch block with a suitable program.
2) Explain the different types of exception in java by giving examples of each(built in exceptions).
3) Explain the difference between throw, throws in exception handling and Write a program to demonstrate
the multiple catch.
4) Explain random access file in java. Explain the methods for writing and reading byte in random access
file class.
5) Explain reading console Input and writing console output in Java with programs.
6) Explain Byte streams and Character streams in detail.
7) Explain the various methods defined in File Reader Class.
8) Demonstrate the use of FileInputStream and Explain serialization in Java with a simple program.
Unit-IV (Assignement Questions)
1) Explain Thread Model and Creating Threads
2) a)Thread Priorities b) Define Synchronized method and Synchronized block
3) Explain about Interthread communication
4) Explain about Hash Table with an example program
5) Explain about properties file with an example program
Unit-V (Assignement Questions)
1) Exaplain about Applet Life Cycle
2) How to pass parameters to applet
3) Exaplin types of JDBC drivers
4) Explain about JDBC Architecture
5) Write a java program to insert values into database table

Object Oriented Programming Through Java Page 288


Object Oriented Programming Through Java Page 289
Object Oriented Programming Through Java Page 290
Object Oriented Programming Through Java Page 291
Object Oriented Programming Through Java Page 292

You might also like