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

Java Lecture Notes

The document provides lecture notes on programming in Java. It covers topics like Java programming basics, OOP concepts, inheritance, packages, interfaces, exception handling, multithreading, collections, I/O streams, event-driven programming and JDBC. It also lists the course objectives, outcomes and units to be covered along with reference books.

Uploaded by

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

Java Lecture Notes

The document provides lecture notes on programming in Java. It covers topics like Java programming basics, OOP concepts, inheritance, packages, interfaces, exception handling, multithreading, collections, I/O streams, event-driven programming and JDBC. It also lists the course objectives, outcomes and units to be covered along with reference books.

Uploaded by

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

Programming in Java – U20EST467

DEPARTMENT OF INFORMATION TECHNOLOGY

LECTURE NOTES

PROGRAMMING IN JAVA – U20EST467

Year / Semester: II / IV

Academic Year: 2022 - 2023

Department of Information Technology -2020 Regulation Page 1


Programming in Java – U20EST467

VISION, MISSION, AND PROGRAM EDUCATIONAL OBJECTIVES


VISION OF THE INSTITUTION
To be globally recognized for excellence in quality education, innovation and research for the
transformation of lives to serve the society.
MISSION OF THE INSTITUTION
M1: Quality Education: To provide comprehensive academic system that amalgamates the
cutting edge technologies with best practices.
M2: Research and Innovation: To foster value-based research and innovation in collaboration
with industries and institutions globally for creating intellectuals with new avenues.
M3: Employability and Entrepreneurship: To inculcate the employability and entrepreneurial
skills through value and skill based training.
M4: Ethical Values: To instil deep sense of human values by blending societal righteousness
with academic professionalism for the growth of society.
VISION OF THE DEPARTMENT
To be a pioneer in the field of Information Technology by achieving academic excellence,
involving in research & development and promoting technical & professional expertise.
MISSION OF THE DEPARTMENT
Expertise: To impart quality education and create excellent engineers with strong analytical,
Programming and Problem solving skills to meet the ever changing demands of IT industry
Eminence: To kindle creative thinking, innovation and foster value-based research in the field
of information technology
Complaisant: To enrich the employability skills, inculcate entrepreneurial ideology and promote
professional expertise
Exemplar: To instil moral values, ethical responsibilities and empowering graduates to be
socially responsible and technically competent
PROGRAM EDUCATIONAL OBJECTIVES
PEO1 Fortify: To prepare the students with fundamental knowledge in programming
languages and in developing applications
PEO2 Equip: To develop skill in understanding the complexity in networking, security, data
mining, web technology and mobile communication so as to develop innovative applications and
projects in these areas for the betterment of society, as well as to enable them to pursue higher
education
PEO3 Endow: To enable the students as full-fledged professionals by providing opportunities
to enhance their analytical, communication skills and problem solving skills along with
organizing abilities
PEO4 Conventional: To familiarize the students with the ethical issues in engineering
profession, issues related to the worldwide economy, nurturing of current job related skills and
emerging technologies

Department of Information Technology -2020 Regulation Page 2


Programming in Java – U20EST467
PROGRAM OUTCOMES AND PROGRAM SPECIFIC OUTCOMES

List of PSO’s
PSO 1: Establishment of Mathematical and computer systems concepts: To use
mathematical and system concepts to solve multidisciplinary problems using appropriate
mathematical analysis, system and programming concepts on various computing
environments.
PSO 2: Establishment of communication and information concepts: To inculcate good
breadth of knowledge to apply and enhance informatics and communication technologies
PSO 3: Establishment of Business, Technological concepts: The ability to interpret and
respond to business agility with relevant software tools and skills and provide newer ideas and
innovations in information technology research

List of Program Outcomes


PO1 Engineering Knowledge: Apply knowledge of mathematics and science, with
fundamentals of Engineering and Technology to be able to solve complex engineering problems
related to IT.
PO2 Problem Analysis: Identify, Formulate, review research literature and analyze complex
engineering problems related to IT and reaching substantiated conclusions using first principles
of mathematics, natural sciences and engineering sciences
PO3 Design/Development of solutions: Design solutions for complex engineering problems
related to IT and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety and the cultural societal and
environmental considerations
PO4 Conduct Investigations of Complex problems: Use research–based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO5 Modern Tool Usage: Create, Select and apply appropriate techniques, resources and
modern engineering and IT tools including prediction and modeling to computer science related
complex engineering activities with an understanding of the limitations
PO6 The Engineer and Society: Apply Reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the IT professional engineering practice
PO7 Environment and Sustainability: Understand the impact of the IT professional
engineering solutions in societal and environmental contexts and demonstrate the knowledge of,
and need for sustainable development
PO8 Ethics: Apply Ethical Principles and commit to professional ethics and responsibilities
and norms of the engineering practice
PO9 Individual and Team Work: Function effectively as an individual and as a member or
leader in diverse teams and in multidisciplinary Settings
PO10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large such as able to comprehend and with write
effective reports and design documentation, make effective presentations and give and receive
clear instructions.
PO11 Project Management and Finance: Demonstrate knowledge and understanding of the
engineering management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multi-disciplinary environments
PO12 Life-Long Learning: Recognize the need for and have the preparation and ability to
engage in independent and life-long learning the broadest context of technological changes.

Department of Information Technology -2020 Regulation Page 3


Programming in Java – U20EST467

L T P C Hrs
U20EST467 PROGRAMMING IN JAVA 3 0 0 3 45

Course Objectives
• To gain and explore the knowledge of java programming
• To know the principles of inheritances, packages, interfaces
• To get familiarized to generic programming, multithreading concepts.
• To gain and explore the advanced concepts in Java.
• To explore database connectivity
Course Outcomes
After completion of the course, the students will be able to
CO1 - Write a maintainable java program for a given algorithm and implement the same. (K2)
CO2 - Demonstrate the use of inheritance, interface and package in relevant applications. (K3)
CO3 - Create java applications using exception handling, thread and generic programming. (K3)
CO4 - Build java distributed applications using Collections and IO streams. (K3)
CO5 - Exemplify simple graphical user interfaces using GUI components and database programs. (K3)

UNIT I INTRODUCTION TO JAVA PROGRAMMING (9 Hrs)


The History and Evolution of Java – Byte code – Java buzzwords – Data types – Variables – Arrays
– operators – Control statements – Type conversion and casting. Concepts of classes and objects:
Basic Concepts of OOPs – constructors – static keyword – Final with data – Access control – This
key word – Garbage collection – Nested classes and inner classes – String class

UNIT II INHERITANCE, PACKAGES AND INTERFACES (9 Hrs)


Inheritance: Basic concepts – Forms of inheritance – Super key word – method overriding –
Abstract classes – Dynamic method dispatch – The Object class. Packages: Defining – Creating
and Accessing – importing packages. Interfaces: Defining – Implementing – Applying – Variables
and extending interfaces

UNIT III EXCEPTION HANDLING, MULTITHREADING (9 Hrs)


Concepts of Exception handling – Types of exceptions – Creating own exception – Concepts of
Multithreading – creating multiple threads – Synchronization – Inter thread communication.
Enumeration: Autoboxing – Generics.

UNIT IV COLLECTIONS, I/O STREAMS (9 Hrs)


Collections: List – Vector – Stack – Queue – Dequeue – Set – Sorted Set. Input / Output Basics –
Streams – Byte streams and Character streams – Reading and Writing Console – Reading and
Writing Files.

UNIT V EVENT DRIVEN PROGRAMMING AND JDBC (9 Hrs)


Events – Delegation event model – Event handling – Adapter classes. AWT: Concepts of
components – Font class – Color class and Graphics. Introduction to Swing: Layout management -
Swing Components. Java Database Connectivity. Develop real time applications.

Text Books
1. Herbert Schildt, “Java: The Complete Reference”, TMH Publishing Company Ltd, 11 th Edition,
2018.
2. Sagayaraj, Denis, Karthik, Gajalakshmi, “JAVA Programming for core and advanced learners”,
Universities Press Private Limited, 2018.
3. Herbert Schildt, “The Complete Reference JAVA 2”, TMH, Seventh Edition, 2006.

Department of Information Technology -2020 Regulation Page 4


Programming in Java – U20EST467
Reference Books
1. H.M.Dietel and P.J.Dietel, “Java How to Program”, 11th Edition, Pearson Education/PHI, 2017.
2. Nageshvar rao, “Core Java and Integrated Approach”, 1st Edition, Dreamtech, 2016.
3. Cay S. Horstmann, Gary cornell, “Core Java Volume –I Fundamentals”, Prentice Hall, 9th
Edition, 2013.
4. P.J. Dietel and H.M Dietel, “Java for Programmers”, Pearson Education, 9th Edition, 2011.
5. Cay.S.Horstmann and Gary Cornell, “Core Java 2”, Pearson Education, 8th Edition, 2008.

Web References
1. http://www.ibm.com/developerworks/java/
2. http://docs.oracle.com/javase/tutorial/rmi/.
3. IBM’s tutorials on Swings, AWT controls and JDBC.
4. https://www.edureka.co/blog
5. https://www.geeksforgeeks.org

CO-POs/PSOs Mapping
Program Specific
Program Outcomes (POs)
COs Outcomes (PSOs)
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
1 2 1 - - 2 - - - - - - - 3 2 1
2 3 2 1 1 3 - - - - - - - 3 2 1
3 3 2 1 1 3 - - - - - - - 3 2 1
4 3 2 1 1 3 - - - - - - - 3 2 1
5 3 2 1 1 3 - - - - - - - 3 2 1
Correlation Level: 1-Low, 2-Medium, 3- High

Department of Information Technology -2020 Regulation Page 5


Programming in Java – U20EST467

UNIT 1 - INTRODUCTION TO JAVA PROGRAMMING

The History and Evolution of Java - Byte code - Java buzzwords - Data types – Variables
– Arrays – operators - Control statements - Type conversion and casting. Concepts of
classes and objects: Basic Concepts of OOPs – Constructors - Static keyword - Final with
data - Access control - This key word - Garbage collection - Nested classes and inner
classes - String class.

What is Computer?
A computer is a device that can accept human instruction processes it and responds to it or a
computer is a computational device which is used to process the data under the control of a
computer program. Program is a sequence of instruction along with data.
The basic components of a computer are:
• Input unit
• Central Processing Unit (CPU)
• Output unit
The CPU is further divided into three parts-
• Memory unit
• Control unit
• Arithmetic Logic unit

What is a Program?
• A program is a set of instructions given to a computer to perform a specific
operation.
• While executing the program, raw data is processed into a desired output format.
• These computer programs are written in a programming language which are high
level languages.
• High level languages are nearly human languages which are more complex then the
computer understandable language which are called machine language, or low level
language.
• So after knowing the basics, we are ready to create a very simple and basic program.
Like we have different languages to communicate with each other, likewise, we have
different languages like C, C++, C#, Java, python, etc to communicate with the
computers.
• The computer only understands binary language (the language of 0’s and 1’s) also
called machine-understandable language or low-level language but the programs we
are going to write are in a high-level language which is almost similar to human
language.

Hierarchy of Computer Language

Department of Information Technology -2020 Regulation Page 6


Programming in Java – U20EST467

Most Popular Programming Languages are:


• C
• Python
• C++
• Java
• SCALA
• C#
• R
• Ruby
• Go
• Swift
• JavaScript

Characteristics of Programming Language:


• A programming language must be simple, easy to learn and use, have good
readability and human recognizable.
• Abstraction is a must-have Characteristics for a programming language in which
ability to define the complex structure and then its degree of usability comes.
• A portable programming language is always preferred.
• Programming language’s efficiency must be high so that it can be easily converted
into a machine code and executed consumes little space in memory.
• A programming language should be well structured and documented so that it is
suitable for ap plication development.
• Necessary tools for development, debugging, testing, maintenance of a program
must be provided by a programming language.
• A programming language should provide single environment known as Integrated
Development Environment (IDE).
• A programming language must be consistent in terms of syntax and semantics.

The History and Evolution of Java:


• The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television
industry at the time.
• The history of Java starts with the Green Team. Java team members (also known
as Green Team), initiated this project to develop a language for digital devices such
as set-top boxes, televisions, etc.
• However, it was suited for internet programming. Later, Java technology was
incorporated by Netscape.
• The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded, Architecture
Neutral, Object-Oriented, Interpreted, and Dynamic".
• Java was developed by James Gosling, who is known as the father of Java, in 1995.
James Gosling and his team members started the project in the early '90s.
• Currently, Java is used in internet programming, mobile devices, games, e-business
solutions, etc.
• There are given significant points that describe the history of Java.
o James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.

Department of Information Technology -2020 Regulation Page 7


Programming in Java – U20EST467
o Initially designed for small, embedded systems in electronic appliances like
set-top boxes.
o Firstly, it was called "Greentalk" by James Gosling, and the file extension
was .gt.
o After that, it was called Oak and was developed as a part of the Green
project.
Why Java named "Oak"?
• Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries
like the U.S.A., France, Germany, Romania, etc.
• In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why Java Programming named "Java"?
• The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the
essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell
and fun to say.According to James Gosling, "Java was one of the top choices along with
Silk". Since Java was so unique, most of the team members preferred Java than other
names.
• Java is an island of Indonesia where the first coffee was produced (called java coffee). It
is a kind of espresso bean. Java name was chosen by James Gosling while having coffee
near his office.
• Notice that Java is just a name, not an acronym.
• Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
• In 1995, Time magazine called Java one of the Ten Best Products of 1995.
• JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc.
Each new version adds the new features in Java.

Java Terminology

Java Virtual Machine (JVM):


This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program
execution. Phases are as follows: we write the program, then we compile the program and at last
we run the program.
• Writing of the program is of course done by java programmer like you and me.
• Compilation of program is done by javac compiler, javac is the primary java compiler
included in java development kit (JDK). It takes java program as input and generates
java bytecode as output.
• In third phase, JVM executes the bytecode generated by compiler. This is called
program run phase.
o So, now that we understood that the primary function of JVM is to execute the
bytecode produced by compiler. Each operating system has different JVM,
however the output they produce after execution of bytecode is same across all
operating systems. That is why we call java as platform independent language.

Bytecode:
As discussed above, javac compiler of JDK compiles the java source code into bytecode so that
it can be executed by JVM. The bytecode is saved in a .class file by compiler.

Department of Information Technology -2020 Regulation Page 8


Programming in Java – U20EST467

Java Development Kit (JDK):


• While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it.
As the name suggests this is complete java development kit that includes JRE (Java
Runtime Environment), compilers and various tools like JavaDoc, Java debugger etc.
• In order to create, compile and run Java program you would need JDK installed on your
computer.

Java Runtime Environment (JRE):


JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on
your system, you can run a java program however you won’t be able to compile it. JRE includes
JVM, browser plugins and applets support. When you only need to run a java program on your
computer, you would only need JRE.

Garbage Collector:
• In Java, programmers can’t delete the objects. To delete or recollect that memory JVM
has a program called Garbage Collector. Garbage Collector can recollect the of objects
that are not referenced. So Java makes the life of a programmer easy by handling
memory management.
• However, programmers should be careful about their code whether they are using
objects that have been used for a long time. Because Garbage cannot recover the
memory of objects being referenced.

ClassPath
• The classpath is the file path where the java runtime and Java compiler looks for .class
files to load. By default, JDK provides many libraries. If you want to include external
libraries they should be added to the classpath.
• Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an
assembler which is an alias representation of a C++ code.
• As soon as a java program is compiled, java bytecode is generated. In more apt terms,
java bytecode is the machine code in the form of a .class file.
• With the help of java bytecode we achieve platform independence in java.

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.
• JVM's are stack-based so they stack implementation to read the codes.

Department of Information Technology -2020 Regulation Page 9


Programming in Java – U20EST467

Advantages of Java Bytecode:


• Hence bytecode is a very important component of any java program.
• The set of instructions for the JVM may differ from system to system but all can
interpret the bytecode.
• A point to keep in mind is that bytecodes are non-runnable codes and rely on the
availability of an interpreter to execute and thus the JVM comes into play.
• Bytecode is essentially the machine level language which runs on the Java Virtual
Machine. Whenever a class is loaded, it gets a stream of bytecode per method of the
class.
• Whenever that method is called during the execution of a program, the bytecode for that
method gets invoked.
• Javac not only compiles the program but also generates the bytecode for the program.
Thus, we have realized that the bytecode implementation makes Java a platform-
independent language.
• This helps to add portability to Java which is lacking in languages like C or C++.
Portability ensures that Java can be implemented on a wide array of platforms like
desktops, mobile devices, severs and many more.
• Supporting this, Sun Microsystems captioned JAVA as "write once, read anywhere" or
"WORA" in resonance to the bytecode interpretation.

Java Buzzwords or features of Java:


The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which
play an important role in the popularity of this language. The features of Java are also known as
java buzzwords.
A list of most important features of Java language is given below.
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted

Department of Information Technology -2020 Regulation Page 10


Programming in Java – U20EST467
• High Performance
• Multithreaded
• Distributed
• Dynamic
Simple:
• Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented:
• Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporates both data and behavior.
• Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.

Platform Independent:
• Java is platform independent because it is different from other languages like C,
C++, etc. which are compiled into platform specific machines while Java is a write
once, run anywhere language. A platform is the hardware or software environment in
which a program runs.
• There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
• The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:
o Runtime Environment
o API(Application Programming Interface)
• Java code can be run on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Secured
• Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
• Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

Department of Information Technology -2020 Regulation Page 11


Programming in Java – U20EST467
• Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,
etc.

Robust:
• Robust simply means strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral:
• Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.

Portable:
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

High-performance:
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.

Distributed:
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes us able
to access files by calling the methods from any machine on the internet.

Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.

Dynamic:
• Java is a dynamic language. It supports 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).

Department of Information Technology -2020 Regulation Page 12


Programming in Java – U20EST467

Example
public class MyFirstJavaProgram
{
/* This is my first java program.
This will print 'Hello World' as the output */
public static void main(String []args)
{
System.out.println("Hello World"); // prints Hello World
}
}

Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps −
1. Open notepad and add the code as above.
2. Save the file as: MyFirstJavaProgram.java.
3. Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\.
4. Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are
no errors in your code, the command prompt will take you to the next line (Assumption:
The path variable is set).
5. Now, type ' java MyFirstJavaProgram ' to run your program.
6. You will be able to see ' Hello World ' printed on the window.
Basic Syntax:
1. About Java programs, it is very important to keep in mind the following points.
2. Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would
have a different meaning in Java.
3. Class Names − For all class names, the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example: class MyFirstJavaClass
4. Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case.
Example: public void myMethodName()
5. Program File Name − Name of the program file should exactly match the class name.

Department of Information Technology -2020 Regulation Page 13


Programming in Java – U20EST467
6. When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
7. public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.

Structure of Java Program:


Java is an object-oriented programming, platform-independent, and secure programming
language that makes it popular. Using the Java programming language, we can develop a wide
variety of applications.

Write a simple program in Java to print “Hello World”.


// Basic java program
// to print "Hello World"

import java.io.*;

class GFG
{
public static void main(String[] args)
{
// prints Hello World
System.out.println("Hello World");
}
}
Output
Hello World

Explanation:
1. Comments: Comments are used for explaining code and are used in a similar manner
in Java or C or C++. Compilers ignore the comment entries and do not execute them. Comments
can be of a single line or multiple lines.

Department of Information Technology -2020 Regulation Page 14


Programming in Java – U20EST467
Single line Comments:
Syntax:
// Single line commentMulti-line comments:
Syntax:
/* Multi line comments*/
2. import java.io.*: Means all the classes of io package can be imported. Java io
package provides a set of input and output streams for reading and writing data to files or other
input or output sources.
3. class: The class contains the data and methods to be used in the program. Methods
define the behaviour of the class. Class GFG has only one method Main in JAVA.
4. static void Main(): static keyword tells us that this method is accessible without
instantiating the class.
5. void: keywords tells that this method will not return anything. The main() method is
the entry point of our application.
6. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
7. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
8. println(): This method in Java is also used to display a text on the console. It prints
the text on the console and the cursor moves to the start of the next line at the console. The next
printing takes place from the next line.

Data Types in Java:


Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

Example
byte myNum = 100;
short myNum = 5000;
int myNum = 5; // Integer (whole number)
long myNum = 15000000000L;
float myFloatNum = 5.99f; // Floating point number
double myNum = 19.99d;
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String

Department of Information Technology -2020 Regulation Page 15


Programming in Java – U20EST467
Non primitive Data types:
• Non-primitive data types are called reference types because they refer to objects.
• The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java.
• Non-primitive types are created by the programmer and are not defined by Java (except
for String).
• Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types start with an
uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive types have all
the same size.

Java Variables:
• A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
• Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
• Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be
changed.

• All Java variables must be identified with unique names.


• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

The general rules for constructing names for variables (unique identifiers) are:
1. Names can contain letters, digits, underscores, and dollar signs
2. Names must begin with a letter
3. Names should start with a lowercase letter and it cannot contain whitespace
4. Names can also begin with $ and _ (but we will not use it in this tutorial)
5. Names are case sensitive ("myVar" and "myvar" are different variables)
6. Reserved words (like Java keywords, such as int or boolean) cannot be used as names

Department of Information Technology -2020 Regulation Page 16


Programming in Java – U20EST467
Declaring or Creating Variables:
To create a variable, you must specify the type and assign it a value:
Syntax
type variable = value;
Where type is one of Java's types (such as int or String), and variable is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.

Types of Variables:
There are three types of variables in Java:
1. local variable
2. instance variable
3. static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware that
the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called
instance variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared
among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class. Memory
allocation for static variable happens only once when the class is loaded in the memory.

Example to understand the types of variables in Java:


class A
{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
} //end of class

Operators:
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
1. Unary Operator,
2. Arithmetic Operator,
3. Shift Operator,
4. Relational Operator,
5. Bitwise Operator,
6. Logical Operator,
7. Ternary Operator and
8. Assignment Operator

Department of Information Technology -2020 Regulation Page 17


Programming in Java – U20EST467
Java Operator Precedence:

Java Unary Operator:


• The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Java Unary Operator Example: ++ and --
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
}
}

Example:
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}

Department of Information Technology -2020 Regulation Page 18


Programming in Java – U20EST467

Java Arithmetic Operator:


Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
Java Arithmetic Operator Example
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
}
}

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.
Java Left Shift Operator Example
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
}
}

Java Right Shift Operator:


The Java right shift operator >> is used to move left operands value to right by the number of
bits specified by the right operand.
Java Right Shift Operator Example
class 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
}
}

Java Shift Operator Example: >> vs >>>


class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
} }

Department of Information Technology -2020 Regulation Page 19


Programming in Java – U20EST467

Java Ternary Operator:


Java Ternary operator is used as one liner 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
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}

Java Assignment Operator:


Java assignment operator is one of the most common operator. It is used to assign the value on
its right to the operand on its left.
Java Assignment Operator Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}

Java AND Operator Example: Logical && and Bitwise &:


The logical && operator doesn't check second condition if first condition is false. It checks
second condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
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
}
}

Java OR Operator Example: Logical || and Bitwise |:


The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;

Department of Information Technology -2020 Regulation Page 20


Programming in Java – U20EST467
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}

Arrays:
• An array is a collection of similar type of elements which has contiguous memory
location.
• Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location.
• It is a data structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Advantages:
1. Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
2. Random access: We can get any data located at an index position.

Disadvantages:
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.

Types of Array in Java:


There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array

Single Dimensional Array in Java:


Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Department of Information Technology -2020 Regulation Page 21


Programming in Java – U20EST467

Declaration, Instantiation and Initialization of Java Array:


We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Example
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Access the Elements of an Array:


You access an array element by referring to the index number.
This statement accesses the value of the first element in cars:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars[0]);
// Outputs Volvo

Change an Array Element:


To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel";

Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars.length); //
Outputs 4

Loop Through an Array:


You can loop through the array elements with the for loop, and use the length property to
specify how many times the loop should run.
The following example outputs all elements in the cars array:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]); }

Loop Through an Array with For-Each:


There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:
Syntax
for (type variable : arrayname) { ... }
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) {
System.out.println(i); }

Department of Information Technology -2020 Regulation Page 22


Programming in Java – U20EST467
Example of Java Array:
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Passing Array to a Method in Java:


We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}

Multidimensional Arrays:
A multidimensional array is an array containing one or more arrays.

Syntax to Declare Multidimensional Array in Java


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[2][2];//2 row and 2 column

Example to initialize Multidimensional Array in Java


arr[0][0]=1;
arr[0][1]=2;

Department of Information Technology -2020 Regulation Page 23


Programming in Java – U20EST467
arr[1][0]=4;
arr[1][1]=5;

Example of Multidimensional Java Array


//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}

Control statements:
A control statement in java is a statement that determines whether the other statements will be
executed or not. It controls the flow of a program. An ‘if’ statement in java determines the
sequence of execution between a set of two statements.
Control Statements can be divided into three categories, namely
1. Selection statements
2. Iteration statements
3. Jump statements

Selection or Decision-Making Statements:


Statements that determine which statement to execute and when are known as decision-
making statements. The flow of the execution of the program is controlled by the control flow
statement.
There are four decision-making statements available in java.
1. Simple if statement
2. if-else statement
3. Nested if statement

Department of Information Technology -2020 Regulation Page 24


Programming in Java – U20EST467
4. Switch statement

Simple if statement:
if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if condition is true
}
Here, condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if
statement will consider the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;
// Here if the condition is true, if block will consider only statement1 to be inside its
block.

Example:
// Java program to illustrate If statement
class IfDemo
{
public static void main(String args[])
{
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
System.out.println("I am Not in if");
}
}

if-else:
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if the
condition is false. Here comes the else statement. We can use the else statement with if
statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{ // Executes this block if // condition is true }
else
{ // Executes this block if // condition is false }

Example:
// Java program to illustrate if-else statement
class IfElseDemo
{
public static void main(String args[])

Department of Information Technology -2020 Regulation Page 25


Programming in Java – U20EST467
{
int i = 10;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output:
i is smaller than 15

Nested-if:
A nested if is an if statement that is the target of another if or else. Nested if statements means
an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example:
// Java program to illustrate nested-if
statement
class NestedIfDemo
{
public static void main(String args[]) {
int i = 10;
if (i == 10)
{
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}

if-else-if ladder:
Here, a user can decide among multiple options.The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed.

Department of Information Technology -2020 Regulation Page 26


Programming in Java – U20EST467
Syntax:
if (condition)
statement;
else if (condition)
statement;
else statement;

Example:
// Java program to illustrate if-else-if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}

Switch-case:
The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on
the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
case valueN:
statementN;
break;
default:
statementDefault;
}

• Expression can be of type byte, short, int char or an enumeration. Beginning with JDK7,
expression can also be of type String.
• Duplicate case values are not allowed.
• The default statement is optional.

Department of Information Technology -2020 Regulation Page 27


Programming in Java – U20EST467
• The break statement is used inside the switch to terminate a statement sequence.
• The break statement is optional. If omitted, execution will continue on into the next case.

Example:
// Java program to illustrate switch-case
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
default:
System.out.println("i is greater than 2.");
}
}

Jump Statements:
• Java supports three jump statement: break, continue and return.
• These three statements transfer control to other part of the program.

Break: In Java, break is majorly used for:


• Terminate a sequence in a switch statement
• To exit a loop.
• Used as a “civilized” form of goto.

Using break to exit a Loop


Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the innermost loop.

Example:
// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;

Department of Information Technology -2020 Regulation Page 28


Programming in Java – U20EST467
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}

Continue:
• Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for
this particular iteration.
• This is, in effect, a goto just past the body of the loop, to the loop’s end.
• The continue statement performs such an action.

Example:
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;
// If number is odd, print it
System.out.print(i + " ");
}
}
}

Return
The return statement is used to explicitly return from a method. That is, it causes a program
control to transfer back to the caller of the method.
Example:
class Return
{
public static void main(String args[])

Department of Information Technology -2020 Regulation Page 29


Programming in Java – U20EST467
{
boolean t = true;
System.out.println("Before the return.");
if (t)
return;
// Compiler will bypass every statement
// after return
System.out.println("This won't execute.");
}
}

Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly
when some conditions become true. There are three types of loops in Java.
• for loop
• while loop
• do-while loop

Department of Information Technology -2020 Regulation Page 30


Programming in Java – U20EST467
Java For Loop vs While Loop vs Do While Loop

Java For Loop


• The Java for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop.
• There are three types of for loops in java.
o Simple For Loop
o For-each or Enhanced For Loop
o Labeled For 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:
• 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.
• 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.
• Statement: The statement of the loop is executed each time until the second condition is
false.
• Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
Syntax:
for(initialization; condition; incr/decr)
{
//statement or code to be executed
}

Department of Information Technology -2020 Regulation Page 31


Programming in Java – U20EST467

Example:
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}

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.
Example:
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}

Java for-each Loop


The for-each loop is used to traverse array or collection in java. It is easier to use than simple
for loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array){
//code to be executed
}
Example:
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}

Department of Information Technology -2020 Regulation Page 32


Programming in Java – U20EST467
Java Labeled For Loop
We can have a name of each Java for loop. To do so, we use label before the for loop. It is
useful if we have nested for loop so that we can break/continue specific for loop.
Usually, break and continue keywords breaks/continues the innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}

Example:
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}

Java Infinitive For Loop


If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;){
//code to be executed
}
Example:
//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}
you need to press ctrl+c to exit from the program.

Department of Information Technology -2020 Regulation Page 33


Programming in Java – U20EST467
Java While Loop
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.

Syntax:
while(condition)
{
//code to be executed
}

Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
}

Java Infinitive While Loop


If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true){
//code to be executed
}

Example:
public class WhileExample2 {
public static void main(String[] args) {
while(true){
System.out.println("infinitive while loop");
} } }

Department of Information Technology -2020 Regulation Page 34


Programming in Java – U20EST467
Java do-while Loop
• The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.
• The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax:
do{
//code to be executed
}while(condition);

Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}

Java Infinitive do-while Loop


If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);
Example:
public class DoWhileExample2 {
public static void main(String[] args) {
do{
System.out.println("infinitive do while loop");
}while(true);
}
}

Type Conversion and Casting


• When you assign value of one data type to another, the two types might not be
compatible with each other.
• If the data types are compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion and if not then they need to be casted or
converted explicitly. For example, assigning an int value to a long variable.
• In Java, there are two types of casting:
• Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Department of Information Technology -2020 Regulation Page 35


Programming in Java – U20EST467
Widening Casting
• Widening casting is done automatically when passing a smaller size type to a larger size
type:
Example
public class Main
{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}

Narrowing Casting
• Narrowing casting must be done manually by placing the type in parentheses in front of
the value:
Example
public class Main
{
public static void main(String[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}

Difference between Type Casting and Type Conversion

S.N Type Casting Type Conversion

1 Type casting is a mechanism in which one Type conversion allows a compiler to convert one
data type is converted to another data type data type to another data type at the compile time of
using a casting () operator by a a program or code.
programmer.

2 It can be used both compatible data type Type conversion is only used with compatible data
and incompatible data type. types, and hence it does not require any casting
operator.

3 It requires a programmer to manually It does not require any programmer intervention to


casting one data into another type. convert one data type to another because the
compiler automatically compiles it at the run time of
a program.

Department of Information Technology -2020 Regulation Page 36


Programming in Java – U20EST467
4 It is used while designing a program by the It is used or take place at the compile time of a
programmer. program.
5 When casting one data type to another, the When converting one data type to another, the
destination data type must be smaller than destination type should be greater than the source
the source data. data type.

6 It is also known as narrowing conversion It is also known as widening conversion because


because one larger data type converts to a one smaller data type converts to a larger data type.
smaller data type.

7 It is more reliable and efficient. It is less efficient and less reliable.

8 There is a possibility of data or information In type conversion, data is unlikely to be lost when
being lost in type casting. converting from a small to a large data type.

9 float b = 3.0; int a = (int) b int x = 5, y = 2, c; float q = 12.5, p; p = q/x;

Introduction of Object Oriented Programming


• Object-Oriented Programming or OOPs refers to languages that use objects in
programming.
• Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc in programming.
• The main aim of OOP is to bind together the data and the functions that operate on them
so that no other part of the code can access this data except that function.

OOPs Concepts:
• Class
• Objects
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing

1. Class:
a) A class is a user-defined data type. It consists of data members and member functions,
which can be accessed and used by creating an instance of that class.
b) It represents the set of properties or methods that are common to all objects of one type.
A class is like a blueprint for an object.
c) For Example:
d) Consider the Class of Cars.
e) There may be many cars with different names and brands but all of them will share some
common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc.
So here, Car is the class, and wheels, speed limits, mileage are their properties.

Department of Information Technology -2020 Regulation Page 37


Programming in Java – U20EST467
2. Object:
a. It is a basic unit of Object-Oriented Programming and represents the real-
life entities.
b. An Object is an instance of a Class. When a class is defined, no memory is allocated
but when it is instantiated (i.e. an object is created) memory is allocated.
c. An object has an identity, state, and behavior. Each object contains data and code to
manipulate the data. Objects can interact without having to know details of each
other’s data or code, it is sufficient to know the type of message accepted and type of
response returned by the objects.
d. For example “Dog” is a real-life Object, which has some characteristics like color,
Breed, Bark, Sleep, and Eats.

3. Data Abstraction & Encapsulation:


a. Data abstraction is one of the most essential and important features of object-
oriented programming. Data abstraction refers to providing only essential
information about the data to the outside world, hiding the background details or
implementation.
b. Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of the car or applying brakes will
stop the car, but he does not know about how on pressing the accelerator the speed is
increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car. This is what abstraction is.
c. Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates.
d. In Encapsulation, the variables or data of a class are hidden from any other class and
can be accessed only through any member function of their class in which they are
declared.
e. As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.

Department of Information Technology -2020 Regulation Page 38


Programming in Java – U20EST467
4. Inheritance:
a. Inheritance is an important pillar of OOP (Object-Oriented Programming). The
capability of a class to derive properties and characteristics from another class is
called Inheritance.
b. When we write a class, we inherit properties from other classes. So when we create a
class, we do not need to write all the properties and functions again and again, as
these can be inherited from another class that possesses it.
c. Inheritance allows the user to reuse the code whenever possible and reduce its
redundancy.

5. Polymorphism:
a. The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
b. For example, A person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.

6. Dynamic Binding:
a. In dynamic binding, the code to be executed in response to the function call is
decided at runtime.
b. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time.
c. Dynamic Method Binding One of the main advantages of inheritance is that some
derived class D has all the members of its base class B. Once D is not hiding any of
the public members of B, then an object of D can represent B in any context where a
B could be used. This feature is known as subtype polymorphism.

Department of Information Technology -2020 Regulation Page 39


Programming in Java – U20EST467
7. Message Passing:
a. It is a form of communication used in object-oriented programming as well as
parallel programming. Objects communicate with one another by sending and
receiving information to each other.
b. A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results.
c. Message passing involves specifying the name of the object, the name of the
function, and the information to be sent.

Concepts of Class and Object


• What is an object in Java?
An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.

An object has three characteristics:


• State: represents the data (value) of an object.
• Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
• Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.

• For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.
• An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class.
Object Definitions:
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.

What is a class in Java?


• A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.
• A class in Java can contain:
(1) Fields
(2) Methods
(3) Constructors

Department of Information Technology -2020 Regulation Page 40


Programming in Java – U20EST467
(4) Blocks
(5) Nested class and interface

Syntax to declare a class:


class <class_name>
{
field;
method;
}
Instance variable in Java
• A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets memory
at runtime when an object or instance is created. That is why it is known as an instance
variable.

Method in Java
• In Java, a method is like a function which is used to expose the behavior of an object.
• Advantage of Method
• Code Reusability
• Code Optimization

New Keyword
• The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.
• In this example, we have created a Student class which has two data members id and
name. We are creating the object of the Student class by new keyword and printing the
object's value.

File: Student.java
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]) {
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}

Object and Class Example: main outside the class


• In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main()
method in another class.
• We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name with
the class name which has main() method.

Department of Information Technology -2020 Regulation Page 41


Programming in Java – U20EST467

File: TestStudent1.java
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
3 Ways to initialize object
There are 3 ways to initialize object in Java.
• By reference variable
• By method
• By constructor

Object and Class Example: Initialization through reference


Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.
File: TestStudent2.java
class Student
{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method. Here, we are displaying the state (data) of
the objects by invoking the displayInformation() method.
File: TestStudent4.java
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;

Department of Information Technology -2020 Regulation Page 42


Programming in Java – U20EST467
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
} }

As you can see in the above figure, object gets the memory in heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and s2
both are reference variables that refer to the objects allocated in memory.

Object and Class Example: Initialization through a constructor


Object and Class Example: Employee
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();

Department of Information Technology -2020 Regulation Page 43


Programming in Java – U20EST467
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}

What are the different ways to create an object in Java?


There are many ways to create an object in java. They are:

Real World Example: Account


File: TestAccount.java
//Java Program to demonstrate the working of a banking-system
class Account{
int acc_no;
String name;
float amount;
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");

Department of Information Technology -2020 Regulation Page 44


Programming in Java – U20EST467
}
}
void checkBalance(){System.out.println("Balance is: "+amount);}
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}

Array of Objects in Java


• Java is an object-oriented programming language. Most of the work done with the help
of objects.
• We know that an array is a collection of the same data type that dynamically creates
objects and can have elements of primitive types.
• Java allows us to store objects in an array. In Java, the class is also a user-defined data
type.
• An array that conations class type elements are known as an array of objects. It stores
the reference variable of the object.

ArrayOfObjects.java
public class ArrayOfObjects
{
public static void main(String args[])
{
//create an array of product object
Product[] obj = new Product[5] ;
//create & initialize actual product objects using constructor
obj[0] = new Product(23907,"Dell Laptop");
obj[1] = new Product(91240,"HP 630");
obj[2] = new Product(29823,"LG OLED TV");
obj[3] = new Product(11908,"MI Note Pro Max 9");
obj[4] = new Product(43590,"Kingston USB");
//display the product object data
System.out.println("Product Object 1:");

Department of Information Technology -2020 Regulation Page 45


Programming in Java – U20EST467
obj[0].display();
System.out.println("Product Object 2:");
obj[1].display();
System.out.println("Product Object 3:");
obj[2].display();
System.out.println("Product Object 4:");
obj[3].display();
System.out.println("Product Object 5:");
obj[4].display();
}
}
//Product class with product Id and product name as attributes
class Product
{
int pro_Id;
String pro_name;
//Product class constructor
Product(int pid, String n)
{
pro_Id = pid;
pro_name = n;
}
public void display()
{
System.out.print("Product Id = "+pro_Id + " " + " Product Name = "+pro_name);
System.out.println();
}
}

Constructor
• In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one constructor is
called.
• It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
• There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
• Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.

Rules for creating Java constructor


• There are two rules defined for the constructor.
a) Constructor name must be the same as its class name
b) A Constructor must have no explicit return type
c) A Java constructor cannot be abstract, static, final, and synchronized
• Types of Java constructors
a) There are two types of constructors in Java:

Department of Information Technology -2020 Regulation Page 46


Programming in Java – U20EST467
i) Default constructor (no-arg constructor)
ii) Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){
Statements;
}

Example of default constructor


//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Example of default constructor that displays the default values


class Student3
{
int id;
String name;
void display()
{
System.out.println(id+" "+name); }
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}

Department of Information Technology -2020 Regulation Page 47


Programming in Java – U20EST467
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?


The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example of parameterized constructor


class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

Difference between constructor and method in Java

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the


object. behavior of an object.

A constructor must not have a return type. A method must have a return
type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if The method is not provided by the
you don't have any constructor in a class. compiler in any case.

The constructor name must be same as the class The method name may or may not
name. be same as the class name.

Department of Information Technology -2020 Regulation Page 48


Programming in Java – U20EST467
Java Copy Constructor
1) There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.
2) There are many ways to copy the values of one object into another in Java. They are:
a) By constructor
b) By assigning the values of one object into another
c) By clone() method of Object class
3) In this example, we are going to copy the values of one object into another using Java
constructor.
class Student6
{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s)
{
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
1) Does constructor return any value?
a) Yes, it is the current class instance (You cannot use return type yet it returns a value).
2) Can constructor perform other tasks instead of initialization?
a) Yes, like object creation, starting a thread, calling a method, etc. You can perform any
operation in the constructor as you perform in the method.
3) Is there Constructor class in Java?
a) Yes.
4) What is the purpose of Constructor class?
a) Java provides a Constructor class which can be used to get the internal information of a
constructor in the class. It is found in the java.lang.reflect package.

Java static keyword


• The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs
to the class than an instance of the class.
• The static can be:
a) Variable (also known as a class variable)
b) Method (also known as a class method)
c) Block
d) Nested class

Department of Information Technology -2020 Regulation Page 49


Programming in Java – U20EST467
1) Java static variable
• If you declare any variable as static, it is known as a static variable.
• The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college name
of students, etc.
• The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable


• It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}
• Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created.
• All students have its unique rollno and name, so instance data member is good in such
case.
• Here, "college" refers to the common property of all objects. If we make it static, this
field will get the memory only once.

Java static method


a) If you apply static keyword with any method, it is known as static method.
b) A static method belongs to the class rather than the object of a class.
c) A static method can be invoked without the need for creating an instance of a class.
d) A static method can access static data member and can change the value of it.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable

Department of Information Technology -2020 Regulation Page 50


Programming in Java – U20EST467
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Restrictions for the static method
• There are two main restrictions for the static method. They are:
• The static method cannot use non static data member or call non-static method directly.
• this and super cannot be used in static context.
• Why is the Java main method static?
It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the
problem of extra memory allocation.

3) Java static block


• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.
• Example of static block
class A2
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}

Department of Information Technology -2020 Regulation Page 51


Programming in Java – U20EST467
Final Keyword in Java
• The final keyword in java is used to restrict the user. The java final keyword can be used in
many contexts. Final can be:
a) variable
b) method
c) class
• The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only.
• The blank final variable can be static also which will be initialized in the static block only.
1. Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value ofthis variable,
but It can't be changed because final variable once assigned a value can never be
changed.
class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Java final method


• If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}

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

Java final class


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

Department of Information Technology -2020 Regulation Page 52


Programming in Java – U20EST467

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

What is blank or uninitialized final variable?


• A final variable that is not initialized at the time of declaration is known as blank final
variable.
• If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.
• It can be initialized only in constructor
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}

Static blank final variable


• A static final variable that is not initialized at the time of declaration is known as static
blank final variable. It can be initialized only in static block.
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}

Q) Is final method inherited?


Yes, final method is inherited but you cannot override it.
Q) Can we declare a constructor final?
No, because constructor is never inherited.
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.

Access Modifiers in Java


• There are two types of modifiers in Java:
a) access modifiers and
b) non-access modifiers.
• The access modifiers in Java specify the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

Department of Information Technology -2020 Regulation Page 53


Programming in Java – U20EST467
• There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

There are four types of Java access modifiers:


• Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
• Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
• Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
• Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

Access within within outside outside


Modifier class package package by package
subclass only

Private Y` N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

this keyword in java


• There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.

Department of Information Technology -2020 Regulation Page 54


Programming in Java – U20EST467

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.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.

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 keyword, compiler automatically adds this keyword while invoking the method. Let's
see the example

Department of Information Technology -2020 Regulation Page 55


Programming in Java – U20EST467
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();
}}

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

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

Department of Information Technology -2020 Regulation Page 56


Programming in Java – U20EST467
Java Garbage Collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime unused memory automatically.
In other words, it is a way to destroy the unused objects.
• To do so, we were using free() function in C language and delete() in C++. But, in java
it is performed automatically. So, java provides better memory management.
• Advantage of Garbage Collection
• 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:
a) By nulling the reference
b) By assigning a reference to another

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;

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

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

Simple Example of garbage collection in java


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;
// requesting JVM for running Garbage Collector
System.gc();
Runtime.getRuntime().gc();
}
}

Department of Information Technology -2020 Regulation Page 57


Programming in Java – U20EST467

Advantage of java inner classes


• There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
• Difference between nested class and inner class in Java
• Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes


• There are two types of nested classes non-static and static nested classes. The non-static
nested classes are also known as inner classes.
• Non-static nested class (inner class)
a) Member inner class
b) Anonymous inner class
c) Local inner class
• Static nested class

Type Description

Member Inner Class A class created within class and outside method.

Local Inner Class A class created within method.

Static Nested Class A static class created within class.

Nested Interface An interface created within class or interface.

Java Member inner class example


In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

Java Local inner class


• A class i.e. created inside a method is called local inner class in java. If you want to
invoke the methods of local inner class, you must instantiate this class inside the
method.

Department of Information Technology -2020 Regulation Page 58


Programming in Java – U20EST467
public class localInner1{
private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}

Rules for Java Local Inner class


• Local variable can't be private, public or protected.
• Local inner class cannot be invoked from outside the method.
• Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is
possible to access the non-final local variable in local inner class.

Java static nested class


• A static class i.e. created inside a class is called static nested class in java. It cannot
access non-static data members and methods. It can be accessed by outer class name.
• It can access static data members of outer class including private.
• Static nested class cannot access non-static (instance) data member or method.
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}

Java Nested Interface


• An interface i.e. declared within another interface or class is known as nested interface.
• The nested interfaces are used to group related interfaces so that they can be easy to
maintain.
• The nested interface must be referred by the outer interface or class. It can't be accessed
directly.
• Points to remember for nested interfaces
• There are given some points that should be remembered by the java programmer.
a) Nested interface must be public if it is declared inside the interface but it can have
any access modifier if declared within the class.
b) Nested interfaces are declared static implicitely.
• Syntax of nested interface which is declared within the interface
interface interface_name{
...

Department of Information Technology -2020 Regulation Page 59


Programming in Java – U20EST467
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}

String Class
• In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string.
• For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
• is same as:
String s="javatpoint";
• Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.

• The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.
• CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create
strings in java by using these three classes.

• The Java String is immutable which means it cannot be changed. Whenever we change
any string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.

• What is String in java


Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create a string
object.

Department of Information Technology -2020 Regulation Page 60


Programming in Java – U20EST467
• How to create a string object?
• There are two ways to create String object:
• By string literal
• By new keyword

1) String Literal
• Java String literal is created by using double quotes. For Example:
• String s="welcome";
• Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If the
string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
• String s1="Welcome";
• String s2="Welcome";//It doesn't create a new instance

• In the above example, only one object will be created. Firstly, JVM will not find any
string object with the value "Welcome" in string constant pool, that is why it will create
a new object.
• After that it will find the string with the value "Welcome" in the pool, it will not create a
new object but will return the reference to the same instance.
• String objects are stored in a special memory area known as the "string constant pool".
• Why Java uses the concept of String literal?
• To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).

2) By new keyword
• String s=new String("Welcome");//creates two objects and one reference varable
• In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool. The
variable s will refer to the object in a heap (non-pool).
public clas s StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal

Department of Information Technology -2020 Regulation Page 61


Programming in Java – U20EST467
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

Java String class methods


• The java.lang.String class provides many useful methods to perform operations on
sequence of char values.

No. Method Description

1 char charAt(int index) returns char value for the particular index

2 int length() returns string length

3 static String format(String format, returns a formatted string.


Object... args)

4 static String format(Locale l, String returns formatted string with given locale.
format, Object... args)

5 String substring(int beginIndex) returns substring for given begin index.

6 String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index.

7 boolean contains(CharSequence s) returns true or false after matching the sequence


of char value.

8 static String join(CharSequence delimiter, returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, returns a joined string.


Iterable<? extends CharSequence>
elements)

10 boolean equals(Object another) checks the equality of string with the given
object.

11 boolean isEmpty() checks if string is empty.

12 String concat(String str) concatenates the specified string.

13 String replace(char old, char new) replaces all occurrences of the specified char
value.

19 int indexOf(int ch) returns the specified char value index.

20 int indexOf(int ch, int fromIndex) returns the specified char value index starting
with given index.

Department of Information Technology -2020 Regulation Page 62


Programming in Java – U20EST467
21 int indexOf(String substring) returns the specified substring index.

22 int indexOf(String substring, int returns the specified substring index starting
fromIndex) with given index.

23 String toLowerCase() returns a string in lowercase.

24 String toLowerCase(Locale l) returns a string in lowercase using specified


locale.

25 String toUpperCase() returns a string in uppercase.

26 String toUpperCase(Locale l) returns a string in uppercase using specified


locale.

27 String trim() removes beginning and ending spaces of this


string.

28 static String valueOf(int value) converts given type into string. It is an


overloaded method.

Java StringBuffer class

No. String StringBuffer

1) String class is immutable. StringBuffer class is mutable.

2) String is slow and consumes more StringBuffer is fast and consumes less memory
memory when you concat too many when you cancat strings.
strings because every time it creates
new instance.
3) String class overrides the equals() StringBuffer class doesn't override the equals()
method of Object class. So you can method of Object class.
compare the contents of two strings by
equals() method.

Difference between StringBuffer and StringBuilder

No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. StringBuilder is non-synchronized i.e. not thread


thread safe. It means two threads can't safe. It means two threads can call the methods of
call the methods of StringBuffer StringBuilder simultaneously.
simultaneously.
2) StringBuffer is less efficient than StringBuilder is more efficient than StringBuffer.
StringBuilder.

Department of Information Technology -2020 Regulation Page 63


Programming in Java – U20EST467
Example
// Java program to demonstrate difference
// between String, StringBuilder and StringBuffer
class Geeksforgeeks {
// Concatenates to String
public static void concat1(String s1)
{
s1 = s1 + "forgeeks";
}
// Concatenates to StringBuilder
public static void concat2(StringBuilder s2)
{
s2.append("forgeeks");
}
// Concatenates to StringBuffer
public static void concat3(StringBuffer s3)
{
s3.append("forgeeks");
}

public static void main(String[] args)


{
String s1 = "Geeks";
// s1 is not changed
concat1(s1);
System.out.println("String: " + s1);

StringBuilder s2 = new StringBuilder("Geeks");


// s2 is changed
concat2(s2);
System.out.println("StringBuilder: " + s2);

StringBuffer s3 = new StringBuffer("Geeks");


// s3 is changed
concat3(s3);
System.out.println("StringBuffer: " + s3);
}
}
OUTPUT:
String: Geeks
StringBuilder: Geeksforgeeks
StringBuffer: Geeksforgeeks

Department of Information Technology -2020 Regulation Page 64


Programming in Java – U20EST467

UNIT II INHERITANCE, PACKAGES AND INTERFACES

Inheritance: Basic concepts – Forms of inheritance – Super key word – method overriding
– Abstract classes – Dynamic method dispatch – The Object class. Packages: Defining –
Creating and Accessing – importing packages. Interfaces: Defining – Implementing –
Applying – Variables and extending interfaces

Inheritance: Basic concepts

• Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
• The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and fields in your current
class also.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
• Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
• Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
• class Subclass-name extends Superclass-name
o {
o //methods and fields
o }
• The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
• In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.

Department of Information Technology -2020 Regulation Page 65


Programming in Java – U20EST467
Forms or Types of Inheritance
• On the basis of class, there can be three types of inheritance in java:
o Single
o multilevel
o hierarchical
• In java programming, multiple and hybrid inheritance is supported through interface
only.
• Single Inheritance:
• Single inheritance enables a derived class (sub class) to inherit properties and behaviour
from a single parent class (super class)
• Multilevel Inheritance :
• When a class is derived from a class which is also a derived from another class (i.e) a
class having more than one parent classes , such inheritance is called multilevel
inheritance .
• Hierarchical Inheritance:
• When more than one classes are derived from a single base class , such inheritance is
known as hierarchical inheritance.

Forms or Types of Inheritance

Inheritance – Single
Import java.io.*;
import java.util.Scanner;
class Student
{

Department of Information Technology -2020 Regulation Page 66


Programming in Java – U20EST467
public int regno;
int year;
String name;
public void method()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter student name:");
name=ob.nextLine();
System.out.print("Enter register number:");
regno=ob.nextInt();
System.out.print("Enter year:");
year=ob.nextInt();
}
}
class Marks extends Student
{
int arr[]=new int[5],tot;
public void method2()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter Student marks : ");
for (int i=0;i<5;i++)
{
arr[i]=ob.nextInt();
tot = tot + arr[i];
}
}
public void display()
{
System.out.println("\t\t\t *****STUDENT DETAILS*****");
System.out.println("Name :"+name);
System.out.println("Register number:"+regno);
System.out.println("Year:"+year);
System.out.println("Total Marks Obtained :"+tot);
}
public static void main(String[] arg)
{
Marks s=new Marks();
s.method();
s.method2();
s.display();
}
}

Department of Information Technology -2020 Regulation Page 67


Programming in Java – U20EST467
Output:

Inheritance – Hierarchical
import java.io.*;
import java.util.Scanner;
class Player
{
public int number;
String name, role, country;
public void method()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter player name :");
name=ob.nextLine();
System.out.print("Enter Jersey number :");
number=ob.nextInt();
System.out.print("Enter the Nationality :");
country=ob.nextLine();
country=ob.nextLine();
} }
class Batsman extends Player
{ float avg;
public void method1()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter the Role of Batsman :"); role=ob.nextLine();
System.out.print("Enter Batting Average:"); avg=ob.nextFloat();
}
public void display()
{

Department of Information Technology -2020 Regulation Page 68


Programming in Java – U20EST467
System.out.println("\n\t\t\t\t *Batsman Details*");
System.out.println("Name : "+name);
System.out.println("Jersey Number : "+number);
System.out.println("Nationality : "+country);
System.out.println("Specialist : "+role);
System.out.println("Batting Average : "+avg);
}
}
class Bowler extends Player
{
float avgb,eco;
public void method2()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter Bowling type : ");
role=ob.nextLine();
System.out.print("Enter Bowling average : ");
avgb=ob.nextFloat();
System.out.print("Enter Economy :");
eco=ob.nextFloat();
}
public void display()
{
System.out.println("\n\t\t\t\t *Bowlwer Details*");
System.out.println("Name : "+name);
System.out.println("Jersey Number : "+number);
System.out.println("Nationality : "+country);
System.out.println("Specialist : "+role);
System.out.println("Bowling Average : "+avgb);
System.out.println("Economy : "+eco);
}
}
class Heirarchical
{
public static void main(String[] arg)
{
Batsman ba=new Batsman();
Bowler bo=new Bowler();
System.out.println("Batsman Details ... ");
ba.method();
ba.method1();
System.out.println("Bowler Details .... ");
bo.method();
bo.method2();
System.out.println("\n\t\t\t *****PLAYER'S DETAILS*****");
ba.display();
bo.display();
}}

Department of Information Technology -2020 Regulation Page 69


Programming in Java – U20EST467
Output:

Inheritance – Multilevel
import java.util.*;
class Grandparent
{
protected long aadharno;
public String gpname;
String address;
String relegion;
public void getgp()
{
Scanner s1=new Scanner(System.in);
System.out.print("\nEnter the aadhar number:");
aadharno=s1.nextLong();
System.out.print("\nEnter the Grand Parent name:");
gpname=s1.next();
System.out.print("\nEnter the address:");
address=s1.next();

}
}
class Parent extends Grandparent
{
String pname,occ;
public void getp()
{
Scanner s2=new Scanner(System.in);
System.out.print("\nEnter the Parent name:");
pname=s2.next();
System.out.print("\nEnter the Occupation:");

Department of Information Technology -2020 Regulation Page 70


Programming in Java – U20EST467
occ=s2.next();
}
}
class Child extends Parent
{
String cname;
int age;
public void getc()
{
Scanner s3=new Scanner(System.in);
System.out.print("\nEnter child name:");
cname=s3.next();
System.out.print("\nEnter the age:");
age=s3.nextInt();
}
public void display()
{
System.out.println("GrandParent:"+gpname);
System.out.println("Address:"+address);
System.out.println("AAdhar number:"+aadharno);
System.out.println("Parent name:"+pname);
System.out.println("Parent occupation:"+occ);
System.out.println("Child name:"+cname);
System.out.println("Age:"+age);
}
}
class multi
{
public static void main(String []arg)
{
System.out.println("*****MULTILEVEL INHERITANCE*****");
Child c=new Child();
c.getgp();
c.getp();
c.getc();
c.display();
}
}

Important facts about inheritance in Java


• Default superclass: Except Object class, which has no superclass, every class has
one and only one direct superclass (single inheritance). In the absence of any other
explicit superclass, every class is implicitly a subclass of the Object class.
• Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not
support multiple inheritances with classes. Although with interfaces, multiple
inheritances are supported by java.

Department of Information Technology -2020 Regulation Page 71


Programming in Java – U20EST467
• Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked from the
subclass.
• Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods(like getters
and setters) for accessing its private fields, these can also be used by the subclass.

SUPER KEYWORD
• The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
• Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
• Usage of Java super Keyword
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
• Note: super() is added in each class constructor automatically by compiler if there is
no super() or this().

1. Use of “super” with variables:


• This scenario occurs when a derived class and base class has same data members. In
that case there is a possibility of ambiguity for the JVM.

Example:
class Vehicle
{
intmaxSpeed = 120;
}
class Car extends Vehicle
{
intmaxSpeed = 180;
void display()
{

Department of Information Technology -2020 Regulation Page 72


Programming in Java – U20EST467
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}

class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

2. Use of super with methods:


• This is used when we want to call parent class method. So whenever a parent and
child class has same named methods then to resolve ambiguity we use “super”
keyword.
Example:
classPerson
{
voidmessage()
{
System.out.println("This is person class");
}
}
classStudent extendsPerson
{
voidmessage()
{
System.out.println("This is student class");
}

voiddisplay()
{
message();
Super.message();
}
}

classTest
{
publicstaticvoidmain(String args[])
{
Student s = newStudent();
s.display();
}
}

Department of Information Technology -2020 Regulation Page 73


Programming in Java – U20EST467
3. Use of super with constructors:

• Super keyword can also be used to access the parent class constructor. One more
important thing is that, ‘’super” can call both parametric and default constructor.

Example:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}

class Student extends Person


{
Student()
{
super();
System.out.println("Student class Constructor");
}
}

class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}

METHOD OVERRIDING:
• Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or
parent classes.
• When a method in a subclass has the same name, same parameters or signature and
same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.

Example:
classParent
{
voidshow()
{
System.out.println("Parent's show()");
}
}

Department of Information Technology -2020 Regulation Page 74


Programming in Java – U20EST467
classChild extendsParent
{
voidshow()
{
super.show();
System.out.println("Child's show()");
}
}

classMain
{
publicstaticvoidmain(String[] args)
{
Parent obj = newChild();
obj.show();
}
}
Output:
Parent's show()
Child's show()

Rules for method overriding:


• Overriding and Access-Modifiers :
• The access modifier for an overriding method can allow more, but not less, access than
the overridden method.
o Example: a protected instance method in the super-class can be made public, but
not private, in the subclass.
• Final methods cannot be overridden
• Static methods cannot be overridden
• Private methods cannot be overridden
• The overriding method must have same return type :
o From Java 5.0 onwards it is possible to have different return type for a overriding
method in child class, but child’s return type should be sub-type of parent’s
return type.
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
• The access level cannot be more restrictive than the overridden method's access level.
For example: If the superclass method is declared public then the overridding method in
the sub class cannot be either private or protected.
• Instance methods can be overridden only if they are inherited by the subclass.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.

Department of Information Technology -2020 Regulation Page 75


Programming in Java – U20EST467
• If a method cannot be inherited, then it cannot be overridden.
• A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
• A subclass in a different package can only override the non-final methods declared
public or protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden method.
• Constructors cannot be overridden.

Abstract class in Java


• 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).
• Before learning the Java abstract class, let's understand the abstraction in Java first.

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, for
example, sending SMS where you type the text and send the message. You don't know
the internal processing about the message delivery.
• Abstraction lets you focus on what the object does instead of how it does it.
• Ways to achieve Abstraction
• There are two ways to achieve abstraction in java
o Abstract class (0 to 100%)
o Interface (100%)

Abstract class in Java


• A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
• Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Example of abstract class

abstract class A
{

Department of Information Technology -2020 Regulation Page 76


Programming in Java – U20EST467
Abstract Method in Java
• A method which is declared as abstract and does not have implementation is known as
an abstract method.
o Example of abstract method
• abstract void printStatus();//no method body and abstract
• Example of Abstract class that has an abstract method
• In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
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();
}

Understanding the real scenario of Abstract class


• In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.
• Mostly, we don't know about the implementation class (which is hidden to the end user),
and an object of the implementation class is provided by the factory method.
• A factory method is a method that returns the instance of the class. We will learn about
the factory method later.
• In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getS
hape() method
s.draw();
}
}

Department of Information Technology -2020 Regulation Page 77


Programming in Java – U20EST467
Another example of Abstract class in java
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Another real scenario of abstract class


• The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.
interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am c");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output: I am a I am b I am c I am d

Department of Information Technology -2020 Regulation Page 78


Programming in Java – U20EST467
Dynamic method dispatch or Runtime Polymorphism
• 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:
o compile-time polymorphism and
o 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.

Static vs Dynamic binding

No Key Static Binding Dynamic Binding

1 Basic It is resolved at compile time It is resolved at run time

2 Resolve static binding use type of the class Dynamic binding uses object to
mechanism and fields resolve binding

3 Example Overloading is an example of static Method overriding is the example


binding of Dynamic binding

4. Type of private, final and static methods and Virtual methods use dynamic
Methods variables uses static binding binding

Runtime Polymorphism in Java


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

Department of Information Technology -2020 Regulation Page 79


Programming in Java – U20EST467
For example:
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. For
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.

Java Runtime Polymorphism Example: Bank


• Consider a scenario where Bank is a class that provides a method to get the rate of interest.
However, the rate of interest may differ according to banks. For example, SBI, ICICI, and
AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism
{
public static void main(String args[]){
Bank b;

Department of Information Technology -2020 Regulation Page 80


Programming in Java – U20EST467
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

Advantages of Dynamic Method Dispatch


• Dynamic method dispatch allow Java to support overriding of methods which is central for
run-time polymorphism.
• It allows a class to specify methods that will be common to all of its derivatives, while
allowing subclasses to define the specific implementation of some or all of those methods.
• It also allow subclasses to add its specific methods subclasses to define the specific
implementation of some.

Object class in Java


• The Object class is the parent class of all the classes in java by default. In other words, it is
the topmost class of java.
• The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as
upcasting.
• Let's take an example, there is getObject() method that returns an object but it can be of any
type like Employee,Student etc, we can use Object class reference to refer that object. For
example:
• Object obj=getObject();

//we don't know what object will be returned from this method
• The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.

Department of Information Technology -2020 Regulation Page 81


Programming in Java – U20EST467
Methods of Object class

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

Method Description

public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the metadata of
this class.

public int hashCode() returns the hashcode number for this object.

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

protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.
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 timeout)throws causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is
being garbage collected.

Department of Information Technology -2020 Regulation Page 82


Programming in Java – U20EST467
PACKAGES
java package
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java can be categorized in two form, built-in package and user-defined
package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
• Here, we will have the detailed learning of creating and using user-defined 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.
• Java package removes naming collision.

Simple example of java package


• The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

Department of Information Technology -2020 Regulation Page 83


Programming in Java – U20EST467
How to compile java package
• If you are not using any IDE, you need to follow the syntax given below:
• javac -d directory javafilename
• For example
• javac -d . Simple.java
• The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows)
etc. If you want to keep the package within the same directory, you can use . (dot).
How to run java package program
• You need to use fully qualified name e.g. mypack.Simple etc to run the class.
• To Compile: javac -d . Simple.java
• To Run: java mypack.SimpleOutput:Welcome to package
• The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package?


• There are three ways to access the package from outside the package.
o import package.*;
o import package.classname;
o 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 of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Department of Information Technology -2020 Regulation Page 84


Programming in Java – U20EST467
2) Using packagename.classname
• If you import package.classname then only declared class of this package will be accessible.
• Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

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

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 of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
} }

Note: If you import a package, subpackages will not be imported.

• 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.
• Note: Sequence of the program must be package then import then class.

Department of Information Technology -2020 Regulation Page 85


Programming in Java – U20EST467

Subpackage in java

• Package inside the package is called the subpackage. It should be created to categorize the
package further.
• Let's take an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc.
• These classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are for networking etc and so on.
• So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.
• Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
• To Compile: javac -d . Simple.java
• To Run: java com.javatpoint.core.Simple
• How to send the class file to another directory or drive?
• There is a scenario, I want to put the class file of A.java source file in classes folder of c:
drive. For example:
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

• To Compile:
• e:\sources> javac -d c:\classes Simple.java

Department of Information Technology -2020 Regulation Page 86


Programming in Java – U20EST467
• To Run:
o To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.e:\sources> set
classpath=c:\classes;.;e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:

• The -classpath switch can be used with javac and java tool.
• To run this program from e:\source directory, you can use -classpath switch of java that
tells where to look for class file. For example:
• e:\sources> java -classpath c:\classes mypack.Simple
• Ways to load the class files or jar files
• There are two ways to load the class files temporary and permanent.
• Temporary
o By setting the classpath in the command prompt
o By -classpath switch
• Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.

Example
package pack;
import java.io.*;
public class Compute
{
int a,b;
public void add(int a,int b)
{

Department of Information Technology -2020 Regulation Page 87


Programming in Java – U20EST467
System.out.println("The result of addition is :" +(a+b));
}
public void sub(int a,int b)
{
System.out.println("The result of subtraction is :" +(a-b));
}
public void mul(int a,int b)
{
System.out.println("The result of multiplication is :" +(a*b));
}
public void div(int a,int b)
{
System.out.println("The result of division is :" +(a/b));
}
}
import pack.Compute;
import java.io.*;
import java.util.Scanner;
class Calculate
{
public static void main(String args[])
{
int a,b,ch;
Scanner s1=new Scanner(System.in);
System.out.println("Enter two numnber : ");
System.out.print(" A : ");
a=s1.nextInt();
System.out.print(" B : ");
b=s1.nextInt();
System.out.println("Enter the operation to be performed : ");
System.out.println(" 1. Addition \n 2. Subtraction" );
System.out.println(" 3. Multiplication \n 4. Division ");
System.out.print("Enter the choice :");
ch=s1.nextInt();
Compute c=new Compute();
switch(ch)
{
case 1: c.add(a,b);
break;
case 2: c.sub(a,b);
break;
case 3: c.mul(a,b);
break;
case 4: c.div(a,b);
break;
default: System.out.println("Invalid choice...");
}
}
}

Department of Information Technology -2020 Regulation Page 88


Programming in Java – U20EST467
Output:

Department of Information Technology -2020 Regulation Page 89


Programming in Java – U20EST467
Interface in Java
• An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
• The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have abstract methods and variables.
It cannot have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.

Why use Java interface?


• There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
Difference between class and Interface
An interface is different from a class in several ways, including −
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.

Department of Information Technology -2020 Regulation Page 90


Programming in Java – U20EST467

Defining Interface

• The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.

Department of Information Technology -2020 Regulation Page 91


Programming in Java – U20EST467

Department of Information Technology -2020 Regulation Page 92


Programming in Java – U20EST467

Implementing Interface

Department of Information Technology -2020 Regulation Page 93


Programming in Java – U20EST467

Department of Information Technology -2020 Regulation Page 94


Programming in Java – U20EST467

Department of Information Technology -2020 Regulation Page 95


Programming in Java – U20EST467

Department of Information Technology -2020 Regulation Page 96


Programming in Java – U20EST467
Interface variable

Department of Information Technology -2020 Regulation Page 97


Programming in Java – U20EST467

Extending interface

Department of Information Technology -2020 Regulation Page 98


Programming in Java – U20EST467

Department of Information Technology -2020 Regulation Page 99


Programming in Java – U20EST467

Example
interface ISports
{
public void SetTeam(String t1,String t2, int score1, int score2);
public void ShowResult();
}

class Cricket implements ISports


{
String team1,team2;
int team1Runs,team2Runs;
public void SetTeam(String t1,String t2, int r1, int r2)
{
team1 = t1;
team2 = t2;
team1Runs = r1;
team2Runs = r2;
}
public void ShowResult()
{
System.out.println("\t\t\t*Cricket*");
System.out.println("\t" +team1 + " - " + team1Runs + " Runs");
System.out.println("\t" +team2 + " - " + team2Runs + " Runs");
if(team1Runs>team2Runs)

Department of Information Technology -2020 Regulation Page 100


Programming in Java – U20EST467
{
System.out.println("\t"+team1+" Won");
}
else
{
System.out.println("\t"+team2+" Won");
}
}
}
class Hockey implements ISports
{
String team1,team2;
int team1Goals,team2Goals;
public void SetTeam(String t1,String t2, int r1, int r2)
{
team1 = t1;
team2 = t2;
team1Goals = r1;
team2Goals = r2;
}
public void ShowResult()
{
System.out.println("\t\t\t*Hockey*");
System.out.println("\t"+team1 + " - " + team1Goals + " Goals");
System.out.println("\t"+team2 + " - " + team2Goals + " Goals");
if(team1Goals>team2Goals)
{
System.out.println("\t"+team1 + " Won");
}
else
{
System.out.println("\t"+team2 + " Won");
}
}
}
class Sports
{
public static void main(String args[])
{
Cricket c = new Cricket();
Hockey h = new Hockey();

c.SetTeam("India", "England",240,220);
h.SetTeam("India", "Germany",3,2);

c.ShowResult();
h.ShowResult();

Department of Information Technology -2020 Regulation Page 101


Programming in Java – U20EST467
}
}

Output:

Summary

Department of Information Technology -2020 Regulation Page 102


Programming in Java – U20EST467
UNIT III EXCEPTION HANDLING, MULTITHREADING

Concepts of Exception handling – Types of exceptions – Creating own exception –


Concepts of Multithreading – creating multiple threads – Synchronization – Inter thread
communication. Enumeration: Autoboxing – Generics.
Exception Handling in Java
• The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
• In this page, we will learn about Java exceptions, its type and the difference between
checked and unchecked exceptions.
What is Exception in Java
• Dictionary Meaning: Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling


• Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException,IOException,SQLException,RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;

statement 10; Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed.
If we perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.

Department of Information Technology -2020 Regulation Page 103


Programming in Java – U20EST467
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited
by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:

Types of Java Exceptions

• There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:
o Checked Exception
o Unchecked Exception
o Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.

Department of Information Technology -2020 Regulation Page 104


Programming in Java – U20EST467
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description
The "try" keyword is used to specify a block where we should place exception code.
Try The try block must be followed by either catch or finally. It means, we can't use try
block alone.
The "catch" block is used to handle the exception. It must be preceded by try block
Catch which means we can't use catch block alone. It can be followed by finally block
later.
The "finally" block is used to execute the important code of the program. It is
finally
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception.
It specifies that there may occur an exception in the method. It is always used with
method signature

Common Scenarios of Java Exceptions

A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.

String s="abc";

int i=Integer.parseInt(s);//NumberFormatException

Department of Information Technology -2020 Regulation Page 105


Programming in Java – U20EST467
A scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch block

Java try block


• Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
• If an exception occurs at the particular statement of try block, the rest of the block code
will not execute. So, it is recommended not to keeping the code in try block that will not
throw an exception.
• Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}

Java catch block


• Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.
• The catch block must be used after the try block only. You can use multiple catch block
with a single try block.

Internal working of java try-catch block

Department of Information Technology -2020 Regulation Page 106


Programming in Java – U20EST467
• The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception occurred).
• Causes the program to terminate.
• But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.

Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.


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 can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling


}public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }

Output:
java.lang.ArithmeticException: / by zero rest of the code

Java catch multiple exceptions

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

Department of Information Technology -2020 Regulation Page 107


Programming in Java – U20EST467
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.

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

Java Nested try block


The try block within a try block is known as nested try block in java.

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

Java finally block


• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.

Department of Information Technology -2020 Regulation Page 108


Programming in Java – U20EST467

Example:
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main ava.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

Java throw exception

Java throw keyword


• The Java throw keyword is used to explicitly throw an exception.
• We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.
• The syntax of java throw keyword is given below.

throw exception;

Let's see the example of throw IOException.


throw new IOException("sorry device error);

Java throw keyword example


In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.

Department of Information Technology -2020 Regulation Page 109


Programming in Java – U20EST467
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid

Java throws keyword


• The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.
• 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
performing check up before the code being used.

Syntax of java throws


return_type method_name() throws exception_class_name{
//method code
}

Which exception should be declared


• Ans) checked exception only, because:
• unchecked Exception: under your control so correct your code.
• error: beyond your control e.g. you 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


Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
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{

Department of Information Technology -2020 Regulation Page 110


Programming in Java – U20EST467
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Difference between throw and throws in Java


There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:

Sl. No throw Throws

1) Java throw keyword is used to Java throws keyword is used to declare an


explicitly throw an exception. exception.

2) Checked exception cannot be Checked exception can be propagated with


propagated using throw only. throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.

Difference between final, finally and finalize


There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:

No. Final Finally finalize

1) Final is used to apply restrictions on class, Finally is used to place Finalize is used to
method and variable. Final class can't be important code, it will perform clean up
inherited, final method can't be overridden be executed whether processing just before
and final variable value can't be changed. exception is handled or object is garbage
not. collected.

2) Final is a keyword. Finally is a block. Finalize is a


method.

Creating Own Exception or Custom Exception


• If you are creating your own Exception that is known as custom exception or user-
defined exception. Java custom exceptions are used to customize the exception
according to user need.
• By the help of custom exception, you can have your own exception and message.

Department of Information Technology -2020 Regulation Page 111


Programming in Java – U20EST467
simple example of java custom exception

class InvalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException1
{
static void validate(int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}

public static void main(String args[])


{
try
{
validate(13);
}
catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}

Output:
Exception occured: InvalidAgeException:not valid
rest of the code…

Multithreading
• Multithreading in Java is a process of executing multiple threads simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
• However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
• Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


• It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
• You can perform many operations together, so it saves time.
• Threads are independent, so it doesn't affect other threads if an exception occurs in a
single thread.

Department of Information Technology -2020 Regulation Page 112


Programming in Java – U20EST467
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU.
Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


• Each process has an address in memory. In other words, each process allocates a
separate memory area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.

What is Thread in java


• A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path
of execution.
• Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
• As shown in the above figure, a thread is executed inside the process.
• There is context-switching between the threads. There can be multiple processes inside
the OS, and one process can have multiple threads.

Department of Information Technology -2020 Regulation Page 113


Programming in Java – U20EST467
Java Thread class
Java provides Thread class to achieve thread programming. Thread class provides constructors
and methods to create and perform operations on a thread. Thread class extends Object class
and implements Runnable interface.

Java Thread Methods

S.No. Modifier and Type Method Description

1. Void start() It is used to start the execution of the


thread.

2. Void run() It is used to do an action for a thread.

3. static void sleep() It sleeps a thread for the specified amount


of time.

4. static Thread currentThread() It returns a reference to the currently


executing thread object.

5. Void join() It waits for a thread to die.

6. Int getPriority() It returns the priority of the thread.

7. Void setPriority() It changes the priority of the thread.

8. String getName() It returns the name of the thread.

9. Void setName() It changes the name of the thread.

10. Long getId() It returns the id of the thread.

11. boolean isAlive() It tests if the thread is alive.

12. static void yield() It causes the currently executing thread


object to pause and allow other threads to
execute temporarily.

13. Void suspend() It is used to suspend the thread.

14. Void resume() It is used to resume the suspended thread.

15. Void stop() It is used to stop the thread.

16. Void destroy() It is used to destroy the thread group and


all of its subgroups.

17. boolean isDaemon() It tests if the thread is a daemon thread.

18. Void setDaemon() It marks the thread as daemon or user


thread.

19. Void interrupt() It interrupts the thread.

Department of Information Technology -2020 Regulation Page 114


Programming in Java – U20EST467
20. boolean isinterrupted() It tests whether the thread has been
interrupted.

21. static boolean interrupted() It tests whether the current thread has been
interrupted.

22. static int activeCount() It returns the number of active threads in


the current thread's thread group.

23. Void checkAccess() It determines if the currently running


thread has permission to modify the thread.

24. static boolean holdLock() It returns true if and only if the current
thread holds the monitor lock on the
specified object.

25. static void dumpStack() It is used to print a stack trace of the


current thread to the standard error stream.

26. StackTraceElement[] getStackTrace() It returns an array of stack trace elements


representing the stack dump of the thread.

27. static int enumerate() It is used to copy every active thread's


thread group and its subgroup into the
specified array.

28. Thread.State getState() It is used to return the state of the thread.

29. ThreadGroup getThreadGroup( It is used to return the thread group to


) which this thread belongs

30. String toString() It is used to return a string representation of


this thread, including the thread's name,
priority, and thread group.

31. Void notify() It is used to give the notification for only


one thread which is waiting for a particular
object.

32. Void notifyAll() It is used to give the notification to all


waiting threads of a particular object.

33. Void setContextClassL It sets the context ClassLoader for the


oader() Thread.

34. ClassLoader getContextClassL It returns the context ClassLoader for the


oader() thread.

35. static getDefaultUncau It returns the default handler invoked when


Thread.UncaughtExce ghtExceptionHan a thread abruptly terminates due to an
ptionHandler dler() uncaught exception.

36. static void setDefaultUncaug It sets the default handler invoked when a
htExceptionHand thread abruptly terminates due to an
ler() uncaught exception

Department of Information Technology -2020 Regulation Page 115


Programming in Java – U20EST467

Life cycle of a Thread (Thread States)


• A thread can be in one of the five states. According to sun, there is only 4 states in
thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
• But for better understanding the threads, we are explaining it in the 5 states.
• The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
o New
o Runnable
o Running
o Non-Runnable (Blocked)
o Terminated

• New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
• Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
• Running
The thread is in running state if the thread scheduler has selected it.
• Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
• Terminated
A thread is in terminated or dead state when its run() method exits.

How to create thread


There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.

Department of Information Technology -2020 Regulation Page 116


Programming in Java – U20EST467
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.
Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class


class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running…

2) Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output: thread is running...

Department of Information Technology -2020 Regulation Page 117


Programming in Java – U20EST467
Thread Scheduler in Java
• Thread scheduler in java is the part of the JVM that decides which thread should run.
• There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.
• Only one thread at a time can run in a single process.
• The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
• Difference between preemptive scheduling and time slicing
• Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence.
• Under time slicing, a task executes for a predefined slice of time and then reenters the
pool of ready tasks.
• The scheduler then determines which task should execute next, based on priority and
other factors.

Sleep method in java


• The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.
• Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
o public static void sleep(long miliseconds)throws InterruptedException
o public static void sleep(long miliseconds, int nanos)throws InterruptedException
• Can we start a thread twice
• No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for
second time, it will throw exception.

Priority of a Thread (Thread Priority):


• Each thread have a priority. Priorities are represented by a number between 1 and 10.
• In most cases, thread schedular schedules the threads according to their priority (known
as preemptive scheduling).
• But it is not guaranteed because it depends on JVM specification that which scheduling
it chooses.
• 3 constants defined in Thread class:
o public static int MIN_PRIORITY
o public static int NORM_PRIORITY
o public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY).
• The value of MIN_PRIORITY is 1
• and the value of MAX_PRIORITY is 10.

Daemon Thread in Java


• Daemon thread in java is a service provider thread that provides services to the user
thread.
• Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.

Department of Information Technology -2020 Regulation Page 118


Programming in Java – U20EST467
Java Thread Pool
• Java Thread pool represents a group of worker threads that are waiting for the job and
reuse many times.
• In case of thread pool, a group of fixed size threads are created.
• A thread from the thread pool is pulled out and assigned a job by the service provider.
After completion of the job, thread is contained in the thread pool again.
• ThreadGroup in Java
• Java provides a convenient way to group multiple threads in a single object. In such
way, we can suspend, resume or interrupt group of threads by a single method call.
• Note: Now suspend(), resume() and stop() methods are deprecated.
• Java thread group is implemented by java.lang.ThreadGroup class.
• A ThreadGroup represents a set of threads. A thread group can also include the other
thread group. The thread group creates a tree in which every thread group except the
initial thread group has a parent.
• A thread is allowed to access information about its own thread group, but it cannot
access the information about its thread group's parent thread group or any other thread
groups.

Example

import java.io.*;
class AnimalThread implements Runnable
{
public void run()
{
for (int x = 1; x < 4; x++)
{
System.out.println("Run by " + Thread.currentThread().getName());
try
{
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}

System.out.println("Thread State of: "+ Thread.currentThread().getName()+ " -


"+Thread.currentThread().getState());
System.out.println("Exit of Thread: "+ Thread.currentThread().getName());
}
}
public class MultiThreadDemo
{
public static void main(String[] args) throws Exception
{
AnimalThread anr = new AnimalThread();
Thread cat = new Thread(anr);
cat.setName("Cat");
Thread dog = new Thread(anr);
dog.setName("Dog");
Thread cow = new Thread(anr);

Department of Information Technology -2020 Regulation Page 119


Programming in Java – U20EST467
cow.setName("Cow");

System.out.println("Thread State of Cat before calling start: "+cat.getState());


System.out.println("Thread State of Dog before calling start: "+dog.getState());
cat.start();
cat.join(1500);
dog.start();
cow.start();
System.out.println("Thread State of Cat in Main method before Sleep: " + cat.getState());
System.out.println("Thread State of Dog in Main method before Sleep: " + dog.getState());
System.out.println("Thread State of Cow in Main method before Sleep: " + cow.getState());
cow.setPriority(3);
dog.setPriority(2);
cat.setPriority(1);
System.out.println("Thread Priority of Cat " + cat.getPriority());
System.out.println("Thread Priority of Dog " + dog.getPriority());
System.out.println("Thread Priority of Cow " + cow.getPriority());

Thread.sleep(10000);
System.out.println("Thread State of Cat in Main method after sleep: " + cat.getState());
System.out.println("Thread State of Dog in Main method after sleep: " + dog.getState());
System.out.println("Thread State of Cow in Main method after sleep: " + cow.getState());
}
}

Synchronization in Java
• Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
• Java Synchronization is better option where we want to allow only one thread to access
the shared resource.

Why use Synchronization


• The synchronization is mainly used to
o To prevent thread interference.
o To prevent consistency problem
• Types of Synchronization
• There are two types of synchronization
o Process Synchronization
o Thread Synchronization
• Here, we will discuss only thread synchronization.

Thread Synchronization
• There are two types of thread synchronization mutual exclusive and inter-thread
communication.
• Mutual Exclusive
o Synchronized method.
o Synchronized block.
o static synchronization.
• Cooperation (Inter-thread communication in java)
• Mutual Exclusive
• Mutual Exclusive helps keep threads from interfering with one another while sharing

Department of Information Technology -2020 Regulation Page 120


Programming in Java – U20EST467
data. This can be done by three ways in java:
o by synchronized method
o by synchronized block
o by static synchronization

Concept of Lock in Java


• Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.
• From Java 5 the package java.util.concurrent.locks contains several lock
implementations.
• Java synchronized method
• If you declare any method as synchronized, it is known as synchronized method.
• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);

Department of Information Technology -2020 Regulation Page 121


Programming in Java – U20EST467
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:
5
10
15
20
25
100
200
300
400
500

Synchronized Block in Java


• Synchronized block can be used to perform synchronization on any specific resource of
the method.
• Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
• If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
• Points to remember for Synchronized block
• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression) {
//code block
}

class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){

Department of Information Technology -2020 Regulation Page 122


Programming in Java – U20EST467
t.printTable(5);
}}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:5
10
15
20
25
100
200
300
400
500

Static Synchronization
• If you make any static method as synchronized, the lock will be on the class not on object.

Problem without static synchronization


• Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.
• In case of synchronized method and synchronized block there cannot be interference

Department of Information Technology -2020 Regulation Page 123


Programming in Java – U20EST467
between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a
single lock.
• But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock
and t3 acquires another lock.
• I want no interference between t1 and t3 or t2 and t4.
• Static synchronization solves this problem.

Example of static synchronization


In this example we are applying synchronized keyword on the static method to perform static
synchronization.
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
} } }
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
} }

class MyThread2 extends Thread{


public void run()
{
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}
}
public class TestSynchronization4
{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
} }

Department of Information Technology -2020 Regulation Page 124


Programming in Java – U20EST467

Deadlock in java
• Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a
thread is waiting for an object lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread. Since, both threads are waiting for
each other to release the lock, the condition is called deadlock.

Inter-thread communication in Java


• Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
• Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:
o wait()
o notify()
o notifyAll()

1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException

2) notify() method
• Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation. Syntax:
• public final void notify()

3) notifyAll() method
• Wakes up all threads that are waiting on this object's monitor. Syntax:
• public final void notifyAll()

Department of Information Technology -2020 Regulation Page 125


Programming in Java – U20EST467

Understanding the process of inter-thread communication

• The point to point explanation of the above diagram is as follows:


• Threads enter to acquire lock.
• Lock is acquired by on thread.
• Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
• If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
• Now thread is available to acquire lock.
• After completion of the task, thread releases the lock and exits the monitor state of the
object.

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
• It is because they are related to lock and object has a lock.
• Difference between wait and sleep?

Let's see the important differences between wait and sleep methods.

wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.

Example of inter thread communication in java


class Customer
{
int amount=10000;
synchronized void withdraw(int amount){

Department of Information Technology -2020 Regulation Page 126


Programming in Java – U20EST467
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}

Java Enumeration
• The Enum in Java is a data type which contains a fixed set of constants.
• It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.
• According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.
• Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change).
• The Java enum constants are static and final implicitly. It is available since JDK 1.5.
• Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.
• Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods
in Java enum.

Points to remember for Java Enum


• Enum improves type safety
• Enum can be easily used in switch
• Enum can be traversed
• Enum can have fields, constructors and methods
• Enum may implement many interfaces but cannot extend any class because it
internally extends Enum class

Department of Information Technology -2020 Regulation Page 127


Programming in Java – U20EST467

Simple Example of Java Enum


class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}

Output:
WINTER
SPRING
SUMMER
FALL

What is the purpose of the values() method in the enum?


• The Java compiler internally adds the values() method when it creates an enum. The
values() method returns an array containing all the values of the enum.
• What is the purpose of the valueOf() method in the enum?
• The Java compiler internally adds the valueOf() method when it creates an enum.
The valueOf() method returns the value of given constant enum.
• What is the purpose of the ordinal() method in the enum?
• The Java compiler internally adds the ordinal() method when it creates an enum. The
ordinal() method returns the index of the enum value.

class EnumExample1
{

Department of Information Technology -2020 Regulation Page 128


Programming in Java – U20EST467
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
//printing all enum
for (Season s : Season.values()){
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());
}
}

Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2

Autoboxing and Unboxing


The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java
programmer doesn't need to write the conversion code.
Advantage of Autoboxing and Unboxing:
No need of conversion between primitives and Wrappers manually so less coding is required.
Simple Example of Autoboxing in java:
class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
System.out.println(a2+" "+a3);
} }

Output:50 5
Simple Example of Unboxing in java:

The automatic conversion of wrapper class type into corresponding primitive type, is known
as Unboxing.
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}

Department of Information Technology -2020 Regulation Page 129


Programming in Java – U20EST467
Output:50

Autoboxing and Unboxing with method overloading


In method overloading, boxing and unboxing can be performed. There are some rules for
method overloading with boxing:
• Widening beats boxing
• Widening beats varargs
• Boxing beats varargs

1) Example of Autoboxing where widening beats boxing


If there is possibility of widening and boxing, widening beats boxing.
class Boxing1{
static void m(int i){System.out.println("int");}
static void m(Integer i){System.out.println("Integer");}
public static void main(String args[]){
short s=30;
m(s);
}
}

Output:int

2) Example of Autoboxing where widening beats varargs


If there is possibility of widening and varargs, widening beats var-args.
class Boxing2{
static void m(int i, int i2){System.out.println("int int");}
static void m(Integer... i){System.out.println("Integer...");}
public static void main(String args[]){
short s1=30,s2=40;
m(s1,s2);
}
}

Output: int int

3) Example of Autoboxing where boxing beats varargs


class Boxing3{
static void m(Integer i){System.out.println("Integer");}
static void m(Integer... i){System.out.println("Integer...");}
public static void main(String args[]){
int a=30;
m(a);
}
}

Output: Integer

Department of Information Technology -2020 Regulation Page 130


Programming in Java – U20EST467

UNIT IV COLLECTIONS, I/O STREAMS


Collections: List – Vector – Stack – Queue – Dequeue – Set – Sorted Set. Input / Output
Basics – Streams – Byte streams and Character streams – Reading and Writing Console –
Reading and Writing Files.

Collections in Java
● The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
● Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
● Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java: A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
● It provides readymade architecture.
● It represents a set of classes and interfaces.
● It is optional.
What is Collection framework
● The Collection framework represents a unified architecture for storing and manipulating
a group of objects. It has:
● Interfaces and its implementations, i.e., classes
● Algorithm

Hierarchy of Collection Framework


The java.util package contains all the classes and interfaces for the Collection framework.

Department of Information Technology -2020 Regulation Page 131


Programming in Java – U20EST467
Methods of Collection interface:
There are many methods declared in the Collection interface. They are as follows:

SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or equal
to the specified element.

NavigableSet tailSet(E It returns a set of elements that are greater than or equal
fromElement, boolean inclusive) to (if, inclusive is true) the specified element.

boolean contains(Object o) It returns true if this set contains the specified element.

boolean isEmpty() It returns true if this set contains no elements.

boolean remove(Object o) It is used to remove the specified element from this set
if it is present.

void clear() It is used to remove all of the elements from this set.

Object clone() It returns a shallow copy of this TreeSet instance.

E first() It returns the first (lowest) element currently in this


sorted set.

E last() It returns the last (highest) element currently in this


sorted set.

int size() It returns the number of elements in this set.

Department of Information Technology -2020 Regulation Page 132


Programming in Java – U20EST467
Iterator interface :
● Iterator interface provides the facility of iterating the elements in a forward direction
only.
● Methods of Iterator interface
○ There are only three methods in the Iterator interface. They are:

Iterable Interface
● The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.
● It contains only one abstract method. i.e.,
● Iterator<T> iterator()
● It returns the iterator over the elements of type T.

Collection Interface
● The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
● Some of the methods of Collection interface are Boolean add ( Object obj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of
Collection interface.

List Interface
● List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have duplicate
values.
● List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
● To instantiate the List interface, we must use :
● List <data-type> list1= new ArrayList();
● List <data-type> list2 = new LinkedList();
● List <data-type> list3 = new Vector();
● List <data-type> list4 = new Stack();
● There are various methods in List interface that can be used to insert, delete, and access
the elements from the list.

Department of Information Technology -2020 Regulation Page 133


Programming in Java – U20EST467
The classes that implement the List interface are given below.
ArrayList:
● The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed. Consider the following example.
● import java.util.*;
● class TestJavaCollection1
● public static void main(String args[]){
● ArrayList<String> list=new ArrayList<String>();//Creating arraylist
● list.add("Ravi");//Adding object in arraylist
● list.add("Vijay");
● list.add("Ravi");
● list.add("Ajay");

//Traversing list through Iterator


Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay

LinkedList :
● LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion order
and is not synchronized. In LinkedList, the manipulation is fast because no shifting is
required.
Consider the following example.
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

Department of Information Technology -2020 Regulation Page 134


Programming in Java – U20EST467
}
}
Output:
Ravi
Vijay
Ravi
Ajay

Vector :
• Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However,
It is synchronized and contains many methods that are not the part of Collection framework.
• Consider the following example.
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima

Stack :
● The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o), which defines its
properties.
● Consider the following example.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();

Department of Information Technology -2020 Regulation Page 135


Programming in Java – U20EST467
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
}
Output:
Ayush
Garvit
Amit
Ashish

Queue Interface
● Queue interface maintains the first-in-first-out order. It can be defined as an ordered list
that is used to hold the elements which are about to be processed. There are various
classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue
interface.
● Queue interface can be instantiated as:
● Queue<String> q1 = new PriorityQueue();
● Queue<String> q2 = new ArrayDeque();
● There are various classes that implement the Queue interface, some of them are given
below.

PriorityQueue
● The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue. Consider the following example.
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
}System.out.println(itr2.next());
}

Department of Information Technology -2020 Regulation Page 136


Programming in Java – U20EST467
}
}
Output:
head:Amit Sharma head:Amit Sharma iterating the queue elements:
Amit Sharma
Raj JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

Deque Interface
● Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables us to
perform the operations at both the ends.
● Deque can be instantiated as:
● Deque d = new ArrayDeque();

ArrayDeque
● ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements from both the ends.
● ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
● Consider the following example.
import java.util.*;
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:
Gautam
Karan
Ajay

Set Interface
● Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.

Department of Information Technology -2020 Regulation Page 137


Programming in Java – U20EST467

● Set can be instantiated as:


● Set<data-type> s1 = new HashSet<data-type>();
● Set<data-type> s2 = new LinkedHashSet<data-type>();
● Set<data-type> s3 = new TreeSet<data-type>();

HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for
storage. Hashing is used to store the elements in the HashSet. It contains unique items.
Consider the following example.
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay

LinkedHashSet

Linked Hash Set class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It
maintains the insertion order and permits null elements.

Consider the following example.


import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();

Department of Information Technology -2020 Regulation Page 138


Programming in Java – U20EST467
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:
Ravi
Vijay
Ajay

Sorted Set Interface


● SortedSet is the alternate of Set interface that provides a total ordering on its elements.
The elements of the SortedSet are arranged in the increasing (ascending) order. The
Sorted Set provides the additional methods that inhibit the natural ordering of the
elements.
● The SortedSet can be instantiated as:
● SortedSet<data-type> set = new TreeSet();

TreeSet
• Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval
time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
• Consider the following example:
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:
Ajay
Ravi
Vijay

Department of Information Technology -2020 Regulation Page 139


Programming in Java – U20EST467
Java ArrayList
• Java ArrayList class uses a dynamic array for storing the elements. It is like an array,
but there is no size limit.
• We can add or remove elements anytime. So, it is much more flexible than the
traditional array.
• It is found in the java.util package.
• The ArrayList in Java can have the duplicate elements also.
• It implements the List interface so we can use all the methods of List interface here.
• The ArrayList maintains the insertion order internally.
• It inherits the AbstractList class and implements List interface.

The important points about Java ArrayList class are:


• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the index basis.
• In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of
shifting needs to occur if any element is removed from the array list.

Java Non-generic Vs. Generic Collection


• Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
• Java new generic collection allows you to have only one type of object in a collection.
Now it is type safe so typecasting is not required at runtime.
Let's see the old non-generic example of creating java collection.
ArrayList list=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have
the only specified type of objects in it. If you try to add another type of object, it gives compile
time error.

Example of Array List


//The get() method returns the element at the specified index,
//whereas the set() method changes the element.
import java.util.*;
public class ArrayListExample4
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));
//changing the element
al.set(1,"Dates");

Department of Information Technology -2020 Regulation Page 140


Programming in Java – U20EST467
//Traversing list
for(String fruit:al)
System.out.println(fruit);
}
}

Example 2
/* Ways to iterate the elements of the collection in Java
There are various ways to traverse the collection elements:
By Iterator interface, By for-each loop. By ListIterator interface. By for loop.
By forEach() method.
By forEachRemaining() method.*/
import java.util.*;
class ArrayList4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
System.out.println("Traversing list through List Iterator:");
//Here, element iterates in reverse order
ListIterator<String> list1=list.listIterator(list.size());
while(list1.hasPrevious())
{
String str=list1.previous();
System.out.println(str);
}
System.out.println("Traversing list through for loop:");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
System.out.println("Traversing list through forEach() method:");
//The forEach() method is a new feature, introduced in Java 8.
list.forEach(a->{ //Here, we are using lambda expression
System.out.println(a);
});
System.out.println("Traversing list through forEachRemaining() method:");
Iterator<String> itr=list.iterator();
itr.forEachRemaining(a-> //Here, we are using lambda expression
{
System.out.println(a);
});
}
}

Example 3
import java.util.*;
class SortArrayList
{
public static void main(String args[])

Department of Information Technology -2020 Regulation Page 141


Programming in Java – U20EST467
{
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}

Java Vector
• Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2.
• It is found in the java.util package and implements the List interface, so we can use all
the methods of List interface here.
• It is similar to the ArrayList, but with two differences-
• Vector is synchronized.
• Java Vector contains many legacy methods that are not the part of a collections
framework.

Java Vector Methods


SN Method Description

1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection to the end of
this Vector.

3) addElement() It is used to append the specified component to the end of this vector. It
increases the vector size by one.
4) capacity() It is used to get the current capacity of this vector.

Department of Information Technology -2020 Regulation Page 142


Programming in Java – U20EST467
5) clear() It is used to delete all of the elements from this vector.
6) clone() It returns a clone of this vector.

7) contains() It returns true if the vector contains the specified element.


8) containsAll() It returns true if the vector contains all of the elements in the specified
collection.
9) copyInto() It is used to copy the components of the vector into the specified array.
10) elementAt() It is used to get the component at the specified index.

11) elements() It returns an enumeration of the components of a vector.

12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It
ensures that the vector can hold at least the number of components specified by
the minimum capacity argument.
13) equals() It is used to compare the specified object with the vector for equality.

14) firstElement() It is used to get the first component of the vector.

15) forEach() It is used to perform the given action for each element of the Iterable until all
elements have been processed or the action throws an exception.
16) get() It is used to get an element at the specified position in the vector.

17) hashCode() It is used to get the hash code value of a vector.

18) indexOf() It is used to get the index of the first occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.
19) insertElementAt( It is used to insert the specified object as a component in the given vector at the
) specified index.
20) isEmpty() It is used to check if this vector has no components.

21) iterator() It is used to get an iterator over the elements in the list in proper sequence.

22) lastElement() It is used to get the last component of the vector.

23) lastIndexOf() It is used to get the index of the last occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.
24) listIterator() It is used to get a list iterator over the elements in the list in proper sequence.

25) remove() It is used to remove the specified element from the vector. If the vector does
not contain the element, it is unchanged.
26) removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.
27) removeAllEleme It is used to remove all elements from the vector and set the size of the vector to
nts() zero.
28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from

Department of Information Technology -2020 Regulation Page 143


Programming in Java – U20EST467
the vector.

29) removeElement It is used to delete the component at the specified index.


At()
30) removeIf() It is used to remove all of the elements of the collection that satisfy the given
predicate.
31) removeRange() It is used to delete all of the elements from the vector whose index is between
fromIndex, inclusive and toIndex, exclusive.
32) replaceAll() It is used to replace each element of the list with the result of applying the
operator to that element.
33) retainAll() It is used to retain only that element in the vector which is contained in the
specified collection.
34) set() It is used to replace the element at the specified position in the vector with the
specified element.
35) setElementAt() It is used to set the component at the specified index of the vector to the
specified object.
36) setSize() It is used to set the size of the given vector.

37) size() It is used to get the number of components in the given vector.

38) sort() It is used to sort the list according to the order induced by the specified
Comparator.
39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in
the list.
40) subList() It is used to get a view of the portion of the list between fromIndex, inclusive,
and toIndex, exclusive.
41) toArray() It is used to get an array containing all of the elements in this vector in correct
order.
42) toString() It is used to get a string representation of the vector.

43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.

Example
import java.util.*;
public class VectorExample1
{
public static void main(String args[])
{
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");

Department of Information Technology -2020 Regulation Page 144


Programming in Java – U20EST467
vec.add("Elephant");
//Check size and capacity
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity after two insertions
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again
System.out.println("Elements are: "+vec);

//Checking if Tiger is present or not in this vector


if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
//Create an empty Vector
Vector<Integer> in = new Vector<>();
//Add elements in the vector
in.add(100);
in.add(200);
in.add(300);
in.add(200);
in.add(400);
in.add(500);
in.add(600);
in.add(700);

//Display the vector elements


System.out.println("Values in vector: " +in);
//use remove() method to delete the first occurence of an element
System.out.println("Remove first occourence of element 200:
"+in.remove((Integer)200));
//Display the vector elements afre remove() method
System.out.println("Values in vector: " +in);
//Remove the element at index 4
System.out.println("Remove element at index 4: " +in.remove(4));
System.out.println("New Value list in vector: " +in);
//Remove an element
in.removeElementAt(5);

Department of Information Technology -2020 Regulation Page 145


Programming in Java – U20EST467
//Checking vector and displays the element
System.out.println("Vector element after removal: " +in);
//Get the hashcode for this vector
System.out.println("Hash code of this vector = "+in.hashCode());
//Get the element at specified index
System.out.println("Element at index 1 is = "+in.get(1));
}
}

Java Stack
• The stack is a linear data structure that is used to store the collection of objects. It is
based on Last-In-First-Out (LIFO). Java collection framework provides many
interfaces and classes to store the collection of objects. One of them is the Stack
class that provides different operations such as push, pop, search, etc.
• In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program. But before moving to the Java Stack class have
a quick view of how the stack works.
• The stack data structure has the two most important operations that are push and pop.
The push operation inserts an element into the stack and pop operation removes an
element from the top of the stack. Let's see how they work on stack.

Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

Department of Information Technology -2020 Regulation Page 146


Programming in Java – U20EST467
Let's remove (pop) 18, 45, and 11 from the stack.

Empty Stack: If the stack has no element is known as an empty stack. When the stack is
empty the value of the top variable is -1.

When we push an element into the stack the top is increased by 1. In the following figure,
Push 12, top=0
Push 6, top=1
Push 9, top=2

When we pop an element from the stack the value of top is decreased by 1. In the following
figure, we have popped 9

Department of Information Technology -2020 Regulation Page 147


Programming in Java – U20EST467

The following table shows the different values of the top.

Methods of the Stack Class


We can perform push, pop, peek and search operation on the stack. The Java Stack class
provides mainly five methods to perform these operations. Along with this, it also provides all
the methods of the Java Vector class.

Method Modifier and Method Description


Type
empty() boolean The method checks the stack is empty or not.

push(E item) E The method pushes (insert) an element onto the top of the stack.

pop() E The method removes an element from the top of the stack and
returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without
removing it.
search(Object o) int The method searches the specified object and returns the
position of the object.

Example of Stack
import java.util.*;
class Stackeg
{
public static void main(String args[])
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);

Department of Information Technology -2020 Regulation Page 148


Programming in Java – U20EST467
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);

result = stk.empty();
System.out.println("Is the stack empty? " + result);
stk.pop();
System.out.println("Elements in Stack: " + stk);
// Access element from the top of the stack
Integer num = stk.peek();
//prints stack
System.out.println("Element at top: " + num);
int location = stk.search(113);
System.out.println("Location of 113: " + location);
// Find the size of the Stack
int x=stk.size();
System.out.println("The stack size is: "+x);
}
}

Java Queue Interface


Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first
element is removed first and last element is removed at last.

Methods of Java Queue Interface


Method Description

boolean add(object) It is used to insert the specified element into this queue and return true upon
success.
boolean offer(object) It is used to insert the specified element into this queue.

Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or returns null if this
queue is empty.

Object element() It is used to retrieves, but does not remove, the head of this queue.

Object peek() It is used to retrieves, but does not remove, the head of this queue, or returns null
if this queue is empty.

Priority Queue class


The PriorityQueue class provides the facility of using queue. But it does not orders the elements
in FIFO manner. It inherits AbstractQueue class.
PriorityQueue class declaration
Let's see the declaration for java.util.PriorityQueue class.
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Java PriorityQueue Example

Department of Information Technology -2020 Regulation Page 149


Programming in Java – U20EST467

import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:head:Amit
head:Amit
iterating the queue elements: Amit
Jai Karan
Vijay
Rahul
after removing two elements: Karan
Rahul
Vijay

Java Deque Interface


• Java Deque Interface is a linear collection that supports element insertion and removal at
both ends. Deque is an acronym for "double ended queue".
Methods of Java Deque Interface
Method Description
boolean add(object) It is used to insert the specified element into this deque and return true
upon success.
boolean offer(object) It is used to insert the specified element into this deque.

Object remove() It is used to retrieves and removes the head of this deque.

Department of Information Technology -2020 Regulation Page 150


Programming in Java – U20EST467
Object poll() It is used to retrieves and removes the head of this deque, or returns null
if this deque is empty.
Object element() It is used to retrieves, but does not remove, the head of this deque.
Object peek() It is used to retrieves, but does not remove, the head of this deque, or
returns null if this deque is empty.

ArrayDeque class
• The ArrayDeque class provides the facility of using deque and resizable-array. It inherits
AbstractCollection class and implements the Deque interface.

The important points about ArrayDeque class are:


• Unlike Queue, we can add or remove elements from both sides.
• Null elements are not allowed in the ArrayDeque.
• ArrayDeque is not thread safe, in the absence of external synchronization.
• ArrayDeque has no capacity restrictions.
• ArrayDeque is faster than LinkedList and Stack.

Java ArrayDeque Example


import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
Output:
After offerFirst Traversal...
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal

Department of Information Technology -2020 Regulation Page 151


Programming in Java – U20EST467
Java HashSet
• Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
• HashSet stores the elements by using a mechanism called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.
• HashSet is the best approach for search operations.
• The initial default capacity of HashSet is 16, and the load factor is 0.75.
Difference between List and Set
• A list can contain duplicate elements whereas Set contains unique elements only.

Methods of Java HashSet class


Various methods of Java HashSet class are as follows:

SN Modifier & Method Description


Type
1) Boolean add(E e) It is used to add the specified element to this set if it is not
already present.
2) Void clear() It is used to remove all of the elements from the set.
3) Object clone() It is used to return a shallow copy of this HashSet instance:
the elements themselves are not cloned.
4) Boolean contains(Object o) It is used to return true if this set contains the specified
element.
5) Boolean isEmpty() It is used to return true if this set contains no elements.
6) Iterator<E> iterator() It is used to return an iterator over the elements in this set.
7) Boolean remove(Object o) It is used to remove the specified element from this set if it
is present.
8) Int size() It is used to return the number of elements in the set.
9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator
over the elements in the set.

Java HashSet example


import java.util.*;
class HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");

Department of Information Technology -2020 Regulation Page 152


Programming in Java – U20EST467
set.add("Arun");
set.add("Sumit");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
System.out.println("Updated List: "+set);
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "
+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Vijay"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("After invoking clear() method: "+set);
}
}
OUTPUT
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit] Updated List: [Vijay, Arun,
Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []

Java TreeSet class


Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class
are stored in ascending order.
The important points about Java TreeSet class are:
• Java TreeSet class contains unique elements only like HashSet.
• Java TreeSet class access and retrieval times are quiet fast.
• Java TreeSet class doesn't allow null element.
• Java TreeSet class is non synchronized.
• Java TreeSet class maintains ascending order.

Department of Information Technology -2020 Regulation Page 153


Programming in Java – U20EST467
Methods of Java TreeSet class
Method Description

boolean add(E e) It is used to add the specified element to this set if it is not
already present.
boolean addAll(Collection<? It is used to add all of the elements in the specified collection to
extends E> c) this set.

E ceiling(E e) It returns the equal or closest greatest element of the specified


element from the set, or null there is no such element.

Comparator<? super E> It returns comparator that arranged elements in order.


comparator()
Iterator descendingIterator() It is used iterate the elements in descending order.

NavigableSet descendingSet() It returns the elements in reverse order.

E floor(E e) It returns the equal or closest least element of the specified


element from the set, or null there is no such element.

SortedSet headSet(E It returns the group of elements that are less than the specified
toElement) element.
NavigableSet headSet(E It returns the group of elements that are less than or equal to(if,
toElement, boolean inclusive) inclusive is true) the specified element.

E higher(E e) It returns the closest greatest element of the specified element


from the set, or null there is no such element.

Iterator iterator() It is used to iterate the elements in ascending order.


E lower(E e) It returns the closest least element of the specified element
from the set, or null there is no such element.

E pollFirst() It is used to retrieve and remove the lowest(first) element.


E pollLast() It is used to retrieve and remove the highest(last) element.
Spliterator spliterator() It is used to create a late-binding and fail-fast spliterator over
the elements.
NavigableSet subSet(E It returns a set of elements that lie between the given range.
fromElement, boolean
fromInclusive, E toElement,
boolean toInclusive)
SortedSet subSet(E It returns a set of elements that lie between the given range
fromElement, E toElement)) which includes fromElement and excludes toElement.

SortedSet tailSet(E It returns a set of elements that are greater than or equal to the
fromElement) specified element.

Department of Information Technology -2020 Regulation Page 154


Programming in Java – U20EST467
NavigableSet tailSet(E It returns a set of elements that are greater than or equal to (if,
fromElement, boolean inclusive is true) the specified element.
inclusive)
boolean contains(Object o) It returns true if this set contains the specified element.
boolean isEmpty() It returns true if this set contains no elements.

boolean remove(Object o) It is used to remove the specified element from this set if it is
present.
void clear() It is used to remove all of the elements from this set.
Object clone() It returns a shallow copy of this TreeSet instance.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
int size() It returns the number of elements in this set.

Java TreeSet Example


import java.util.*;
class TestCollection11{
public static void main(String args[]){
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
TreeSet<Integer> set=new TreeSet<Integer>();
set.add(24);
set.add(66);
set.add(12);
set.add(15);
System.out.println("Highest Value: "+set.pollFirst());
System.out.println("Lowest Value: "+set.pollLast());
}

TreeSet<String> set1=new TreeSet<String>();


set1.add("A");
set1.add("B");
set1.add("C");
set1.add("D");
set1.add("E");
System.out.println("Initial Set: "+set1);
System.out.println("Reverse Set: "+set1.descendingSet());
System.out.println("Head Set: "+set1.headSet("C", true));
System.out.println("SubSet: "+set1.subSet("A", false, "E", true));

Department of Information Technology -2020 Regulation Page 155


Programming in Java – U20EST467
System.out.println("TailSet: "+set1.tailSet("C", false));
}

OUTPUT
Ajay
Ravi
Vijay
Highest Value: 12
Lowest Value: 66
Initial Set: [A, B, C, D, E]
Reverse Set: [E, D, C, B, A]
Head Set: [A, B, C]
SubSet: [B, C, D, E]
TailSet: [D, E]

Input / Output Basics


• Java I/O (Input and Output) is used to process the input and produce the output.
• Java uses the concept of a stream to make I/O operation fast. The java.io package contains
all the classes required for input and output operations.
• We can perform file handling in Java by Java I/O API.
Stream
• A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
• In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
• System.out: standard output stream
• System.in: standard input stream
• System.err: standard error stream
• Let's see the code to print output and an error message to the console.
• System.out.println("simple message");
• System.err.println("error message");
• Let's see the code to get input from console.
• int i=System.in.read();//returns ASCII code of 1st character
• System.out.println((char)i);//will print the character

OutputStream vs InputStream
• The explanation of OutputStream and InputStream classes are given below:
• OutputStream
• Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
• InputStream
• Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.

Department of Information Technology -2020 Regulation Page 156


Programming in Java – U20EST467
Let's understand the working of Java OutputStream and InputStream by the figure given
below.

OutputStream class
• OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some
sink.
Useful methods of OutputStream
Method Description
1) public void write(int)throws is used to write a byte to the current output stream.
IOException
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.

OutputStream Hierarchy

Department of Information Technology -2020 Regulation Page 157


Programming in Java – U20EST467
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
Useful methods of InputStream
Method Description
1) public abstract int read()throws IOException reads the next byte of data from the input stream. It
returns -1 at the end of the file.
2) public int available()throws IOException returns an estimate of the number of bytes that can
be read from the current input stream.

3) public void close()throws IOException is used to close the current input stream.

InputStream Hierarchy

Department of Information Technology -2020 Regulation Page 158


Programming in Java – U20EST467
Byte array stream and Character array stream

Byte array stream Versus Character array stream

Department of Information Technology -2020 Regulation Page 159


Programming in Java – U20EST467
Java FileOutputStream Class
• Java FileOutputStream is an output stream used for writing data to a file.
• If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.
FileOutputStream class declaration
public class FileOutputStream extends OutputStream
FileOutputStream class methods

Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.

void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at
offset off to the file output stream.

void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.

FileDescriptor getFD() It is used to return the file descriptor associated with the stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte


import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Java FileOutputStream example 2: write string

Department of Information Technology -2020 Regulation Page 160


Programming in Java – U20EST467

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader class.
Java FileInputStream class declaration
public class FileInputStream extends InputStream
Java FileInputStream class methods

Method Description
int available() It is used to return the estimated number of bytes that can be read from
the input stream.

int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, int It is used to read up to len bytes of data from the input stream.
len)
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the file
input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

Department of Information Technology -2020 Regulation Page 161


Programming in Java – U20EST467
protected void finalize() It is used to ensure that the close method is call when there is no more
reference to the file input stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character


import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}
catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be created. In
this file, we are having following content:

Java FileInputStream example 2: read all characters


import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Department of Information Technology -2020 Regulation Page 162


Programming in Java – U20EST467
Java BufferedOutputStream Class
• Java BufferedOutputStream class is used for buffering an output stream. It internally uses
buffer to store data. It adds more efficiency than to write data directly into a stream. So, it
makes the performance fast.
• For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see
the syntax for adding the buffer in an OutputStream:
• OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\te
stout.txt"));
Java BufferedOutputStream class declaration
public class BufferedOutputStream extends FilterOutputStream
Java BufferedOutputStream class constructors
Constructor Description
BufferedOutputStream(OutputStream It creates the new buffered output stream which is used for
os) writing the data to the specified output stream.

BufferedOutputStream(OutputStream It creates the new buffered output stream which is used for
os, int size) writing the data to the specified output stream with a specified
buffer size.

Java BufferedOutputStream class methods


Method Description

void write(int b) It writes the specified byte to the buffered output stream.

void write(byte[] b, int off, int len) It write the bytes from the specified byte-input stream
into a specified byte array, starting with the given offset

void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:


In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one stream
and send it into another. It is required if you have connected the one stream with another.
import java.io.*;
public class BufferedOutputStreamExample
{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);

Department of Information Technology -2020 Regulation Page 163


Programming in Java – U20EST467
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}

Java BufferedInputStream Class


• Java BufferedInputStream class is used to read information from stream. It internally
uses buffer mechanism to make the performance fast.
• The important points about BufferedInputStream are:
o When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.
Java BufferedInputStream class declaration
public class BufferedInputStream extends FilterInputStream
Java BufferedInputStream class constructors
Constructor Description
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it argument, the
input stream IS, for later use.
BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified buffer
int size) size and saves it argument, the input stream IS, for later use.

Java BufferedInputStream class methods


Method Description

int available() It returns an estimate number of bytes that can be read from the input stream
without blocking by the next invocation method for the input stream.

int read() It read the next byte of data from the input stream.

int read(byte[] b, int off, It read the bytes from the specified byte-input stream into a specified byte
int ln) array, starting with the given offset.

void close() It closes the input stream and releases any of the system resources
associated with the stream.

void reset() It repositions the stream at a position the mark method was last called on
this input stream.

void mark(int readlimit) It sees the general contract of the mark method for the input stream.

long skip(long x) It skips over and discards x bytes of data from the input stream.

boolean markSupported() It tests for the input stream to support the mark and reset methods.

Department of Information Technology -2020 Regulation Page 164


Programming in Java – U20EST467
Example of Java BufferedInputStream
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Java DataOutputStream Class


• Java DataOutputStream class allows an application to write primitive Java data types to
the output stream in a machine-independent way.
• Java application generally uses the data output stream to write data that can later be read
by a data input stream.
Java DataOutputStream class declaration
public class DataOutputStream extends FilterOutputStream implements DataOutput

Java DataOutputStream class methods


Method Description
int size() It is used to return the number of bytes written to the data
output stream.
void write(int b) It is used to write the specified byte to the underlying output
stream.
void write(byte[] b, int off, int It is used to write len bytes of data to the output stream.
len)
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte
value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.

void writeChars(String s) It is used to write string to the output stream as a sequence of


characters.

Department of Information Technology -2020 Regulation Page 165


Programming in Java – U20EST467
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte
value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of
bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8
encoding in portable manner.
void flush() It is used to flushes the data output stream.

Example of DataOutputStream class


import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
} }
Java DataInputStream Class
• Java DataInputStream class allows an application to read primitive data from the input
stream in a machine-independent way.
• Java application generally uses the data output stream to write data that can later be
read by a data input stream.
Java DataInputStream class declaration
public class DataInputStream extends FilterInputStream implements DataInput

Java DataInputStream class Methods


Method Description

int read(byte[] b) It is used to read the number of bytes from the input stream

int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.

int readInt() It is used to read input bytes and return an int value.

Department of Information Technology -2020 Regulation Page 166


Programming in Java – U20EST467
byte readByte() It is used to read and return the one input byte.

char readChar() It is used to read two input bytes and returns a char value.

double readDouble() It is used to read eight input bytes and returns a double value.

boolean readBoolean() It is used to read one input byte and return true if byte is non
zero, false if byte is zero.

int skipBytes(int x) It is used to skip over x bytes of data from the input stream.

String readUTF() It is used to read a string that has been encoded using the UTF-
8 format.

void readFully(byte[] b) It is used to read bytes from the input stream and store them
into the buffer array.

void readFully(byte[] b, int off, It is used to read len bytes from the input stream.
int len)

Example of DataInputStream class


In this example, we are reading the data from the file testout.txt file.
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}

Java FilterOutputStream Class


Java FilterOutputStream class implements the OutputStream class. It provides different sub
classes such as BufferedOutputStream and DataOutputStream to provide additional
functionality. So it is less used individually.
Java FilterOutputStream class declaration
public class FilterOutputStream extends OutputStream

Department of Information Technology -2020 Regulation Page 167


Programming in Java – U20EST467
Java FilterOutputStream class Methods
Method Description
void write(int b) It is used to write the specified byte to the output stream.
void write(byte[] ary) It is used to write ary.length byte to the output stream.
void write(byte[] b, int off, int It is used to write len bytes from the offset off to the output
len) stream.
void flush() It is used to flushes the output stream.

void close() It is used to close the output stream.

Example of FilterOutputStream class


import java.io.*;
public class FilterExample {
public static void main(String[] args) throws IOException {
File data = new File("D:\\testout.txt");
FileOutputStream file = new FileOutputStream(data);
FilterOutputStream filter = new FilterOutputStream(file);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
filter.write(b);
filter.flush();
filter.close();
file.close();
System.out.println("Success...");
}
}
Java FilterInputStream Class
Java FilterInputStream class implements the InputStream. It contains different sub classes
as BufferedInputStream, DataInputStream for providing additional functionality. So it is less
used individually.
Java FilterInputStream class declaration
public class FilterInputStream extends InputStream
Java FilterInputStream class Methods
Method Description
int available() It is used to return an estimate number of bytes that can be read from the
input stream.

int read() It is used to read the next byte of data from the input stream.

Department of Information Technology -2020 Regulation Page 168


Programming in Java – U20EST467
int read(byte[] b) It is used to read up to byte.length bytes of data from the input stream.
long skip(long n) It is used to skip over and discards n bytes of data from the input stream.

boolean markSupported() It is used to test if the input stream support mark and reset method.
void mark(int readlimit) It is used to mark the current position in the input stream.

void reset() It is used to reset the input stream.


void close() It is used to close the input stream.

Example of FilterInputStream class


import java.io.*;
public class FilterExample {
public static void main(String[] args) throws IOException {
File data = new File("D:\\testout.txt");
FileInputStream file = new FileInputStream(data);
FilterInputStream filter = new BufferedInputStream(file);
int k =0;
while((k=filter.read())!=-1){
System.out.print((char)k);
}
file.close();
filter.close();
}
}

Java - ObjectStreamClass
ObjectStreamClass act as a Serialization descriptor for class. This class contains the name and
serialVersionUID of the class.
Fields
Modifier and Type Field Description
static ObjectStreamField[] NO_FIELDS serialPersistentFields value indicating no serializable
fields

Methods
Modifier and Type Method Description
Class<?> forClass() It returns the class in the local VM that this
version is mapped to.

ObjectStreamField getField(String name) It gets the field of this class by name.

Department of Information Technology -2020 Regulation Page 169


Programming in Java – U20EST467
ObjectStreamField[] getFields() It returns an array of the fields of this serialization
class.
String getName() It returns the name of the class described by this
descriptor.
Long getSerialVersionUID() It returns the serialVersionUID for this class.

Static ObjectStreamClass lookup(Class<?> cl) It finds the descriptor for a class that can be
serialized.
Static ObjectStreamClass lookupAny(Class<?> It returns the descriptor for any class, regardless
cl) of whether it implements Serializable.
String toString() It returns a string describing this
ObjectStreamClass.

import java.io.ObjectStreamClass;
import java.util.Calendar;
public class ObjectStreamClassExample {
public static void main(String[] args) {

// create a new object stream class for Integers


ObjectStreamClass osc = ObjectStreamClass.lookup(SmartPhone.class);

// get the value field from ObjectStreamClass for integers


System.out.println("" + osc.getField("price"));

// create a new object stream class for Calendar


ObjectStreamClass osc2 = ObjectStreamClass.lookup(String.class);

// get the Class instance for osc2


System.out.println("" + osc2.getField("hash"));

}
}

The Java Console Class


• The Java Console class is be used to get input from console. It provides methods to
read texts and passwords.
• If you read password using Console class, it will not be displayed to the user.
• The java.io.Console class is attached with system console internally. The Console class
is introduced since 1.5.

Department of Information Technology -2020 Regulation Page 170


Programming in Java – U20EST467
Let's see a simple example to read text from console.
String text=System.console().readLine();
System.out.println("Text is: "+text);
Java Console class declaration
public final class Console extends Object implements Flushable

Java Console class methods


Method Description

Reader reader() It is used to retrieve the reader object associated


with the console

String readLine() It is used to read a single line of text from the


console.

String readLine(String fmt, Object... It provides a formatted prompt then reads the
args) single line of text from the console.

char[] readPassword() It is used to read password that is not being


displayed on the console.

char[] readPassword(String fmt, It provides a formatted prompt then reads the


Object... args) password that is not being displayed on the
console.

Console format(String fmt, Object... It is used to write a formatted string to the console
args) output stream.

Console printf(String format, Object... It is used to write a string to the console output
args) stream.

PrintWriter writer() It is used to retrieve the PrintWriter object


associated with the console.

void flush() It is used to flushes the console.

How to get the object of Console


System class provides a static method console() that returns the singleton instance of Console
class.
public static Console console(){}
Let's see the code to get the instance of Console class.
Console c=System.console();

Java Console Example


import java.io.Console;
class ReadStringTest{
public static void main(String args[]){

Department of Information Technology -2020 Regulation Page 171


Programming in Java – U20EST467
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output
Enter your name: Nakul Jain
Welcome Nakul Jain

Java Console Example to read password


import java.io.Console;
class ReadPasswordTest
{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}

Output

Enter password: Password is: 123

Java Reader
Java Reader is an abstract class for reading character streams. The only methods that a
subclass must implement are read(char[], int, int) and close(). Most subclasses, however,
will override some of the methods to provide higher efficiency, additional functionality, or
both.
Fields
Modifier and Field Description
Type

protected Object lock The object used to synchronize operations on this stream.

Department of Information Technology -2020 Regulation Page 172


Programming in Java – U20EST467
Constructor
Modifier Constructor Description

protected Reader() It creates a new character-stream reader whose critical


sections will synchronize on the reader itself.
protected Reader(Object lock) It creates a new character-stream reader whose critical
sections will synchronize on the given object.

Methods
Modifier and Method Description
Type

abstract void close() It closes the stream and releases any


system resources associated with it.

Void mark(int readAheadLimit) It marks the present position in the


stream.

Boolean markSupported() It tells whether this stream supports the


mark() operation.

Int read() It reads a single character.

Int read(char[] cbuf) It reads characters into an array.

abstract int read(char[] cbuf, int off, int len) It reads characters into a portion of an
array.

Int read(CharBuffer target) It attempts to read characters into the


specified character buffer.

Boolean ready() It tells whether this stream is ready to be


read.

Void reset() It resets the stream.

Long skip(long n) It skips characters.

Example
import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);

Department of Information Technology -2020 Regulation Page 173


Programming in Java – U20EST467
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

Java Writer
It is an abstract class for writing to character streams. The methods that a subclass must
implement are write(char[], int, int), flush(), and close(). Most subclasses will override some
of the methods defined here to provide higher efficiency, functionality or both.
Fields
Modifier and Field Description
Type
protected Object lock The object used to synchronize operations on this stream.

Constructor
Modifier Constructor Description

protected Writer() It creates a new character-stream writer whose critical


sections will synchronize on the writer itself.

protected Writer(Object lock) It creates a new character-stream writer whose critical


sections will synchronize on the given object.

Methods
Modifier and Method Description
Type

Writer append(char c) It appends the specified character to this


writer.

Writer append(CharSequence csq) It appends the specified character


sequence to this writer

Writer append(CharSequence csq, int It appends a subsequence of the specified


start, int end) character sequence to this writer.

abstract void close() It closes the stream, flushing it first.

abstract void flush() It flushes the stream.

Department of Information Technology -2020 Regulation Page 174


Programming in Java – U20EST467
Void write(char[] cbuf) It writes an array of characters.

abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of
characters.

Void write(int c) It writes a single character.

Void write(String str) It writes a string.

Void write(String str, int off, int len) It writes a portion of a string.

Java Writer Example


import java.io.*;
public class WriterExample {
public static void main(String[] args) {
try {
Writer w = new FileWriter("output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
}
catch (IOException e) {
e.printStackTrace();
}
}
}

Java FileWriter Class


• Java FileWriter class is used to write character-oriented data to a file. It is character-
oriented class which is used for file handling in java.
• Unlike FileOutputStream class, you don't need to convert string into byte array because
it provides method to write string directly.
Java FileWriter class declaration
public class FileWriter extends OutputStreamWriter
Constructors of FileWriter class
Constructor Description
FileWriter(String file) Creates a new file. It gets file name in string.

FileWriter(File file) Creates a new file. It gets file name in File object.

Department of Information Technology -2020 Regulation Page 175


Programming in Java – U20EST467

Methods of FileWriter class


Method Description
void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[] c) It is used to write char array into FileWriter.

void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.

Java FileWriter Example


In this example, we are writing the data in the file testout.txt using Java FileWriter class.
import java.io.FileWriter;
public class FileWriterExample
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}

Java FileReader Class


Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.
It is character-oriented class which is used for file handling in java.
Java FileReader class declaration
public class FileReader extends InputStreamReader

Department of Information Technology -2020 Regulation Page 176


Programming in Java – U20EST467
Constructors of FileReader class
Constructor Description
FileReader(String file) It gets filename in string. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read mode.
If file doesn't exist, it throws FileNotFoundException.

Methods of FileReader class


Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
void close() It is used to close the FileReader class.

Java FileReader Example


In this example, we are reading the data from the text file testout.txt using Java FileReader
class.
import java.io.FileReader;
public class FileReaderExample
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}

Java BufferedWriter Class


Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing the
efficient writing of single arrays, characters, and strings.
Class declaration
public class BufferedWriter extends Writer

Department of Information Technology -2020 Regulation Page 177


Programming in Java – U20EST467
Class constructors
Constructor Description
BufferedWriter(Writer wrt) It is used to create a buffered character output stream
that uses the default size for an output buffer.
BufferedWriter(Writer wrt, int size) It is used to create a buffered character output stream
that uses the specified size for an output buffer.

Class methods
Method Description

void newLine() It is used to add a new line by writing a line separator.


void write(int c) It is used to write a single character.

void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.

void write(String s, int off, int len) It is used to write a portion of a string.

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream

Example of Java BufferedWriter


Let's see the simple example of writing the data to a text file testout.txt using Java
BufferedWriter.
import java.io.*;
public class BufferedWriterExample
{
public static void main(String[] args) throws Exception
{
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
}
}

Java BufferedReader Class


Java BufferedReader class is used to read the text from a character-based input stream. It can
be used to read data line by line by readLine() method. It makes the performance fast. It
inherits Reader class.

Department of Information Technology -2020 Regulation Page 178


Programming in Java – U20EST467
Java BufferedReader class declaration
public class BufferedReader extends Reader
Java BufferedReader class constructors
Constructor Description

BufferedReader(Reader rd) It is used to create a buffered character input stream that


uses the default size for an input buffer.

BufferedReader(Reader rd, int size) It is used to create a buffered character input stream that
uses the specified size for an input buffer.

Java BufferedReader class methods


Method Description
int read() It is used for reading a single character.

int read(char[] cbuf, int off, It is used for reading characters into a portion of an array.
int len)
boolean markSupported() It is used to test the input stream support for the mark and reset
method.
String readLine() It is used for reading a line of text.

boolean ready() It is used to test whether the input stream is ready to be read.

long skip(long n) It is used for skipping the characters.

void reset() It repositions the stream at a position the mark method was last
called on this input stream.
void mark(int It is used for marking the present position in a stream.
readAheadLimit)
void close() It closes the input stream and releases any of the system
resources associated with the stream.

Java BufferedReader Example


import java.io.*;
public class BufferedReaderExample
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1){

Department of Information Technology -2020 Regulation Page 179


Programming in Java – U20EST467
System.out.print((char)i);
}
br.close();
fr.close();
}
}

Reading data from console by InputStreamReader and BufferedReader


In this example, we are connecting the BufferedReader stream with
the InputStreamReader stream for reading the line by line data from the keyboard.
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Another example of reading data from console until user writes stop
In this example, we are reading and printing the data until the user prints stop.
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";

Department of Information Technology -2020 Regulation Page 180


Programming in Java – U20EST467
while(!name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}

Java CharArrayReader Class


The CharArrayReader is composed of two words: CharArray and Reader. The CharArrayReader
class is used to read character array as a reader (stream). It inherits Reader class.
Java CharArrayReader class declaration
public class CharArrayReader extends Reader
Java CharArrayReader class methods
Method Description
int read() It is used to read a single character
int read(char[] b, int off, int len) It is used to read characters into the portion of an array.
boolean ready() It is used to tell whether the stream is ready to read.
boolean markSupported() It is used to tell whether the stream supports mark()
operation.
long skip(long n) It is used to skip the character in the input stream.
void mark(int readAheadLimit) It is used to mark the present position in the stream.

void reset() It is used to reset the stream to a most recent mark.


void close() It is used to closes the stream.

Example of CharArrayReader Class:


import java.io.CharArrayReader;
public class CharArrayExample{
public static void main(String[] ag) throws Exception {
char[] ary = { 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't' };
CharArrayReader reader = new CharArrayReader(ary);
int k = 0;
// Read until the end of a file
while ((k = reader.read()) != -1) {

Department of Information Technology -2020 Regulation Page 181


Programming in Java – U20EST467
char ch = (char) k;
System.out.print(ch + " : ");
System.out.println(k);
}
}
}

Output
j : 106
a : 97
v : 118
a : 97
t : 116
p : 112
: 111
i : 105
n : 110
t : 116

Java CharArrayWriter Class


The CharArrayWriter class can be used to write common data to multiple files. This class
inherits Writer class. Its buffer automatically grows when data is written in this stream. Calling
the close() method on this object has no effect.
Java CharArrayWriter class declaration
public class CharArrayWriter extends Writer
Java CharArrayWriter class Methods
Method Description
int size() It is used to return the current size of the buffer.

char[] toCharArray() It is used to return the copy of an input data.

String toString() It is used for converting an input data to a string.

CharArrayWriter append(char c) It is used to append the specified character to the


writer.
CharArrayWriter It is used to append the specified character sequence
append(CharSequence csq) to the writer.
CharArrayWriter It is used to append the subsequence of a specified
append(CharSequence csq, int start, character to the writer.
int end)
void write(int c) It is used to write a character to the buffer.

void write(char[] c, int off, int len) It is used to write a character to the buffer.

void write(String str, int off, int len) It is used to write a portion of string to the buffer.

Department of Information Technology -2020 Regulation Page 182


Programming in Java – U20EST467
void writeTo(Writer out) It is used to write the content of buffer to different
character stream.
void flush() It is used to flush the stream.

void reset() It is used to reset the buffer.

void close() It is used to close the stream.

Example of CharArrayWriter Class:


In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt.
import java.io.CharArrayWriter;
import java.io.FileWriter;
public class CharArrayWriterExample {
public static void main(String args[])throws Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("Welcome to javaTpoint");
FileWriter f1=new FileWriter("D:\\a.txt");
FileWriter f2=new FileWriter("D:\\b.txt");
FileWriter f3=new FileWriter("D:\\c.txt");
FileWriter f4=new FileWriter("D:\\d.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
System.out.println("Success...");
}
}

Java PrintStream Class


The PrintStream class provides methods to write data to another stream. The
PrintStream class automatically flushes the data so there is no need to call flush() method.
Moreover, its methods don't throw IOException.
Class declaration
public class PrintStream extends FilterOutputStream implements Closeable. Appendable

Department of Information Technology -2020 Regulation Page 183


Programming in Java – U20EST467
Methods of PrintStream class
Method Description
void print(boolean b) It prints the specified boolean value.

void print(char c) It prints the specified char value.

void print(char[] c) It prints the specified character array values.

void print(int i) It prints the specified int value.

void print(long l) It prints the specified long value.

void print(float f) It prints the specified float value.

void print(double d) It prints the specified double value.

void print(String s) It prints the specified string value.

void print(Object obj) It prints the specified object value.

void println(boolean b) It prints the specified boolean value and terminates the line.

void println(char c) It prints the specified char value and terminates the line.

void println(char[] c) It prints the specified character array values and terminates
the line.

void println(int i) It prints the specified int value and terminates the line.

void println(long l) It prints the specified long value and terminates the line.

void println(float f) It prints the specified float value and terminates the line.

void println(double d) It prints the specified double value and terminates the line.

void println(String s) It prints the specified string value and terminates the line.

void println(Object obj) It prints the specified object value and terminates the line.

void println() It terminates the line only.

void printf(Object format, It writes the formatted string to the current stream.
Object... args)

void printf(Locale l, Object It writes the formatted string to the current stream.
format, Object... args)

void format(Object format, It writes the formatted string to the current stream using

Department of Information Technology -2020 Regulation Page 184


Programming in Java – U20EST467
Object... args) specified format.

void format(Locale l, Object It writes the formatted string to the current stream using
format, Object... args) specified format.

Example of java PrintStream class


In this example, we are simply printing integer and string value.
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");
PrintStream pout=new PrintStream(fout);
pout.println(2016);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
System.out.println("Success?");
}
}

Example of printf() method using java PrintStream class:


Let's see the simple example of printing integer value by format specifier
using printf() method of java.io.PrintStream class.
class JavaFormatter1
{
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing simple integer: x = %d\n", x);
// this will print it upto 2 decimal places
System.out.printf("Formatted with precison: PI = %.2f\n", Math.PI);
float n = 5.2f;
// automatically appends zero to the rightmost part of decimal
System.out.printf("Formatted to specific width: n = %.4f\n", n);
n = 2324435.3f

Department of Information Technology -2020 Regulation Page 185


Programming in Java – U20EST467
// here number is formatted from right margin and occupies a
// width of 20 characters
System.out.printf("Formatted to right margin: n = %20.4f\n", n);
}
}

Output:
Printing simple integer: x = 100
Formatted with precison: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500

Java Scanner
• Scanner class in Java is found in the java.util package. Java provides various ways to
read input from the keyboard, the java.util.Scanner class is one of them.
• The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various primitive
values.
• The Java Scanner class is widely used to parse text for strings and primitive types
using a regular expression. It is the simplest way to get input in Java. By the help of
Scanner in Java, we can get input from the user in primitive types such as int, long,
double, byte, float, short, etc.
• The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
• The Java Scanner class provides nextXXX() methods to return the type of value such
as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call
next().charAt(0) method which returns a single character.
Java Scanner Class Declaration
public final class Scanner
extends Object
implements Iterator<String>

How to get Java Scanner


To get the instance of Java Scanner which reads input from the user, we need to pass the input
stream (System.in) in the constructor of Scanner class. For Example:
Scanner in = new Scanner(System.in);
To get the instance of Java Scanner which parses the strings, we need to pass the strings in the
constructor of Scanner class. For Example:
Scanner in = new Scanner("Hello Javatpoint");

Department of Information Technology -2020 Regulation Page 186


Programming in Java – U20EST467
Java Scanner Class Methods
S Modifier & Method Description
N Type
1) Void close() It is used to close this scanner.
2) Pattern delimiter() It is used to get the Pattern which the Scanner class is
currently using to match delimiters.

3) Stream<MatchR findAll() It is used to find a stream of match results that match the
esult> provided pattern string.
4) String findInLine() It is used to find the next occurrence of a pattern
constructed from the specified string, ignoring delimiters.

5) String findWithinHor It is used to find the next occurrence of a pattern


izon() constructed from the specified string, ignoring delimiters.

6) Boolean hasNext() It returns true if this scanner has another token in its
input.

7) Boolean hasNextBigDe It is used to check if the next token in this scanner's input
cimal() can be interpreted as a BigDecimal using the
nextBigDecimal() method or not.

8) Boolean hasNextBigInt It is used to check if the next token in this scanner's input
eger() can be interpreted as a BigDecimal using the
nextBigDecimal() method or not.

9) boolean hasNextBoole It is used to check if the next token in this scanner's input
an() can be interpreted as a Boolean using the nextBoolean()
method or not.

10) boolean hasNextByte( It is used to check if the next token in this scanner's input
) can be interpreted as a Byte using the nextBigDecimal()
method or not.

11) boolean hasNextDoub It is used to check if the next token in this scanner's input
le() can be interpreted as a BigDecimal using the nextByte()
method or not.

12) boolean hasNextFloat( It is used to check if the next token in this scanner's input
) can be interpreted as a Float using the nextFloat() method
or not.

13) boolean hasNextInt() It is used to check if the next token in this scanner's input
can be interpreted as an int using the nextInt() method or
not.

Department of Information Technology -2020 Regulation Page 187


Programming in Java – U20EST467
14) boolean hasNextLine( It is used to check if there is another line in the input of
) this scanner or not.

15) boolean hasNextLong( It is used to check if the next token in this scanner's input
) can be interpreted as a Long using the nextLong()
method or not.

16) boolean hasNextShort It is used to check if the next token in this scanner's input
() can be interpreted as a Short using the nextShort()
method or not.

17) IOException ioException() It is used to get the IOException last thrown by this
Scanner's readable.
18) Locale locale() It is used to get a Locale of the Scanner class.

19) MatchResult match() It is used to get the match result of the last scanning
operation performed by this scanner.

20) String next() It is used to get the next complete token from the scanner
which is in use.
21) BigDecimal nextBigDecim It scans the next token of the input as a BigDecimal.
al()
22) BigInteger nextBigInteger It scans the next token of the input as a BigInteger.
()

23) Boolean nextBoolean() It scans the next token of the input into a boolean value
and returns that value.
24) Byte nextByte() It scans the next token of the input as a byte.
25) Double nextDouble() It scans the next token of the input as a double.

26) Float nextFloat() It scans the next token of the input as a float.
27) Int nextInt() It scans the next token of the input as an Int.

28) String nextLine() It is used to get the input string that was skipped of the
Scanner object.

29) Long nextLong() It scans the next token of the input as a long.

30) Short nextShort() It scans the next token of the input as a short.

31) Int radix() It is used to get the default radix of the Scanner use.

32) Void remove() It is used when remove operation is not supported by this
implementation of Iterator.

Department of Information Technology -2020 Regulation Page 188


Programming in Java – U20EST467
33) Scanner reset() It is used to reset the Scanner which is in use.
34) Scanner skip() It skips input that matches the specified pattern, ignoring
delimiters
35) Stream<String> tokens() It is used to get a stream of delimiter-separated tokens
from the Scanner object which is in use.
36) String toString() It is used to get the string representation of Scanner
using.
37) Scanner useDelimiter() It is used to set the delimiting pattern of the Scanner
which is in use to the specified pattern.

38) Scanner useLocale() It is used to sets this scanner's locale object to the
specified locale.
39) Scanner useRadix() It is used to set the default radix of the Scanner which is
in use to the specified radix.

Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations. If end-of-file is reached before the desired number of
byte has been read than EOFException is thrown. It is a type of IOException.
Constructor
Constructor Description

RandomAccessFile(File file, String mode) Creates a random access file stream to read
from, and optionally to write to, the file
specified by the File argument.
RandomAccessFile(String name, String mode) Creates a random access file stream to read
from, and optionally to write to, a file with the
specified name.

Methods
Modifier Method Method
and Type
void close() It closes this random access file stream and releases any system
resources associated with the stream.
Int readInt() It reads a signed 32-bit integer from this file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs.
void writeDouble(double It converts the double argument to a long using the
v) doubleToLongBits method in class Double, and then writes that
long value to the file as an eight-byte quantity, high byte first.

Department of Information Technology -2020 Regulation Page 189


Programming in Java – U20EST467
void writeFloat(float v) It converts the float argument to an int using the floatToIntBits
method in class Float, and then writes that int value to the file as a
four-byte quantity, high byte first.

void write(int b) It writes the specified byte to this file.


Int read() It reads a byte of data from this file.
long length() It returns the length of this file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs.

Example
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
} }
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
} }

Department of Information Technology -2020 Regulation Page 190


Programming in Java – U20EST467

UNIT V EVENT DRIVEN PROGRAMMINGAND JDBC


Events - Delegation event model - Event handling - Adapter classes. AWT: Concepts of
components - Font class - Color class and Graphics - Introduction to Swing – Layout
management - Swing Components - Java Database Connectivity - Programming Example.
Java AWT
• Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
• Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.
• The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
• What is API
• API (Application programming interface) is a document that contains a description of all
the features of a product or software. It represents classes and interfaces that software
programs can follow to communicate with each other. An API can be created for
applications, libraries, operating systems, etc.
Java AWT Hierarchy
• The hierarchy of Java AWT classes are given below.

Department of Information Technology -2020 Regulation Page 191


Programming in Java – U20EST467
• Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
• Window
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
• Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
• Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default
false.

Java AWT Example


• To create simple awt example, you need a frame. There are two ways to create a frame
in AWT.
a) By extending Frame class (inheritance)
b) By creating the object of Frame class (association)
AWT Example by Inheritance
• Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position

Department of Information Technology -2020 Regulation Page 192


Programming in Java – U20EST467
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the
aboveexample that sets the position of the awt button.

AWT Example by Association


• Let's see a simple example of AWT where we are creating instance of Frame class.
Here, we are showing Button component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);

Department of Information Technology -2020 Regulation Page 193


Programming in Java – U20EST467
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Event and Listener (Java Event Handling)
• Changing the state of an object is known as an event.
• Event listeners represent the interfaces responsible to handle events. Java provides
various Event listener classes, however, only those which are more frequently used will
be discussed. Every method of an event listener method has a single argument as an
object which is the subclass of EventObject class.
• For example, mouse event listener methods will accept instance of MouseEvent, where
MouseEvent derives from EventObject.
• For example, click on button, dragging mouse etc. The java.awt.event package provides
many event classes and Listener interfaces for event handling.
• Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Department of Information Technology -2020 Regulation Page 194


Programming in Java – U20EST467
Java ActionListener Interface
• The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in
java.awt.event package. It has only one method: actionPerformed().
actionPerformed() method
• The actionPerformed() method is invoked automatically whenever you click on the
registered component.
• public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
The common approach is to implement the ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e) {
//Write the code here }
Java MouseListener Interface
• The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in java.awt.event
package. It has five methods.
Methods of MouseListener interface
• The signature of 5 methods found in MouseListener interface are given below:
• public abstract void mouseClicked(MouseEvent e);
• public abstract void mouseEntered(MouseEvent e);
• public abstract void mouseExited(MouseEvent e);
• public abstract void mousePressed(MouseEvent e);
• public abstract void mouseReleased(MouseEvent e);
Java MouseMotionListener Interface
• The Java MouseMotionListener is notified whenever you move or drag mouse. It is
notified against MouseEvent. The MouseMotionListener interface is found in
java.awt.event package. It has two methods.

Department of Information Technology -2020 Regulation Page 195


Programming in Java – U20EST467
Methods of MouseMotionListener interface
• The signature of 2 methods found in MouseMotionListener interface are given below:
• public abstract void mouseDragged(MouseEvent e);
• public abstract void mouseMoved(MouseEvent e);
Java ItemListener Interface
• The Java ItemListener is notified whenever you click on the checkbox. It is notified
against ItemEvent. The ItemListener interface is found in java.awt.event package. It has
only one method: itemStateChanged().
• itemStateChanged() method
• The itemStateChanged() method is invoked automatically whenever you click or unclick
on the registered checkbox component.
• public abstract void itemStateChanged(ItemEvent e);
Java KeyListener Interface
• The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package. It has
three methods.
Methods of KeyListener interface
• The signature of 3 methods found in KeyListener interface are given below:
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
Java WindowListener Interface
• The Java WindowListener is notified whenever you change the state of window. It is
notified against WindowEvent. The WindowListener interface is found in java.awt.event
package. It has three methods.
Methods of WindowListener interface
• The signature of 7 methods found in WindowListener interface are given below:
• public abstract void windowActivated(WindowEvent e);
• public abstract void windowClosed(WindowEvent e);
• public abstract void windowClosing(WindowEvent e);
• public abstract void windowDeactivated(WindowEvent e);
• public abstract void windowDeiconified(WindowEvent e);
• public abstract void windowIconified(WindowEvent e);

Department of Information Technology -2020 Regulation Page 196


Programming in Java – U20EST467
• public abstract void windowOpened(WindowEvent e);
Steps to perform Event Handling
Following steps are required to perform event handling:
• Register the component with the Listener
• Registration Methods
• For registering the component with the Listener, many classes provide the registration
methods. For example:
• Button
a) public void addActionListener(ActionListener a){}
• MenuItem
a) public void addActionListener(ActionListener a){}
• TextField
a) public void addActionListener(ActionListener a){}
b) public void addTextListener(TextListener a){}
• TextArea
a) public void addTextListener(TextListener a){}
• Checkbox
a) public void addItemListener(ItemListener a){}
• Choice
a) public void addItemListener(ItemListener a){}
• List
a) public void addActionListener(ActionListener a){}
b) public void addItemListener(ItemListener a){}

Java Event Handling Code


• We can put the event handling code into one of the following places:
a) Within class
b) Other class
c) Anonymous class
Java event handling by implementing ActionListener (AWT Button)
import java.awt.*;

Department of Information Technology -2020 Regulation Page 197


Programming in Java – U20EST467
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, txtfield etc.
Java AWT TextField
• The object of a TextField class is a text component that allows the editing of a single
line text. It inherits TextComponent class.
• AWT TextField Class Declaration
• public class TextField extends TextComponent

Department of Information Technology -2020 Regulation Page 198


Programming in Java – U20EST467
Java AWT TextField Example
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements ActionListener{
TextField tf1,tf2,tf3;
Button b1,b2;
TextFieldExample(){
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);add(tf2);add(tf3);add(b1);add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){ c=a+b; }

Department of Information Technology -2020 Regulation Page 199


Programming in Java – U20EST467
else if(e.getSource()==b2){ c=a-b; }
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}
}
Java AWT Checkbox
• The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or
off (false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to
"on".
AWT Checkbox Class Declaration
public class Checkbox extends Component implements ItemSelectable, Accessible
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));

Department of Information Technology -2020 Regulation Page 200


Programming in Java – U20EST467
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: " + (e.getStateChange()==1?"checked":"unhecked
"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
} }
Java Adapter Classes
• Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
• The adapter classes are found
in java.awt.event, java.awt.dnd and javax.swing.event packages.
• The Adapter classes with their corresponding listener interfaces are given below.

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

Department of Information Technology -2020 Regulation Page 201


Programming in Java – U20EST467
Java KeyAdapter Example
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter
{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args) {
new KeyAdapterExample();
}
}

Font, Color, Graphics Class


Graphics Class
• In GUI applications, we can use Graphics class of java.awt package to create various
graphics like lines, rectangles, circles, polygons etc.
• Let’s look at some of the methods available in the Graphics class:
• void drawLine(int startX, startY, endX, endY) – Used to draw a line between twi points.
• void drawRect(int startX, int startY, int width, int height) – Used to draw a rectangle
starting from the top left corner with the given width and height. The coordinates of the
top left corner of the rectangle are startX and startY.
• void fillRect(int startX, int startY, int width, int height) – Used to draw a solid (colored)
rectangle with the given parameters.

Department of Information Technology -2020 Regulation Page 202


Programming in Java – U20EST467
• void drawRoundRect(int startX, int startY, int width, int height, int xDiam, int yDiam) –
Used to draw a rounded rectangle whose x-diameter and y-diameter of the corners is
given by xDiam and yDiam respectively.
• void fillRoundRect(int startX, int startY, int width, int height, int xDiam, int yDiam) –
Used to draw a solid (colored) rounded rectangle whose x-diameter and y-diameter of
the corners is given by xDiam and yDiam respectively.
• void drawOval(int startX, int startY, int width, int height) – Used to draw an ellipse
inside an imaginary rectangle whose dimensions are specified by the given parameters.
We can get a circle by giving the same value for both width and height.
• void fillOval(int startX, int startY, int width, int height) – Used to draw a solid (colored)
ellipse inside an imaginary rectangle whose dimensions are specified by the given
parameters. We can get a circle by giving the same value for both width and height.
• void drawArc(int startX, int startY, int width, int height, int startAngle, int
sweepAngle) – Used to draw an arc inside an imaginary rectangle. The start angle and
the sweep angle are specified by using startAngle and sweepAngle respectively.
• void fillArc(int startX, int startY, int width, int height, int startAngle, int sweepAngle) –
Used to draw a solid (colored) arc inside an imaginary rectangle. The start angle and the
sweep angle are specified by using startAngle and sweepAngle respectively.
• void drawPolygon(int x[], int y[], int numPoints) – Used to draw a polygon whose x
coordinates and y coordinates of the points are specified using the x array and y array
respectively. Number of points are specified using numPoints.
• void fillPolygon(int x[], int y[], int numPoints) – Used to draw a solid (colored) polygon
whose x coordinates and y coordinates of the points are specified using the x array and y
array respectively. Number of points are specified using numPoints.
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame
{
MyFrame()
{
setSize(600, 400);
setTitle("My Application");
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public void paint(Graphics g)
{

Department of Information Technology -2020 Regulation Page 203


Programming in Java – U20EST467
g.drawLine(20, 60, 80, 100);
g.drawRect(100, 60, 80, 40);
g.fillRect(200, 60, 80, 40);
g.drawRoundRect(300, 60, 80, 40, 20, 20);
g.fillRoundRect(400, 60, 80, 40, 20, 20);
g.drawOval(20, 120, 80, 40);
g.fillOval(120, 120, 80, 40);
g.drawArc(220, 120, 80, 40, 90, -90);
g.fillArc(320, 120, 80, 40, 90, -90);
int[] x = {20, 100, 80, 20};
int[] y = {200, 180, 240, 260};
g.drawPolygon(x, y, 4);
int[] fillx = {120, 200, 180, 120};
int[] filly = {200, 180, 240, 260};
g.fillPolygon(fillx, filly, 4);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
Color
• AWT provides java.awt.Color class that enables to specify and work with different
colors.
Color class defines some constant to specify a number of common colors (for example -
Color.RED/Color.red, Color.GREEN/ Color.green, Color.PINK/Color.pink etc).
• Note - Color class supports both uppercase and lowercase color constants.
Color class also have several constructors to specify your own colors. Some popular one
is as follows –
1- public Color(int r, int g, int b ) -
• where r, g, b indicates the red, green and blue colors whose values must be between 0
and 255.
• if r, g or b are outside of the range 0 to 255 it will throw an IllegalArgumentException.
• Example -
Color c1 = new Color(0, 0, 0); // Black color
Color c2 = new Color(255, 255, 255); //White Color
Color c3 = new Color(100, 0 ,0); // Light red color
2- public Color(float r, float g, float b) -
• where r, g, b indicates the red, green and blue colors whose values must be between 0.0
and 1.0.

Department of Information Technology -2020 Regulation Page 204


Programming in Java – U20EST467
• if r, g or b are outside of the range 0.0 to 1.0, it will throw
an IllegalArgumentException .
• Example -
Color c1 = new Color(0.0f, 0.0f, 0.0f); // Black color
Color c2 = new Color(1.0f, 1.0f, 1.0f); // White color
Color c3 = new Color(0.5f, 0.0f, 0.0f); //Light red color
3- public Color(int rgb) –
• It will creates a color with the specified combined RGB value consisting of the red
component in bits 16-23, the green component in bits 8-15, and the blue component in
bits 0-7.
• Example -
Color c = new Color(0xff0000); // Red color
Color c = new Color(0x00ff00); //Green color
Color c = new Color(0x0000ff); // Blue color
Setting the current graphics color -
• You can change the color of graphics you are drawing by using Graphics
class setColor() method.
• It has the following syntax –
• public abstract void setColor(Color c)
• Where c is new rendering color.
Example -
import java.awt.*;
public class Test extends Frame
{
public static void main(String ar[]) {
Test t=new Test();
t.setVisible(true); }
public void paint(Graphics g)
{
Color c1 = new Color(255,100,50);
Color c2 = new Color(50,100,255);
g.setColor(c1);
g.drawLine(10,10,100,10);

Department of Information Technology -2020 Regulation Page 205


Programming in Java – U20EST467
g.drawRect(20,20,100,100);
g.setColor(c2);
g.drawLine(30,30,100,30);
g.drawRect(40,40,100,100);
}
}
Working with Fonts
• You can select the font style of your choice by using Font class of java.awt package.
Font class support the following constructor to create a new font –
• public Font(String name, int style, int size)
• Where –
• name specifies the font name. The font name can be a font face name or a font family
name.
• Font style can have one of the following three values ? Font.BOLD, Font.PLAIN,
Font.ITALIC.
• We can also combine these styles. For example if we want bold and italic then we can
combine Font.BOLD + Font.ITALIC.
• size specifies the font size.
• Using Fonts -
• After creating new font, you can use it by using setFont() method.It has the following
syntax –
• public abstract void setFont(Font fontObj)
• Where fontObj specifies the new font you cerated.
Example -
import java.awt.*;
public class Test extends Frame
{
public static void main(String ar[])
{
Test t=new Test();
t.setVisible(true);
}
public void paint(Graphics g)

Department of Information Technology -2020 Regulation Page 206


Programming in Java – U20EST467
{
Font f1 = new Font("Dialog",Font.BOLD + Font.ITALIC, 35);
g.setFont(f1);
g.drawString("This is juat a demo", 100, 100);
}
}
Delegation Event Model
• The Delegation Event model is defined to handle events in GUI programming
languages. The GUI stands for Graphical User Interface, where a user
graphically/visually interacts with the system.
• The GUI programming is inherently event-driven; whenever a user initiates an activity
such as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped
to a code to respond to functionality to the user. This is known as event handling.
• In this section, we will discuss event processing and how to implement the delegation
event model in Java. We will also discuss the different components of an Event Model.
Event Processing in Java
• Java support event processing since Java 1.0. It provides support for AWT ( Abstract
Window Toolkit), which is an API used to develop the Desktop application. In Java 1.0,
the AWT was based on inheritance. To catch and process GUI events for a program, it
should hold subclass GUI components and override action() or handleEvent() methods.
The below image demonstrates the event processing.

Department of Information Technology -2020 Regulation Page 207


Programming in Java – U20EST467
• But, the modern approach for event processing is based on the Delegation Model. It
defines a standard and compatible mechanism to generate and process events.
• In this model, a source generates an event and forwards it to one or more listeners. The
listener waits until it receives an event. Once it receives the event, it is processed by the
listener and returns it.
• The UI elements are able to delegate the processing of an event to a separate function.
• The key advantage of the Delegation Event Model is that the application logic is
completely separated from the interface logic.
• In this model, the listener must be connected with a source to receive the event
notifications. Thus, the events will only be received by the listeners who wish to receive
them.
• So, this approach is more convenient than the inheritance-based event model (in Java
1.0).
• In the older model, an event was propagated up the containment until a component was
handled. This needed components to receive events that were not processed, and it took
lots of time. The Delegation Event model overcame this issue.
• Basically, an Event Model is based on the following three components:
a) Events
b) Events Sources
c) Events Listeners
Types of Events
• The events are categories into the following two categories:
The Foreground Events:
• The foreground events are those events that require direct interaction of the user. These
types of events are generated as a result of user interaction with the GUI component. For
example, clicking on a button, mouse movement, pressing a keyboard key, selecting an
option from the list, etc.
The Background Events :
• The Background events are those events that result from the interaction of the end-user.
For example, an Operating system interrupts system failure (Hardware or Software).
• To handle these events, we need an event handling mechanism that provides control
over the events and responses.

Department of Information Technology -2020 Regulation Page 208


Programming in Java – U20EST467
The Delegation Model
• The Delegation Model is available in Java since Java 1.1. it provides a new delegation-
based event model using AWT to resolve the event problems. It provides a convenient
mechanism to support complex Java programs.
Design Goals
• The design goals of the event delegation model are as following:
• It is easy to learn and implement
• It supports a clean separation between application and GUI code.
• It provides robust event handling program code which is less error-prone (strong
compile-time checking)
• It is Flexible, can enable different types of application models for event flow and
propagation.
• It enables run-time discovery of both the component-generated events as well as
observable events.
• It provides support for the backward binary compatibility with the previous model.

Java Program to Implement the Event Deligation Model


import java.awt.*;
import java.awt.event.*;
public class TestApp {
public void search() {
// For searching
System.out.println("Searching...");
}
public void sort() {
// for sorting
System.out.println("Sorting....");
}
static public void main(String args[]) {
TestApp app = new TestApp();
GUI gui = new GUI(app);
}
}
class Command implements ActionListener
{
static final int SEARCH = 0;
static final int SORT = 1;
int id;
TestApp app;

public Command(int id, TestApp app) {


this.id = id;
this.app = app;
}
public void actionPerformed(ActionEvent e) {

Department of Information Technology -2020 Regulation Page 209


Programming in Java – U20EST467
switch(id) {
case SEARCH:
app.search();
break;
case SORT:
app.sort();
break;
}
}
}
class GUI {
public GUI(TestApp app) {
Frame f = new Frame();
f.setLayout(new FlowLayout());
Command searchCmd = new Command(Command.SEARCH, app);
Command sortCmd = new Command(Command.SORT, app);
Button b;
f.add(b = new Button("Search"));
b.addActionListener(searchCmd);
f.add(b = new Button("Sort"));
b.addActionListener(sortCmd);
List l;
f.add(l = new List());
l.add("Alphabetical");
l.add("Chronological");
l.addActionListener(sortCmd);
f.pack();
f.show();
}
}
Java Swing
• Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight components.
• The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


• There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.
2) AWT components are heavyweight. Swing components are lightweight.

Department of Information Technology -2020 Regulation Page 210


Programming in Java – U20EST467
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
5) AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.

What is JFC
• The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Hierarchy of Java Swing classes
• The hierarchy of java swing API is given below.

Department of Information Technology -2020 Regulation Page 211


Programming in Java – U20EST467
Commonly used Methods of Component class
• The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default


false.

Java Swing Examples


• There are two ways to create a frame:
a) By creating the object of Frame class (association)
b) By extending Frame class (inheritance)
• We can write the code of swing inside the main(), constructor or any other method.
Example of Swing by Association inside constructor
import javax.swing.*;
public class Simple {
Simple(){
JFrame f=new JFrame(); //creating instance of JFrame
JButton b=new JButton("click"); //creating instance of JButton
b.setBounds(130,100,100, 40);
f.add(b); //adding button in JFrame
f.setSize(400,500); //400 width and 500 height
f.setLayout(null); //using no layout managers
f.setVisible(true); //making the frame visible
}
public static void main(String[] args) {
new Simple();
}
}

Department of Information Technology -2020 Regulation Page 212


Programming in Java – U20EST467
Simple example of Swing by inheritance
import javax.swing.*;
public class Simple2 extends Jframe //inheriting JFrame
{
JFrame f;
Simple2(){
JButton b=new JButton("click"); //create button
b.setBounds(130,100,100, 40);
add(b); //adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}
Java JPasswordField
• The object of a JPasswordField class is a text component specialized for password entry.
It allows the editing of a single line of text. It inherits JTextField class.
JPasswordField class declaration
• Let's see the declaration for javax.swing.JPasswordField class.
• public class JPasswordField extends JTextField
Commonly used Constructors:

Constructor Description

JPasswordField() Constructs a new JPasswordField, with a default document, null


starting text string, and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the specified
number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the specified
text.
JPasswordField(String text, int Construct a new JPasswordField initialized with the specified text
columns) and columns.

Department of Information Technology -2020 Regulation Page 213


Programming in Java – U20EST467
Java JPasswordField Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
final JLabel label = new JLabel();
label.setBounds(20,150, 200,50);
final JPasswordField value = new JPasswordField();
value.setBounds(100,75,100,30);
JLabel l1=new JLabel("Username:");
l1.setBounds(20,20, 80,30);
JLabel l2=new JLabel("Password:");
l2.setBounds(20,75, 80,30);
JButton b = new JButton("Login");
b.setBounds(100,120, 80,30);
final JTextField text = new JTextField();
text.setBounds(100,20, 100,30);
f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username " + text.getText();
data += ", Password: "
+ new String(value.getPassword());
label.setText(data);
}
});
}
}

Department of Information Technology -2020 Regulation Page 214


Programming in Java – U20EST467
Java JRadioButton
• The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.
• It should be added in ButtonGroup to select one radio button only.
• JRadioButton class declaration
• Let's see the declaration for javax.swing.JRadioButton class.
• public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(Strings, Creates a radio button with the specified text and selected status.
boolean selected)

Commonly used Methods:

Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JRadioButton Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;

Department of Information Technology -2020 Regulation Page 215


Programming in Java – U20EST467
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}
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.

Department of Information Technology -2020 Regulation Page 216


Programming in Java – U20EST467
• 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

Java JMenuItem and JMenu Example


import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);

Department of Information Technology -2020 Regulation Page 217


Programming in Java – U20EST467
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Java LayoutManagers
• The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers.
• There are following classes that represents the layout managers:
a) java.awt.BorderLayout
b) java.awt.FlowLayout
c) java.awt.GridLayout
d) java.awt.CardLayout
e) java.awt.GridBagLayout
f) javax.swing.BoxLayout
g) javax.swing.GroupLayout
h) javax.swing.ScrollPaneLayout
i) javax.swing.SpringLayout etc.
Java BorderLayout
• The BorderLayout is used to arrange the components in five regions: north, south, east,
west and center. Each region (area) may contain one component only. It is the default
layout of frame or window.
• The BorderLayout provides five constants for each region:
a) public static final int NORTH
b) public static final int SOUTH
c) public static final int EAST
d) public static final int WEST
e) public static final int CENTER
• Constructors of BorderLayout class:
a) BorderLayout(): creates a border layout but with no gaps between the
components.

Department of Information Technology -2020 Regulation Page 218


Programming in Java – U20EST467
b) JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
Example of BorderLayout class:
import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
} }

Department of Information Technology -2020 Regulation Page 219


Programming in Java – U20EST467
Java GridLayout
• The GridLayout is used to arrange the components in rectangular grid. One component
is displayed in each rectangle.
Constructors of GridLayout class
• GridLayout(): creates a grid layout with one column per component in a row.
• GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
• GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
Example
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

Department of Information Technology -2020 Regulation Page 220


Programming in Java – U20EST467
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Java FlowLayout
• The FlowLayout is used to arrange the components in a line, one after another (in a
flow). It is the default layout of applet or panel.
• Fields of FlowLayout class
a) public static final int LEFT
b) public static final int RIGHT
c) public static final int CENTER
d) public static final int LEADING
e) public static final int TRAILING
• Constructors of FlowLayout class
a) FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
b) FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
c) FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");

Department of Information Technology -2020 Regulation Page 221


Programming in Java – U20EST467
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Java JDBC
• JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database. There are four types of
JDBC drivers:
a) JDBC-ODBC Bridge Driver,
b) Native Driver,
c) Network Protocol Driver, and
d) Thin Driver
• We can use JDBC API to access tabular data stored in any relational database. By the
help of JDBC API, we can save, update, delete and fetch data from the database. It is
like Open Database Connectivity (ODBC) provided by Microsoft.

• The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It
is based on the X/Open SQL Call Level Interface. The java.sql package contains classes
and interfaces for JDBC API.
• A list of popular interfaces of JDBC API are given below:

Department of Information Technology -2020 Regulation Page 222


Programming in Java – U20EST467
a) Driver interface
b) Connection interface
c) Statement interface
d) PreparedStatement interface
e) CallableStatement interface
f) ResultSet interface
g) ResultSetMetaData interface
h) DatabaseMetaData interface
i) RowSet interface
• A list of popular classes of JDBC API are given below:
a) DriverManager class
b) Blob class
c) Clob class
d) Types class
Why Should We Use JDBC
• Before JDBC, ODBC API was the database API to connect and execute the query with
the database. But, ODBC API uses ODBC driver which is written in C language (i.e.
platform dependent and unsecured). That is why Java has defined its own API (JDBC
API) that uses JDBC drivers (written in Java language).
• We can use JDBC API to handle database using Java program and can perform the
following activities:
a) Connect to the database
b) Execute queries and update statements to the database
c) Retrieve the result received from the database.
What is API
• API (Application programming interface) is a document that contains a description of all
the features of a product or software. It represents classes and interfaces that software
programs can follow to communicate with each other. An API can be created for
applications, libraries, operating systems, etc.
Java Database Connectivity with 5 Steps
• There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
a) Register the Driver class
b) Create connection

Department of Information Technology -2020 Regulation Page 223


Programming in Java – U20EST467
c) Create statement
d) Execute queries
e) Close connection
1) Register the driver class
• The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.Syntax of forName() method
• public static void forName(String className)throws ClassNotFoundException
• Example to register the OracleDriver class
• Here, Java program is loading oracle driver to esteblish database connection.
• Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
• The getConnection() method of DriverManager class is used to establish connection
with the database.Syntax of getConnection() method
• 1) public static Connection getConnection(String url)throws SQLException
• 2) public static Connection getConnection(String url,String name,String password) thr
ows SQLException
• Example to establish connection with the Oracle database
• Connection con=DriverManager.getConnection(
• "jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
• The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
• Syntax of createStatement() method
• public Statement createStatement()throws SQLException
• Example to create the statement object
• Statement stmt=con.createStatement();
4) Execute the query
• The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the
records of a table.
• Syntax of executeQuery() method
• public ResultSet executeQuery(String sql)throws SQLException
• Example to execute query
• ResultSet rs=stmt.executeQuery("select * from emp");
• while(rs.next()){
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• }
5) Close the connection object
• By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
• Syntax of close() method
• public void close()throws SQLException

Department of Information Technology -2020 Regulation Page 224


Programming in Java – U20EST467
• Example to close connection
• con.close();
Java Database Connectivity with Oracle
To connect java application with the oracle database, we need to follow 5 following
steps. In this example, we are using Oracle 10g as the database. So we need to know
following information for the oracle database:
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is
running, we may also use IP address, 1521 is the port number and XE is the
Oracle service name. You may get all these information from the tnsnames.ora
file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.
Create a Table
• Before establishing connection, let's first create a table in oracle database. Following is
the SQL query to create a table.
• create table emp(id number(10),name varchar2(40),age number(3));
• Example to Connect Java Application with Oracle database
• In this example, we are connecting to an Oracle database and getting data
from emp table. Here, system and oracle are the username and password of the Oracle
database.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();

Department of Information Technology -2020 Regulation Page 225


Programming in Java – U20EST467
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
To connect java application with the Oracle database ojdbc14.jar file is required to be
loaded.
To ways to load the jar file:
• paste the ojdbc14.jar file in jre/lib/ext folder
• set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
• Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file
here.
2) set classpath:
• There are two ways to set the classpath:
1. temporary
2. Permanent
How to set the temporary classpath:
• Firstly, search the ojdbc14.jar file then open command prompt and write:
• C:>set classpath=c:\folder\ojdbc14.jar;.;
How to set the permanent classpath:
• Go to environment variable then click on new tab. In variable name write classpath and
in variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;

Department of Information Technology -2020 Regulation Page 226

You might also like