0% found this document useful (0 votes)
6 views273 pages

Java Programming

Uploaded by

selvakumarandy88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views273 pages

Java Programming

Uploaded by

selvakumarandy88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 273

JAVA PROGRAMMING

MONOGRAPH
(Internal Circulation Only)
TABLE OF CONTENTS

Topic No. Topic Name Page No.


CHAPTER I
INTRODUCTION TO JAVA
1.1 History of Java 1
1.1.1 1991: Project Genesis 1
1.1.2 1994: The Web Emerges 1
1.1.3 1995: Java 1.0 (Beta) 1
1.1.4 1996: Java 1.0 Released 2
1.1.5 1998-1999: Java 2 (J2SE 1.2) 2
1.1.6 2009: Oracle Acquires Sun Microsystems 2
1.1.7 1996: Java 1.0 Released 2
1.1.8 1998-1999: Java 2 (J2SE 1.2) 2
1.1.9 2009: Oracle Acquires Sun Microsystems 2
1.2 Features of Java 2
1.2.1 Platform Independent 2
1.2.2 Object-Oriented Programming 3
1.2.3 Simplicity 3
1.2.4 Robustness 3
1.2.5 Security 3
1.2.6 Distributed 4
1.2.7 Multithreading 4
1.2.8 Portability 4
1.2.9 High Performance 4
1.3 Java Architecture 4
1.3.1 Class Loader Subsystem 5
1.3.2 Class Loaders 7
1.3.3 JVM Memory Areas 8
1.3.4 Execution Engine 9
1.3.5 Java Native Interface (JNI) 10
1.3.6 Native Method Libraries 10
1.4 Java Environment 10
1.4.1 JDK (Java Development Kit) 11
1.4.2 JRE (Java Runtime Environment) 16
1.4.3 JVM (Java Virtual Machine) 16
1.4.4 JDK vs JRE vs JVM 17
1.5 Java Basic Syntax 17
1.5.1 Steps to Implement Java Program 17
1.5.2 Structure of java Program: 19
1.6 Comments 20
1.6.1 Single-line Comments 20
1.6.2 Java Multi-line Comments 20
1.7 Data Types 20

i
1.7.1 Primitive Data Types 22
1.7.2 Non-Primitive Data Types 25
1.8 Variables 25
1.8.1 Declaring (Creating) Variables 25
1.8.2 Final Variables 26
1.8.3 Display Variables 26
1.8.4 Declare Many Variables 26
1.9 Operators 27
1.9.1 Arithmetic Operators 28
1.9.2 Java Assignment Operators 28
1.9.3 Java Comparison Operators 29
1.9.4 Java Logical Operators 30
1.9.5 Bitwise Operators in Java 31
1.10 Type Conversion and Casting 33
1.10.1 Type Casting 33
1.10.2 Type Conversion 34
1.11 Flow Control Statements 39
1.11.1 Decision-Making statements: 40
1.11.2 Switch Statement 45
1.11.3 Loop Statements 47
1.11.4 Jump Statements 52
1.12 Reading Input from keyboard 54
1.13 Using Scanner class 54
1.14 Command Line Arguments 61
1.15 Arrays 62
1.15.1 Single-Dimensional Array in Java 63
1.15.2 Multidimensional Array in Java 66
1.16 Classes and Objects 68
1.16.1 Classes 68
1.16.2 Fields 68
1.16.3 Methods 68
1.16.4 Constructors 68
1.16.5 Blocks 69
1.16.6 Nested Class and Interface 69
1.16.7 Objects 70
1.17 Methods 71
1.17.1 Method Declaration 71
1.17.2 Method in Java 71
1.17.3 Predefined Method 73
1.17.4 User-defined Method 74
1.18 Static Variables and Methods 75
1.18.1 Method Overloading 76
1.18.2 Object Initialization through Reference Variable 78
1.18.3 Object Initialization through Method 78
1.19 Constructors 79

ii
1.20 UML Class diagram 80
1.20.1 Describing class and class attributes 80
1.20.2 Describing class constructor 81
1.20.3 Describing class methods 81
1.21 Use of this keyword 83
1.22 Encapsulation 84
1.23 Concept of Access Control 86
1.23.1 Private Access Modifier 87
1.23.2 Default Access Modifier 88
1.23.3 Protected Access Modifier 89
1.23.4 Public Access Modifier 90

CHAPTER II
INHERITANCE
2.1 Inheritance 92
2.1.1 Why Do We Need Java Inheritance? 92
2.1.2 Important Terminologies Used in Java Inheritance 92
2.1.3 How to Use Inheritance in Java? 92
2.2 Types Of Inheritance 95
2.2.1 Single Inheritance 95
2.2.2 Multilevel Inheritance 96
2.2.3 Hierarchical Inheritance 97
2.2.4 Multiple Inheritances (Through Interfaces) 98
2.2.5 Hybrid Inheritance 98
2.3 Subclass And Superclass 99
2.4 Super Keyword 100
2.4.1 Use of super with Variables 101
2.4.2 Use of super with Methods 101
2.4.3 Use of super with constructors 102
2.4.4 Advantages of Using Java Super Keyword 104
2.5 Final Class And Methods 104
2.5.1 Java Final Variable 105
2.5.2 Java final Method 106
2.5.3 Java final Class 106
2.5.4 Advantages of final Keyword in Java 107
2.6 Object Class In Java 107
2.6.1 toString() Method 109
2.6.2 hashCode() Method 109
2.6.3 equals (Object obj) Method 111
2.6.4 getClass() Method 111
2.6.5 finalize() method 112
2.6.6 clone() Method 113
2.6.7 wait() Method 114
2.6.8 notify() Method 114
2.6.9 notifyAll() Method 114

iii
2.7 Polymorphism 114
2.7.1 Compile-time Polymorphism (Method Overloading) 114
2.7.2 Runtime Polymorphism (Method Overriding) 114
2.8 Method Overloading 115
2.8.1 Method Overloading: Different Number of Arguments 116
2.8.2 Method Overloading: Different Type of Arguments 117
2.9 Method Overriding 118
2.10 Constructor Overloading 120
2.10.1 Java No-Argument Constructors 121
2.10.2 Java Parameterized Constructor 123
2.10.3 Java Default Constructor 123
2.11 Dynamic Method Dispatching or Runtime polymorphism 126
2.12 Garbage Collection 127
2.12.1 Unreachable Objects 128
2.12.2 Eligibility for Garbage Collection 128
2.12.3 Finalization 129
2.13 String Class 130
2.13.1 Serializable (Interface) 130
2.13.2 Comparable (Interface) 130
2.13.3 CharSequence (Interface) 130
2.14 String Buffer Class 131
2.15 String Builder Class 132

CHAPTER III
DATA ABSTRACTION
3.1 Packages 134
3.2 Introduction to Packages 134
3.2.1 Types of Java Packages 134
3.2.2 Realtime Example of Packages in Java 135
3.2.3 Advantage of using Packages in Java 135
3.2.4 Built-in Java Packages(Pre-Defined Package) 135
3.3 User Defined Package 137
3.3.1 Steps to Create and Use a Package: 137
3.3.2 Utilize the package 138
3.3.3 Compile the java files 139
3.4 Accessing Package 139
3.4.1 Using packagename 139
3.4.2 Using packagename.classname 140
3.4.3 Using fully qualified name 140
3.5 Abstract Classes and Methods 141
3.5.1 Key Features of Abstract Classes 141
3.5.2 Abstract Class:Constructor, Data Member and Methods 143
3.6 Interface 145
3.7 Defining an interface 145
3.8 Implementing Multiple Interfaces 149

iv
3.9 Extending an Interface 149
3.9.1 Extending Multiple Interfaces 149
3.9.2 Level wise -Implementation 150
3.10 Inheritance 157
3.10.1 The Diamond Problem: 158
3.10.2 Simplicity 158
3.11 Exception Handling 162
3.11.1 Key Components of Java Exception Handling 162
3.12 Errors Vs. Exceptions 163
3.12.1 Types of Exceptions 163
3.13 Exception Hierarchy in Java 164
3.14 Exception handling using try...catch 164
3.14.1 Multiple catch Blocks 165
3.14.2 Nested try-catch 165
3.15 Java throw and finally block 166
3.15.1 Throw Method 167
3.15.2 Throws Method 167
3.16 Creating Custom or User Defined Exceptions in Java 168
3.17 Built-In Exceptions 168
3.17.1 Checked Exceptions 168
3.17.2 Unchecked Exceptions 169
3.17.3 Error (not typically handled by applications) 169

CHAPTER IV
COLLECTION API AND LAMBDA
4.1 Introduction to wrapper classes 170
4.2 Predefined wrapper classes 170
4.2.1 Uses of Wrapper Class in Java 170
4.2.2 Need for using Wrapper Classes in Java: 171
4.3 Autoboxing and unboxing 172
4.3.1 Autoboxing 172
4.3.2 Unboxing 172
4.3.3 Disadvantages of Wrapper Class in Java 173
4.4 Utility methods 173
4.5 Java Collections API 175
4.6 Java Collections Framework 175
4.7 Generics 175
4.7.1 Before Java Generics 175
4.7.2 After Java Generics 176
4.7.3 Generics K and V parameters 177
4.8 Java List interface 178
4.8.1 Create a List 178
4.8.2 Insert Elements at Specific Index 179
4.8.3 Insert All Elements From One List Into Another 179
4.8.4 Get Elements from a Java List 179

v
4.8.5 Find Elements in a List 180
4.8.6 Find Last Occurrence of Element in a List 180
4.8.7 Remove Elements From a Java List 181
4.8.8 Remove All Elements From a Java List 181
4.8.9 Sublist of List 182
4.9 Java Set interface 183
4.10 Java MAP interface 186
4.10.1 Classes that implement Map 186
4.10.2 Interfaces that extend Map 186
4.10.3 Add elements to a Map 186
4.10.4 Removing Elements 188
4.10.5 Collection Interface 189
4.10.6 Collection 191
4.10.7 Vector 192
4.10.8 PriorityQueue 193
4.11 Lambda Expressions 194
4.12 Functional Interface of Lambda 195
4.12.1 Defining lambda expression in Java 195
4.12.2 Types of Lambda Body 196
4.13 Lambda and Local Variables 197
4.14 Manipulating local variable outside the lambda function 198
4.15 Predicates 199
4.16 Consumer 199
4.17 Supplier 202
4.18 Predicate& function 203
4.19 Streams API 203
4.19.1 Creating a Stream 204
4.19.2 The map Method 204
4.20 Filter Method 205
4.21 Reduce Method 206
4.22 Parallel Streams 207

CHAPTER V
JDBC AND MULTITHREADING
5.1 Introduction to JDBC 209
5.1.1 JDBC Components 209
5.1.2 JDBC Driver Types 209
5.1.3 JDBC Architecture: How Java Database Connectivity Works 210
5.2 Establishing Connection 211
5.3 Executing Query 212
5.4 Prepared Statement in JDBC 212
5.4.1 Processing Results: 213
5.4.2 Prepared Statement: 213
5.4.3 Advantages of Prepared Statement 213
5.4.4 Steps to use Prepared Statement 213

vi
5.5 Callable Statement 214
5.6 Transactions 215
5.7 Meta Data Objects 218
5.8 Multithreading in Java 219
5.8.1 Need for Multithreading 219
5.8.2 Different Ways to Create Threads 219
5.9 Process vs Thread 224
5.10 Thread Life Cycle 225
5.10.1 Life Cycle of a Thread 226
5.10.2 New 227
5.10.3 Runnable 227
5.10.4 Blocked 227
5.10.5 Waiting 228
5.10.6 Timed Waiting 228
5.10.7 Terminated 228
5.11 Thread Class 233
5.12 Runnable Interface 233
5.13 Thread Creation 234
5.14 Thread Control and Priorities 234
5.15 Thread Synchronization 234
QUESTION BANK
Part A 237
CHAPTER I
Part B 242
Part A 243
CHAPTER II
Part B 247
Part A 248
CHAPTER III
Part B 251
Part A 252
CHAPTER IV
Part B 255
Part A 256
CHAPTER V
Part B 260
GLOSSARY
LIST OF ABBREVIATIONS 263
TEXTBOOKS 264
REFERENCES WEBSITES 265
SOFTWARES 265

vii
Chapter no 1: Introduction to JAVA

CHAPTER 1
INTRODUCTION TO JAVA
1.1 History of Java

 The journey of this powerful programming language first began in 1991 by James
Gosling, Mike Sheridan, and Patrick Naughton, a team of engineers at Sun Microsystems
of USA. Arthur Van Hoff rewrote the Java 1.0 compiler to strictly comply with its
specifications, ensuring its reliability and cross- platform capabilities.

 In 1997, Sun Microsystems again aimed to formalize Java through the ISO standards
body but eventually withdrew from the process.

 Sun Microsystems offered most Java implementations at no cost, earning revenue by


licensing specialized products such as the Java Enterprise System.

 In 2006, Sun Microsystems released a large portion of the Java Virtual Machine (JVM)
as free, open- source software.

 In 2007, the core JVM code was fully available under open-source distribution terms.

1.1.1 1991: Project Genesis

 James Gosling, Mike Sheridan, and Patrick Naughton, the "Green Team" at Sun
Microsystems, started a project to develop a language for consumer electronics,
specifically interactive television and set-top boxes.

 The initial name for the language was "Oak", after an oak tree outside Gosling's office.

 The team aimed for a language that was simple, robust, portable, and secure, suitable
for devices with limited resources.

1.1.2 1994: The Web Emerges

 The team realized their language could be revolutionary for the emerging World Wide
Web, which needed a platform-independent language.

1.1.3 1995: Java 1.0 (Beta)

Sun Microsystems officially launched Java, emphasizing the "Write Once, Run
Anywhere" (WORA) principle, meaning Java programs could run on any device or

1
OOPS AND JAVA

operating system with a Java Virtual Machine (JVM). Java 1.0 was released as a beta
version in 1995.
1.1.4 1996: Java 1.0 Released

 The first public implementation, Java 1.0, was released, providing a no-cost runtime
environment across popular platforms.

 The Java 1.0 compiler was rewritten by Arthur van Hoff to strictly comply with the
Java 1.0 language specification.

1.1.5 1998-1999: Java 2 (J2SE 1.2)

 With the advent of Java 2, new versions had multiple configurations built for
different types of platforms.

1.1.6 2009: Oracle Acquires Sun Microsystems

Oracle acquired Sun Microsystems, the company that developed Java, which meant that
Java became part of Oracle.
1.1.7 1996: Java 1.0 Released

 The first public implementation, Java 1.0, was released, providing a no-cost runtime
environment across popular platforms.

 The Java 1.0 compiler was rewritten by Arthur van Hoff to strictly comply with the
Java 1.0 language specification.

1.1.8 1998-1999: Java 2 (J2SE 1.2)

 With the advent of Java 2, new versions had multiple configurations built for
different types of platforms.

1.1.9 2009: Oracle Acquires Sun Microsystems

 Oracle acquired Sun Microsystems, the company that developed Java, which meant
that Java became part of Oracle.

1.2 Features of Java

1.2.1. Platform Independent

Compiler converts source code to byte code and then the JVM executes the bytecode

2
Chapter no 1: Introduction to JAVA

generated by the compiler. This byte code can run on any platform be it Windows,
Linux, or macOS which means if we compile a program on Windows, then we can run it
on Linux and vice versa. Each operating system has a different JVM, but the output
produced by all the OS is the same after the execution of the byte code. That is why we
call java a platform-independent language.

1.2.2. Object-Oriented Programming

Java is an object-oriented language, promoting the use of objects and classes. Organizing
the program in the terms of a collection of objects is a way of object-oriented
programming, each of which represents an instance of the class.

The four main concepts of Object-Oriented programming are:

 Abstraction

 Encapsulation

 Inheritance

 Polymorphism

1.2.3 Simplicity

Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It
eliminates complex features like pointers and multiple inheritances, making it
easier to write, debug, and maintain code.

1.2.4. Robustness

Java language is robust which means reliable. It is developed in such a way that it puts
a lot of effort into checking errors as early as possible, that is why the java compiler is
able to detect even those errors that are not easy to detect by another programming
language. The main features of java that make it robust are garbage collection, exception
handling, and memory allocation.

1.2.5. Security

In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e., it shows

3
OOPS AND JAVA

ArrayIndexOutOfBound Exception. That’s why several security flaws like stack


corruption or buffer overflow are impossible to exploit in Java. Also, java programs run
in an environment that is independent of the OS (Operating System) environment which
makes java programs more secure.

1.2.6. Distributed

Remote Method Invocation (RMI) and Enterprise Java Beans (EJB) are used for creating
distributed applications in java. The java programs can be easily distributed on one or
more systems that are connected to each other through an internet connection.

1.2.7. Multithreading

Java supports multithreading, enabling the concurrent execution of multiple parts of a


program. This feature is particularly useful for applications that require high
performance, such as games and real-time simulations.

1.2.8. Portability

The platform-independent feature of java in which its platform-independent bytecode


can be taken to any platform for execution makes java portable. WORA (Write Once
Run Anywhere) makes java application to generates a ‘.class’ file that corresponds to
our applications(program) but contains code in binary format. It provides architecture-
neutral ease, as bytecode is independent of any machine architecture. It is the primary
reason java is used in the enterprising IT industry globally worldwide.

1.2.9. High Performance

Java architecture is defined in such a way that it reduces overhead during the runtime
and at sometimes java uses Just In Time (JIT) compiler where the compiler compiles
code on-demand basis where it only compiles those methods that are called making
applications to execute faster.

1.3 Java Architecture

• JVM (Java Virtual Machine) runs Java applications as a run-time engine.

4
Chapter no 1: Introduction to JAVA

• JVM is the one that calls the main method present in a Java code. JVM is a part of JRE
(Java Runtime Environment)..

Figure 1.1 Java Architecture

1.3.1. Class Loader Subsystem

It is mainly responsible for three activities.

 Loading

 Linking

 Initialization

Loading

 The Class loader reads the “.class” file, generate the corresponding binary data and
save it in the method area. For each “.class” file, JVM stores the following information
in the method area - the fully qualified name of the loaded class and its immediate parent
class, Modifier, Variables and Method information etc.

 After loading the “.class” file, JVM creates an object of type Class to represent this
file in the heap memory.

 These Class object can be used by the programmer for getting class level information
like the name of the class, parent name, methods and variable information etc.

To get this object reference we can use getClass () method of Object class.

5
OOPS AND JAVA

Example:
class Student { private String name; private int roll_No;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getRoll_no() { return roll_No; }
public void setRoll_no(int roll_no)

this.roll_No = roll_no;

}}

Output:

Student

getName

setName

getRoll_no

setRoll_no

name

roll_No

Linking

Performs verification, preparation, and (optionally) resolution.

 Verification: It ensures the correctness of the .class file i.e., it checks whether this file is
properly formatted and generated by a valid compiler or not. If verification fails, we get
run-time exception java.lang.VerifyError. This activity is done by the component
ByteCodeVerifier. Once this activity is completed then the class file is ready for
compilation.

 Preparation: JVM allocates memory for class static variables and initializing the
memory to default values.

 Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.

6
Chapter no 1: Introduction to JAVA

Initialization

In this phase, all static variables are assigned with their values defined in the code and
static block. This is executed from top to bottom in a class and from parent to child in the
class hierarchy. In general, there are three class loaders:

 Bootstrap class loader: Every JVM implementation must have a bootstrap class loader,
capable of loading trusted classes. It loads core java API classes present in the
“JAVA_HOME/lib” directory. This path is popularly known as the bootstrap path. It
is implemented in native languages like C, C++.

Example:
// Java code to demonstrate Class Loader subsystem

public class Test {


public static void main(String[] args)

// String class is loaded by bootstrap loader, and

// bootstrap loader is not Java object, hence null


System.out.println(String.class.getClassLoader());
// Test class is loaded by Application loader
System.out.println(Test.class.getClassLoader());
}

Output:

Null

jdk.internal.loader.Class Loaders$AppClassLo ader@8bcc55f

1.3.2. Class Loaders

There are three primary types of class loaders:

 Bootstrap Class Loader: Loads core Java API classes from the JAVA_HOME/lib
directory. It is implemented in native code and is not a Java object.

 Extension Class Loader: Loads classes from the JAVA_HOME/jre/lib/ext directory or

7
OOPS AND JAVA

any directory specified by the java.ext.dirs system property. It is implemented in Java.

 System/Application Class Loader: Loads classes from the application classpath, which
is specified by the java.class.path environment variable. It is also implemented in Java

 These 3 class loaders is described in the Figure 1.2 Class Loaders.

Figure 1.2 Class Loaders


Example:
public class Test {

public static void main(String[] args)

System.out.println(String.class.getClassLoader());
System.out.println(Test.class.getClassLoader());
}

Output:

null

sun.misc.Launcher$AppClassLoader@<hashcode>
1.3.3. JVM Memory Areas
 Method area: In the method area, all class level information like class name,
immediate parent class name, methods and variables information etc. are stored,
including static variables.
 There is only one method area per JVM, and it is a shared resource.

8
Chapter no 1: Introduction to JAVA

 Heap area: Information of all objects is stored in the heap area. There is also one
Heap Area per JVM.
 It is also a shared resource.
 Stack area: For every thread, JVM creates one run-time stack which is stored here.
 Every block of this stack is called activation record/stack frame which stores
methods calls.
 All local variables of that method are stored in their corresponding frame.
 After a thread terminates, its run-time stack will be destroyed by JVM. It is not a
shared resource.
 PC Registers: Store address of current execution instruction of a thread.
 Obviously, each thread has separate PC Registers.
 Native method stacks: For every thread, a separate native stack is created.
It stores native method information and it is described in the Figure 1.3 JVM
Memory Area.

Figure 1.3 JVM Memory Area

1.3.4. Execution Engine

Execution engine executes the “.class” (bytecode). It reads the byte-code line by line,
uses data and information present in various memory area and executes instructions.
It can be classified into three parts:

 Interpreter: It interprets the bytecode line by line and then executes. The
disadvantage here is that when one method is called multiple times, every time
interpretation is required.

 Just-In-Time Compiler (JIT): It is used to increase the efficiency of an interpreter. It

9
OOPS AND JAVA

compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so re-
interpretation is not required, thus efficiency is improved.

 Garbage Collector: It destroys un-referenced objects. For more on Garbage


Collector, refer Garbage Collector.

1.3.5. Java Native Interface (JNI)

It is an interface that interacts with the Native Method Libraries and provides the native
libraries (C, C++) required for the execution. It enables JVM to call C/C++ libraries and
to be called by C/C++ libraries which may be specific to hardware.

1.3.6. Native Method Libraries

These are collections of native libraries required for executing native methods. They
include libraries written in languages like C and C++.

1.4 Java environment

The programming environment of Java consists of three components mainly:


 JDK

 JRE

 JVM It is shown in the Figure 1.4 Java Environment.

Figure 1.4 Java Environment

10
Chapter no 1: Introduction to JAVA

1.4.1 JDK (Java Development Kit)

 It is a complete software development kit (SDK) for Java, including the compiler
(javac), libraries, and tools needed to develop and run Java applications.

 It contains both JRE and JVM.

 Used by developers to write, compile, and debug Java programs.

JDK=JRE + Development Tools


JDK – Architecture Diagram: The JDK is like a toolkit that Java developers use to
build, test, and run their applications. It’s more than just a bunch of tools. The JDK
includes everything we need to turn the source code into a working program — whether
we are building a small command-line tool or a large-scale enterprise application.

The JDK, JRE, and JVM each play a unique role in the Java ecosystem:

 The JDK provides the full set of development tools for building Java applications.

 The JRE offers a runtime environment with libraries and tools for executing
applications.

The JVM executes the Java bytecode, making Java platform-independent.


The JDK is composed of several key components, each serving a unique purpose in the
Java development process and it is described in Figure 1.5 Java development kit JDK.

Java Compiler: The Java Compiler (javac) is a critical component of the JDK. It takes
human-readable Java source code and converts it into bytecode, which the Java Virtual
Machine (JVM) can execute.The compiler checks the code for syntax errors and then
translates it into bytecode, which is stored in .class files.

Development Tools: The JDK comes with various development tools that assist in
creating, managing, and debugging Java applications.

 javadoc: Generates HTML documentation from code comments.

 jar: Packages compiled code into a JAR file for distribution.

jdb: Java Debugger, allows to inspect variables, set breakpoints, and step through code to
diagnose and fix bugs and it is described as Figure 1.6 Java Development tools.

11
OOPS AND JAVA

Figure 1.5 Java development kit JDK

Figure 1.6 Java Development tools

Most Popular JDKs are

 Oracle JDK: the most popular JDK and the main distributor of Java11

12
Chapter no 1: Introduction to JAVA

 OpenJDK: Ready for use: JDK 15, JDK 14, and JMC,

 Azul Systems Zing: efficient and low latency JDK for Linux OS

 Azul Systems: based Zulu brand for Linux, Windows, Mac OS X,

 IBM J9 JDK: for AIX, Linux, Windows, and many other OS,

 Amazon Corretto: the newest option with the no-cost build of OpenJDK and long-term

support.

Set-Up: Setting up JDK in a development environment is easy

Installation of JDK:

 Go to this Oracle’s official Download Page

 Select the latest JDK version and click Download and add it to the class path.

 Just check the JDK software is installed or not on your computer at the correct location,
for example, at C:\Program Files\Java\jdk11.0.9.

Set JAVA_HOME for Windows:

 Right-click My Computer and select Properties.

 Go to the Advanced tab and select Environment Variables, and then edit JAVA_HOME to
point to the exact location where the JDK software is stored, for example, C:\Program
Files\Java\jdk11.0.9 is the default location in windows.
 Java maintains backward compatibility, so the latest release can be downloaded and

get all the old and many new features. After Installing the JDK and JRE adds the java
command to the command line. We can verify this through the command prompt by the
java -version command. In some cases, we need to restart the system after installing the
JDK.

JDK Version

 Compile and Run Java Code using JDK: We can use the JDK compiler to convert the

Java text file into an executable program. The Java text segment is converted into

13
OOPS AND JAVA

bytecode after compilation which carries the .class extension. 

 A Java text file is created and saved it using a user defined name. Here it is saved as

Hello.java and it is described in Figure 1.7 java -version command. 

Figure 1.7 java -version command

Class Hello

Public static void main (String[]


args) { System.out.println("Hello
Geek!");
}

 After that use the javac command, which is used for the compilation purpose in Java.

 The command should be similar to the given below example where Hello is the file
name and the full path to the file is specified before the file name.

 The path and javac.exe should be inside the quotes.“C:\Program Files\Java\jdk-


11.0.9\bin\javac.exe” Hello.java
 The Hello.class file is being created in the same directory as Hello.java. Now execute
the code by simply using the java Hello command, which will give the desired result
according to the code. C:\Users\Pinaki\Documents>java Hello (Output:) Hello Geek!

14
Chapter no 1: Introduction to JAVA

The Jar component

 JDK contains many useful tools and among them, the most popular after javac is the jar

tool.The jar file is nothing but a full pack of Java classes. 

 After creating the .class files, we can put them together in a .jar, which compresses and

structures them in a predictable fashion. Now, let’s convert our Hello.class to a jar file. 

 Before proceeding, check the present working directory where Hello.java file was

saved. Now place the command given below in the command line. 

Creating a .jar file

 C:\Users\Pinaki\Documents>” c:\Program Files\Java\jdk-11.0.9\bin\jar.exe” –create –


file Hello.jar Hello.class.Hello.jar file had been created in the same directory using
Hello.class file and jar.exe. We can use the jar file by adding it to the classpath and
executing the program inside it.

 The -cp stands for classpath which helps to add the jar to the same classpath.

Executing the .jar file

 java -cp hello_world.jar hello_world

Table 1.1 Important Components of JDK


Component Use
javac Java compiler converts source code into Java bytecode
java The loader of the java apps.
javap Class file disassembler.
javadoc Documentation generator.
jar Java Archiver helps manage JAR files.
appletviewer Debugging of Java applets without a web browser,
xjc Accepts an XML schema and generates Java classes,
apt Annotation-processing tool,
jdb Debugger,
jmc Java Mission Control,
JConsole Monitoring and Management Console,
pack200 JAR compression tool,

15
OOPS AND JAVA

extcheck Utility tool to detects JAR file conflicts,


idlj IDL-to-Java compiler,
keytool The keystore manipulating tool,
jstatd jstat daemon (experimental)
jstat JVM statistics monitoring tool
jshell jshell introduced in java 9.
jstack Prints Java stack traces(experimental)
jrunscript Java command-line script shell.
jhat Java Heap Analysis Tool (experimental)
jpackage Generate self-contained application bundles.
javaws Web Start launcher for JNLP applications,
javah C header and stub generator,
jarsigner jar signing and verification tool
jinfo configuration information(experimental)
javafxpackager Package and sign JavaFX applications

1.4.2 JRE (Java Runtime Environment)

 It provides the necessary environment to run Java applications.

 It includes the JVM and standard libraries but does not contain development tools

like the compiler.

 Used by end-users who only need to run Java applications.

1.4.3 JVM (Java Virtual Machine)

 It is the core component that allows Java code to be platform-independent.

 It converts Java bytecode (compiled code) into machine code that the operating system
can execute.

 It includes features like Just-In-Time (JIT) compilation, memory management, and


garbage collection.

16
Chapter no 1: Introduction to JAVA

1.4.4 JDK vs JRE vs JVM

Table 1.2 JDK vs JRE vs JVM


Aspect JDK JRE JVM
Purpose Used to develop Java Used to run Java Responsible for
running Java code
applications applications
Platform Platform-dependent Platform-dependent Platform-
Independent
Dependency
Includes It includes development It includes libraries to run It runs the java
tools like (compiler) + Java application + JVM byte code and
JRE makes java
application to work
on
any platform.
Use Case Writing and compiling Running a Java Convert bytecode
Java code application on a system into native machine
code

1.5 Java Basic Syntax

Java Syntax refers to a set of rules that defines how Java programs are written and
interpreted by the compiler. These rules ensure that the code is readable, logically correct,
and error-free. The Syntax and Structure of Java Programs with a basic “Hello World”
program are given below.

1.5.1 Steps to Implement Java Program

The implementation of a Java program involves the following steps. They include:

 Creating the program

 Compiling the program

 Running the program

1. Create a Java Program

Java programs can be written in a text editor (Notepad, VS Code) or an IDE (IntelliJ,
Eclipse, NetBeans).

17
OOPS AND JAVA

Example:

// Simple Java Hello World Program

class HelloWorld

public static void main(String[] args)

System.out.println(“Hello, World”);

Output:

Hello, World

Save the file as HelloWorld.java

2. Compile the Java Program

To compile the program, we must run the Java compiler (javac), with the name of the
source file on the “command prompt” (Windows) or “Terminal” (Mac/Linux) as follows:

javac HelloWorld.java

 Run the Java Program


We need to use the Java Interpreter to run a program. Execute and compile Java program
with below command: java HelloWorld

Output: Hello, World

The execution of a Java application code involves three main steps and it is described as
Figure 1.8 Java Code Execution:

18
Chapter no 1: Introduction to JAVA


Figure 1.8 Java Code Execution

1.5.2 Structure of java Program

Class Declaration

 Every Java program starts with a class declaration using the class keyword.

 “A class is a blueprint of an object”

Class is a logical template that shares common properties and


methods.
class HelloWorld
{ //statement}

Object:The object is an instance of a class. It is an entity that has behavior and state.

Main Method: The public static void main(String args[]) method is the entry point
where the program starts execution.
public static void main(String[] args)

System.out.println("Hello, World"); }

Statements: Each line of code inside the method must end with a semicolon (;)

System.out.println("Hello, World");

Output

Hello, World

19
OOPS AND JAVA

1.6 Comments

Comments can be used to explain Java code, and to make it more readable. It can also
be used to prevent execution when testing alternative code.

1.6.1 Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed). This
example uses a single-line comment before a line of code:
Example

System.out.println("Hello World");

1.6.2 Java Multi-line Comments

Multi-line comments start with /*


and ends with */. Any text between
/* and */ will be ignored by Java.
Example

/* The code below will print the words Hello Worldto the screen, and it is amazing */
System.out.println("Hello World");

1.7 Data Types

Java is statically typed and also a strongly typed language because, in Java, each type
of data (such as integer, character, hexadecimal, packed decimal, and so forth) is
predefined as part of the programming language and all constants or variables defined for
a given program must be described with one of the Java data types.

Data types in Java are of different sizes and values that can be stored in the variable that
is made as per convenience and circumstances to cover up all test cases. Java has two
categories in which data types are segregated and it is described in Figure 1.9 Data Types
in Java.

Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double. The
Boolean with uppercase B is a wrapper class for the primitive data type boolean in Java.

Non-Primitive Data Type or Object Data type: such as String, Array, etc.

20
Chapter no 1: Introduction to JAVA

Example
int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

booleanmyBool = true;

String myText = "Hello";

Output:

5.99

true Hello


Figure 1.9 Data Types in Java

21
OOPS AND JAVA

1.7.1 Primitive Data Types


A primitive data type specifies the type of a variable and the kind of values it can hold.
There are eight primitive data types in Java.
Table 1.3 Primitive Data Types
Data Type Description
byte Stores whole numbers from -128 to 127
short Stores whole numbers from -32,768 to 32,767

int Stores whole numbers from -2,147,483,648 to 2,147,483,647

long Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal
digits
double Stores fractional numbers. Sufficient for storing 15 to 16
decimal digits
boolean Stores true or false values

char Stores a single character/letter or ASCII values

Numbers

Primitive number types are divided into two groups:

Integer types store whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long.

Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.

Integer Types

Byte: The byte data type can store whole numbers from -128 to 127. This can be used
instead of int or other integer types to save memory when we are certain that the value
will be within -128 and 127.
Short:
The short data type can store whole numbers from -32768 to 32767

22
Chapter no 1: Introduction to JAVA

Int: The int data type can store whole numbers from -2147483648 to 2147483647. In
general, and in our tutorial, the int data type is the preferred data type when we create
variables with a numeric value.
Example
int myNum = 100000;
System.out.println(myNum);
Long:The long data type can store whole numbers from -
9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the value.

Example
long myNum = 15000000000L;

System.out.println(myNum);

Floating Point Types: The floating-point type whenever you need a number with a
decimal, such as 9.99 or 3. 14515.The float and double data types can store fractional
numbers.
Example
float myNum = 5.75f;
System.out.println(myNum);
Use float or double?

The precision of a floating-point value indicates how many digits the value can have after
the decimal point. The precision of float is only six or seven decimal digits, while double
variables have a precision of about 16 digits. Therefore, it is safer to use double for most
calculations.

Scientific Numbers: A floating-point number can also be a scientific number with an "e"
to indicate the power of 10.
Boolean Types

Very often in programming, we will need a data type that can only have one of two values,
like:

YES / NO

23
OOPS AND JAVA

ON / OFF

TRUE / FALSE

For this, Java has a boolean data type, which can only take the values true or false:

Example

booleanisJavaFun = true;
booleanisFishTasty = false;

System.out.println(isJavaFun);

System.out.println(isFishTasty);

Characters

The char data type is used to store a single character. The character must be surrounded
by single quotes, like 'A' or 'c'Alternatively, if we are familiar with ASCII values, we can
use those to display certain characters.
Strings

The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:

A String in Java is actually a non-primitive data type, because it refers to an object. The
String object has methods that are used to perform certain operations on strings.

Create variables of different data types


public class Main {

public static void main(String[] args)

{
// Create variables of different data types int items = 50;
float costPerItem = 9.99f;
float totalCost = items * costPerItem; char currency = '$';
// Print variables
System.out.println("Number of items: " + items);

24
Chapter no 1: Introduction to JAVA

System.out.println("Cost per item: " + costPerItem +currency);

System.out.println("Total cost = " + totalCost + currency)

}}
1.7.2 Non-Primitive Data Types

 Non-primitive data types are called reference types because they refer to objects.

The main differences between primitive and non-primitive data types are:

 Primitive types in Java are predefined and built into the language, while non-primitive
types are created by the programmer (except for String).

 Non-primitive types can be used to call methods to perform certain operations, whereas
primitive types cannot.

 Primitive types start with a lowercase letter (like int), while non-primitive types typically
starts with an uppercase letter (like String).

 Primitive types always hold a value, whereas non-primitive types can be null.

1. 8 Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

String - stores text, such as "Hello". String values are surrounded by double quotes.
 int - stores integers (whole numbers), without decimals, such as 123 or -123

 float - stores floating point numbers, with decimals, such as 19.99 or -19.99

 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

 boolean - stores values with two states: true or false

1.8.1 Declaring (Creating) Variables

To create a variable, we must specify the type and assign it a value:

25
OOPS AND JAVA

Syntax
type variableName = value;
Where type is one of Java's types (such as int or String), and variableName is the name of
the variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Example

Create a variable called name of type String and assign it the


value "John". Then we use println() to print the name variable:
String name = "John";

System.out.println(name);
To create a variable that should store a number, look at the following example:

1.8.2 Final Variables

If we don't want others to overwrite existing values, use the final keyword (this will declare
the variable as "final" or "constant", which means unchangeable and read-only):
1.8.3 Display Variables

 The println() method is often used to display variables.

To combine both text and a variable, use the + character:

1.8.4 Declare Many Variables

To declare more than one variable of the same type, we can use a comma-separated list:
Identifiers:

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

26
Chapter no 1: Introduction to JAVA

Example
public class Main {

public static void main(String[] args) {

int minutesPerHour = 60;

int m = 60;

System.out.println(minutesPerHour);

System.out.println(m);}}
The general rules for naming variables are:

 Names can contain letters, digits, underscores, and dollar signs

 Names must begin with a letter

 Names should start with a lowercase letter, and cannot contain whitespace

 Names can also begin with $ and _

 Names are case-sensitive ("myVar" and "myvar" are different variables)

 Reserved words (like Java keywords, such as int or boolean) cannot be used as names

1.9 Operators

Operators are used to perform operations on variables and values.

Java divides the operators into the following groups:

 Arithmetic operators

 Assignment operators

 Comparison operators

 Logical operators

27
OOPS AND JAVA

 Bitwise operators

1.9.1 Arithmetic Operators


Arithmetic operators are used to perform common mathematical operations.

Table 1.4 Arithmetic Operators

Operator Name Description Example

+ Addition Adds together two x+ y


values

- Subtraction Subtracts one value x- y


from another

* Multiplication Multiplies two values x* y

/ Division Divides one value by x / y


another

% Modulus Returns the division x% y


remainder

++ Increment Increases the value of a ++x


variable by 1

-- Decrement Decreases the value of a --x


variable by 1

1.9.2 Java Assignment Operators

 Assignment operators are used to assign values to variables.

 The assignment operator (=) is used to assign the value 10 to a variable called x.

Example 1:

int x = 10;

The addition assignment operator (+=) adds a value to a variable:

28
Chapter no 1: Introduction to JAVA

Example 2:

int x = 10;

x+=10;

Table 1.5 A list of all assignment operators

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x- 3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x% 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

1.9.3 Java Comparison Operators

 Comparison operators are used to compare two values (or variables). This is important
in programming, because it helps us to find answers and make decisions.
 The return value of a comparison is either true or false. These values are known as
Boolean values.

29
OOPS AND JAVA

 In the following example, we use the greater than operator (>) to find out if 5 is greater
than 3:

Table 1.6 Java Comparison Operators

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x> y

< Less than x< y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

1.9.4 Java Logical Operators

Logical operators are used to determine the logic between variables or values:

Table 1.7 Java Logical Operators

Operator Name Description Example

&& Logical Returns true if both statements are true x < 5 && x<
10
and

|| Logical or Returns true if one of the statements is x < 5 || x < 4


true

! Logical not Reverse the result, returns false if !(x < 5 &&
the result is true x < 10)

30
Chapter no 1: Introduction to JAVA

1.9.5 Bitwise Operators in Java

In Java, Operators are special symbols that perform specific operations on one or more
than one operand. They build the foundation for any type of calculation or logic in
programming.

There are so many operators in Java, among all, bitwise operators are used to perform
operations at the bit level. These operators are useful when we work with low-level
programming, bit manipulation tasks like flags, encryption, and graphics programming
etc.

What Are Bitwise Operators?

 Bitwise operators work on individual bits as discussed above. It works with integer
types (byte, short, int, long). When a bitwise operation is performed, each bit of the
particular number is treated as an individual based on the operation.
1. Bitwise AND (&)

This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values,
i.e., if both bits are 1, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)

b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101

& 0111

0101 = 5 (In decimal)

2. Bitwise OR (|)

This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values,
i.e., if either of the bits is 1, it gives 1, else it shows 0.

31
OOPS AND JAVA

Example:

a = 5 = 0101 (In Binary)

b = 7 = 0111 (In Binary)

Bitwise OR
Operation of 5 and
7 0101
| 0111

0111 = 7 (In decimal)

3. Bitwise XOR (^)

This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input
values, i.e., if corresponding bits are different, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)

b = 7 = 0111 (In Binary)

Bitwise XOR
Operation of 5 and
7 0101
^ 0111

0010 = 2 (In decimal)

4. Bitwise Complement (~)

This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement
representation of the input value, i.e., with all bits inverted, which means it makes every 0
to 1, and every 1 to 0.

32
Chapter no 1: Introduction to JAVA

Example:

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5 in java (8 bits)

~ 00000101
11111010 = -6 (In decimal)

1.10 Type Conversion and Casting

 There are many situations that come when we have to change the functionality of the
output as well as the type of output according to the need of the requirements. For e.g.
Entered PI value in decimal format should be converted in the decimal format so that value
can be used efficiently without any kind of errors and wrong output.

There are two ways we can change the type from one to another.

 Type casting

 Type conversion

1.10.1 Type Casting:

 Type Casting means to change one state to another state and is done by the
programmer using the cast operator.

 Type Casting is done during the program design time by the programmer.

 Typecasting also refers to Narrow Conversion or Narrow Casting. Because in


many cases, we have to Cast large datatype values into smaller datatype values according
to the requirement of the operations.

Syntax: () is Cast Operator

RequiredDatatype=(TargetType) Variable
Example:
import java.io.*;

// Main class

33
OOPS AND JAVA

public class TypeCast{

// Main driver method

public static void main(String[] args)

// Declaring an Integer datatype int a = 3;


// Casting to Large datatype double db = (double)a;
// Print and display the casted value System.out.println(db);
// Narrow Casting conversion int db1 = (int)db;
// Print an display narrow casted value System.out.println(db1);
}}
Output

3.0
3
1.10.2 Type Conversion:

 Type Conversion is a type conversion that is done by compiler done by a compiler


without the intention of the programmer during the compile time.

 Type Conversion sometimes creates an error or incorrect answer if the proper resultant
data type does not mention at the end of the multiple expression of the datatype that’s why
Type Conversion is less efficient than Type Casting.

The working mechanism of type conversion is as follows:


double > float > long > int > short > byte

Example: Error during type conversion


import java.io.*;

// Main class

public class TypeConversion {


// Main driver method

public static void main(String[] args)

34
Chapter no 1: Introduction to JAVA

// Declaring and initializing variables to values


// with different return type long a = 3;
byte b = 2; double c = 2.0;
// Type Conversion

int final_datatype = (a + b + c);

// Print statement System.out.print(final_datatype);


}}
Output:
prog.java:9: error: incompatible types: possible lossy conversion from double to int
int final_datatype = (a + b + c);^ 1 error
Output explanation:

When we assign the 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 cast or converted explicitly. For example, assigning an int value to a long
variable.
Data Types and Their Memory Allocation
Table 1.8 Data Types and Their Memory Allocation
Datatype Bits Acquired In Memory
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
short 16(2 bytes)
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)

Example:
class GFG {

// Main driver method

public static void main(String[] args)

35
OOPS AND JAVA

int i = 100;

// Automatic type conversion

// Integer to long type long l = i;


// Automatic type conversion

// long to float type float f = l;


// Print and display commands
System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
}
Output:

Int value 100


Long value 100
Float value 100.0
Widening or Automatic Type Conversion:

Widening conversion takes place when two data types are automatically converted.

The two data types are compatible.

 When we assign a value of a smaller data type to a bigger data type.

 For Example, in java, the numeric data types are compatible with each other but no
automatic conversion is supported from numeric type to char or boolean. Also, char and
boolean are not compatible with each other.

Narrowing or Explicit Conversion

 If we want to assign a value of a larger data type to a smaller data type, we perform
explicit type casting or narrowing.
This is useful for incompatible data types where automatic conversion cannot be done. The
target type specifies the desired type to convert the specified value to.

36
Chapter no 1: Introduction to JAVA

Type Promotion in Expressions

While evaluating expressions, the intermediate value may exceed the range of operands
and hence the expression value will be promoted. Some conditions for type promotion
are:
1. Java automatically promotes each byte, short, or char operand to int when evaluating
an expression.
2. If one operand is long, float or double the whole expression is promoted to long,
float, or double respectively.
Example:
class conv {

// Main driver method

public static void main(String args[])

// Declaring and initializing primitive types byte b = 42;


char c = 'a'; short s = 1024; int i = 50000; float f =
5.67f;
double d = .1234;

// The Expression

double result = (f * b) + (i / c) - (d * s);


// Printing the result obtained after

// all the promotions are done System.out.println("result = " + result);


}
}
Output
result = 626.7784146484375
Explicit Type Casting in Expressions
While evaluating expressions, the result is automatically updated to a larger data type
of the operand. But if we store that result in any smaller data type it generates a compile-

37
OOPS AND JAVA

time error, due to which we need to typecast the result.


Program:
classconv {

// Main driver method

publicstatic void main(String args[])

// Declaring byte array

byte b = 50;

// Type casting int to byte

b = (byte)(b * 2);

// Display value in byte

System.out.println(b);

}
}
Output
100
Table 1.9 Difference Between Explicit and Implicit Conversion
Aspect Implicit Conversion Explicit Conversion
Syntax No additional syntax required. Requires explicit
type casting (e.g., (int)).

Data Compatibility Only works with compatible Works with both


compatible and
types (e.g., numeric).
incompatible types.
Risk of Data Loss No risk of data loss. May result in data loss
(e.g., truncation).
Direction Smaller type to larger type. Larger type to smaller
type.

38
Chapter no 1: Introduction to JAVA

Table 1.10 Difference between Type Casting and Type Conversion


S.NO TYPE CASTING TYPE CONVERSION
1. In type casting, a data type is converted Whereas in type conversion, a
into anotherdata type by a data type is converted into
programmer using casting operator. another data type by a compiler.
2. Type casting can be applied to Whereas type conversion can
compatible data types as well only be applied to compatible
as incompatible data types. datatypes.
3. In type casting, casting operator is needed in Whereas in type conversion,
order to cast a data type to there is no need for a casting
another data type. operator.
4. In type casting, the destination data type may Whereas in type conversion, the
be smaller than the source data type, when destination data type can’t be
converting the data type smaller than source data type.
to another data type.
5. Type casting takes place during the Whereas type conversion is done
program design by programmer. at the compile time.
6. Type casting is also called narrowing Whereas type conversion is also
conversion because in this, the destination called widening conversion
data type may be smaller than the source databecause in this, the destination
type. data type cannot be smaller than
the source data type.
7. Type casting is often used in coding and Whereas type conversion is less
competitive programming works. used in coding and competitive
programming as it might cause
incorrect answer.
8. Type casting is more efficient and Whereas type conversion is less
reliable. efficient and less reliable.

1.11 Flow Control Statements

 Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear.

 However, Java provides statements that can be used to control the flow of Java code.

39
OOPS AND JAVA

Such statements are called control flow statements.

 It is one of the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

Decision Making statements

1. if statements

2. switch statement

Loop statements

1. do while loop
2. while loop
3. for loop
4. for-each loop

Jump statements

1. break statement

2. continue statement

1.11.1 Decision-Making statements:

 Decision-making statements decide which statement to execute and when.

 Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided.

 There are two types of decision-making statements in Java, i.e., If statement and switch
statement.
1)If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives
a Boolean value, either true or false.

40
Chapter no 1: Introduction to JAVA

Four types of if-statements are

 Simple if statement

 if-else statement

 if-else-if ladder

 Nested if-statement

Simple if statement:

 It is the most basic statement among all control flow statements in Java.

 It evaluates a Boolean expression and enables the program to enter a block of code if
the expression evaluates to true.

Syntax:

if(condition) {

statement 1; //executes when condition is true


}
Example:
public class Main {
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y> 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20

41
OOPS AND JAVA

if-else statement

 The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block.

 The else block is executed if the condition of the if-block is evaluated as false.

Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else
{
statement 2; //executes when condition is false
}
Example:
public class Main {
public static void main(String[] args)
{
int x = 10;
int y = 12; if(x+y< 10)
{
System.out.println("x + y is less than 10");
}
else {
System.out.println("x + y is greater than 20");
} }}
if-else-if ladder:
 The if-else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that it is the chain of if-else statements that create
a decision tree where the program may enter in the block of code where the condition is
true.
 We can also define an else statement at the end of the chain.

42
Chapter no 1: Introduction to JAVA

Syntax:

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Example
public class Main {
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}
else if (city == "Noida")
{
System.out.println("city is noida");
}
else if(city == "Agra")
{
System.out.println("city is agra");
}
else
{
System.out.println(city);
}
}}

43
OOPS AND JAVA

Output:
Delhi
Nested if-statement
 In nested if-statements, the if statement can contain a if or if-else statement inside another
if or else-if statement.

Syntax:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Example
public class Main
{
public static void main(String[] args)
{
Delhi String address = "Delhi, India";
if(address.endsWith("India"))
{
if(address.contains("Meerut"))
{
System.out.println("Your city is Meerut");
}
else if(address.contains("Noida"))
{
System.out.println("Your city is Noida");
}
else
{

44
Chapter no 1: Introduction to JAVA

System.out.println(address.split(",")[0]);
}
}
else
{
System.out.println("You are not living in India");
}
}}

Output:
Delhi

1.11.2. Switch Statement:

 In Java, Switch statements are similar to if-else-if statements.

 The switch statement contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched.

 The switch statement is easier to use instead of if-else-if statements.

 It also enhances the readability of the program.

 The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java

 Cases cannot be duplicate

 Default statement is executed when any of the case doesn't match the value of
expression. It is optional.

 Break statement terminates the switch block when the condition is satisfied.

 It is optional, if not used, next case is executed.

 While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
Syntax:
switch (expression){ case value1:

45
OOPS AND JAVA

statement1; break;
..
case valueN: statementN;
break; default:
default statement;
}
Example:
public class Main {
public static void main(String[] args) {
int num = 2;
switch (num){ case 0:
System.out.println("number is 0");
break;
case 1:

System.out.println("number is 1");

break;
default: System.out.println(num);
}}}

 While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.

 The switch permits only int, string, and Enum type variables to be used.

Example:

import java.io.*;

class control {

public static void main(String[] args)

int a = 10; if (a == 5) {

46
Chapter no 1: Introduction to JAVA

System.out.println("a is equal to 5");

else {

System.out.println("a is not equal to 5");

}}}

Output

a is not equal to 5

Example 2:
import java.io.*;
class ctl {
public static void main(String[] args)

int a = 15; if (a == 5) {
System.out.println("a is equal to 5");

else if (a == 10) { System.out.println("a is equal to 10");


}

else {

System.out.println("a is not equal to 5 or 10");


}}}
Output

a is not equal to 5 or 10
1.11.3 Loop Statements

 In programming, sometimes we need to execute the block of code repeatedly


while some condition evaluates to true.

 However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.

47
OOPS AND JAVA

In Java, we have three types of loops that execute similarly.

 for loop

 while loop

 do-while loop

Java for loop

 In Java, for loop is similar to C and C++. It enables us to initialize the loop variable,
check the condition, and increment/decrement in a single line of code.

 We use the for loop only when we exactly know the number of times, we want to
execute the block of code.

Syntax:
for(initialization, condition, increment/decrement) {
//block of statements
}
Example
public class Main {

public static void main(String[] args) {

// TODO Auto-generated method stub


int sum = 0;

for(int j = 1; j<=10; j++) { sum = sum + j;


}

System.out.println("The sum of first 10 natural numbers is " + sum);

}}

Output:

The sum of first 10 natural numbers is 55


Java for-each loop

 Java provides an enhanced for loop to traverse the data structures like array or

48
Chapter no 1: Introduction to JAVA

collection. In the for-each loop, we don't need to update the loop variable.

Syntax:

for(data_type var : array_name/collection_name)

{
//statements

Consider the following example to understand the functioning of the for-each loop in
Java is described in Figure 1.10 For each loop.

Figure 1.10 For each loop

Example:
public class Main {

public static void main(String[] args)

String[] names = {"Java","C","C++","Python","JavaScript"};

System.out.println("Printing the content of the array names:");


for(String name:names)
{
System.out.println(name);
}} }
Output:

Printing the content of the array names:


Java

49
OOPS AND JAVA

C
C++
Python
JavaScript
Java while loop
 The while loop is also used to iterate over the number of statements multiple times.
 Unlike for loop, the initialization and increment/decrement doesn't take place inside the
loop statement in while loop.

 It is also known as the entry-controlled loop since the condition is checked at the start
of the loop.

 If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.

Syntax:

while(condition){

//looping statements

The flow chart for the while loop is given in the following image Figure 1.11 while loop.

Figure 1.11 while loop

Example
public class Main {

50
Chapter no 1: Introduction to JAVA

public static void main(String[] args)

int i = 0;
System.out.println("Printing the list of first 10 even numbers");
while(i<=10)
{
System.out.println(i);
i = i + 2;
}} }
Output:
Printing the list of first 10 even numbers 0
2

8
10
Java do-while loop

 The do-while loop checks the condition at the end of the loop after executing the loop
statements.

 When the number of iterations is not known and we have to execute the loop at least
once, we can use do-while loop is described in Figure 1.12 do-while loop.

Figure 1.12 do-while loop

51
OOPS AND JAVA

 It is also known as the exit-controlled loop since the condition is not checked in advance.

Syntax:
do
{
//statements
} while (condition);

Example
public class Main {

public static void main(String[] args) {

int i = 0;
System.out.println("Printing the list of first 10 even numbers ");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);

} }
Output:
Printing the list of first 10 even numbers 0
2

8
10
1.11.4 Jump Statements

 Jump statements are used to transfer the control of the program to the specific statements.
In other words, jump statements transfer the execution control to the other part of the
program.

 There are two types of jump statements in Java, i.e., break and continue.

52
Chapter no 1: Introduction to JAVA

Java break statement

 As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However,
it breaks only the inner loop in the case of the nested loop.

 The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.

Example
public class Main {

public static void main(String[] args) {

for(int i = 0; i<= 10; i++) {

System.out.println(i);
if(i==6) {
break;
} } } }
Output:

5
6
Java continue statement

 Unlike break statement, the continue statement doesn't break the loop, whereas, it skips
the specific part of the loop and jumps to the next iteration of the loop immediately.
Example
public class Main {

public static void main(String[] args) {

53
OOPS AND JAVA

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


for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}

System.out.println(j);

} } } }
Output:

3
5
1

1.12 Reading Input from keyboard

 The java.io package provides various classes to read write data from various sources and
destinations.

 We read data from user (keyboard) using various classes such as, Scanner,
BufferedReader ,InputStreamReader, Console etc.

1.13. Using Scanner class

 From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream,

54
Chapter no 1: Introduction to JAVA

Path and, String objects, reads all the primitive data types and Strings (from the given
source) token by token using regular expressions.

 By default, whitespace is considered as the delimiter (to break the data into tokens).

 To read data from keyboard we need to use standard input as source (System.in).

 For each datatype a nextXXX() is provided namely, nextInt(), nextShort(), nextFloat(),


nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(),
nextByte(), nextFloat(), next().

Example
import java.util.Scanner;
class Student{
String name;
int age;
float percent;
Boolean isLocal;
char grade;
Student(String name,int age, float percent, Boolean is Local, char grade)
{
this.name = name;

this.age = age;
this.percent = percent; this.isLocal = isLocal;
this.grade grade;
}

public void displayDetails(){ System.out.println("Details");


System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Percent: "+this.percent);
if(this.isLocal) { System.out.println("Nationality: Indian");
}else {

System.out.println("Nationality: Foreigner");

55
OOPS AND JAVA

System.out.println("Grade: "+this.grade);

public class ReadData {

public static void main(String args[]) {

Scanner sc =new Scanner(System.in);


System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your age: ");
int age = sc.nextInt();
System.out.println("Enter your percent: ");
float percent = sc.nextFloat();
System.out.println("Are you local (enter true or false): ");
booleanisLocal = sc.nextBoolean();
System.out.println("Enter your grade(enter A, or, B or,C or, D): ");
char grade = sc.next().toCharArray()[0];
Student std = new Student(name, age, percent, isLocal, grade);
std.displayDetails();
}
}
OUTPUT

Enter your name: Krishna


Enter your age: 25

Enter your percent: 86

Are you local (enter true or false):


true
Enter your grade(enter A, or, B or, C or, D):
A Details..............
Name: Krishna
Age: 25
Percent: 86.0

56
Chapter no 1: Introduction to JAVA

Nationality: Indian
Grade: A
2.UsingBufferedReader

 The BufferedReader class of Java is used to read stream of characters from the specified
source (character- input stream).

 The constructor of this class accepts an InputStream object as a parameter, we


can to pass an InputStreamReader.
Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Student{
String name; int age;
float percent;
Boolean isLocal;
char grade;
Student(String name, int age, float percent, booleanisLocal, char grade){
this.name = name;
this.age = age;
this.percent = percent;
this.isLocal = isLocal;
this.grade = grade;
}

public void displayDetails(){

System.out.println("Details ........ ");


System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Percent: "+this.percent);
if(this.isLocal) { System.out.println("Nationality: Indian");
}else {
System.out.println("Nationality: Foreigner");

57
OOPS AND JAVA

System.out.println("Grade: "+this.grade);

}}

public class ReadData {

public static void main(String args[]) throws IOException {


BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your name: ");
String name = reader.readLine();
System.out.println("Enter your age: ");

int age= Integer.parseInt(reader.readLine());


System.out.println("Enter your percent: ");
float percent = Float.parseFloat(reader.readLine());
System.out.println("Are you local (enter true or false): ");
booleanisLocal=Boolean.parseBoolean(reader.readLine());
System.out.println("Enter your grade(enter A, or, B or, C or, D): ");

char grade = (char) reader.read();

Student std = new Student (name, age, percent, isLocal, grade);


std.displayDetails();
}
}
Output

Enter your name:

Krishna

Enter your age: 25

Enter your percent: 86

Are you local (enter true or false): true


Enter your grade(enter A, or, B or, C or, D):
A Details..............
Name: Krishna

58
Chapter no 1: Introduction to JAVA

Age: 25
Percent: 86.0
Nationality: Indian
Grade: A
3. Using Console class

 This class is used to write/read data from the console (keyboard/screen) devices. It
provides a readLine() method which reads a line from the key-board.
We can get an object of the Console class using the console () method.
Example
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
class Student{
String name;
int age;
float
percent
;
boolean isLocal;
char
grade;
Student(String name, int age, float percent, booleanisLocal, char grade)
{
this.name = name;
this.age = age;
this.percent = percent;
this.isLocal = isLocal;
this.grade = grade;
}

public void displayDetails(){

System.out.println("Details ........ ");

59
OOPS AND JAVA

System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Percent: "+this.percent);
if(this.isLocal) {
System.out.println("Nationality: Indian");
}else {

System.out.println("Nationality: Foreigner");

System.out.println("Grade: "+this.grade);

} }
public class ReadData {
public static void main(String args[]) throws IOException {
Console console = System.console();
if (console == null) {
System.out.println("Console is not supported");
System.exit(1);

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

String name = console.readLine();


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

int age= Integer.parseInt(console.readLine());


System.out.println("Enter your percent: ");
float percent = float.parseFloat(console.readLine());
System.out.println("Are you local (enter true or false): ");
booleanisLocal=Boolean.parseBoolean(console.readLine());

System.out.println("Enter your grade(enter A,or, B or, C or, D): ");

char grade = console.readLine().toCharArray()[0];

Student std = new Student(name, age, percent, isLocal, grade);


std.displayDetails();

60
Chapter no 1: Introduction to JAVA

}
Output

Enter your name: Krishna

Enter your age: 26

Enter your percent: 86

Are you local (enter true or false): true


Enter your grade(enter A, or, B or, C or, D):
A Details..............
Name: Krishna Age: 26
Percent: 86.0 Nationality: Indian Grade: A

1.14 Command Line Arguments

 The Java command-line argument is an argument i.e. passed at the time of running the
java program.

 The arguments passed from the console can be received in the java program and it can
be used as an input. So, it provides a convenient way to check the behavior of the
program for the different values.
 We can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple Example of Command Line Arguments in java

 In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.

Example
class CommandLineExample{

public static void main(String args[]){

System.out.println("Your first argument is: "+args[0]);


}

}
Example of Command-Line Arguments that prints all the values

 In this example, we are printing all the arguments passed from the command-line. For

61
OOPS AND JAVA

this purpose, we have traversed the array using for loop.

Example
class A{

public static void main(String args[]){

for(int i=0;i<args.length;i++)

System.out.println(args[i]);
}

compile by >javac A.java

run by > java A Shahul Rahul 1 3


1.15 Arrays

 An array is typically a grouping of elements of the same kind that are stored in a single,
contiguous block of memory.

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

 In contrast to C/C++, the length member allows us to obtain the array's length. We must
utilise the sizeof operator in C/C++.

 An object of a dynamically formed class is called an array in Java. Java arrays implement
the Serializable and Cloneable interfaces and derive from the Object class.

 In Java, an array can hold objects or primitive values.

 Java allows us to create single- or multi-dimensional arrays, just like C/C++ does.

 Additionally, C/C++ does not support the anonymous array functionality that Java does.

62
Chapter no 1: Introduction to JAVA

Advantages

 Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.

 Random access: We can get any data located at an index position.

Disadvantages

 Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.

Types of Arrays in java

There are two types of arrays.

 Single Dimensional Array

 Multidimensional Array

1.15.1 Single-Dimensional Array in Java

 A single-dimensional array in Java is a linear collection of elements of the same data type.

Syntax:
dataType[] arr; (or) dataType[] arr; (or) dataTypearr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
String[] cars = {"Volvo", "BMW","Ford", "Mazda"};
System.out.println(cars[0]);
Output:
Volvo
Change an Array Element

To change the value of a specific element, refer to the index number:

cars[0] = "Opel";

Declaration, Instantiation and Initialization of Java Array

63
OOPS AND JAVA

 In Java, you can declare, instantiate, and initialize an array in a single line, as
demonstrated below: int a[]={33,3,4,5};//declaration, instantiation and initialization
Example
public class Main
{
public static void main(String args[]){
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
} }
For-each Loop for Java Array

 The Java for-each loop prints the array elements one by one.

 It holds an array element in a variable, then executes the body of the loop.

Syntax:

for(data_typevariable:array)

//body of the loop }

Example
public class Main{

public static void main(String args[]){

int arr[]={33,3,4,5};
for(int i:arr)
System.out.println(i);
} }
Passing Array to a Method in Java

 We can pass the Java array to the method so that we can reuse the same logic on any
array.

64
Chapter no 1: Introduction to JAVA

 When we pass an array to a method in Java, we are essentially passing a reference to the
array.

 It means that the method will have access to the same array data as the calling code, and
any modifications made to the array within the method will affect the original array.

Example:

public class Main


{

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

inta[]={33,3,4,5};
min(a);

} }
 The min method takes an integer array arr as a parameter and finds the minimum
element in the array using a simple iterative loop.

 In the main method, an integer array a is declared and initialized with values {33, 3, 4,
5}, and then the min method is called with this array as an argument.

 The min method iterates through the array to find the minimum element and prints it to
the console.

Anonymous Array in Java

 Java's anonymous arrays eliminate the requirement for separate declarations of array
variables by enabling developers to build and initialize arrays directly within method
calls or other expressions.
 When working with temporary arrays that are just needed for a single job and don't
need a persistent reference within the program, this is quite helpful.

65
OOPS AND JAVA

Returning Array from the Method

 In Java, methods are not limited to returning simple data types or objects; they can also
return arrays.

 This feature allows for more flexibility in method design and enables developers to
encapsulate complex logic for generating arrays within methods.
1.15.2 Multidimensional Array in Java

 A multidimensional array in Java is an array of arrays where each element can be an


array itself. It is useful for storing data in row and column format.
Syntax:
dataType[][] arrayRefVar; (or)
dataType[][]arrayRefVar; (or)
dataTypearrayRefVar[][]; (or)
dataType[]arrayRefVar[];
Example
public class Main

public static void main(String args[])

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

{7, 8, 9}}; // 3x3 matrix

// Printing the 2D array for (int i = 0; i< 3; i++)


{

for (int j = 0; j < 3; j++)

System.out.print(arr[i][j] + " ");

System.out.println();

} } }

66
Chapter no 1: Introduction to JAVA

Jagged Arrays in Java

 In Java, a jagged array is an array of arrays where each row of the array can have a
different number of columns.

 This contrasts with a regular two-dimensional array, where each row has the same
number of columns.

Declaring and Initializing a Jagged Array

To declare a jagged array in Java, we first declare the array of arrays, and then initialize
each row separately with its own array of columns.
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
Example:
class Student{

public String name; Student(String name){

this.name = name;

@Override

public String toString(){ return name;


}}

public class Main{

public static void main (String[] args){

// declares an Array and initializing the

// elements of the array

Student[] myStudents = new Student[]

{
new Student("Dharma"),new Student("sanvi"), new Student("Rupa"),

67
OOPS AND JAVA

new Student("Ajay")
};

// accessing the elements of the specified array

for(Student m:myStudents)
{
System.out.println(m);
}
}}
1.16 Classes and Objects

 In object-oriented programming, classes and objects play a vital role in programming.


These are the two main pillars of OOPs (Object-Oriented Programming). Without class
and object, we cannot create a program in Java.

 An object is an instance of a class, representing a specific entity with a defined state


and behavior.
1.16.1 Classes

 A class is a blueprint for creating objects, providing initial values for


member variables and implementations of behaviors (methods).

 A class in Java can contain:


1.16.2 Fields
Variables stated inside a class that indicate the status of objects formed from that class
are called fields, sometimes referred to as instance variables. They specify the data that
will be stored in each class object. Different access modifiers, such as public, private,
and protected, can be applied to fields to regulate their visibility and usability.
1.16.3 Methods

Methods are functions defined inside a class that includes the actions or behaviors that
objects of that class are capable of performing. These techniques allow the outside world
to function and change the object's state (fields). Additionally, methods can be void (that
is, they return nothing) or have different access modifiers. They can also return values.

1.16.4 Constructors

Constructors are unique methods that are used to initialize class objects. When an object

68
Chapter no 1: Introduction to JAVA

of the class is created using the new keyword, they are called with the same name as the
class. Constructors can initialize the fields of an object or carry out any additional setup
that's required when an object is created.

1.16.5 Blocks

Within a class, Java allows two different kinds of blocks: instance blocks, commonly
referred to as initialization blocks and static blocks. Static blocks, which are usually used
for static initialization, are only executed once when the class is loaded into memory.
Instance blocks can be used to initialize instance variables and are executed each time a
class object is generated.

1.16.6 Nested Class and Interface

Java permits the nesting of classes and interfaces inside other classes and interfaces. The
members (fields, methods) of the enclosing class are accessible to nested classes, which
can be static or non-static. Nested interfaces can be used to logically group related
constants and methods together because they are implicitly static.

Syntax
class ClassName
{
// Fields dataTypefieldName;
// Constructor ClassName(parameters)
{
// Initialize fields
}
// Methods returnTypemethodName(parameters)
{
// Method body
}
}
ClassName: The name of the class.

fieldName: Variables that hold the state of the class. Constructor: A special method
used to initialize objects.
methodName: Functions defined within the class to perform actions.

69
OOPS AND JAVA

1.16.7 Objects

 An object is an instance of a class.

 It is created using the new keyword followed by the class constructor.

Characteristics of an Object:

 State: It represents the data (value) of an object.

 Behavior: It represents the behavior (functionality) of an object such as deposit,


withdraw, etc.

 Identity: An object's identity is typically implemented via a unique ID. The ID's value is
not visible to the external user; however, it is used internally by the JVM to identify each
object uniquely.

Syntax

ClassNameobjectName = new ClassName(arguments);

objectName: The name of the object.

arguments: Values passed to the constructor to initialize the object.


new keyword in Java

 The new keyword is used to allocate memory at runtime. All objects get memory in
the Heap memory area.

 In Java, an instance of a class (also referred to as an object) is created using the new
keyword.

 The new keyword dynamically allocates memory for an object of that class and returns
a reference to it when it is followed by the class name and brackets with optional
arguments.
Defining a Class and Creating an Object

 In this example, the Car class has fields color and year, a constructor to initialize these
fields, and a method displayInfo() to display the car's details.

 An object myCar is created using the Car class.

70
Chapter no 1: Introduction to JAVA

1.17. Methods

 In general, a method is a way to perform some tasks. Similarly, the method in Java
is a collection of instructions that performs a specific task.

 It provides the reusability of code. We can also easily modify code using methods.

What is a Method in Java?

 A method is a block of code or collection of statements or a set of code grouped


together to perform a certain task or operation.

 It is used to achieve the reusability of code. We write a method once and use it many
times.

We do not require to write code again and again.


 It also provides the easy modification and readability of code, just by adding or
removing a chunk of code. The method is executed only when we call or invoke it.

Why Methods (Key Characteristics)?

 Reusability

 Modularity

 Maintainability

 Abstraction.

1.17.1 Method Declaration

 The method declaration provides information about method attributes, such as


visibility, return-type, name, and arguments.

1.17.2 Method in Java

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our

71
OOPS AND JAVA

application.

Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.

Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.

Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use void
keyword.

Method Name: It is a unique name that is used to define the name of a method. It must
be corresponding to the functionality of the method. Suppose, if we are creating a method
for subtraction of two numbers, the method name must be subtraction (). A method is
invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair
of parentheses. It contains the data type and variable name. If the method has no parameter,
left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.The method body is enclosed in
curly braces {} and contains the statements that defines the functionality or working of
method.
Naming a Method
 While defining a method, the method name must be a verb and start with a lowercase
letter.
 If the method name has more than two words, the first name must be a verb followed
by adjective or noun.

 In the multi-word method name, the first letter of each word must be in uppercase except
the first word.

Example:

 Single-word method name: sum(), area()

72
Chapter no 1: Introduction to JAVA

 Multi-word method name: areaOfCircle(), stringComparision()

 It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.

Types of Method

 Predefined Method

 User-defined Method

1.17.3 Predefined Method

 In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods.
 It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point.
 Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.

 When we call any of the predefined methods in our program, a series of codes related to
the corresponding method runs in the background that is already stored in the library.

 Each and every predefined method is defined inside a class. Such as print() method
is defined in the java.io.PrintStream class.

 It prints the statement that we write inside the method. For example, print("Java"), it
prints Java on the console.

Example:
public class Demo

public static void main(String[] args)

// using the max() method of Math class

System.out.print("The maximum number is: " + Math.max(9,7));

} }

73
OOPS AND JAVA

In the above example, we have used three predefined methods main(), print(), and max().

Method in Java

 In the above method signature, we see that the method signature has access specifier
public, non-access modifier static, return type int, method name max(), parameter list (int
a, int b).

 In the above example, instead of defining the method, we have just invoked the
method. This is the advantage of a predefined method. It makes programming less
complicated.

1.17.4 User-defined Method

 The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.

How to Create a User-defined Method?

 To create a user defined method that checks the number is even or odd. First, we will define
the method.
 The method body contains the steps to check the number is even or odd. If the number is
even, it prints the number is even, else prints the number is odd.

How to Call or Invoke a User-defined Method?

 Once we have defined a method, it should be called. The calling of a method in a program
is simple.

 When we call or invoke a user-defined method, the program control transfers to the called
method.

EvenOdd.java
import java.util.Scanner; public class EvenOdd
{

public static void main (String args[])

Scanner scan=new Scanner(System.in);

System.out.print("Enter the number: ");

74
Chapter no 1: Introduction to JAVA

int num=scan.nextInt();
//method calling findEvenOdd(num);
}

//user defined method

public static void findEvenOdd(int num)

//method body if(num%2==0)

System.out.println(num+" is even");

Else

System.out.println(num+" is odd");

}}
1.18. Static Variables and Methods

 A method that has static keyword is known as static method. In other words, a method
that belongs to a class rather than an instance of a class is known as a static method.

 We can also create a static method by using the keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It
can access static data members and also change the value of it. It is used to create an
instance method.It is invoked by using the class name. The best example of a static
method is the main () method.

Example:
public class Display

public static void main(String[] args)

show();

static void show()

75
OOPS AND JAVA

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


}
}
1.18.1 Method Overloading

 Method overloading is a feature in Java that allows multiple methods with the same
name but different parameter lists to exist within the same class.

 It enhances the flexibility and readability of the code.

Example

public class PrintUtil {

// Method with one parameter


public void print(String message) {
System.out.println(message);

// Overloaded method with two parameters


public void print(String message, int times) {
for (int i = 0; i< times; i++) {
System.out.println(message);
}} }
Instance Method

 The method of the class is known as an instance method. It is a non-static method defined
in the class.

 Before calling or invoking the instance method, it is necessary to create an object of its
class.

There are two types of instance method:

 Accessor Method

 Mutator Method

76
Chapter no 1: Introduction to JAVA

Accessor Method:

 The method(s) that reads the instance variable(s) is known as the accessor method. We
can easily identify it because the method is prefixed with the word get.

 It is also known as getters. It returns the value of the private field. It is used to get
the value of the private field.
Mutator Method:

 The method(s) read the instance variable(s) and also modify the values. We can easily
identify it because the method is prefixed with the word set.
 It is also known as setters or modifiers. It does not return anything. It accepts a
parameter of the same data type that depends on the field. It is used to set the value of the
private field.
Abstract Method

 The method that does not has method body is known as abstract method. In other
words, without an implementation is known as abstract method.

 It always declares in the abstract class. It means the class itself must be abstract if it has
abstract method. To create an abstract method, we use the keyword abstract.

Syntax

abstract void method_ name();


Factory method

 It is a method that returns an object to the class to which it belongs. All static methods are
factory methods.

 For example, NumberFormat obj = NumberFormat.getNumberInstance();


Initializing Object in Java

There are the following three ways to initialize object in Java.

 By reference variable

 By method

 By constructor

77
OOPS AND JAVA

1.18.2 Object Initialization through Reference Variable

 Initializing an object means storing data in the object.

Example:
class Student{ int id;
String name;

public class Main{

public static void main(String args[]){

//Creating objects

Student s1=new Student();

Student s2=new Student();


//Initializing objects s1.id=101;
s1.name="Sonoo"; s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}

}
1.18.3 Object Initialization through Method

The two objects of Student class and initializing the value to these objects by invoking the
insertRecord method.

Example

class Student{
int rollno; String name;
//Creating a method to insert record
void insertRecord(int r, String n)
{
rollno=r;

78
Chapter no 1: Introduction to JAVA

name=n;
}

Void displayInformation(){

System.out.println(rollno+" "+name);

}
//Creating a Main class to create objects and call methods
public class Main{
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();

}
1.19 Constructors

 The concept of object initialization through a constructor is essential to object-oriented


programming in Java.

 Special methods inside a class called constructors are called when an object of that class
is created with the new keyword.

 They initialize the state of objects by entering initial values in their fields or carrying
out any required setup procedures.
The constructor is automatically invoked upon object instantiation, guaranteeing correct
initialization of the object prior to usage.
Example
class Student
{
int id; String name;

79
OOPS AND JAVA

// Constructor with parameters

public Student(int id, String name)

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

}
// Method to display student information public void displayInformation()
{
System.out.println("Student ID: " + id);
System.out.println("Student Name: " + name);
}
}
public class Main {
public static void main (String [] args)
{

// Creating objects of Student class with constructor

Student student1 = new Student (1, "John Doe");

Student student2 = new Student (2, "Jane Smith");


// Displaying information of the objects student1.displayInformation();
student2.displayInformation();
} }
1.20 UML Class diagram

 A class diagram is a diagram used in designing and modeling software to describe


classes and their relationships.

 Class diagrams enable us to model software in a high level of abstraction and without
having to look at the source code.

 Classes in a class diagram correspond with classes in the source code.

 The diagram shows the names and attributes of the classes, connections between
the classes, and sometimes also the methods of the classes.
1.20.1 Describing class and class attributes
 In a class diagram, a class is represented by a rectangle with the name of the class
written on top.

80
Chapter no 1: Introduction to JAVA

 A line below the name of the class divides the name from the list of attributes (names
and types of the class variables).
 The attributes are written one attribute per line.
In a class diagram, class attributes are written "attributeName: attributeType". A +
before the attribute name means the attribute is public, and a - means the attribute is private.

1.20.2 Describing class constructor

Below we have the source code for a constructor for our Person class. The constructor gets
the name of the person as a parameter.
public class Person {
private String name; private int age;
public Person(String initialName)
{
this.name = initialName;
this.age = 0;} }

1.20.3 Describing class methods

Below we have added a method printPerson() which returns void to the


Person class. public class Person {
private
String
name;
private int
age;
public Person(String
initialName) { this.name =
initialName;
this.age = 0; }

81
OOPS AND JAVA

public void printPerson() {

System.out.println(this.name + ", age " + this.age + " years");


}}
 In a class diagram, we list all class methods including the constructors; constructors
are listed first and then all class methods. We also write the return type of a method in
the class diagram.

A class diagram describes classes, constructors and methods

 A class diagram describes classes and their attributes, constructors and methods as well
as the connections between classes. However, a class diagram tells us nothing about the
implementation of the constructors or the methods.
 Therefore, a class diagram describes the structure of an object but not its functionality.
public class
Person {
private String
name; private
int age;
public Person(String initialName) {
this.name = initialName;
this.age = 0;

public void printPerson() {

System.out.println(this.name + ", age " + this.age + " years");

public String getName() {

82
Chapter no 1: Introduction to JAVA

return this.name;
}}

1.21 Use of this keyword

 The this keyword refers to the current object in a method or constructor.

 The most common use of the this keyword is to eliminate the confusion between class

attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter). If we omit the keyword in the example above, the
output would be "0" instead of "5".

Using this with a


class attribute (x):
public class Main
{
int x;

// Constructor with a parameter

public Main(int x) {

this.x = x;

// Call the constructor

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println("Value of x = " + myObj.x);

83
OOPS AND JAVA

}}

Output:

Value of x =5

“this” keyword can also be used to:

 Invoke current class constructor

 Invoke current class method

 Return the current class object

 Pass an argument in the method call

 Pass an argument in the constructor call

1.22 Encapsulation

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. Another way to think
about encapsulation is, that it is a protective shield that prevents the data from being
accessed by the code outside this shield.

 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 its own class.

 A private class can hide its members or methods from the end user, using

abstraction to hide implementation details, by combining data hiding and abstraction.

 Encapsulation can be achieved by Declaring all the variables in the class as private and

writing public methods in the class to set and get the values of variables.

 It is more defined with the setter and getter method.

Example
class Programmer {
private String name;
// Getter and Setter for name
public String getName() { return name; }

84
Chapter no 1: Introduction to JAVA

public void setName(String name) { this.name = name; }


}
public class Geeks {
public static void main(String[] args) {
Programmer p = new Programmer();
p.setName("Geek");
System.out.println("Name=> " + p.getName());
}}
Output

Name=> Geek

Explanation: In this example, the class restricts direct access to it from outside. The getName()
and setName() methods, known as getters and setters, provide controlled access to
the name attribute. This encapsulation mechanism protects the internal state of the
Programmer object and allows for better control and flexibility in how the name attribute
is accessed and modified.

Uses

Using encapsulation in Java has many benefits:

 Data Hiding: The internal data of an object is hidden from the outside world, preventing

direct access.

 Data Integrity: Only validated or safe values can be assigned to an object’s attributes

via setter methods.

 Reusability: Encapsulated code is more flexible and reusable for future


modifications or requirements.

 Security: Sensitive data is protected as it cannot be accessed directly.

The image below demonstrates the concept of encapsulation, where a class (represented
by the capsule) hides its internal data (variables) and only exposes a controlled interface
(encapsulation) and it is described in Figure 1.13 Encapsulation.

85
OOPS AND JAVA

Figure :1.13 Encapsulation

1.23. Concept of Access Control

Access Modifiers
It is an essential tool that define how the members of a class, like variables,
methods, and even the class itself can be accessed from other parts of our program.
They are an important part of building secure and modular code when designing large
applications.
Types of Access Modifiers

There are 4 types of access modifiers available in Java and its is described in Figure
1.14 Access Modifiers:

1. Default – No keyword required

2. Private

3. Protected

4. Public

Figure 1.14 Access Modifiers

86
Chapter no 1: Introduction to JAVA

1.23.1 Private Access Modifier

The private access modifier is specified using the keyword private. The methods or
data members declared as private are accessible only within the class in which they are
declared.

 Any other class of the same package will not be able to access these members.

 Top-level classes or interfaces can not be declared as private because,

o private means “only visible within the enclosing class”.

o protected means “only visible within the enclosing class and any subclasses”.

These modifiers in terms of application to classes, apply only to nested classes and
not on top-level classes.
Example: In this example, we will create two classes A and B within the same
package p1. We will declare a method in class A as private and try to access this
method from class B and see the result.
// Error while using class from different package with

// private access modifier

packagep1;

// Class A

classA {
private void display() {

System.out.println("GeeksforGeeks");

}}

// Class B

classB {

publicstatic void main(String args[]) {

87
OOPS AND JAVA

A obj = new A();

// Trying to access private method

// of another class

obj.display();

}}

Explanation: The above code will show a compile-time error when trying to access
a private method from class B, even within the same package.

1.23.2 Default Access Modifier

When no access modifier is specified for a class, method, or data member, it is said to
have the default access modifier by default. This means only classes within the same
package can access it.

Example 1: Demonstrating Default Access Modifier Within the Same Package


In this example, we will create two packages and the classes in the packages will be
having the default access modifiers and we will try to access a class from one package
from a class of the second package.
// default access modifier
package p1;

// Class Geek is having


// Default access modifier

classGeek {
void display()
{
System.out.println("Hello World!");

}}

Example 2: Error when Accessing Default Modifier Class across Packages


In this example, the program will show the compile-time error when we try to access a

88
Chapter no 1: Introduction to JAVA

default modifier class from a different package.


// error while using class from different

// package with default modifier

Package p2;

Import p1. *; // importing package p1

// This class is having

// default access modifier

classGeekNew {

publicstatic void main(String args[]) {

// Accessing class Geek from package p1

Geek o = new Geek();

o.display();
}
}

1.23.3 Protected Access Modifier

The protected access modifier is specified using the keyword protected. The methods or
data members declared as protected are accessible within the same package or subclasses
in different packages.
Example 1: In this example, we will create two packages p1 and p2. Class A in p1 is
made public, to access it in p2. The method display in class A is protected and class B is
inherited from class A and this protected method is then accessed by creating an object
of class B.
// protected access modifier

Package p1;

89
OOPS AND JAVA

// Class A
publicclassA {
protected void display() {
System.out.println("GeeksforGeeks");
}
}

So, it demonstrates that a protected method is accessible within the same package.
Example 2: In this example, we will create two packages, p1 and p2. Class A in p1 has a
protected method display. Class B in p2 extends A and accesses the protected method
through inheritance by creating an object of class B.
// protected modifier
Package p2;
// importing all classes
// in package p1
Import p1.*;
// Class B is subclass of A
classBextends A {
publicstatic void main(String args[]) {
B obj = new B();
obj.display();}}
Explanation: The above example demonstrates that a protected method is accessible in a
subclass from a different package using inheritance.

1.23.4 Public Access Modifier

The public access modifier is specified using the keyword public.

 The public access modifier has the widest scope among all other access modifiers.

 Classes, methods, or data members that are declared as public are accessible from

everywhere in the program. There is no restriction on the scope of public data members.
Example 1: Here, the code shows that a public method is accessible within the same
package.
// public modifier

Package p1; public classA {

90
Chapter no 1: Introduction to JAVA

public void display() {

System.out.println("GeeksforGeeks");

}
Example 2: Here, the example shows that a public method is accessible across packages.
package
p2;
import
p1.*;
classB {
publicstatic void main(String args[]) {
A obj = new A();
obj.display(); }}
Table 1.11 Comparison Table of Access Modifiers in Java

91
OOPS AND JAVA

CHAPTER II
INHERITANCE
2.1 INHERITANCE
Java Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features (fields and methods)
of another class. In Java, Inheritance means creating new classes based on existing ones. A
class that inherits from another class can reuse the methods and fields of that class. In addition,
you can add new fields and methods to your current class as well.
2.1.1 Why Do We Need Java Inheritance?
• Code Reusability: The code written in the Superclass is common to all subclasses. Child
classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance. It is one
of the ways by which Java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all details is achieved
through inheritance. Abstraction only shows the functionality to the user.
2.1.2 Important Terminologies Used in Java Inheritance
• Class: Class is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. Class is not a real-world entity. It is just a template or blueprint or
prototype from which objects are created.
• Super Class/Parent Class: The class whose features are inherited is known as a superclass
(or a base class or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a subclass (or a
derived class, extended class, or child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
2.1.3 How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates you
are derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax:
class DerivedClass extends BaseClass

92
Chapter no 2: Inheritance

{
//methods and fields
}
Example: In the below example of inheritance, class Bicycle is a base class, class Mountain Bike
is a derived class that extends the Bicycle class and class Test is a driver class to run the program.
// Java program to illustrate the concept of inheritance
// base class class Bicycle {
// the Bicycle class has two fields public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear; this.speed = speed;
}
// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
// toString() method to print info of Bicycle
public String toString()
{
return ("No of gears are " + gear + "\n" + "speed of bicycle is " + speed); }}
// derived class
class MountainBike extends Bicycle {
// the MountainBike subclass adds one more field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int gear, int speed,int startHeight)
{

93
OOPS AND JAVA

// invoking base-class(Bicycle) constructor super(gear, speed);


seatHeight = startHeight;
}
// the MountainBike subclass adds one more method
public void setHeight(int newValue)
{
seatHeight = newValue;
}
// overriding toString() method
// of Bicycle to print more info @Override public String toString()
{
return (super.toString() + "\nseat height is "+ seatHeight);
}}
// driver class public class Test {
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString()); }}
Output
No of gears are 3 speed of bicycle is 100 seat height is 25
In the above program, when an object of Mountain Bike class is created, a copy of all methods
and fields of the superclass acquires memory in this object. That is why by using the object
of the subclass we can also access the members of a superclass.
Please note that during inheritance only the object of the subclass is created, not the superclass
and described in the Figure 2.1: Illustrative image of the program.

Figure 2.1: Illustrative image of the program

94
Chapter no 2: Inheritance

2.2 TYPES OF INHERITANCE


Below are the different types of inheritance which are supported by Java.
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
• Hybrid Inheritance
2.2.1 Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties
and behavior of a single-parent class. Sometimes, it is also known as simple inheritance. In
the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’ inherits all the
properties of the class ‘A’ and it is described in the Figure2.2: Single inheritance.

Figure 2.2: Single inheritance


Program:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
public class Main{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}

95
OOPS AND JAVA

}
Output:
barking... eating...
2.2.2 Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the
derived class also acts as the base class for other classes. In the below image, class A serves
as a base class for the derived class B, which in turn serves as a base class for the derived class
C. In Java, a class cannot directly access the grandparent’s members and it is described in the
Figure 2.3: Multilevel Inheritance.

Figure 2.3: Multilevel Inheritance


Program:
class Animal{
void eat(){
System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");}

96
Chapter no 2: Inheritance

}
public class Main{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping... barking... eating...
2.2.3 Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
subclass. In the below image, class A serves as a base class for the derived classes B, C, and
D and it is described in the Figure 2.4: Hierarchical Inheritance.

Figure 2.4: Hierarchical Inheritance


Program:
class Animal {
void eat () {
System.out.println("eating...");}
}
class Dog extends Animal {
void bark () {
System.out.println("barking...");}
}

97
OOPS AND JAVA

class Cat extends Animal {


void meow () {
System.out.println("meowing...");}
}
public class Main{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing... eating...
2.2.4 Multiple Inheritances (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features
from all parent classes. Please note that Java does not support multiple inheritances with
classes. In Java, we can achieve multiple inheritances only through Interfaces. In the image
below, Class C is derived from interfaces A and B and it is described in the Figure 2.5:
Multiple Inheritances.

Figure 2.5: Multiple Inheritances


2.2.5 Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support
multiple inheritances with classes, hybrid inheritance involving multiple inheritance is also
not possible with classes.
In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve
multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require the use
of Multiple Inheritance exclusively.

98
Chapter no 2: Inheritance

It can be achieved through a combination of Multilevel Inheritance and Hierarchical


Inheritance with classes, Hierarchical and Single Inheritance with classes. Therefore, it is
indeed possible to implement Hybrid inheritance using classes alone, without relying on
multiple inheritance type and it is described in the Figure2.6: Hybrid Inheritance.

Figure2.6: Hybrid Inheritance


2.3 Subclass And Superclass
In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
• subclass (child) - the class that inherits from another class
• superclass (parent) - the class being inherited from
• To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits the attributes and methods from the
Vehicle class (superclass):
Example
class Vehicle
{
protected String brand = "Ford";
// Vehicle attribute public void honk()
// Vehicle method
{
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute public static void main(String[]
args) {
// Create a myCar object Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object

99
OOPS AND JAVA

myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Output:
Tuut, tuut! Ford Mustang
2.4 SUPER KEYWORD
• The super keyword refers to superclass (parent) objects.
• It is used to call superclass methods, and to access the superclass constructor.
• The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
Example
Using super to call the superclass of Dog (subclass):
class Animal { // Superclass (parent)
public void animalSound() {
The animal makes a sound System.out.println("The animal makes a sound");
}
}
class Dog extends Animal { // Subclass (child)
public void animalSound() {
super.animalSound(); // Call the superclass method
System.out.println("The dog says: bow wow");
}}
public class Main {
public static void main(String args[]) {
Animal myDog = new Dog();
// Create a Dog object myDog.animalSound();
// Call the method on the Dog object
}}
Use of super keyword in Java
It is majorly used in the following contexts as mentioned below:
• Use of super with Variables

100
Chapter no 2: Inheritance

• Use of super with Methods


• Use of super with Constructors
2.4.1. Use of super with Variables
This scenario occurs when a derived class and base class have the same data members. In that
case, there is a possibility of ambiguity in the JVM.
Example
// Base class vehicle class Vehicle {
int maxSpeed = 120; }
// sub class Car extending vehicle class Car extends Vehicle {
int maxSpeed = 180;
void display()
{ // print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "+ super.maxSpeed);
}}
// Driver Program class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display(); }}
Output:
Maximum Speed: 120
In the above example, both the base class and subclass have a member maxSpeed. We could
access the maxSpeed of the base class in subclass using super keyword.
2.4.2. Use of super with Methods
This is used when we want to call the parent class method. So whenever a parent and child
class have the same-named methods then to resolve ambiguity we use the super keyword.
Example
// superclass Person
class Person {
void message()
{
System.out.println("This is person class\n");
}

101
OOPS AND JAVA

}
// Subclass Student
class Student extends Person { void message()
{
System.out.println("This is student class"); }
// Note that display() is
// only in Student class void display()
{
// will invoke or call current
// class message() method message();
// will invoke or call parent // class message() method super.message(); }}
// Driver Program
class Test {
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student s.display(); }}
Output:
This is student class This is person class
In the above example, we have seen that if we only call method message () then, the current
class message () is invoked but with the use of the super keyword, message () of the superclass
could also be invoked.
2.4.3. Use of super with constructors
The super keyword can also be used to access the parent class constructor. One more
important thing is that ‘super’ can call both parametric as well as non-parametric constructors
depending on the situation.
Example 1:
// superclass Person
class Person { Person()
{
System.out.println("Person class Constructor");
}}
// subclass Student extending the Person class

102
Chapter no 2: Inheritance

class Student extends Person {


Student()
{
// invoke or call parent class constructor super();
System.out.println("Student class Constructor");
}}
// Driver Program class Test {
public static void main(String[] args)
{
Student s = new Student(); }}
Output
Person class Constructor Student class Constructor
In the above example, we have called the superclass constructor using the keyword ‘super’
via subclass constructor.
Example 2:
class ParentClass {
public booleanisTrue() { return true; }}
class ChildClass extends ParentClass {
public booleanisTrue()
{
// calls parent implementation of isTrue() booleanparentResult = super.isTrue();
// negates the parent result return !parentResult; }}
public class Main {
public static void main(String[] args)
{
ChildClass child = new ChildClass();
// calls child implementation
// of isTrue()
boolean result = child.isTrue();
// prints "false" System.out.println(result); } }
Output
false

103
OOPS AND JAVA

2.4.4 Advantages of Using Java Super Keyword

 The super keyword in Java provides many advantages in object-oriented programming are
as follows:
 Enables reuse of code: Using the super keyword allows subclasses to inherit functionality
from their parent classes, which promotes the reuse of code and reduces duplication.
 Supports polymorphism: Because subclasses can override methods and access fields from
their parent classes using super, polymorphism is possible. This allows for more flexible and
extensible code.
 Provides access to parent class behaviour: Subclasses can access and use methods and fields
defined in their parent classes through the super keyword, which allows them to take
advantage of existing behaviour without having to reimplement it.
 Allows for customization of behaviour: By overriding methods and using super to call the
parent implementation, subclasses can customize and extend the behaviour of their parent
classes.
 Facilitates abstraction and encapsulation: The use of super promotes encapsulation and
abstraction by allowing subclasses to focus on their behaviour while relying on the parent
class to handle lower-level details.
 Overall, the super keyword is a key feature of inheritance and polymorphism in Java, and it
provides several benefits for developers seeking to write reusable, extensible, and well-
organized code.

2.5 FINAL CLASS AND METHODS


The final Keyword in Java is used as a non-access modifier applicable only to a variable, a
method, or a class. It is used to restrict a user in Java.
The following are different contexts where the final is used:
• Variable
• Method
•Class
Characteristics of final keyword in Java:

 In Java, the final keyword is used to indicate that a variable, method, or class cannot be
modified or extended. Here are some of its characteristics:

104
Chapter no 2: Inheritance

 Final variables: When a variable is declared as final, its value cannot be changed once
it has been initialized. This is useful for declaring constants or other values that should
not be modified.
 Final methods: When a method is declared as final, it cannot be overridden by a subclass.
This is useful for methods that are part of a class’s public API and should not be modified
by subclasses.
 Final classes: When a class is declared as final, it cannot be extended by a subclass. This
is useful for classes that are intended to be used as is and should not be modified or
extended.
 Initialization: Final variables must be initialized either at the time of declaration or in
the constructor of the class. This ensures that the value of the variable is set and cannot
be changed.
 Performance: The use of a final can sometimes improve performance, as the compiler
can optimize the code more effectively when it knows that a variable or method cannot
be changed.
 Security: The final can help improve security by preventing malicious code from
modifying sensitive data or behavior.
 Overall, the final keyword is a useful tool for improving code quality and ensuring that
certain aspects of a program cannot be modified or extended. By declaring variables,
methods, and classes as final, developers can write more secure, robust, and maintainable
code.

2.5.1. Java Final Variable


When a variable is declared with the final keyword, its value can’t be changed, essentially,
a constant. This also means that you must initialize a final variable.
If the final variable is a reference, this means that the variable cannot be re-bound to reference
another object, but the internal state of the object pointed by that reference variable can be
changed i.e. you can add or remove elements from the final array or final collection.
Example:
public class ConstantExample {
public static void main(String[] args) {
// Define a constant variable PI final double PI = 3.14159;
// Print the value of PI System.out.println("Value of PI: " + PI); }}

105
OOPS AND JAVA

Output
Value of PI: 3.14159
Initializing a final Variable
We must initialize a final variable, otherwise, the compiler will throw a compile-time
error. A final variable can only be initialized once, either via an initializer or an assignment
statement.
There are three ways to initialize a final variable:
We can initialize a final variable when it is declared. This approach is the most common.
A final variable is called a blank final variable if it is not initialized while declaration. Below
are the two ways to initialize a blank final variable. A blank final variable can be initialized
inside an instance-initializer block or the constructor. If you have more than one constructor
in your class then it must be initialized in all of them, otherwise, a compile-time error will be
thrown. A blank final static variable can be initialized inside a static block.
2.5.2. Java final Method
In Java, the final method cannot be overridden by the child class.
Example:
class A {
final void display() { System.out.println("This is a final method.");
}}
class B extends A {
// Cannot override display() here
}
public class Main {
public static void main(String[] args) { B obj = new B();
obj.display(); // Calls the final method from class A
}}
Output:
This is a final method.
2.5.3. Java final Class
In Java, the final class cannot be inherited by another class.
Example:
// create a final class final
class FinalClass {

106
Chapter no 2: Inheritance

public void display() {


System.out.println("This is a final method.");
}}
// try to extend the final class
class Main extends FinalClass {
public voiddisplay() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}}
Output:
This is a final class.
2.5.4 Advantages of final Keyword in Java:
The final keyword in Java provides several advantages, including:
Ensuring immutability: When a variable or reference is marked as final, its value cannot be
changed once it is assigned. This helps ensure that data is immutable and cannot be
accidentally or maliciously modified.
Improving performance: The use of the final can sometimes help improve performance, as
the Java Virtual Machine (JVM) can optimize code more effectively when it knows that
certain values or references cannot be changed.
Making code easier to understand: By declaring variables, methods, or classes as final,
developers can make their code easier to understand and reason about. When a value or
reference is marked as final, it is clear that it will not change, which can simplify code analysis
and debugging.
Promoting code reuse: By declaring methods as final, developers can prevent subclasses
from overriding them. This can help promote code reuse and reduce duplication, as subclasses
must use the parent class’s implementation of the method.
Enhancing security: The use of final can help enhance security by preventing malicious code
from modifying sensitive data or behaviour.
2.6 OBJECT CLASS IN JAVA
The Object class is the parent class of all the classes in java by default. In other words, it is

107
OOPS AND JAVA

the topmost class of java.The Object class is beneficial if you want to refer any object whose
type we don't know. Notice that parent class reference variable can refer the child class object,
known as upcasting.Let's take an example, there is getObject() method that returns an object
but it can be of any type like Employee,Studentetc, 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 and it is described in the Figure2.7:
Object Class in Java.

Figure2.7: Object Class In Java


Table 2.1. Methods and its description
Method Description

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

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

protected Object clone() throws Clone creates and returns the exact copy (clone) of
NotSupported Exception this 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.

108
Chapter no 2: Inheritance

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

2.6.1. toString() Method


The toString() method in Java furnishes a String representation of an object, converting it into
a human- readable format. By default, the toString() method in the Object class generates a
string comprising the class name of the object, an '@' symbol, and the object's hexadecimal
hash code.
Program:
import java.util.*;
public class Main {
int car_no; Main(int car_no){ this.car_no=car_no;
}
// Driver code
public static void main(String args[])
{
Main s = new Main(16);
// Below two statements are equivalent System.out.println(s.toString());
System.out.println(s); }}
Output:
Main@d716361 Main@d716361
Here we can see that when we tried to print the string representation of car_no using toString()
method and print statement, it printed its hexadecimal representation. It was not the desired
result. So, here we have to override the toString() method so that we get the exact value as a
string that the variable has stored.
2.6.2. hashCode() Method
A hash code is an integer value that gets generated by the hashing algorithm. Hash code is
associated with each object in Java and is a distinct value.

109
OOPS AND JAVA

It converts an object's internal address to an integer through an algorithm.


It is not the memory address; it is the integer representation of the memory address.
Another point to be noted is that this method is a Native method.
A native method allows us to use code from another language like C, or C++ in Java.
In Java, we cannot find the memory address of objects, so the hashCode() method is written
in C or C++ which fetches the object's address in Java.
Syntax
public int hashCode() import java.util.*; public class Main {
int car_no; Main(int car_no){ this.car_no=car_no;
}
// Driver code
public static void main(String args[])
{
Main s = new Main(16); System.out.println(s.hashCode());
}
}
Output:
225534817
The above code shows the default behavior of the hashCode() method. Here we have not
overridden the hashCode() method.
It's essential to override the hashCode() method to ensure that each object produces a distinct
number
Example
import java.util.*;
public class Main {
int car_no;
Main(int car_no)
{
this.car_no=car_no;
}
//Overriding the hashCode() @Override public int hashCode() {
return car_no;
}
// Driver code

110
Chapter no 2: Inheritance

public static void main(String args[])


{
Main s = new Main(16);
Main ss = new Main(17);
System.out.println(s.hashCode());
System.out.println(ss.hashCode());
} }
2.6.3. equals (Object obj) Method
This method compares two objects and returns whether they are equal or not. It is used to
compare the value of the object on which the method is called and the object value which is
passed as the parameter.
It is usually recommended to override the hashCode() method whenever this method is
overridden, as it'll ensure that equal objects must have equal hash codes.
Example
public booleanequals(Object obj)
{
return (this == obj);
}
Explanation
The default implementation checks whether the two objects i.e., the object on which the
method is called and the obj object are equal or not. Here equal means whether they are
referring to the same object. If they are the same, it returns true, else it returns false.
2.6.4. getClass() Method
It is used to return the class object of this object. Also, it fetches the actual runtime class of
the object on which the method is called. This is also a native method. It can be used to get
the metadata of the this class. Metadata of a class includes the class name, fields name,
methods, constructor, etc.
Program:
import java.util.*; public class Main {
public static void main(String[] args)
{
Object s = new String("Hi"); Object i= new Integer(19); Class c = s.getClass();
Class d= i.getClass();
//for the String System.out.println("Class of Object s is : " + c.getName());

111
OOPS AND JAVA

//for the integer System.out.println("Class of Object iis : " + d.getName());


}
}
Output:
Class of Object s is :java.lang.String
Class of Object iis :java.lang.Integer
2.6.5. finalize () method
Just before Java's garbage collector reclaims an object, the finalize() method is invoked,
ensuring a last chance for any necessary cleanup tasks when no references to the object
remain. It offers a chance to perform cleanup tasks and release system resources, thereby
reducing memory leaks. For instance, in web applications, it's common practice to use
finalize() to clean up session-related resources in Servlet objects before they are destroyed by
the container. It's important to note that finalize() is called only once on an object, even if it's
eligible for garbage collection multiple times.
Program
public class Resource
{
private int resourceId;
public Resource(int id) {
this.resourceId = id;
}
// Method to simulate resource cleanup
public void cleanup() {
System.out.println("Cleaning up resource " + resourceId);
}
@Override
protected void finalize() {
System.out.println("Finalizing resource " + resourceId);
cleanup();
}
}
public class Test {
public static void main(String[] args) {

112
Chapter no 2: Inheritance

Resource resource1 = new Resource(1);


Resource resource2 = new Resource(2);
// Nullifying references resource1 = null;
resource2 = null;
// Triggering garbage collection System.gc();
System.out.println("End of main");
}
Output:
End of main Finalizing resource 2
Cleaning up resource 2
Finalizing resource 1
Cleaning up resource 1
2.6.6. clone () Method
The clone () method is used to create an exact copy of this object. It makes a new object and
copies all the data of this object to the new object.
Program:
import java.util.*;
class Main implements Cloneable {
// declare variables String name;
int age;
public static void main(String[] args) {
// create an object of Main
class Main obj1 = new Main();
// initialize name and age using obj1
obj1.name = "xyz";
obj1.age = 19;
// print variable System.out.print(obj1.name); // xyz
System.out.println(" "+ obj1.age); // 19
try {
// create clone of obj1
Main obj2 = (Main)obj1.clone();
// print the variables using obj2
System.out.print(obj2.name);

113
OOPS AND JAVA

// xyz System.out.println(" "+ obj2.age); // 19 }


catch (Exception e) {
System.out.println(e);
} }}
2.6.7. wait () Method
The wait () method instructs the current thread to release its lock and enter a sleeping state. It
happens until some different thread enters the same monitor and calls the methods like notify
() or notifyAll() method.
2.6.8. notify () Method
The notify () method is used to wake up only one single thread that is waiting on the object,
and that thread starts the execution. If multiple threads are waiting on the current object (this),
the notify () method will awaken one of them arbitrarily. This method does not return any
value.
2.6.9. notify All () Method
The notifyAll() method awakens all threads currently waiting on the object instance where it's
invoked.It will execute all the threads individually. All threads get the notification but only
one thread gets a lock.
A lock serves as a mechanism to regulate access to a shared resource by multiple threads
simultaneously. So only one thread proceeds with the execution at a time after that next one
will be executed.
2.7 POLYMORPHISM
Polymorphism in Java is a core concept of object-oriented programming (OOP) that allows
objects to be treated as instances of their parent class.
It facilitates flexibility and the ability to define methods in multiple forms. Polymorphism is
primarily achieved through method overriding and method overloading.
Polymorphism is used to perform a single action in different ways. It allows for the
implementation of dynamic method dispatch, where the method to be executed is determined
at runtime. This is beneficial for implementing a cleaner and more maintainable codebase.
2.7.1 Compile-time Polymorphism (Method Overloading)
Achieved by defining multiple methods with the same name but different parameters within
the same class.
2.7.2 Runtime Polymorphism (Method Overriding)
Achieved when a subclass provides a specific implementation of a method already defined in

114
Chapter no 2: Inheritance

its superclass.
2.8 METHOD OVERLOADING
When a class has two or more methods by the same name but different parameters, at the time
of calling based on the parameters passed respective method is called (or respective method
body will be bonded with the calling line dynamically). This mechanism is known as method
overloading.
Advantage of Method Overloading
Method overloading improves the code readability and reduces code redundancy. Method
overloading also helps to achieve compile-time polymorphism.
Example 1: Method Overloading
// Java Example: Compile Time Polymorphism
public class Main {
// method to add two integers
public int addition (int x, int y) {
return x + y;
}
// method to add three integers
public int addition (int x, int y, int z) {
return x + y + z;
}
// method to add two doubles
public double addition (double x, double y) {
return x + y;
}
// Main method
public static void main (String [] args) {
// Creating an object of the Main method Main number = new Main ();
// calling the overloaded methods
int res1 = number.addition(444, 555);
System.out.println("Addition of two integers: " + res1);
int res2 = number.addition(333, 444, 555);
System.out.println("Addition of three integers: " + res2);
double res3 = number.addition(10.15, 20.22);
System.out.println("Addition of two doubles: " + res3);

115
OOPS AND JAVA

}}
Output
Addition of two integers: 999
Addition of three integers: 1332
Addition of two doubles: 30.369999999999997
In this example, the add method is overloaded with two different parameter lists. The
appropriate method is called based on the arguments passed.
Different Ways of Java Method Overloading
Method overloading can be achieved using following ways while having same name methods
in a class.
Use different number of arguments
Use different type of arguments
2.8.1 Method Overloading: Different Number of Arguments
We can implement method overloading based on the different number of arguments.
Example: Different Number of Arguments (Static Methods)
In this example, we've created a Calculator class having two static methods with same name
but different arguments to add two and three int values respectively. In main() method, we're
calling these methods and printing the result. Based on the type of arguments passed, compiler
decides the method to be called and result is printed accordingly.
Program:
class Calculator {
public static int add (int a, int b)
{
return a + b;
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}
public class Tester {
public static void main (String args[]) {
System.out.println(Calculator.add(20, 40));

116
Chapter no 2: Inheritance

System.out.println(Calculator.add(40, 50, 60));


}
}
Example: Different Number of Arguments (Non-Static Methods)
In this example, we've created a Calculator class having two non-static methods with same
name but different arguments to add two and three int values respectively. In main () method,
we're calling these methods using object of Calculator class and printing the result. Based on
the number of arguments passed, compiler decides the method to be called and result is printed
accordingly
class Calculator {
public int add(int a, int b){
return a + b;
}
public int add(int a, int b, int c){
return a + b + c;
}}
public class Tester {
public static void main(String args[]){
Calculator calculator = new Calculator();
System.out.println(calculator.add(20, 40));
System.out.println(calculator.add(40, 50, 60));
}}
2.8.2 Method Overloading: Different Type of Arguments
We can implement method overloading based on the different type of arguments.
Example: Different Type of Arguments
In this example, we've created a Calculator class having two non-static methods with same
name but different types of arguments to add two int values and two double values
respectively.
In main () method,
we're calling these methods using object of Calculator class and printing the result. Based on
the type of arguments passed, compiler decides the method to be called and result is printed
accordingly.
Program:
class Calculator{

117
OOPS AND JAVA

public int add(int a, int b){ return a + b;


}
public double add(double a, double b){ return a + b;
}
}
public class Tester {
public static void main(String args[]){ Calculator calculator = new Calculator();
System.out.println(calculator.add(20, 40));
System.out.println(calculator.add(20.0, 40.0));
}
}
Output
60
60.0
2.9 METHOD OVERRIDING:
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
In other words, if a subclass provides the specific implementation of the method that has been
declared by one of its parent classes, it is known as method overriding.
Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a method that is already
provided by its superclass.
• Method overriding is used for runtime polymorphism.
• Method overriding allows subclasses to reuse and build upon the functionality provided by
their superclass, reducing redundancy and promoting modular code design.
• Subclasses can override methods to tailor them to their specific needs or to implement
specialized behaviour that is unique to the subclass.
• Method overriding enables dynamic method dispatch, where the actual method
implementation to be executed is determined at runtime based on the type of object,
supporting flexibility and polymorphic behaviour.
Rules for Java Method Overriding
Same Method Name: The overriding method in the subclass must have the same name as the
method in the superclass that it is overriding.

118
Chapter no 2: Inheritance

Same Parameters: The overriding method must have the same number and types of
parameters as the method in the superclass. This ensures compatibility and consistency with
the method signature defined in the superclass.
IS-A Relationship (Inheritance): Method overriding requires an IS-A relationship between
the subclass and the superclass. This means that the subclass must inherit from the superclass,
either directly or indirectly, to override its methods.
Same Return Type or Covariant Return Type: The return type of the overriding method
can be the same as the return type of the overridden method in the superclass, or it can be a
subtype of the return type in the superclass. This is known as the covariant return type,
introduced in Java 5.
Access Modifier Restrictions: The access modifier of the overriding method must be the
same as or less restrictive than the access modifier of the overridden method in the superclass.
Specifically, a method declared as public in the superclass can be overridden as public or
protected but not as private. Similarly, a method declared as protected in the superclass can
be overridden as protected or public but not as private. A method declared as default (package-
private) in the superclass can be overridden with default, protected, or public, but not as
private.
Output
Addition of two integers: 999
Addition of three integers: 1332
Addition of two doubles: 30.369999999999997
Methods declared as final in the superclass cannot be overridden in the subclass. This is
because final methods cannot be modified or extended.
No Static Methods: Static methods in Java are resolved at compile time and cannot be
overridden. Instead, they are hidden in the subclass if a method with the same signature is
defined in the subclass.
Example of Method Overriding
// Java Example: Run Time Polymorphism
class Vehicle {
public void displayInfo() {
System.out.println("Some vehicles are there.");
}
}
class Car extends Vehicle {

119
OOPS AND JAVA

// Method overriding
public void displayInfo() {
System.out.println("I have a Car.");
}
}
class Bike extends Vehicle {
// Method overriding
public void displayInfo() {
System.out.println("I have a Bike.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v1 = new Car();
// Upcasting Vehicle v2 = new Bike();
// Upcasting
// Calling the overridden displayInfo() method of Car class
v1.displayInfo();
// Calling the overridden displayInfo() method of Bike class
v2.displayInfo();
}
}
Output:
I have a Car. I have a Bike.
2.10 CONSTRUCTOR OVERLOADING:
A constructor in Java is similar to a method that is invoked when an object of the class is
created. Unlike Java methods, a constructor has the same name as that of the class and does
not have any return type.
For example,
class Test {
Test () {
// constructor body
}
}

120
Chapter no 2: Inheritance

Here, test () is a constructor. It has the same name as that of the class and doesn't have a return
type.
Example: Java Constructor
class Main {
private String name;
// constructor
Main () {
System.out.println("Constructor Called:");
name = "Programiz";
}
public static void main (String [] args) {
// constructor is invoked while
// creating an object of the Main class Main obj = new Main ();
System.out.println("The name is " + obj.name);
}}
Output:
Constructor Called:
The name is Programiz
In the above example, we have created a constructor named Main (). Inside the constructor,
we are initializing the value of the name variable. Notice the statement creating an object of
the Main class.
Main obj = new Main ();
Here, when the object is created, the Main () constructor is called. And the value of the name
variable is initialized.
Hence, the program prints the value of the name variables as Programiz.
Types of Constructors
In Java, constructors can be divided into three types:
• No-Argument Constructor
• Parameterized Constructor
• Default Constructor
2.10.1. Java No-Argument Constructors
Similar to methods, a Java constructor may or may not have any parameters (arguments). If a
constructor does not accept any parameters, it is known as a no-argument constructor.
For example,

121
OOPS AND JAVA

private Constructor() {

// body of the constructor

class Main {
int i;

// constructor with no parameter private Main () {


i = 5;
System.out.println("Constructor is called");
}
public static void main (String [] args) {
// calling the constructor without any parameter Main
obj = new Main ();
System.out.println("Value of i: " + obj.i);
}
}
In the above example, we have created a constructor Main (). Here, the constructor does not
accept any parameters. Hence, it is known as a no-arg constructor.
We have declared the constructor as private.Once a constructor is declared private, it cannot be
accessed from outside the class.So, creating objects from outside the class is prohibited using the
private constructor.
Here, we are creating the object inside the same class. Hence, the program is able to access the
constructor. To learn more, visit Java Implement Private Constructor.
However, if we want to create objects outside the class, then we need to declare the constructor
as public.
Example: Java Public no-arg Constructors
class Company {
String name;
// public constructor
public Company() {
name = "KAHE";
}
class Main {

122
Chapter no 2: Inheritance

public static void main(String[] args) {


// object is created in another class Company obj = new Company();
System.out.println("Company name = " + obj.name);
}}
2.10.2. Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructors with parameters).
Example: Parameterized Constructor
class Main {
String languages;
// constructor accepting single value Main(String lang)
{
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Output
Java Programming Language
Python Programming Language
C Programming Language
In the above example, we have created a constructor named Main (). Here, the constructor
takes a single parameter. Notice the expression: Main obj1 = new Main("Java");
Here, we are passing the single value to the constructor.
Based on the argument passed, the language variable is initialized inside the constructor.
2.10.3. Java Default Constructor
If we do not create any constructor, the Java compiler automatically creates a no-arg
constructor during the execution of the program.This constructor is called the default

123
OOPS AND JAVA

constructor.
Example: Default Constructor
class Main {
int a; boolean b;
public static void main (String [] args) {
// calls default constructor Main
obj = new Main ();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}}
Output
Default Value:
a=0
b = false
Here, we haven't created any constructors. Hence, the Java compiler automatically creates the
default constructor. The default constructor initializes any uninitialized instance variables
with default values.
Type Default Value
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
object Reference null
In the above program, the variables a and b are initialized with default value 0 and false
respectively. The above program is equivalent to:
class Main {
int a;
boolean b;
Main() {

124
Chapter no 2: Inheritance

a = 0;
b = false;
}
public static void main(String[] args) {
// call the constructor Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output
Default Value:
a=0
b = false
Important Notes on Java Constructors
• Constructors are invoked implicitly when you instantiate objects.
• The two rules for creating a constructor are:
• The name of the constructor should be the same as the class.
• A Java constructor must not have a return type.
• If a class doesn't have a constructor, the Java compiler automatically creates a default
constructor during run-time. The default constructor initializes instance variables with default
values. For example, the int variable will be initialized to 0
• Constructor types:
• No-Arg Constructor - a constructor that does not accept any arguments
• Parameterized constructor - a constructor that accepts arguments
• Default Constructor - a constructor that is automatically created by the Java compiler if it is
not explicitly defined.
• A constructor cannot be abstract or static or final.
• A constructor can be overloaded but cannot be overridden.
• Similar to Java method overloading, we can also create two or more constructors with
different parameters. This is called constructor overloading.
Example: Java Constructor Overloading
class Main {
String language;

125
OOPS AND JAVA

// constructor with no parameter


Main() {
this.language = "Java";
}
// constructor with a single parameter
Main(String language) {
this.language = language;
}
public void getName() {
System.out.println("Programming Language: " + this.language);
}
public static void main(String[] args) {
// call constructor with no parameter Main
obj1 = new Main();
// call constructor with a single parameter Main obj2 = new Main("Python"); obj1.getName();
obj2.getName();
}}
Output
Programming Language: Java
Programming Language: Python
In the above example, we have two constructors: Main() and Main(String language).
Here, both the constructors initialize the value of the variable language with different values.
Based on the parameter passed during object creation, different constructors are called, and
different values are assigned. It is also possible to call one constructor from another
constructor.
2.11 Dynamic Method Dispatching or Runtime polymorphism
Dynamic Method Dispatch is a fundamental concept in Java, enabling polymorphism one of
the four pillars of Object-Oriented Programming. It refers to the process by which a method
call to an overridden method is resolved at runtime, rather than compile-time.
Dynamic Binding
• Java uses dynamic binding for method invocation. This means that the method to be called
is determined at runtime based on the actual object, not on the type of reference variable.
• The “actual object” refers to the specific instance of a class. It is the concrete object that has

126
Chapter no 2: Inheritance

been created by the new keyword followed by the constructor of the class.
•The “type of the reference variable,” on the other hand, is the type that you declare for a
variable that will hold a reference to an object. It dictates what methods and properties you
can call on the object that the variable refers.
2.12 GARBAGE COLLECTION:
Garbage collection in Java is an automatic memory management process that helps Java
programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual
Machine (JVM).
When Java programs run on the JVM, objects in the heap, which is a portion of memory
dedicated to the program.
Eventually, some objects will no longer be needed.
The garbage collector finds these unused objects and deletes them to free up memory.
In C/C++, programmers have to manually create and delete objects, which can sometimes
lead to memory leaks and errors when there isn’t enough memory available. This happens
when unused objects are not deleted properly.
In Java, this process is automated. The garbage collector automatically finds and removes
objects that are no longer needed, freeing up memory in the heap.
It runs in the background as a daemon thread, helping to manage memory efficiently without
requiring the programmer’s constant attention.
Working of Garbage Collection
• Java garbage collection is an automatic process that manages memory in the heap.
• It identifies which objects are still in use (referenced) and which are not in use
(unreferenced).
• Unreferenced objects can be deleted to free up memory.
• The programmer does not need to mark objects to be deleted explicitly.
Types of Activities in Java Garbage Collection
Two types of garbage collection activity usually happen in Java. These are:
Minor or incremental Garbage Collection: This occurs when unreachable objects in the Young
Generation heap memory are removed.
Major or Full Garbage Collection: This happens when objects that survived minor garbage
collection are removed from the Old Generation heap memory. It occurs less frequently than
minor garbage collection.
Important Concepts on Garbage Collection

127
OOPS AND JAVA

2.12.1. Unreachable Objects


An object is said to be unreachable if it doesn’t contain any reference to it. Note: Objects
which are part of the island of isolation are also unreachable.
Integer i = new Integer (4);
// the new Integer object is reachable via the reference in ‘i’ i = null;
// the Integer object is no longer reachable and it is described in the Figure 2.8: Unreachable
Objects.

Figure 2.8: Unreachable Objects


2.12.2. Eligibility for Garbage Collection
An object is said to be eligible for garbage collection if it is unreachable. After i = null, integer
object 4 in the heap area is suitable for garbage collection in the above image.
How to Make an Object Eligible for Garbage Collection?
Even though the programmer is not responsible for destroying useless objects but it is highly
recommended to make an object unreachable (thus eligible for GC) if it is no longer required.
There are generally four ways to make an object eligible for garbage collection.
• Nullifying the reference variable: Set the reference to null.
• Re-assigning the reference variable: Assign a new object to the reference.
• An object created inside the method: Objects created within a method are eligible for
garbage collection once the method completes.
•Island of Isolation: Objects that are isolated and not referenced by any reachable objects.
Ways to Request JVM to Run Garbage Collection
Once an object is eligible for garbage collection, it may not be destroyed immediately. The

128
Chapter no 2: Inheritance

garbage collector runs at the JVM’s discretion, and you cannot predict when it will occur.
We can also request JVM to run Garbage Collector. There are two ways to do it:
Using System.gc(): This static method requests the JVM to perform garbage collection.
Using Runtime.getRuntime().gc(): This method also requests garbage collection through the
Runtime class.
2.12.3. Finalization
Before destroying an object, the garbage collector calls the finalize () method to perform
cleanup activities. The method is defined in the Object class as follows:
protected void finalize () throws Throwable
• The finalize () method is called by Garbage Collector, not JVM.
• The default implementation of finalize () is empty, so overriding it is recommended for
resource cleanup.
• The finalize () method is called only once per object.
• If an uncaught exception is thrown by the finalize () method, the exception is ignored, and
the finalization of that object terminates.
Advantages of Garbage Collection in Java
It makes java memory-efficient because the 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 extra effort.
Example for Garbage Collection
public class GarbageExample {
public void finalize() {
System.out.println("Object is garbage collected"); }
public static void main(String[] args) {
GarbageExample obj1 = new GarbageExample();
GarbageExample obj2 = new GarbageExample();
obj1 = null; // Eligible for garbage collection
obj2 = null; // Eligible for garbage collection
System.gc(); // Suggest JVM to run Garbage Collector
}}
Output:
Object is garbage collected Object is garbage collected.

129
OOPS AND JAVA

2.13 STRING CLASS


Java string class implements the following properties:
2.13.1. Serializable (Interface)
Allows a String object to be converted into a byte stream, enabling it to be saved or
transmitted.
String & Serializable:
String implements Serializable so it can be saved to files or sent over networks.
2.13.2. Comparable (Interface)
Provides natural ordering by implementing compareTo() method.
String & Comparable:
String implements Comparable<String>, allowing strings to be sorted alphabetically.
2.13.3.CharSequence (Interface)
Defines a readable sequence of characters with methods like length(), charAt(), and
subSequence().
String &CharSequence:
String implements CharSequence, meaning it can be used wherever CharSequence is
expected. It provides a lot of methods to perform operations on strings such as:
compareTo()
The compareTo() method compares two strings lexicographically and returns 0 if equal, a
negative value if the first is smaller, and a positive value if it's larger.
System.out.println("apple".compareTo("banana"));//Output:negativevalue
System.out.println("apple".compareTo("apple")); // Output: 0
concat()
Combines two strings into one.
String a = "Hello ";
String b = a.concat("World!");
equals ()
Compares two strings for value equality.
String a = "test";
boolean result = a.equals("test");
split ()
Splits a string into an array based on a delimiter.
String data = "apple,banana,grape";

130
Chapter no 2: Inheritance

String [] fruits = data.split(",");


length ()
Returns the number of characters in the string.
String a = "Hello";
int len = a.length();
replace ()
Replaces characters or substrings with another value.
String a = "apple";
String b = a.replace("p", "b");
intern ()
Returns the canonical representation from the string pool.
String a = new String("hello");
String b = a.intern();
substring ()
Extracts a portion of the string.
String a = "HelloWorld";
String b = a.substring(0, 5);
2.14 STRINGBUFFER CLASS
A mutable sequence of characters, used to modify strings without creating new objects
(thread-safe). Methods of String Buffer class include:
1.append()
Explanation: Adds text at the end of the current content.
Example:
StringBuffer sb = new StringBuffer("Hello"); sb.append(" World");
2.insert()
Explanation: Inserts text at a specified position.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " Java");
3.replace()
Explanation: Replaces characters between two indexes with new text.
Example:
StringBuffer sb = new StringBuffer("Hello Java"); sb.replace(6, 10, "World");

131
OOPS AND JAVA

4.delete()
Explanation: Removes characters from a specified start to end index.
Example:
StringBuffer sb = new StringBuffer("Hello World"); sb.delete(5, 11);
5.reverse()
Explanation: Reverses the sequence of characters in the buffer.
Example:
StringBuffer sb = new StringBuffer("Hello"); sb.reverse();
6.capacity()
Explanation: Returns the current capacity (allocated size) of the buffer.
Example:
StringBuffer sb = new StringBuffer(); int cap = sb.capacity();
7.charAt()
Explanation: Returns the character at a specific index.
Example:
StringBuffer sb = new StringBuffer("Hello"); char ch = sb.charAt(1);
8.setCharAt()
Explanation: Sets a character at a specific index.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.setCharAt(1, 'a');
2.15 STRING BUILDER CLASS
A mutable sequence of characters like StringBuffer but not thread-safe, making it faster for
single-threaded use.
Methods of String Builder class include:
1.append()
Explanation: Adds text at the end of the current content.
Example:
StringBuilder sb = new StringBuilder("Hello"); sb.append(" World");
2.insert()
Explanation: Inserts text at a specified index.
Example:
StringBuilder sb = new StringBuilder("Hello"); sb.insert(5, " Java");

132
Chapter no 2: Inheritance

3.replace()
Explanation: Replaces characters between start and end indexes with given text.
Example:
StringBuilder sb = new StringBuilder("Hello Java"); sb.replace(6, 10, "World");
4.delete()
Explanation: Removes characters from a specified range.
Example:
StringBuilder sb = new StringBuilder("Hello World"); sb.delete(5, 11);
5.reverse()
Explanation: Reverses the character sequence in the builder.
Example:
StringBuilder sb = new StringBuilder("Hello"); sb.reverse();
6.capacity()
Explanation: Returns the current capacity (internal buffer size).
Example:
StringBuilder sb = new StringBuilder(); int cap = sb.capacity();
7.charAt()
Explanation: Returns the character at a specific position.
Example:
StringBuilder sb = new StringBuilder("Hello"); char ch = sb.charAt(1);
8.setCharAt()
Explanation: Replaces the character at a given index.
Example:
StringBuilder sb = new StringBuilder("Hello"); sb.setCharAt(1, 'a');

133
OOPS AND JAVA

CHAPTER III
DATA ABSTRACTION
3.1 Packages
• A package is a physical folder structure (directory) that contains a group of related classes,
interfaces, and sub-packages according to their functionality.

3.2 Introduction to Packages


• It provides a convenient way to organize a work.
• A Java package is a group of similar types of classes, interfaces and sub-packages.

3.2.1 Types of Java Packages

Figure 3.1: Types of Java Packages


• Built-in Packages: Provided by Java API for various functionalities.
Example: java.util, java.io, java.net

• User-defined Packages: Created by developers to organize custom classes.

Figure 3.2: Built-in Packages

134
Chapter 3: Data Abstraction

3.2.2 Realtime Example of Packages in Java


• A real-life example is when we download a movie, song, or game, we make a different folder
for each category, like movie, song, etc. In the same way, a group of packages in Java is just
like a library.

• The classes and interfaces of a package are like books in the library that can reuse several
times when we need them. This reusability nature of packages makes programming easy.

• Therefore, when we create any software or application in Java programming language, they
contain hundreds or thousands of individual classes and interfaces. So, they must be organized
into a meaningful package name to make proper sense, and reusing these packages in other
programs could be easier.

3.2.3 Advantage of using Packages in Java


1. Maintenance: Packages in Java are used for proper maintenance.

2. Reusability: We can place the common code in a common folder so that everybody can
check that folder and use it whenever needed.

3. Name conflict: Packages help to resolve the naming conflict between the two classes with
the same name. Assume that there are two classes with the same name Student.java. Each
class will be stored in its own packages, such as stdPack1 and stdPack2 without having any
conflict of names.

4. Organized: It also helps in organizing the files within a project.

5. Access Protection: A package provides access protection. It can be used to provide


visibility control. The members of the class can be defined in such a manner that they will be
visible only to elements of that package.

3.2.4 Built-in Java Packages (Pre-Defined Package)


• Predefined packages in Java are those which are developed by the Sun Microsystem. They
are also called built-in packages.

• These packages consist of a large number of predefined classes, interfaces, and methods that
are used by the programmer to perform any task in his programs.

• These packages offer utilities for file handling, networking, data structures and more.
• To use a class or a package from the library, we need to use the import keyword.

import package.name.Class; // Import a single class


135
OOPS AND JAVA

import package.name. *; // Import the whole package

• Java APIs contains the following predefined packages, as shown in the below Figure.3.3:
Predefined packages in Java.

Figure 3.3: Predefined packages in Java


Some of the commonly used built-in packages are:

• java.lang: Contains language support classes(e.g classes which defines primitive data types,
math operations). This package is automatically imported.

• java.io: Contains classes for supporting input / output operations.

• java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.

• java.applet: Contains classes for creating Applets.

• java.awt: Contain classes for implementing the components for graphical user interfaces
(like button;menus etc).

• java.net: Contain classes for supporting networking operations.

Example: Using java.util package


import java.util.ArrayList;

public class Main {


public static void main(String[] args) {

136
Chapter 3: Data Abstraction

// Using ArrayList from java.util package ArrayList<String>

list = new ArrayList<>(); list.add("Java");

list.add("Packages"); System.out.println(list);
}

Output:
[Java, Packages]

3.3 User Defined Package


Creating a User-Defined Package

3.3.1 Steps to Create and Use a Package:


• Create the Package: Use the package keyword at the top of the class file.

• Compile the Package: Compile the file using javac -d to specify the package directory.

• Use the Package: Import the package in other classes using the import statement.

Example: Create a package


package MyPackage;

public class MyClass {

public void displayMessage() {

System.out.println("This is a user-defined package.");

}
}

// Save this file as MyPackage/MyClass.java

Compile the Package


javac -d . MyClass.java

Use the Package


import MyPackage.MyClass;

public class Main {

public static void main (String [] args) {

MyClass obj = new MyClass();


obj.displayMessage();

137
OOPS AND JAVA

}}

Output:
This is a user-defined package.

Example 2:
Create a package “animals”

package animals; interface Animal {

public void eat(); public void travel();

3.3.2 Utilize the package


/* File name : MammalInt.java */

package animals;

public class MammalInt implements Animal {

public void eat() {

System.out.println("Mammal eats");

public void travel() {


System.out.println("Mammal travels");

public int noOfLegs() {

return 0;

public static void main(String args[]) {

MammalInt m = new MammalInt(); m.eat();

m.travel();

interface Animal {

public void eat();


public void travel();

138
Chapter 3: Data Abstraction

3.3.3 Compile the java files


• A package/folder with the name animals will be created in the current directory

• Execute the class file within the package and get the result as shown below

3.4 Accessing Package


There are three ways to access the package from outside the package.

• import packagename.*;

• import package.classname;

• fully qualified name.

3.4.1 Using packagename. *


• If you use packagename. * 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 filename as A.java

// Create a package pack package pack;

public class A{

public void msg(){

System.out.println("Hello");}

//Save filename as B.java

// Create a package mypack package mypack;

import pack.*;

class B{

public static void main(String args[]){


A obj = new A();

obj.msg();
}

139
OOPS AND JAVA

Output:
Hello

3.4.2 Using packagename.classname


//Save filename as A.java

// Create a package pack package pack;

public class A{

public void msg(){

System.out.println("Hello");}

//Save filename as B.java

// Create a package mypack package mypack;

import pack.A; class B{

public static void main(String args[]){ A obj = new A();

obj.msg(); } }

Output:
Hello

3.4.3 Using fully qualified name


• If we use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But we 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


• If we import a package, subpackages will not be imported.

• If we import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, we need to import the
subpackage as well.

• Sequence of the program must be package then import then class.

140
Chapter 3: Data Abstraction

3.5 Abstract Classes and Methods


• Data abstraction is the process of hiding certain details and showing only essential
information to the user.

• Abstraction can be achieved with either abstract classes or interfaces.

• The abstract keyword is a non-access modifier, used for classes and methods:

1. Abstract class: is a restricted class that cannot be used to create objects (to access it, it must
be inherited from another class).

2. Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).

3.5.1 Key Features of Abstract Classes

• Abstract Methods: Abstract classes can have abstract methods, which are declared without
a body. Subclasses must provide concrete implementations for these methods.

• Concrete Methods: Abstract classes can also contain concrete methods with defined
behavior. Subclasses inherit these methods along with their implementations.

• Cannot be Instantiated: Abstract classes cannot be instantiated directly. They serve as a


blueprint for other classes and must be extended to be used.

• Can Have Constructors: Abstract classes can have constructors, which are invoked when
a subclass object is created. These constructors are used to initialize the state of the abstract
class.

Why use Abstract Classes?

Abstract classes are beneficial in various scenarios, including:

• Code Reusability: Abstract classes facilitate code reuse by allowing common methods to be
implemented once and inherited by multiple subclasses.

• Defining a Common Interface: Abstract classes can define a common interface for a group
of related classes, ensuring consistency in their structure and behavior.

• Enforcing Method Implementation: Abstract classes can enforce the implementation of


certain methods by declaring them as abstract, thereby ensuring that subclasses provide
necessary functionality.

141
OOPS AND JAVA

Syntax:

Abstract Class
abstract class ClassName {

// Abstract methods abstract void methodName();

// Concrete methods void concreteMethod() {

// Method body

Example:
abstract class Animal {

public abstract void animalSound();

public void sleep() {

System.out.println("Zzz");

To access the abstract class, it must be inherited from another class


// Create an Abstract class

abstract class Animal {

// Create Abstract method animalSound that does not have a body

public abstract void animalSound();

// create a Regular method that has statements

public void sleep() {

System.out.println("Zzz"); }}

// Subclass (inherit from Animal)

class Pig extends Animal

public void animalSound()

{
// The body of animalSound() is provided here in inherited class

142
Chapter 3: Data Abstraction

System.out.println("The pig says: wee wee");

}}

// Create the main file class AnimalClasses {


public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

}}

Output:
• The pig says: wee wee

• Zzz

3.5.2 Abstract Class: Having Constructor, Data Member and Methods:


An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main () method.

Example
//Example of an abstract class that has abstract and non-abstract methods

abstract class Bike {

// create a constructor Bike Bike ()

{
System.out.println("bike is created");

}
// create an abstract method run ()

abstract void run ();

// create a method changeGear()

void changeGear()

System.out.println("gear changed");

}
} // End of abstract class Bike

143
OOPS AND JAVA

//Creating a Child class which inherits Abstract class

class Honda extends Bike {

void run()

System.out.println("running safely..");

//Creating a Main class which calls abstract and non-abstract methods public class Vehicle {
public static void main(String args[])

Bike obj = new Honda();

obj.run();

obj.changeGear();

Output:
bike is created running safely

gear changed

Rule: If there is an abstract method in a class, that class must be abstract. class Bike12{

abstract void run(); }

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

144
Chapter 3: Data Abstraction

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

public class InterfaceMain{

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

3.6 Interface
• An Interface in Java programming language is defined as an abstract type used to specify
the behaviour of a class.

3.7 Defining an interface


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


145
OOPS AND JAVA

• There can be only abstract methods in the Java interface, not method body.

• It is used to achieve abstraction and multiple inheritance in Java.

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

Why use Java interface?


There are mainly three reasons to use interface.

• It is used to achieve abstraction.


• By interface, we can support the functionality of multiple inheritance.

• It can be used to achieve loose coupling.

How to declare an interface?


• An interface is declared by using the interface keyword.

• It provides total abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default.

• A class that implements an interface must implement all the methods declared in the
interface.

Advantages of Interfaces
• Without bothering about the implementation part, we can achieve the security of the
implementation.

• In Java, multiple inheritances are not allowed, however, you can use an interface to make
use of it as you can implement more than one interface.

Syntax:
interface <interface_name>

// declare constant fields

// declare methods that abstract


// by default.

Example:
interface Animal

146
Chapter 3: Data Abstraction

void eat();

void sleep();
}
In this example, the Animal interface declares two method signatures: eat () and sleep (). Any
class implementing the Animal interface must provide concrete implementations for these
methods.

Example
interface Language {

public void getType();

public void getVersion();


}

Here,Language is an interface.It includes abstract methods: getType() and getVersion().

• Implementing an Interface Like abstract classes, we cannot create objects of interfaces.

• To use an interface, other classes must implement it.


• We use the implements keyword to implement an interface.

Example: Java Interface


interface Polygon {

void getArea(int length, int breadth);

// implement the Polygon interface

class Rectangle implements Polygon {

// implementation of abstract method


public void getArea(int length, int breadth) {

System.out.println("The area of the rectangle is " + (length * breadth));

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

147
OOPS AND JAVA

Rectangle r1 = new Rectangle();

r1.getArea(5, 6);

Output
The area of the rectangle is 30

In the above example, an interface named Polygon is created. The interface contains an abstract
method getArea().

Here, the Rectangle class implements Polygon. And, provides the implementation of the
getArea() method.

Example 2: Java Interface


// create an interface

interface Language {

void getName(String name);

// class implements interface

class ProgrammingLanguage implements Language {

// implementation of abstract method public void getName(String name) {

System.out.println("Programming Language: " + name);

}}

class programMain {

public static void main(String[] args) {


ProgrammingLanguage language = new ProgrammingLanguage();
language.getName("Java");

}}

Output
Programming Language: Java

In the above example, we have created an interface named Language. The interface includes an
abstract method getName().

148
Chapter 3: Data Abstraction

Here, the Programming Language class implements the interface and provides the
implementation for the method.

3.8 Implementing Multiple Interfaces


In Java, a class can also implement multiple interfaces. For example,

interface A {

// members of A} interface B {

// members of B}

class C implements A, B {

// abstract members of A

// abstract members of B
}

3.9 Extending an Interface


• One interface can inherit another by the use of keyword extends.

• When a class implements an interface that inherits another interface, it must provide an
implementation for all methods required by the interface inheritance chain.

Syntax - interface
interface Line {

// members of Line interface

// extending interface

interface Polygon extends Line {

// members or methods of Polygon interface

// members or methods of Line interface

}
Here, the Polygon interface extends the Line interface. Now, if any class implements Polygon,
it should provide implementations for all the abstract methods of both Line and Polygon.

3.9.1 Extending Multiple Interfaces


An interface can extend multiple interfaces. For example,

149
OOPS AND JAVA

interface A {

...

interface B {
...

interface C extends A, B {

...
}

3.9.2 Level wise -Implementation


In general, the development process is executed in different Levels:
• Level 1 – interfaces: It contains the service details.

• Level 2 – abstract classes: It contains partial implementation.

• Level 3 – implementation classes: It contains all implementations.

• Level 4 – Final Code / Main Method: It have access of all interfaces data.

Example
// Level 1 interface Bank {

void deposit ();

void withdraw ();

void loan ();

void account ();

// Level 2

abstract class Dev1 implements Bank {

public void deposit ()

System.out.println("Your deposit Amount:" + 100);

}
abstract class Dev2 extends Dev1 {
150
Chapter 3: Data Abstraction

public void withdraws ()

System.out.println("You withdraw Amount:" + 50);


}

// Level 3

class Dev3 extends Dev2 {

public void loan() {}

public void account() {}

// Level 4
class exampleMain

public static void main(String[] args)

Dev3 d = new Dev3();

d.account();

d.loan();
d.deposit();

d.withdraw();

}}

Output
Your deposit Amount :100 You withdraw Amount :50

Example 1:
sqrt function
import java.lang.Math; interface Polygon

{
void getArea();
// calculate the perimeter of a Polygon default

151
OOPS AND JAVA

void getPerimeter(int sides)

int perimeter = 0; for (int side: sides) {

perimeter += side;

System.out.println("Perimeter: " + perimeter);

}
class Triangle implements Polygon {

private int a, b, c;

private double s, area;

// initializing sides of a triangle Triangle (int a, int b, int c)

this.a = a;

this.b = b; this.c = c;

s = 0;

// calculate the area of a triangle public void getArea() {

s = (double) (a + b + c)/2;

area = Math.sqrt(s*(s-a)*(s-b)*(s-c));

System.out.println("Area: " + area);


}

}
class polygonMain

public static void main(String[] args) {

Triangle t1 = new Triangle(2, 3, 4);

// calls the method of the Triangle


class t1.getArea();

152
Chapter 3: Data Abstraction

// calls the method of Polygon

t1.getPerimeter(2, 3, 4);

} }

Output
Area: 2.9047375096555625

Perimeter: 9

Example 2:
class Triangle implements Polygon {

private int a, b, c;

private double, area;

// initializing sides of a triangle Triangle (int s1, int s2, int s3) {

a = s1;

b = s2;

c = s3; s = 0;

// calculate the area of a triangle

public void getArea() {

s = (double) (a + b + c)/2;

area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("Area: " + area);

class PolygonMain {

public static void main(String[] args) {

Triangle t1 = new Triangle(2, 3, 4);

// calls the method of the Triangle

class t1.getArea();

// calls the method of Polygon


t1.getPerimeter(2, 3, 4);

153
OOPS AND JAVA

Output
Area: 2.9047375096555625

Perimeter: 9

• In the above program, we have created an interface named Polygon. It includes a default
method getPerimeter() and an abstract method getArea().

• We can calculate the perimeter of all polygons in the same manner so we implemented the
body of getPerimeter() in Polygon.

• Any class that implements Polygon must provide an implementation of getArea().

Difference Between Class and Interface


Although Class and Interface seem the same there are certain differences between Classes and
Interface.

Table: Differences between a class and an interface


Features Class Interface
Instantiation In class, you can create an object. In an interface, you can’t
create an object
Variables Class can have instance variables Variables are public static
final (constants
only).
Methods Class can have concrete methods In an interface, methods are
abstract by default
Inheritance It supports single inheritance Supports multiple inheritance

Constructors Can have constructors. No constructors allowed.


Access Modifiers Supports private, protected, public, In an interface, all members
default. are public by default

Keyword Defined using class. Defined using interface.


Default Methods It does not support default methods It supports default methods
(JDK 8+)
Static Methods Can have static methods. Supports static methods (JDK
8+)
Private Methods Can have private methods. Supports private methods
(JDK 9+).
Main Method Can have main () for execution. Can have main () (since
JDK 8, as static methods are
allowed).

154
Chapter 3: Data Abstraction

When to Use Class and Interface?


• Use a Class when:

o Use a class when you need to represent a real-world entity with attributes (fields) and
behaviors (methods).

o Use a class when you need to create objects that hold state and perform actions

o Classes are used for defining templates for objects with specific functionality and properties.

• Use a Interface when:

o Use an interface when you need to define a contract for behaviour that multiple classes can
implement.

o Interface is ideal for achieving abstraction and multiple inheritance.

Implementation: To implement an interface, we use the keyword implements


Example of Vehicles like bicycles, cars, and bikes share common functionalities, which can be
defined in an interface, allowing each class (e.g., Bicycle, Car, Bike) to implement them in its
own way.

This approach ensures

• code reusability

• scalability

• consistency
Example: The example demonstrates how an interface can be used to define common behavior
for different classes (Bicycle and Bike) that implement the interface.

import java.io.*;

interface Vehicle {

// Abstract methods defined void changeGear(int a);

void speedUp(int a);

void applyBrakes(int a);

// Class implementing vehicle interface


class Bicycle implements Vehicle {

int speed;
int gear;

155
OOPS AND JAVA

// method change Gear overrides from Vehicle class

public void changeGear(int newGear){

gear = newGear;

// method Increase speed overrides from Vehicle class

public void speedUp(int increment) {

speed = speed + increment;

}
public void applyBrakes(int decrement) {

speed = speed - decrement;

public void printStates() {

System.out.println("speed: " + speed + " gear: " + gear);

// Class implementing vehicle interface

class Bike implements Vehicle {

int speed;

int gear;

// Change gear @Override

public void changeGear(int newGear){


gear = newGear;

}
// Increase speed @Override

public void speedUp(int increment){

speed = speed + increment;

public void printStates() { System.out.println("speed: " + speed + " gear: " + gear);
}

156
Chapter 3: Data Abstraction

class VehicleMain

{
public static void main (String[] args)

// Instance of Bicycle(Object) Bicycle

bicycle = new Bicycle();

bicycle.changeGear(2);

bicycle.speedUp(3);

bicycle.applyBrakes(1);

System.out.print("Bicycle present state : ");


bicycle.printStates();

// Instance of Bike (Object) Bike

bike = new Bike();

bike.changeGear(1);

bike.speedUp(4);

bike.applyBrakes(3);

System.out.print("Bike present state : ");


bike.printStates();

}}

Output
Bicycle present state : speed: 2 gear: 2 Bike present state : speed: 1 gear: 1

3.10 Inheritance
• Inheritance is one of the important features of OOPs (Object Oriented Programming System)
through which a class inherits all of the attributes and methods of another class.

• The class that inherits the properties of another class is referred to as the child class, while
the class whose properties are being inherited is referred to as the parent class. In Java, we
utilize the extend keyword to inherit a class.

157
OOPS AND JAVA

• Single Inheritance is the inheritance of a single derived class from a single base class while
in multiple inheritance a child class can inherit features from more than one parent object or
parent class.

Why multiple inheritance is not possible in Java?


• Multiple inheritance is supported by C++, Python, and a few other languages, but not by
Java.

• To prevent the ambiguity produced by multiple inheritance, Java does not allow it.
• The diamond problem, which happens in multiple inheritance, is one example of such a
problem.

There are two reasons that explains why Java does not support multiple inheritance.

3.10.1. The Diamond Problem:


• Consider a class A that has a foo() method

• Class B and C is derived from A and have their own foo() implementation

• Class D derives from B and C using multiple inheritance

• In this case the compiler will not be able to distinguish which foo() it should execute if we
only refer to foo().
• This is also known as the Diamond problem because the structure of this inheritance scenario
is comparable to a four-edged diamond, as shown below and it’s described in the Figure .3.4:
Diamond Problem.

Figure .3.4: Diamond Problem

3.10.2. Simplicity:
• Dealing with the complexity caused by multiple inheritance is quite difficult.
• It causes issues during various operations like casting and constructor chaining

158
Chapter 3: Data Abstraction

• All the above-mentioned reason is that there are very few circumstances in which multiple
inheritance is required, thus it is preferable to avoid it to keep things simple and easy.

Multiple Inheritance Using Interface

In Java, the concept of "multiple inheritance" (where a class inherits from multiple parent
classes) is not directly supported, it can be achieved with similar functionality by using
interfaces, allowing a class to implement multiple interfaces, effectively inheriting from
multiple "types".

Syntax of implementing multiple interfaces:


• To implement multiple interfaces in Java, the following syntax is used:

class MyClass implements Interface1, Interface2, Interface3 {

// class body }

• The classes "MyClass" and "Interface1", "Interface2", and "Interface3" can now inherit and
implement methods from other interfaces.

• As a result, the class is able to display the behaviours specified in every interface it
implements and it’s described in the Figure.3.5: Multiple inheritance in Java.

Figure.3.5: Multiple inheritance in Java

How to Achieve Multiple Inheritance in Java


• Multiple Inheritance is a concept in object-oriented programming that allows a class to
inherit properties from one or multiple parent classes.

• Multiple inheritance creates ambiguity

• The problem arises when methods with similar signatures exist in both subclasses and
superclasses.

159
OOPS AND JAVA

• The compiler is unable to determine which class method should be called first or given
priority when calling the method.

• In Java, we can achieve multiple inheritance through the concept of interface.

• An interface is like a class that has variables and methods, however, unlike a class, the
methods in an interface are abstract by default.

• Multiple inheritance through interface occurs in Java when a class implements multiple
interfaces or when an interface extends multiple interfaces and it’s described in the
Figure .3.6: Multiple Inheritance .

Figure .3.6: Multiple Inheritance

Example
In the above example, it illustrates multiple inheritance via an interface.

• Each interface, Dog and Cat, has one abstract method, i.e., bark() and meow(), respectively.
The Animal class implements the interfaces Dog and Cat.
• The main() method of the Demo class creates an object of the Animal class. Then, the bark()
and meow() functions are called.

Implementation of Multiple inheritance in Java through Interface


interface Dog {

void bark();

interface Cat { void meow();

}
class Animal implements Dog, Cat {

160
Chapter 3: Data Abstraction

public void bark() { System.out.println("Dog is barking");

public void meow() { System.out.println("Cat is meowing");


}

class Main {

public static void main(String args[]) {

Animal a = new Animal();

a.bark();

a.meow();

}
}

Output:
Dog is barking

Cat is meowing
Example: This example demonstrates how a class can implement multiple interfaces (Add and
Sub) to provide functionality for both addition and subtraction operations.

import java.io. *;

// Add interface interface Add {

int add(int a,int b);

// Sub interface interface Sub {

int sub(int a,int b);

// Calculator class implementing

// Add and Sub

class Cal implements Add, Sub

{ // Method to add two numbers


public int add(int a,intb){

161
OOPS AND JAVA

return a+b;

// Method to sub two numbers

public int sub(int a,intb){

return a-b;

class Main{
// Main Method

public static void main (String[] args)

// instance of Cal class Cal x = new Cal();

System.out.println("Addition : " + x.add(2,1));

System.out.println("Substraction : " + x.sub(2,1)); }}

Output
Addition: 3

Subtraction: 1

3.11 Exception Handling


• Java Exception Handling is a mechanism to handle runtime errors, allowing a program to
continue operating or terminate gracefully.

• It separates error-handling code from regular code, enhancing readability and


maintainability.

• Without proper exception handling, an error can cause the entire application to crash, leading
to a poor user experience.

3.11.1 Key Components of Java Exception Handling


Java catches errors using the try-catch block. When an exception occurs in the try block, the
control is transferred to the corresponding catch block. If no catch block matches the exception
type, the JVM looks for the catch block in the calling method, and this process continues up the
call stack.

• try: The block of code where exceptions might occur.

162
Chapter 3: Data Abstraction

• catch: The block of code that handles the exception.

• finally: An optional block that executes regardless of whether an exception was thrown or
not, typically used for cleanup activities.

3.12 Errors Vs. Exceptions


Table 3.1 Errors Vs. Exceptions
Errors Exceptions
Belongs to the java.lang.Error class Defined in java.lang.Exception package
Errors are of Unchecked type Exceptions can be both checked and
unchecked.
Errors mainly occur during run-time. Only the unchecked exceptions are
encountered in run-time.
Errors are irrecoverable Exceptions can be handled using exception-
handling mechanisms

3.12.1 Types of Exceptions


Java categorizes exceptions into three main types and it’s described in the Figure .3.7: Types
of Exceptions

Figure 3.7: Types of Exceptions


• Checked Exceptions: These are exceptions that are checked at compile-time. Examples
include IOException, SQL Exception, and Class Not Found Exception. Checked exceptions
must be either caught or declared in the method signature using the throws keyword.

• Unchecked Exceptions: These are exceptions that occur at runtime and are not checked at
compile-time. Examples include Null Pointer Exception, Array Index out of Bounds Exception,
and Illegal Argument Exception. Unchecked exceptions are subclasses of Runtime Exception.

163
OOPS AND JAVA

• Errors: These are serious issues that are not typically caught by the application code.
Examples include out of Memory Error and Stack Overflow Error. Errors are subclasses of
Error and usually indicate problems that the application cannot recover from.

3.13 Exception Hierarchy in Java


• Exception and Error are subclasses of Throwable, the hierarchy's base class.

• Exception, for example, is used for exceptional conditions that user programs should catch.
Error, on the other hand, is used by the Java run-time system (JVM) to indicate errors related
to the run-time environment (JRE), such as Stack Over flow Error and it’s described in the
Figure.3.8: Exception Hierarchy.

Figure 3.8: Exception Hierarchy

3.14 Exception handling using try...catch


In the example, we are trying to divide a number by 0. Here, this code generates an exception.

class Main {

public static void main(String[] args) {

try {

// code that generate exception

int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");

}
164
Chapter 3: Data Abstraction

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

} }}

Output
ArithmeticException => / by zero

3.14.1 Multiple catch Blocks


• We can use multiple catch statements for different kinds of exceptions that can occur from
a single block of code in the try block

3.14.2 Nested try-catch


class NestingTry {

public static void main(String args[]) {

//main try-block try {

//try-block2 try {

//try-block3 try {

int arr[] = {10, 20,30, 40};

System.out.println(arr[10]);

catch (ArithmeticException e)

{
System.out.print("Arithmetic Exception");

System.out.println(" handled in try-block3");


}

catch (ArithmeticException e)

System.out.print("Arithmetic Exception");

System.out.println(" handled in try-block2");

}
}

165
OOPS AND JAVA

catch (ArithmeticException e3)

System.out.print("Arithmetic Exception");

System.out.println(" handled in main try-block");

catch (ArrayIndexOutOfBoundsException e4)

System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");

catch (Exception e5) { System.out.print("Exception");

System.out.println(" handled in main try-block");

In the above code, the ArrayIndexOutOfBoundsException occurred in the grandchild try-


block3.

Since try-block3 is not handling this exception, the control then gets transferred to the parent
try-block2.
Since try-block2 also does not handle that exception, the control gets transferred to the main
try-block, where it finds the appropriate catch block for an exception.

Output
Array Index out of Bounds Exception handled in main try-block

3.15 Java throw and finally block


• In Java, the finally block is always executed no matter whether there is an exception or not.

• The finally block is optional. And, for each try block, there can be only one finally block.

class ExceptionMain {

public static void main(String[] args) {

try
{

166
Chapter 3: Data Abstraction

// code that generates exception int divideByZero = 5 / 0;

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());

}
finally {
System.out.println("This is the finally block");
}
}
}
Output
ArithmeticException => / by zero

This is the finally block Java throw and throws

3.15.1 Throw Method


• The Java throw keyword is used to explicitly throw a single exception.

• When we throw an exception, the flow of the program moves from the try block to the catch
block.

class ExceptionMain {

public static void divideByZero() {

// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) { divideByZero();

Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0 at
Main.divideByZero(Main.java:5) at Main.main(Main.java:9)

3.15.2 Throws Method


• The throws keyword is used to declare the type of exceptions that might occur within the
method.
• It is used in the method declaration.

167
OOPS AND JAVA

import java.io.*;

class ExceptionMain {

// declareing the type of exception

public static void findFile() throws IOException {

// code that may generate IOException File newFile = new File("test.txt");

FileInputStream stream = new FileInputStream(newFile);

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


findFile();

catch (IOException e) { System.out.println(e);

Output
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)

3.16 Creating Custom or User Defined Exceptions in Java


• Java allows developers to create their own exception classes.

• Custom exceptions can provide more meaningful error messages and handle specific error
scenarios.

3.17 Built-In Exceptions


Built-in exceptions are part of the Java Exception Hierarchy and are provided by the Java API.
These exceptions handle common error conditions that can occur during program execution.

3.17.1. Checked Exceptions


These are exceptions that are checked at compile time. The programmer must handle them
using a try- catch block or declare them using the throws keyword.

Common Checked Exceptions:


• IOException & FileNotFoundException
• ClassNotFoundException & SQLException

168
Chapter 3: Data Abstraction

• InterruptedException

3.17.2. Unchecked Exceptions


These are exceptions that occur at runtime and are not checked during compilation. They are
subclasses of Runtime Exception.

Common Unchecked Exceptions:


• ArithmeticException

• NullPointerException

• ArrayIndexOutOfBoundsException

• IllegalArgumentException

• NumberFormatException

• ClassCastException

3.17.3. Error (not typically handled by applications)


Errors indicate serious problems that applications should not try to catch.

Common Errors:
• OutOfMemoryError

• StackOverflowError
• VirtualMachineError

• AssertionError

Example:
Handling a Built-in Exception

public class ExceptionExample {


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

int result = 10 / 0; // will throw ArithmeticException

} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");

169
OOPS AND JAVA

CHAPTER IV
COLLECTION API AND LAMBDA
4.1 Introduction to wrapper classes
The wrapper classes in Java are used to convert primitive types (int, char, float, etc) into
corresponding objects. The Java compiler can directly convert the primitive types into
corresponding objects. This process is known as auto-boxing and described in the Figure.4.1:
wrapper class

Figure 4.1: wrapper class

4.2 Predefined wrapper classes


Wrapper classes are part of the java.lang package

Table 4.1: Predefined wrapper classes

Primitive Type Wrapper Class (Objects)


byte Wraps the primitive type byte
Character Wraps the primitive type char
Boolean Wraps the primitive type boolean
Double Wraps the primitive type double
Float Wraps the primitive type
4.2.1 Uses of Wrapper Class in Java
Storing null values
Primitive data types in Java cannot store null values, but wrapper classes can be set to null,
which can be useful in representing missing or unknown values.

Autoboxing and Unboxing

Java provides automatic conversion between primitive types and their corresponding wrapper
classes through autoboxing and unboxing.

170
Chapter 4: Collection API And Lambda

Converting between primitive data types and strings


Wrapper classes provide methods for converting primitive values to and from strings, which
can be useful for reading data from a file or user input.

Collections

ArrayList and HashMap are examples of Java collections that can only contain objects, not
primitives.

4.2.2 Need for using Wrapper Classes in Java

Object-oriented compatibility: In object-oriented programming, everything is treated as an


object. Wrapper classes allow primitive data types to be treated as objects, enabling them to
participate in object- oriented paradigms like inheritance, polymorphism, and encapsulation.

Nullable values: Primitive types cannot represent null values, which can be essential in certain
scenarios, such as when dealing with databases or APIs. Wrapper classes like Integer, Double,
etc., allow for nullable values by providing a null reference.

Collections: Many collection classes in Java, such as ArrayList or HashMap, require objects,
not primitives. Wrapper classes allow primitive values to be stored in collections by wrapping
them in objects.

Generics: Java’s generics do not support primitive types. Therefore, when we need to use
generics with primitives, wrapper classes are necessary. For instance, List<Integer> is valid,
but List<int> is not.

Type conversions: Wrapper classes provide methods to convert between primitive types and
objects. For example, Integer.parseInt() converts a string to an int, and Integer.toString()
converts an Integer object to a string.

Utility methods: Wrapper classes offer various utility methods for working with primitive
values, such as comparing, sorting, and finding the minimum or maximum value.

Interoperability: In scenarios where primitive types need to be passed to methods expecting


objects, wrapper classes facilitate interoperability by allowing primitives to be wrapped and
passed as arguments.

Constants and methods:Wrapper classes often provide constants (like Integer.MAX_VALUE)


and methods (like Integer.valueOf()) that are useful in various programming scenarios.
171
OOPS AND JAVA

Reflection: Wrapper classes play a crucial role in reflection, allowing you to inspect and
manipulate primitive types as objects during runtime.

4.3 Autoboxing and unboxing


4.3.1 Autoboxing
Autoboxing is the automatic conversion of primitive types to their corresponding wrapper
classes. For example, when assigning a primitive value to a wrapper class object, autoboxing
automatically converts the primitive to its wrapper class equivalent.

4.3.2 Unboxing

Unboxing is the automatic conversion of wrapper class objects to their corresponding primitive
types.For example, when a wrapper class object is used in a context where a primitive type is
expected, unboxing automatically extracts the primitive value from the wrapper object and it’s
described in the Figure 4.2: Autoboxing and Unboxing

Figure 4.2: Autoboxing and Unboxing

Example:
public class AutoboxingUnboxing

public static void main(String[] args)

{
Integer integer = 100; // Autoboxing

int num = integer; // Unboxing

System.out.println(num); // Output: 100

}}

172
Chapter 4: Collection API And Lambda

4.3.3 Disadvantages of Wrapper Class in Java


Performance Overhead
The process of converting primitive data types to and from Wrapper classes can result in
performance overhead, especially in large-scale applications

Increased Memory Usage

Wrapper classes consume more memory than primitive data types, as they are objects and
contain additional information like type information, methods, etc.

Immutable
Wrapper classes are immutable, meaning their values cannot be changed once they are created.

4.4 Utility methods


Class wrapper java provides utility methods to convert between types and perform various
operations.

For example, the Integer class provides methods to parse a string as an integer

public class IntegerMethodsExample

public static void main(String[] args)

String str = "123";

int num = Integer.parseInt(str);


System.out.println(num); // Output: 123

}}

Which of the following is a valid way to create an Integer object with the value 10?
a. Integer val = new Integer(10);

b. Integer val = Integer.valueOf(10);

c. Integer val = 10;

d. int val = 10;

The valueOf() method of the Integer class is a static factory method used to create an Integer
object with the specified value.

173
OOPS AND JAVA

Which of the following methods can be used to parse a string representation of a number
into its corresponding primitive data type?
Integer.parseInt() Integer.valueOf() Integer.intValue()
Integer.parse()

The parseInt() method of the Integer class parses a string representation of an integer into its
corresponding primitive data type.

To create a wrapper object of an int type called myInt, which of the following is used?
Integer myInt = 5; Int myInt = 5; Number myInt = 5;

Wrap myInt = Integer(5)

Example: Convert an Integer to a String, and use the length() method of the String class to output
the length of the "string"

public class typeConversion {

public static void main(String[] args) {

Integer myInt = 100;

String myString = myInt.toString();

System.out.println(myString.length())

Methods used to get the value associated with the corresponding wrapper object:
intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(),
booleanValue().

Example
public class Example {

public static void main(String[] args) {

Integer myInt = 5;

Double myDouble = 5.99;

System.out.println(myInt.intValue());

System.out.println(myDouble.doubleValue());

System.out.println(myChar.charValue());

} }

174
Chapter 4: Collection API And Lambda

4.5 Java Collections API

Collections are like containers that group multiple items in a single unit. For example, a jar of
chocolates, a list of names, etc. Collections frameworks reduce programming effort by
providing useful data structures and algorithms commonly used in most software systems.
They also promote software reuse, since the interfaces and behaviours (methods) encourage
reusability.

4.6 Java Collections Framework


It consists of the following parts:

1. Interfaces

2. Implementation Classes

3. Algorithms

Types of Interfaces
• Collection Interface

• Set Interface

• List Interface

• Maps

• SortedSet and SortedMap

4.7 Generics
A major part of software engineering is building components that not only have well-defined
and consistent APIs, but are also reusable.

In Java, one of the main tools in the toolbox for creating reusable components is generics

The java generics is a language feature that allows creating methods and class which can handle
any type of data values

4.7.1 Before Java Generics:


//Compiler doesn't know the type of this ArrayListsoit will allow both the additions and

//the program willthrow an error during runtime.

ArrayListarrList = new ArrayList();


arrList.add(101);

175
OOPS AND JAVA

arrList.add("hello");

4.7.2 After Java Generics:


//Compiler now knows the type of the Array List so it will throw compile-time error

// try to add any element to this list which is not an integer

ArrayList<Integer>arrList = new ArrayList<Integer>();

arrList.add(101);

arrList.add("hello"); //this will throw compilation error

Code reusability using Generics


Generics allows a single class or method to be used for multiple data types.

For example: We can create an object of ArrayList class for multiple data types. Instead of
creating an ArrayList class for a single data type, it is created using generics which allows us
to create object of ArrayList class with the desired data type.

//List of Strings

ArrayList<String> names = new ArrayList<String>();

//List of whole numbers

ArrayList<Integer> age = new ArrayList<Integer>();

//List of float numbers

ArrayList<Float>arrList = new ArrayList<Float>();

//List of characters

ArrayList<Character>arrList = new ArrayList<Character> ();

In java, the generics feature implemented using the following.

• Generic Method

• Generic Classes

Example - Generic method


GenericFunctions obj = new GenericFunctions();

obj.displayData(45.6f, 10);

obj.displayData(10, 10);

obj.displayData("Hi", 'c');
} }

176
Chapter 4: Collection API And Lambda

Example - Generic class


public class GenericsExample<T> {

T obj;

public GenericsExample(T anotherObj) {

this.obj = anotherObj;

public T getData() {

return this.obj;
}
public static void main(String[] args) {
GenericsExample<Integer> actualObj1 = new GenericsExample<Integer>(100);
System.out.println(actualObj1.getData());
GenericsExample<String> actualObj2 = new GenericsExample<String>("Java");
System.out.println(actualObj2.getData());
GenericsExample<Float> actualObj3 = new GenericsExample<Float>(25.9f);
System.out.println(actualObj3.getData());
} }

4.7.3 Generics K and V parameters


The HashMap class is declared with the K and V parameters. Here, first parameter in generics
is the type of the Key and the second parameter is the type of the Value. In the following
example, the HashMap accepts integer key values and string values.

import java.util.*;
public class JavaExample{

public static void main (String args[]) {

//HashMap <k, V> where K is the type of key

//and V is the type of value

HashMap<Integer,String>hMap=new HashMap<> ();

hMap.put(101,"Chaitanya");
hMap.put(120,"Carl");

177
OOPS AND JAVA

hMap.put(141,"Aditya");

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

for (Map.EntrymEntry :hMap.entrySet()) {


System.out.print("key: "+ mEntry.getKey() + " & Value: ");
System.out.println(mEntry.getValue());

} } }

Output:
HashMap elements:

key: 101 & Value: Chaitanya key: 120 & Value: Carl

key: 141 & Value: Aditya

Collections
• Collections with Ordering: Lists

• Collections for Uniqueness: Sets

• Collections for Pairs: Maps

4.8 Java List interface


Java List Interface is in java.util.List. It represents an ordered sequence of objects. The elements
contained in a Java List can be inserted, accessed, iterated and removed according to the order
in which they appear internally in the Java List.

Each element in a Java List has an index. The first element in the List has index 0, the second
element has index 1 etc

We can add any Java object to a List.

4.8.1 Create a List


Create a List instance by creating an instance of one of the classes,for example

List listA = new ArrayList();

List listB = new LinkedList();

List listC = new Vector();


List listD = new Stack(); Insert Elements in a Java List

We can insert elements (objects) into a Java List using itsadd() method.

178
Chapter 4: Collection API And Lambda

List<String>listA = new ArrayList<>();

listA.add("Apple");

listA.add("Orange");

listA.add("Grapes");

The add() calls add a String instance ( Apple, Orange ,Grapes )to the end of the list.

4.8.2 Insert Elements at Specific Index


It is possible to insert an element into a Java List at a specific index.

The List interface has add() method that takes an index as first parameter, and the element to
insert as the second parameter.

Inserting an element at index 0 into a Java List:


list.add(0, "element 4");
If the List already contains elements, these elements will now get pushed further down in the
List's internal sequence.

The element that had index 0 before the new element was inserted now will get pushed to index
1.

4.8.3 Insert All Elements from One List into Another


It is possible to add all elements from one Java List into another List. The resulting List is the
union of the two lists.

List <String>listSource = new ArrayList<> ();

listSource.add("123");

listSource.add("456");

// adds all elements from listSource into listDest.

List<String>listDest = new ArrayList<>();

listDest.addAll(listSource);

4.8.4 Get Elements from a Java List


We can get the elements from a Java List using the index of the elements. This is done using
theget(int index) method.

List<String>listA = new ArrayList<>();

listA.add("Apple");
179
OOPS AND JAVA

listA.add("Orange");

listA.add("Grapes");

//access via index

String element0 = listA.get(0);

// get element at index 0 - Apple

String element1 = listA.get(1); // get element at index 1 - Orange

String element3 = listA.get(2); // get element at index 2 - Apple

4.8.5 Find Elements in a List


There are 2 methods to find an element: indexOf(),lastIndexOf()

The indexOf() method finds the index of the first occurrence in the List of the given element.

List<String> list = new ArrayList<>();

String element1 = "element 1";

String element2 = "element 2";

list.add(element1); list.add(element2);

int index1 = list.indexOf(element1);

int index2 = list.indexOf(element2);


System.out.println("index1 = " + index1);// output = 0

System.out.println("index2 = " + index2);// output = 1

4.8.6 Find Last Occurrence of Element in a List


The lastIndexOf() method finds the index of the last occurrence in the List of a given element.

List<String> list = new ArrayList<>();

String element1 = "element 1";

String element2 = "element 2";

list.add(element1);
list.add(element2);

int lastIndex = list.lastIndexOf(element1);

System.out.println("lastIndex = " + lastIndex);// output - lastIndex = 2

Check if List Contains Element


Check if a Java List contains a given element using the List contains() method.

180
Chapter 4: Collection API And Lambda

List<String> list = new ArrayList<>();

String element1 = "element 1";

list.add(element1);

booleandecision =list.contains("element 1");

System.out.println(decision); // OUTPUT = True

It is possible to add null values to a List, it is actually possible to check if the List contains a
null value. list.add(null);

decision =list.contains(null);

System.out.println(decision);

4.8.7 Remove Elements from a Java List


Remove elements from a Java List via these two methods: remove (Object element)
remove (int index)

remove (Object element) removes that element in the list, if it is present. All subsequent
elements in the list are then moved up in the list. Their index thus decreases by 1.

List<String> list = new ArrayList<>();

String element = "first element";

list.add(element); list.remove(element);

The List remove (int index) method removes the element at the given index. All subsequent
elements in the list are then moved up in the list. Their index thus decreases by 1.
List<String> list = new ArrayList<>();

String element1 = "Apple";

String element2 = "Orange";


list.add(element1);

list.add(element2);

list.remove(0);

The List would contain the Java String elements element 1 and element 2 at index 0 and 1. The
first element (Apple) has been removed from the List.

4.8.8 Remove All Elements From a Java List


The Java List interface contains a clear() method which removes all elements from the list when
called. Removing all elements from a List is also referrred to as clearing a List.

181
OOPS AND JAVA

List<String> list = new ArrayList<>(); list.add("object 1");

list.add("object 2"); list.clear();

First, a new List is created and Second, two elements are added to the List.

Third, the clear() method is called. After the clear() method has been called, the List will be
completely empty.

4.8.9 Sublist of List


The Java List interface has a method called subList() which can create a new List with a subset
of the elements from the original List.

The subList() method takes 2 parameters:

 Start index
 End index.

The start index is the index of the first element from the original List to include in the sublist.
The end index is the last index of the sublist, but the element at the last index is not included in
the sublist.

List<String> list = new ArrayList<>();

list.add("element 1");

list.add("element 2");

list.add("element 3");

list.add("element 4");

List<String>sublist = list.subList(1, 3);

Convert List to Set


Convert a Java List to a Java Set by creating a new Set and adding all elements from the List to
it. The Set will remove all duplicates.

List<String> list = new ArrayList<>();

list.add("element 1");

list.add("element 2");

list.add("element 3");
list.add("element 3");

Set<String> set = new HashSet<>(); set.addAll(list);

The resulting set will contain the Strings element 1, element 2 and only one element 3.

182
Chapter 4: Collection API And Lambda

Sort List
Sort a Java List using the Collections sort() method.

List<String> list = new ArrayList<>();

list.add("c");

list.add("b");

list.add("a"); Collections.sort(list);

Iterate List
The three most common ways are:

 Using an Iterator
 Using a for loop
 Iterate a List is to use a standard for loop

List listabc = new ArrayList();

listabc.add("first");

listabc.add("second");

listabc.add("third");

for(int i=0; i<listabc.size(); i++)

{ Object element = listabc.get(i);


}

Iterate a List is to use a Java Iterator.


List<String> list = new ArrayList<>();

list.add("first");

list.add("second");

list.add("third");

Iterator<String>itr = list.itr();

while(itr.hasNext()) {
String next = itr.next();}

4.9 Java Set interface


The Java Set interface, java.util.Set, represents a collection of objects where each object in the
Java Set is unique. The same object cannot occur more than once in a Java Set.

183
OOPS AND JAVA

Create a Set
Create a Set instance:

import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set;

import java.util.TreeSet; public class SetExample {

public static void main(String[] args) { Set setA = new HashSet();

Set setB = new LinkedHashSet(); Set setC = new TreeSet();

} }

Remove Elements from Set


Remove elements from a Java Set by calling the remove (Object O) method.
set. Remove("object-to-remove");

NOTE: There is no way to remove an object based on index in a Set, since the order of the
elements depends on the Set implementation.

Remove All Elements from Set


Remove all elements from a Java Set using the clear () method.

set.clear();

Add All Elements from Another Collection


In set theory add corresponds to the union of the Set and the other Collection.

Set<String> set1 = new HashSet<> ();

set1.add("one");

set1.add("two");

set1.add("three");
Set<String> set2 = new HashSet<>();

set2.add("four");

set2.addAll(set1); // The set2 will contain element four and also elements one, two and three
from set1.
Remove All Elements from Another Collection
The Java Set interface as a method called remove All () which removes all elements in the Set
which are also present in another Collection. In set theory, this is referred to as the difference
between the Set and the other Collection.

Set<String> set1 = new HashSet<>();

184
Chapter 4: Collection API And Lambda

set1.add("one");

set1.add("two");

set1.add("three");

Set set2 = new HashSet ();

set2.add("three");

set1.removeAll(set2);
The set1 will contain the String elements one and two. The element three has been removed,
because it was present in set2

Check if Set is Empty


Check if a Java Set is empty, meaning it contains no elements, by calling the isEmpty() method
on the Set.

Set<String> set = new HashSet<>();

booleanisEmpty = set.isEmpty();
After execution isEmpty variable will contain the value true, because the Set is empty (has no
elements in it). Another method to check if a Set is empty by comparing the value returned by
the size() method with 0.

Set<String> set = new HashSet<>();

booleanisEmpty = (set.size() == 0);

Check if Set Contains Element


Check if a Java Set contains a given element (object) by calling the contains() method.

Set<String> set = new HashSet<>(); set.add("123");

set.add("456");

boolean contains123 = set.contains("123");

Convert Java Set to List


Convert a Java Set to a Java List by creating a List and calling its addAll() method, passing the
Set as parameter to the addAll() method.

Set<String> set1 = new HashSet<>(); set1.add("123");

set1.add("456");

185
OOPS AND JAVA

List<String> list = new ArrayList<>();

list.addAll(set1);

4.10 Java MAP interface


The maps interface in java is a collection that links a key with value pairs. Each entry in the
map store the data in a key and its corresponding value.

Map interface contains only unique keys and does not allow any duplicate keys. The map
interface in Java is a part of the java.util.map interface.

A key is an object that you use to access the value later, it is associated with a single value. A
map is used when you need to search, edit, or remove elements based on a key.

A Map cannot be traversed, therefore you must use the keySet() or entrySet() method to convert
it into a Set.

4.10.1 Classes that implement Map


Table 4.2: Classes and its description

Class Description
LinkedHashMap The implementation of Map is LinkedHashMap. It inherits the
class HashMap. The insertion order is maintained.
HashMap Although HashMap implements Map, it doesn’t maintain any
kind of order.
TreeMap both the map and the sortedMap interfaces are implemented. In
TreeMap, the order is always maintained in ascending order.

4.10.2 Interfaces that extend Map


Interfaces Description
Map Duplicate keys are not allowed in a map, although duplicate values
are.
SortedMap In SortedMap, elements can be traversed in the sorted order of their
keys.
4.10.3 Add elements to a Map
The put() method is used to add new elements to the map. However, the hashmap does not keep
track of the insertion order. Internally, a unique hash is created for each element, and the
elements are indexed based on this hash to increase efficiency. The time complexity for adding
the element is O(1).

186
Chapter 4: Collection API And Lambda

Example:
import java.util.*; class GFG {

public static void main(String args[])

// Standard Initialization of a Map

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

// Initialization of a Map using Generics

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


// Inserting the Elements map1.put(1, "Java");

map1.put(2, "C++");
map1.put(3, "Python "); map2.put(new Integer(1), "Java"); map2.put(new Integer(2), "C++");
map2.put(new Integer(3), "Python");

System.out.println(map1);

System.out.println(map2);

Output:
{1=Java, 2=C++, 3=Python}

{1=Java, 2=C++, 3=Python}


Map has its implementation in various classes like TreeMap which sorts the entries based on
keys

Example:
import java.util.Map; import java.util.TreeMap;
public class CollectionsDemo {

public static void main(String[] args) { Map<String, String> m1 = new TreeMap<>();

m1.put("Zara", "8");

m1.put("Mahnaz", "31");
m1.put("Ayan", "12");

187
OOPS AND JAVA

m1.put("Daisy", "14"); System.out.println(); System.out.println(" Map Elements");


System.out.print("\t" + m1);

} }

Output
Map Elements

{Ayan=12, Daisy=14, Mahnaz=31, Zara=8}

Access an Item
To access a value in the HashMap, use the get() method and refer to its key

map1.get( “Zara”);

Changing Element
If we want to update an element after adding it, we can do so by adding it once more using the
put() method. The values of the keys can be modified by simply inputting the updated value for
the key that needs to be changed because the elements in the map are indexed using the keys.
The time complexity for changing the element is O(1).

Program
map.put(new Integer(2), "with");

System.out.println("Updated Map " + map);

} }

Output
Original Map {1=Learn, 2=in, 3=Scaler}

Updated Map {1=Learn, 2=with, 3=Scaler}

4.10.4 Removing Elements


The remove () method can be used to remove an element from the Map. If there is a mapping
for a key in the map, it is removed using this method, which accepts the key value. The time
complexity for removing the element is O(1).

Example:
import java.util.*; class GFG {

public static void main(String args[]) {


// Initialization of a Map using Generics

188
Chapter 4: Collection API And Lambda

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

// Inserting the Elements cg.put(new Integer(1), "Sahil");

cg.put(new Integer(2), "Vishal");

cg.put(new Integer(3), "Karan");

cg.put(new Integer(4), "Nikhil");

// Initial Map System.out.println("Original Map " + cg);

cg.remove(new Integer(4));

// Final Map System.out.println("Updated Map " +cg);

}}

Output:
Original Map {1=Sahil, 2=Vishal, 3=Karan, 4=Nikhil}

Updated Map {1=Sahil, 2=Vishal, 3=Karan}

Iterating through the Map


The Map can be iterated through in a number of ways. The most well-known method is to
retrieve the keys using a for-each loop. The getValue() method is used to determine the key's
value. Since it is iterating through all the elements, Hence the time complexity becomes O(n).

4.10.5 Collection Interface

The Collection interface represents a group of elements and provides a high level of abstraction
for transferring data between unrelated interfaces and it’s described in the Fig.4.3: Java
collections framework

Fig.4.3: Java collections framework

189
OOPS AND JAVA

Features of Collections in Java Framework


Consistent API: Common methods across different collection classes (like add(), remove(),
and size())

Reusability: No need to reinvent data structures like linked lists, hash tables, or trees

Efficiency: Collections are highly optimized for performance

Interoperability: Easy to switch between different collection types

Extensibility: Create own collection classes if needed

Hierarchical Structure of Java Collections Framework


The Java Collections Framework consists of several core interfaces such as Collection,
List, Set, Queue, Deque, Map, and their corresponding implementations

java.util.Collection
├── List

│ ├── ArrayList

│ ├── LinkedList

│ └── Vector

│ └── Stack

├── Set

│ ├── HashSet
│ ├── LinkedHashSet
│ └── TreeSet

└── Queue

├── LinkedList

├── PriorityQueue

└── ArrayDeque java.util.Map

├── HashMap

├── LinkedHashMap

├── TreeMap

└── Hashtable

190
Chapter 4: Collection API And Lambda

4.10.6 Collection:
The root interface of the collection hierarchy. It defines the basic operations that all collections
must implement, such as add, remove, size, and iterator

Create a Collection
A Collection instance cannot be created directly, but an instance of one of the subtypes (List,
Set, SortedSet, Queue) of Collection can be applied.
Example of creating a List which is a subtype of Collection

Collection Mycollection = new ArrayList();

Add Element to Collection


String anElement = "an element";

Collection collection = new HashSet();


Boolean didCollectionChange = collection.add(anElement);

The add() method adds the given element to the collection and returns true if the Collection has
changed as a result of calling the add() method.

Creating a Linked List from Collection


It will create a Linked List with all the elements of Collection C. Use the LinkedList class and
new keyword to create a constructor which contains the elements of collection.

LinkedList list=new LinkedList(C);

Let us take a look at an example of Linked List. import java.util.*;

public class ScalerTopics{

public static void main(String args[]){

//creating a LinkedList

LinkedList<String> list= new LinkedList<String>();

//displaying the initial size

System.out.println("Size at the beginning "+list.size());

//add elements

list.add("Java");
list.add("C++");

list.add("JavaScript");
list.addFirst("C#");

191
OOPS AND JAVA

list.addLast("Kotlin");

list.add(2,"Python");

//displaying the LinkedList

System.out.println("Original Linked List " + list);

//displaying the size

System.out.println("Size after addition "+list.size());

//remove element at index 5 list.remove(5);

list.remove("C#");
//display the new LinkedList

System.out.println("New Linked List "+ list);

//display the new size

System.out.println("Size after removal "+list.size());

} }

Output
Size at the beginning 0

Original Linked List [C#, Java, Python, C++, JavaScript, Kotlin]


Size after addition 6

New Linked List [Java, Python, C++, JavaScript]

Size after removal 4

4.10.7 Vector
Like ArrayList, Vectors in Java are used for dynamic arrays. It extends the AbstractList and
implements the List interface.Vector is synchronised. Synchronised means only one thread at a
time can access the code. This means if one thread is working on Vector, no other thread can
get a hold of it. Only one operation on vector can be performed at a time. For example, if
addition is being performed by one thread, other operation cannot be performed until the first
one is over.

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

192
Chapter 4: Collection API And Lambda

//creating a Vector

Vector<Integer> v= new Vector<Integer>();

//displaying the size

System.out.println("Size at the beginning "+v.size());

//add elements v.add(19);

v.add(88);

v.add(1);

v.add(39);

//displaying the Vector System.out.println(v);

//displaying the size


System.out.println("Size after addition "+v.size());

//remove element at index 3 v.remove(3);

//display the new Vector System.out.println(v);

//display the new size


System.out.println("Size after removal "+v.size());

} }

Output:
Size after addition 4 [19, 88, 1]
Size after removal 3

4.10.8 PriorityQueue
The PriorityQueue class extends AbstractQueue and implements the Queue Interface. As the
name suggests, they follow the principle of priority of the elements.

We know that we follow First-In, First-Out for queues, but at times, the elements need to be
processed in terms of their priority. This is where the PriorityQueue comes into play.

It does not allow null values to be stored inside it.

The add() method is used to add an element while the poll() method is used to remove the top-
most element. While, peek() is used to display the top-most element.

import java.util.*;

193
OOPS AND JAVA

public class ScalerTopics{

public static void main(String args[])

// Creating a priority queue

PriorityQueue<Integer>pq = new PriorityQueue<Integer>();

//displaying the PriorityQueue

System.out.println("New PriorityQueue after removal" + pq);

//display the new size


System.out.println("Size after removal "+pq.size());

} }

Output
Size at the beginning 0

New PriorityQueue[18, 34, 27, 99]

Size after addition 4

Top-most element 18

Removing 18
New PriorityQueue after removal[27, 34, 99] Size after removal 3

4.11 Lambda Expressions


Lambda expression is an anonymous or unnamed method. The lambda expression does not
execute on its own. Instead, it is used to implement a method defined by a functional
interface.They are designed to accept a set of parameters as input and return a value as an
output.

Function

A Function is another in-build functional interface in java.util.function package, the function


takes an input value and returns a value.

4.12 Functional Interface of Lambda


If a Java interface contains one and only one abstract method then it is termed as functional
interface.
import java.lang.FunctionalInterface;

194
Chapter 4: Collection API And Lambda

public interface MyInterface

// the single abstract method double getValue();

In the above example, the interface MyInterface has only one abstract method getValue().
Hence, it is a functional interface.

Why do we Need a Lambda Expression?


The three primary reasons why we need Java Lambda expressions.

Lambda converts the code segment into an argument

It is a method that can be created without instantiating a class

// it will throw an error


MyInterface ref = new myInterface();

// it is valid MyInterface ref;

Lambda can be treated as an Object

4.12.1 Defining lambda expression in Java


Syntax
(parameter list) -> lambda body

or

([comma separated argument-list]) ->{body}


The new operator (->) used is known as an arrow operator or a lambda operator.

Example
Suppose, we have a method like this:

double getPiValue() { return 3.1415;

We can write this method using lambda expression as:

() -> 3.1415
Here, the method does not have any parameters. Hence, the left side of the operator includes an
empty parameter. The right side is the lambda body that specifies the action of the lambda
expression. In this case, it returns the value 3.1415.

195
OOPS AND JAVA

4.12.2 Types of Lambda Body


In Java, the lambda body is of two types.

 A body with a single expression


 A body that consists of a block of code.
1. A body with a single expression

() ->System.out.println("Lambdas are great");

2. A body that consists of a block of code.

() -> { double pi = 3.1415; return pi;};

Example Program - Lambda Expression with Zero Parameter

interface MyInterface

{
// abstract method double getPiValue();

public class lambaExpr {


public static void main( String[] args )

// declare a reference to MyInterface MyInterface ref;

// lambda expression ref = () -> 3.1415;

System.out.println("Value of Pi = " + ref.getPiValue());

}}

Output:
Value of Pi = 3.1415
Lambda Expression with One Parameter interface cube

int calculate(int a);

public class functional

{
public static void main(String args[])

196
Chapter 4: Collection API And Lambda

{ int x = 5;

cube c = (int a)->a*a*a;

int result = c.calculate(x);

System.out.println(result);

Lambda Expression with Multiple Parameters

@functional_interface interface Product {

float Mul(float x, float y);

}
public class LambdaMP {

public static void main(String[] args)

{ Product Mul1 = (x, y) -> (x * y);

System.out.println(Mul1.Mul(2, 5));
Product Mul2 = (float x, float y) -> (x * y);

System.out.println(Mul2.Mul(100, 200));

}}

4.13 Lambda and Local Variables


• Lambda consumes local variable initialized in a method

• Local variable initialized in the Lambda function

• Manipulating local variable inside the lambda function

• Manipulating local variable outside the lambda function

Local variable initialized in a method


@FunctionalInterface

interface PrintCoin{

void print();

class Doge{
public void getDoge() {

197
OOPS AND JAVA

int coin = 100; //local variable

PrintCoinprintingCoin = () ->System.out.println("Hey ! I see coins” + coin);


printingCoin.print();
}

public static void main(String []args){ Doge doger = new Doge();

doger.getDoge();

} }

Output
Hey ! I see coins. 100

4.14 Manipulating local variable outside the lambda function


@FunctionalInterface interface PrintCoin{
void print();

class Doge{

public void getDoge()

int coin = 100; PrintCoinprintingCoin = () ->

System.out.println("Hey ! I see coins." + coin);


};//lambda consumes coin

coin ++; //manipulating outside lambda function

System.out.println(coin);
printingCoin.print();

public static void main(String []args)

Doge doge = new Doge();

doge.getDoge();
}}

198
Chapter 4: Collection API And Lambda

Output:
java: local variables referenced from a lambda expression must be final or effectively final

4.15 Predicates
The essential functional interfaces provided by the java.util.function package are the interfaces

• Consumer

• Predicate

• Supplier

These interfaces provide powerful tools for

• Consuming

• Filtering

• generating objects

enabling developers to write clean, modular, and reusable code

4.16 Consumer
The Consumer interface represents an operation that accepts a single input argument and
performs some action on it, without returning any result.

Common use cases of the Consumer interface include printing, logging, and updating state.

interface MyInterface

{
// abstract method double getPiValue();

public class lambaExpr {

public static void main( String[] args )

// declare a reference to MyInterface MyInterface ref;

// lambda expression ref = () -> 3.1415;

System.out.println("Value of Pi = " + ref.getPiValue());

}
}

199
OOPS AND JAVA

Output
5

Example Consumer
public class Student

int rollNo;

String className; String name;

public Student(int rollNo, String className, String name)

{
this.rollNo = rollNo; this.className = className;

this.name = name;

public int getRollNo()

return rollNo;

public void setRollNo(int rollNo)

this.rollNo = rollNo;

public String getClassName()

return className;

}
public void setClassName(String className)

this.className = className;

}
public String getName() { return name;

200
Chapter 4: Collection API And Lambda

public void setName(String name) { this.name = name;

Consumer Code
import java.util.function.Consumer;

public class ExampleOfConsumerForStudent

public static void main(String[] args)

{
// Adding data of Student

Student studentOne= newStudent(1, "CSE", "Ram");

Student studentTwo= newStudent(2, "CYBER", "Sham");

Consumer<Student> consumer = (object) ->


{

System.out.println(object.getName());

System.out.println(object.getRollNo());

System.out.println(object.getClassName());

};

System.out.println("First student data:");

consumer.accept(studentOne);
System.out.println("Second student data:");

consumer.accept(studentTwo);

Output
First student data: Ram

1
CSE

201
OOPS AND JAVA

Second student data: Sham

CYBER

4.17 Supplier
Supplier is a functional interface that takes no inputs and returns a result. The results produced
each time can be the same or different.

The interface contains one method, get():

@FunctionalInterface

public interface Supplier<T> {

/**

* Gets a result.
*

* @return a result

*/

T get();
}

Code Snippet

int max=intList.stream().max((x,y) -> x - y).get();

Example Supplier
import java.util.function.Supplier; public class Main {

public static void main(String args[])

// This function returns a random value.

Supplier<Double>randomValue = () ->Math.random();

// Print the random value using get()

System.out.println(randomValue.get());

Output: 0.5685808855697841

202
Chapter 4: Collection API And Lambda

4.18 Predicate& function


It is a functional interface that is used to test a condition.

Predicate accept only one argument and return a boolean value.

For e.g. the signature of filter method is filter(Predicate predicate)

@FunctionalInterface

public interface Predicate<T>

booleantest(T t); //It also contains some other default and static methods.

Code snippet:
Predicate<Integer> predicate= x -> x % 2 == 0;

System.out.println(predicate.test(5));

The output:

false

Example Predicate
import java.util.function.Predicate;
public class PredicateInterfaceExample1 {

public static void main(String[] args)

// Creating predicate Predicate<Integer>lesserthan = i -> (i< 18);

// Calling Predicate method

System.out.println(lesserthan.test(10));

}}

4.19 Streams API


• Lambda expressions and Streams API which allows to work with sequences of elements,
such as lists and arrays

• The map method in Streams can transform each element in a stream using a lambda
expression,

203
OOPS AND JAVA

• The filter method can select a subset of elements based on a boolean-valued lambda
expression.

• The reduce method can compute a result using all elements in a stream, and requires an
identity element and a lambda expression that can handle a partial result and the current
element.

4.19.1 Creating a Stream


A stream is just a sequence of items.

Every class which implements the java.util.Collection interface has a stream method which
allows to convert its instances into Stream objects.

An example which converts an ArrayList of Integer objects into a Stream:

// Create an ArrayList

List<Integer>myList = new ArrayList<Integer>();

myList.add(1);

myList.add(5);
myList.add(8);

// Convert it into a Stream Stream<Integer>myStream = myList.stream();

Lists, use the stream method available in the Arrays class to convert any array into a stream.

Example:
// Create an array

Integer[] myArray = {1, 5, 8};

// Convert it into a Stream

Stream<Integer>myStream = Arrays.stream(myArray);

4.19.2 The map Method


Once a Stream object is created, we can use a variety of methods to transform it into another
Stream object. The first such method is the map method.

It takes a lambda expression as its only argument, and uses it to change every individual element
in the stream.

Its return value is a new Stream object containing the changed elements.

collect(Collectors.toList());
// Print the squared numbers

204
Chapter 4: Collection API And Lambda

System.out.println("Original list: " + numbers);

System.out.println("Squared list: " + squaredNumbers);

}}

4.20 Filter Method


In Java, the filter() method is used in conjunction with streams to select elements based on a
given predicate. It filters out elements from a stream that don’t match the specified condition.

import java.util.Arrays;
import java.util.List;

import java.util.stream.Collectors;

public class FilterExample {

public static void main(String[] args) {

// Create a list of integers

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Filter out even numbers List<Integer>evenNumbers = numbers.stream()

.filter(num -> num % 2 == 0)

.collect(Collectors.toList());

// Print the even numbers

System.out.println("Original list: " + numbers);

System.out.println("Even numbers: " + evenNumbers);

Output
Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Even numbers: [2, 4, 6, 8, 10]

Filter Sort Method import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;
public class SortedExample {

public static void main(String[] args) {


205
OOPS AND JAVA

// Create a list of strings

List<String> words = Arrays.asList("banana", "apple", "grape", "orange", "pear");

// Sort the words in natural order

List<String>sortedWords = words.stream(). sorted (). collect (Collectors.toList());

// Print the sorted words

System.out.println("Original list: " + words);

System.out.println("Sorted list: " + sortedWords);

}
}

Output:
Original list: [banana, apple, grape, orange, pear]

Sorted list: [pple, banana, grape, orange, pear]

4.21 Reduce Method


In Java, the reduce() method in streams is a terminal operation that performs a reduction on the
elements of the stream.

It combines the elements of the stream into a single result using a binary operator.

The reduce() method is useful for tasks such as calculating the sum, finding the maximum or
minimum element, or performing custom aggregations

import java.util.Arrays;

import java.util.List;

import java.util.Optional;

public class ReduceExample {

public static void main(String[] args) {

// Create a list of integers

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// Calculate the sum of all elements using reduce()

Optional<Integer> sum = numbers.stream().reduce((x, y) -> x + y);

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


// Find the maximum element using reduce()

206
Chapter 4: Collection API And Lambda

Optional<Integer>max = numbers.stream().reduce(Integer::max);
System.out.println("Maximum element: " + max.orElse(0));

// Concatenate all strings in a list using reduce()

List<String> strings = Arrays.asList("Hello", " ", "world", "!");


Optional<String>concatenatedString = strings.stream().reduce((x, y) -> x + y);
System.out.println("Concatenated string: " + concatenatedString.orElse(""));

Output
Sum of all elements: 15

Maximum element: 5
Concatenated string: Hello world!

4.22 Parallel Streams


Parallel streams allow operations to be executed in parallel on different threads, which can lead
to better performance on multiprocessor systems.

To create a parallel Stream, we can call the parallelStream() method on a collection or the
parallel() method on an existing Stream.

Stream<String>parallelStream = list.parallelStream();

List<Integer>listOfNumbers = Arrays.asList(1, 2, 3, 4);

listOfNumbers.parallelStream();

forEach(number->System.out.println(number + " " + Thread.currentThread().getName()));

Output Based on the thread


The actual result might differ depending on the number of threads used in the common fork-
join pool.

4 ForkJoinPool.commonPool-worker-3

2 ForkJoinPool.commonPool-worker-5

1 ForkJoinPool.commonPool-worker-7

3 main

207
OOPS AND JAVA

Figure.4.4: Sequential stream vs Parallel stream

Performance Considerations
 When using Streams, it is important to be aware of the performance implications.
Operations such as sorted and distinct can be costly as they require additional
processing.
 Furthermore, the use of Parallel Streams does not always guarantee a performance
increase and may even be counterproductive if the cost of splitting and merging tasks is
greater than the gain of parallel processing.

208
Chapter no 5: JDBC and Multithreading

CHAPTER V
JDBC AND MULTITHREADING
5.1 Introduction to JDBC:
• Java Database Connectivity (JDBC) is a standard API provided by Java for connecting to
and interacting with relational databases such as MySQL, Oracle, PostgreSQL, and others.

• JDBC enables Java applications to execute SQL statements, retrieve results, and manage
data in a platform-independent manner.

• It plays a crucial role in developing enterprise applications by allowing seamless integration


of database functionality into Java programs.

• JDBC provides a set of interfaces and classes that abstract the details of interacting with
different database systems, making database programming consistent and efficient.

5.1.1 JDBC Components


There are four main JDBC components:
• JDBC API – Defines methods and interfaces for database access.

• JDBC Driver Manager – Manages database drivers and establishes connections.


• JDBC Test Suite – Ensures compliance with JDBC standards.

• JDBC-ODBC Bridge – Facilitates interoperability between JDBC and ODBC.

5.1.2 JDBC Driver Types


JDBC drivers are classified into four types based on their interaction with databases:

1. JDBC-ODBC Bridge:

A JDBC-ODBC Bridge provides application developers with a way to access JDBC drivers via
the JDBC API. Type 1 JDBC drivers translate the JDBC calls into ODBC calls and then send
the calls to the ODBC driver. Type 1 JDBC drivers are generally used when the database client
libraries need to be loaded on every client machine.

2. Native API/Partly Java Driver:

A Native API/Partly Java Driver is a partial Java driver because it converts JDBC calls into
database- specific calls. Type 2 Native API/Partly Java Driver communicates directly with the
database server.

209
OOPS AND JAVA

3. Pure Java Driver:


A Pure Java Driver works in a three-tiered architecture. The JDBC calls are passed via the
network to the middle tier server. This server translates the calls to the database specific native
interface to further request the server. JDBC drivers available from Simba are Type 3 and Type
4 drivers.

4. Native Protocol Java Driver:

A Native Protocol Java Driver converts JDBC calls into the database-specific calls so that the
client applications can communicate directly with the server.

5.1.3 JDBC Architecture: How Java Database Connectivity Works

JDBC in Java follows a layered architecture to establish seamless communication between Java
applications and databases shown in the Figure 5.1: JDBC Architecture.

The architecture consists of:

Java Application Layer: The layer where developers write Java programs containing database
queries.

JDBC API Layer: Provides interfaces and classes that enable interaction between Java
applications and databases.

JDBC Driver Layer: The bridge that translates Java commands into database-specific calls.

Database Layer: The relational database where data is stored and retrieved.

Example:
// Import JDBC packages

import java.sql.* public class Demo

{
public static void main(String[] args) throws Exception

Class.forName("com.mysql.cj.jdbc.Driver");

// Load driver
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306 / test","root",
"password");

210
Chapter no 5: JDBC and Multithreading

System.out.println("Connected!");
con.close();

Figure 5.1: JDBC Architecture

5.2 Establishing Connection:


Before Establishing a JDBC Connection in Java (the front end, i.e., your Java Program, and the
back end, i.e., the database), we should learn what precisely a JDBC is and why it came into
existence and it’s described in the Figure 5.2: Java database connectivity

Figure.5.2: Java database connectivity

Example:
// Import JDBC packages

import java.sql.*;

211
OOPS AND JAVA

public class Demo {

public static void main(String[] args) throws Exception {


Class.forName("com.mysql.cj.jdbc.Driver"); // Load driver

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",


"password");

System.out.println("Connected!");

con.close();

} }

5.3 Executing Query:


Java programming provides a lot of packages for solving problems in our case we need to
execute SQL queries by using JDBC. We can execute a SQL query in two different approaches
by using Prepared Statement and Statement. These two interfaces are available in java.sql
package. When comparing both of them the Prepared Statement approach is secure. Approaches
to Execute a SQL Query using JDBC

We have two different approaches to executing a SQL query using JDBC.

• Using Statement

• Using Prepared Statement

Statement in JDBC
• The Statement is an interface that is available in java.sql package with JDBC.

• This interface is part of JDBC API and can execute simple SQL queries without parameters.

• We can create a Statement by using createStatement().

• This method is available in the Connection class.

5.4 Prepared Statement in JDBC


The Prepared Statement is an interface, and it provides for security for our data by using
parameter concept in Java. It can prevent SQL Injection attack also from unknown source. It is
better than Statement. We can create Prepared Statement by using prepare Statement () from
connection class and it can take SQL query as String value.

212
Chapter no 5: JDBC and Multithreading

Example:

Statement stmt = con.createStatement();

ResultSetrs = stmt.executeQuery("SELECT * FROM users");

5.4.1 Processing Results:


After executing a query, the result is returned in the form of a ResultSet object. This object
allows iteration over rows of data using methods like next(), and data can be accessed using
methods such as getInt(), getString(), and getDate(). Proper handling of the ResultSet ensures
that the data retrieved from the database is processed correctly. It also supports navigation and
metadata extraction, which are useful for building dynamic applications.

Example:
while (rs.next())
{

System.out.println(rs.getString("name"));}

5.4.2 Prepared Statement:


A Prepared Statement is a pre-compiled SQL statement. It is a sub interface of Statement.
Prepared Statement objects have some useful additional features than Statement objects. Instead
of hard coding queries, Prepared Statement object provides a feature to execute a parameterized
query.

5.4.3 Advantages of Prepared Statement


When Prepared Statement is created, the SQL query is passed as a parameter. This Prepared
Statement contains a pre-compiled SQL query, so when the Prepared Statement is executed,
DBMS can just run the query instead of first compiling it. We can use the same Prepared
Statement and supply with different parameters at the time of execution. An important
advantage of Prepared Statements is that they prevent SQL injection attacks.

5.4.4 Steps to use Prepared Statement


1. Create Connection to Database
Connection myCon = DriverManager.getConnection(path,username,password)

2. Prepare Statement
Instead of hardcoding queries like,

213
OOPS AND JAVA

select * from students where age>10 and name ='Chhavi'

Set parameter placeholders(use question mark for placeholders) like, select * from students
where age> ? and name = ?

Prepared Statement myStmt;

myStmt = myCon.prepareStatement(select * from students where age> ? and name = ?);

3. Set parameter values for type and position


myStmt.setInt(1,10); myStmt.setString(2,"Chhavi");

4. Execute the Query

ResultSetmyRs= myStmt.executeQuery(); Methods of Prepared Statement:

setInt(int, int): This method can be used to set integer value at the given parameter index.
setString(int, string): This method can be used to set string value at the given parameter index.
setFloat(int, float): This method can be used to set float value at the given parameter index.
setDouble(int, double): This method can be used to set a double value at the given parameter
index.
executeUpdate(): This method can be used to create, drop, insert, update, delete etc. It returns
int type.
executeQuery(): It returns an instance of ResultSet when a select query is executed.
Example:
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setInt(1, 101);

ResultSet rs = ps.executeQuery();

5.5 Callable Statement:


The Callable Statement of JDBC API is used to call a stored procedure.

• A Callable statement can have output parameters, input parameters, or both.


• The prepareCall() method of connection interface will be used to create Callable Statement
object.

Following are the steps to use Callable Statement in Java to call Stored Procedure:

1) Load MySQL driver and create a database connection.


import java.sql.*;
public class JavaApplication1 {
public static void main(String[] args) throws Exception

214
Chapter no 5: JDBC and Multithreading

{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection (“jdbc:mysql://localhost/ root”,
”geek”,”geek”);
}
}

2) Create a SQL String


We need to store the SQL query in a String.

String sql_string=”insert into student values(?,?,?)”;

3) Create CallableStatement Object


The prepareCall() method of connection interface will be used to create Callable Statement
object. The sql_string will be passed as an argument to the prepareCall() method.

CallableStatement cs = con.prepareCall(sql_string);

4) Set The Input Parameters

Depending upon the data type of query parameters we can set the input parameter by calling

setInt() or setString() methods.

cs.setString(1,”geek1″);

cs.setString(2,”python”);

cs.setString(3,”beginner”);

5) Call Stored Procedure


Execute stored procedure by calling execute () method of Callable Statement class. Example of
using Callable Statement in Java to call Stored Procedure

Example:

CallableStatement cs = con.prepareCall("{call getUser(?)}");


cs.setInt(1, 101);

ResultSetrs = cs.executeQuery();

5.6 Transactions:
A transaction is a group of operations performed as a single unit of work.

215
OOPS AND JAVA

In JDBC, transactions are controlled using the Connection object’s methods such as
setAutoCommit(false), commit(), and rollback(). By default, JDBC uses auto-commit mode,
where each SQL statement is treated as a transaction. Disabling auto-commit allows
developers to control when changes are saved to the database, ensuring data consistency and
atomicity, especially in applications involving multiple related database operations.

Example:
con.setAutoCommit(false);

stmt.executeUpdate("INSERT INTO users VALUES (101, 'John')"); con.commit();

public static void main(String[] args) {

// Open a connection

try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);


Statement stmt = conn.createStatement();

ResultSetrs = stmt.executeQuery(QUERY);) {

// Extract data from result set while (rs.next()) {


// Retrieve by column name System.out.print("ID: " + rs.getInt("id"));

System.out.print(", Age: " + rs.getInt("age"));


System.out.print(", First: " + rs.getString("first"));

System.out.println(", Last: " + rs.getString("last"));

} catch (SQLException e) {

e.printStackTrace();
} }}

C:\>java SelectExample Connecting to database... Creating statement...

ID: 100, Age: 18, First: Zara, Last: Ali

ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan

ID: 103, Age: 28, First: Sumit, Last: Mittal

Update Records
import java.sql. *;

public class UpdateExample {

216
Chapter no 5: JDBC and Multithreading

static final String DB_URL = "jdbc: mysql://localhost/TPOINT";


static final String USER = "guest";

static final String PASS = "guest123";

static final String QUERY1 = "UPDATE Employees SET age=20 where id=100";

static final String QUERY2= "SELECT id, first, last, age FROM Employees";

public static void main (String [] args) {


// Open a connection

try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

Statement stmt = conn.createStatement(); {


stmt.executeUpdate(QUERY1);

ResultSetrs=stmt.executeQuery(QUERY2);
// Extract data from result set while (rs.next()) {

// Retrieve by column name System.out.print("ID: " + rs.getInt("id"));

System.out.print(", Age: " + rs.getInt("age"));

System.out.print(", First: " + rs.getString("first"));

System.out.println(", Last: " + rs.getString("last"));

} } catch (SQLException e) {

e.printStackTrace();

} }} C:\>java UpdateExample

ID: 100, Age: 20, First: Zara, Last: Ali

ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan

ID: 103, Age: 28, First: Sumit, Last: Mittal C:\>

Delete Records
import java.sql. *;

public class DeleteExample {

static final String DB_URL = "jdbc: mysql://localhost/TPOINT";

static final String USER = "guest";

static final String PASS = "guest123";

static final String QUERY1 = "DELETE from Employees where id=100";

217
OOPS AND JAVA

static final String QUERY2= "SELECT id, first, last, age FROM Employees";

public static void main (String [] args) {


// Open a connection

try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

Statement stmt = conn.createStatement();

stmt.executeUpdate(QUERY1); ResultSetrs=stmt.executeQuery(QUERY2);

// Extract data from result set while (rs.next()) {


// Retrieve by column name System.out.print("ID: " + rs.getInt("id"));

System.out.print(", Age: " + rs.getInt("age"));

System.out.print(", First: " + rs.getString("first"));

System.out.println(", Last: " + rs.getString("last"));

} }

catch (SQLException e) {

e.printStackTrace(); } }}

C:\>java DeleteExample

ID: 101, Age: 25, First: Mahnaz, Last: Fatma

ID: 102, Age: 30, First: Zaid, Last: Khan


ID: 103, Age: 28, First: Sumit, Last: Mittal C:\>

5.7 Meta Data Objects:


JDBC provides two types of metadata objects: Database Meta Data and ResultSet Meta Data.
Database Meta Data is used to gather information about the structure of the database, such as
available tables, supported SQL features, and database product name. ResultSet Meta Data
provides details about the columns in a ResultSet, including column name, data type, and size.
Meta data is essential for creating dynamic database applications that can adapt to different
schemas and data formats.

Example:
DatabaseMetaDatadbmd = con.getMetaData();
System.out.println(dbmd.getDatabaseProductName());

218
Chapter no 5: JDBC and Multithreading

5.8 Multithreading in Java


Introduction to Multithreading:
Multithreading is a programming concept that allows a single process to execute multiple
threads concurrently. Threads are lightweight sub-processes within a process that share the
same memory space, but they can run independently. Each thread represents a separate flow of
control, making it possible to perform multiple tasks simultaneously within a single program.

5.8.1 Need for Multithreading


Multithreading offers several advantages, making it a valuable tool in software development:

Improved Responsiveness:
Multithreading allows applications to remain responsive to user input, even when performing
resource- intensive tasks. For example, a text editor can continue responding to user actions
while performing a spell- check in the background.

Enhanced Performance:

Multithreaded programs can take advantage of multi-core processors, leading to better


performance. Tasks can be divided among multiple threads, speeding up computation.

Resource Sharing:

Threads can share data and resources within the same process, which can lead to more efficient
memory usage. This can be crucial in memory-intensive applications.

Concurrency:

Multithreading enables concurrent execution of tasks, making it easier to manage multiple tasks
simultaneously. For instance, a web server can handle multiple client requests concurrently
using threads.

5.8.2 Different Ways to Create Threads


Threads can be created by using two mechanisms:
Extending the Thread class Implementing the Runnable Interface

1. By Extending the Thread Class


We create a class that extends the java.lang.Thread class.

219
OOPS AND JAVA

This class overrides the run() method available in the Thread class. A thread begins its life inside
the run() method.

We create an object of our new class and call the start() method to start the execution of a
thread.start() invokes the run() method on the Thread object.

Example:
/* Creating three threads using the class Thread and then running them concurrently. */

class ThreadA extends Thread{

public void run( ) {

for(int i = 1; i<= 5; i++) {


System.out.println("From Thread A with i = "+ -1*i);

System.out.println("Exiting from Thread A ...");

}}

class ThreadB extends Thread {

public void run( ) {

for(int j = 1; j <= 5; j++) {

System.out.println("From Thread B with j= "+2* j);

System.out.println("Exiting from Thread B ...");

}}
class ThreadC extends Thread{

public void run( ) {


for(int k = 1; k <= 5; k++) {

System.out.println("From Thread C with k = "+ (2*k-1));

}
System.out.println("Exiting from Thread C ...");

} }

public class Demonstration_111 {

public static void main(String args[]) {

220
Chapter no 5: JDBC and Multithreading

ThreadA a = new ThreadA();


ThreadB b = new ThreadB();

ThreadC c = new ThreadC();

a.start();

b.start();

c.start();
System.out.println("... Multithreading is over "); }}

OUTPUT:

From Thread A with i = -1


From Thread A with i = -2

From Thread A with i = -3


From Thread B with j= 2

From Thread A with i = -4

From Thread A with i = -5

Exiting from Thread A ...

... Multithreading is over

From Thread C with k = 1

From Thread B with j= 4

From Thread B with j= 6

From Thread B with j= 8

From Thread B with j= 10

Exiting from Thread B ...

From Thread C with k = 3

From Thread C with k = 5

From Thread C with k = 7 From Thread C with k = 9


Exiting from Thread C ...

In the above example, we create a MyThread class by extending Thread. The run() method
contains the code to be executed in the new thread. We create two instances of MyThread and
start them using the start () method.

221
OOPS AND JAVA

2. By Implementing the Runnable Interface

We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.

Example:
Demonstrating the multithreading by implementing the Runnable interface.

/* Creating three threads using the Runnable interface and then running them concurrently.

*/

class ThreadX implements Runnable{

public void run( ) {

for(int i = 1; i<= 5; i++) {


System.out.println("Thread X with i = "+ -1*i);

System.out.println("Exiting Thread X ...");

} }

class ThreadY implements Runnable {


public void run( ) {

for(int j = 1; j <= 5; j++) {

System.out.println("Thread Y with j = "+ 2*j);

System.out.println("Exiting Thread Y ...");

} }

class ThreadZ implements Runnable{ public void run( ) {

for(int k = 1; k <= 5; k++) {

System.out.println("Thread Z with k = "+ (2*k-1));

}
System.out.println("Exiting Thread Z ...");

} }

public class Demonstration_112 {

public static void main(String args[]) {

222
Chapter no 5: JDBC and Multithreading

ThreadX x = new ThreadX();


Thread t1 = new Thread(x);

ThreadY y = new ThreadY();

Thread t2 = new Thread(y);

//ThreadZ z = new ThreadZ();

//Thread t3 = new Thread(z);


Thread t3 = new Thread(new ThreadZ());

t1.start();

t2.start();
t3.start();

System.out.println("... Multithreading is over ");


}}

OUTPUT:
Thread X with i = -1

Thread X with i = -2

Thread Z with k = 1

Thread Z with k = 3

Thread Z with k = 5

Thread Z with k = 7

Thread Z with k = 9

Exiting Thread Z ...

... Multithreading is over

Thread Y with j = 2

Thread Y with j = 4

Thread Y with j = 6

Thread Y with j = 8

Thread Y with j = 10

Exiting Thread Y ...

Thread X with i = -3

223
OOPS AND JAVA

Thread X with i = -4

Thread X with i = -5
Exiting Thread X ...

In the above example, we create a MyRunnable class that implements the Runnable interface.
The run() method contains the code to be executed in the new thread. We create two Thread
instances, passing the MyRunnable instance as a constructor argument. Then, we start both
threads.

5.9 Process vs Thread:


Process and threads are the basic components in OS. Process is a program under execution
whereas a thread is part of process.

Threads allow a program to perform multiple tasks simultaneously, like downloading a file
while you browse a website or running animations while processing user input.

A process can consists of multiple threads.

What is Process?
• Processes are basically the programs that are dispatched from the ready state and are
scheduled in the CPU for execution.

• PCB (Process Control Block) holds the context of process.

• A process can create other processes which are known as Child Processes.

• The process takes more time to terminate, and it is isolated means it does not share the
memory with any other process.

• The process can have the following states new, ready, running, waiting, terminated and
suspended.

What is Thread?
• Threads are often called “lightweight processes” because they share some features of
processes but are smaller and faster.

• Each thread is always part of one specific process. A thread has three states: Running, Ready
and Blocked.

224
Chapter no 5: JDBC and Multithreading

• A thread takes less time to terminate as compared to the process but unlike the process,
threads do not isolate.

Table 5.1 Process vs thread

Process Thread
A process takes more time to A thread takes less time to terminate.
terminate.
It takes more time for creation. It takes less time for creation.
It also takes more time for context It takes less time for context switching.
switching.
Process means a program in execution Thread means a segment of a process.
execution.
Process switching uses an interface in Thread switching may not require
an operating system. calling involvement of operating
system.

5.10 Thread Life Cycle:


• A Java thread has several states during its life cycle: New, Runnable, Running,
Blocked/Waiting, and Terminated.

• A thread starts in the new state when created, moves to Runnable when start () is called, and
runs when the CPU schedules it.

• A thread may enter the Blocked or Waiting state due to synchronization or inter-thread
communication.

• Once the task is completed, the thread enters the Terminated state.

• Understanding the life cycle is crucial for managing thread behaviour and debugging
multithreaded applications.

225
OOPS AND JAVA

Figure 5.3: Thread Life Cycle

5.10.1 Life Cycle of a Thread


There are multiple states of the thread in a lifecycle as mentioned below:

New Thread:
When a new thread is created, it is in the new state.

The thread has not yet started to run when the thread is in this state.

When a thread lies in the new state, its code is yet to be run and has not started to execute.

Runnable State:
A thread that is ready to run is moved to a runnable state.

In this state, a thread might actually be running or it might be ready to run at any instant of
time. It is the responsibility of the thread scheduler to give the thread, time to run.

A multi-threaded program allocates a fixed amount of time to each individual thread. Each and
every thread get a small amount of time to run.

After running for a while, a thread pauses and gives up the CPU so that other threads can run.

Blocked:

The thread will be in blocked state when it is trying to acquire a lock but currently the lock is
acquired by the other thread.

The thread will move from the blocked state to runnable state when it acquires the lock.

226
Chapter no 5: JDBC and Multithreading

Waiting state:

The thread will be in waiting state when it calls wait() method or join() method.

It will move to the runnable state when other thread will notify or that thread will be terminated.

Timed Waiting:
A thread lies in a timed waiting state when it calls a method with a time-out parameter. A thread
lies in this state until the timeout is completed or until a notification is received.

For example, when a thread calls sleep or a conditional wait, it is moved to a timed waiting
state.

Terminated State:
A thread terminates because of either of the following reasons: Because it exits
normally.

This happens when the code of the thread has been entirely executed by the program.

Because there occurred some unusual erroneous event, like a segmentation fault or an
unhandled exception. Thread States in Java

In Java, to get the current state of the thread, use Thread.getState() method to get the current
state of the thread.

Java provides java.lang.Thread.State enum that defines the ENUM constants for the state of a
thread.

5.10.2 New
Thread state for a thread that has not yet started.

public static final Thread.State NEW

5.10.3 Runnable
Thread state for a runnable thread.

A thread in the runnable state is executing in the Java virtual machine but it may be waiting for
other resources from the operating system such as a processor.

public static final Thread.State RUNNABLE

5.10.4. Blocked
Thread state for a thread blocked waiting for a monitor lock.

227
OOPS AND JAVA

A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method
or re-enter a synchronized block/method after calling Object. Wait ().

public static final Thread.State BLOCKED

5.10.5. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the
following methods:

Object.wait with no timeout

Thread.join with no timeout

LockSupport.park

public static final Thread.State WAITING

5.10.6 Timed Waiting


Thread state for a waiting thread with a specified waiting time.

A thread is in the timed waiting state due to calling one of the following methods with a
specified positive waiting time:

Thread.sleep

Object.wait with timeout

Thread.join with timeout

LockSupport.parkNanos
LockSupport.parkUntil

public static final Thread.State TIMED_WAITING

5.10.7. Terminated
Thread state for a terminated thread. The thread has completed execution.

public static final Thread.State TERMINATED


/* Demonstration of thread class methods :getID() */

/* Java code for thread creation by extending the Thread class */


class ThreadId extends Thread {

public void run() {

try {

// Displaying the thread that is running

228
Chapter no 5: JDBC and Multithreading

System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); }


catch (Exception e) {

// Throwing an exception System.out.println ("Exception is caught");

} } }

public class Demonstration_113{

public static void main(String[] args)


{

int n = 8;

// Number of threads
for (int i=0; i<8; i++)

{
ThreadId object = new ThreadId();

object.start(); } } }

OUTPUT:
Thread 21 is running

Thread 22 is running

Thread 23 is running

Thread 25 is running

Thread 26 is running

Thread 27 is running

Thread 24 is running

Thread 28 is running

/* Use of yield(), stop() and sleep() methods */

class ClassA extends Thread{

public void run() {

System.out.println("Start Thread A ");

for(int i = 1; i<= 5; i++) {

if (i==1) yield();

System.out.println("From Thread A: i = "+ i);

229
OOPS AND JAVA

System.out.println(" Exit Thread A");


} }

class ClassB extends Thread{

public void run() {

System.out.println("Start Thread B ");

for(int j = 1; j <= 5; j++) {

System.out.println("From Thread B: j = "+ j);


if (j==2) stop();

System.out.println(" Exit Thread B");

} }

class ClassC extends Thread{

public void run() {

System.out.println("Start Thread C ");

for(int k = 1; k <= 5; k++) {

System.out.println("From Thread B: j = "+ k);

if (k==3){
try{

sleep(1000);

catch(Exception e){}

}
}

System.out.println(" Exit Thread C");

} }

public class Demonstration_115{

public static void main (String args[]) {

ClassA t1 = new ClassA();

230
Chapter no 5: JDBC and Multithreading

ClassB t2 = new ClassB(); ClassC t3 = new ClassC();


t1.start();

t2.start();

t3.start();

System.out.println(" End of executuion ");

} }

OUTPUT:

Start Thread A ....

Start Thread C ....


Start Thread B ....

... End of executuion


From Thread A: i = 1

From Thread B: j = 1

From Thread B: j = 2

From Thread B: j = 1

From Thread A: i = 2

From Thread A: i = 3

From Thread A: i = 4

From Thread A: i = 5

... Exit Thread A

From Thread B: j = 2

From Thread B: j = 3

From Thread B: j = 4

From Thread B: j = 5

... Exit Thread C


/* Use of suspend() and resume() methods */

class Thread1 extends Thread {


public void run( ) {

try{

231
OOPS AND JAVA

System.out.println (" First thread starts running" );

sleep(10000);
System.out.println (" First thread finishes running" );

catch(Exception e){ }

}}

class Thread2 extends Thread {

public void run( ) {


try{

System.out.println( "Second thread starts running");

System.out.println( "Second thread is suspended itself ");

suspend( );

System.out.println (" Second thread runs again" );

catch(Exception e){ }

} }

class Demonstration_116{

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


Thread1 first = new Thread1( ); // It is a newborn thread i.e. in Newborn state

Thread2 second= new Thread2( ); // another new born thread

first.start( ); // first is scheduled for running second.start( );

// second is scheduled for running

System.out.println("Revive the second thread" );


// If it is suspended second.resume( );

System.out.println ("Second thread went for 10 seconds sleep “);

second.sleep (10000);

System.out.println ("Wake up second thread and finishes running”);

System.out.println(“Demonstration is finished ");

232
Chapter no 5: JDBC and Multithreading

catch(Exception e)
{

} }

OUTPUT:
Revive the second thread First thread starts running Second thread starts running

Second thread is suspended itself

Second thread went for 10 second’s sleep

5.11 Thread Class:


The Thread class in Java is a built-in way to create and control threads. By extending the Thread
class and overriding its run() method, we define the task the thread will perform. To execute
the thread, we call the start() method, which internally invokes the run() method in a new thread
of execution. The Thread class provides many useful methods like sleep(), join(), getName(),
and setPriority().

Example:
class MyThread extends Thread {
public void run() {

System.out.println("Hello from thread");


}}

5.12 Runnable Interface:


The Runnable interface provides a flexible way to implement multithreading in Java. A class
implements Runnable and overrides the run() method. This Runnable object is then passed to a
Thread constructor, and the thread is started using the start() method. This approach is preferred
when the class already extends another class, promoting better design and reusability.

Example:
class MyRunnable implements Runnable {

public void run() {


System.out.println("Runnable running");

}}

233
OOPS AND JAVA

5.13 Thread Creation:


There are two main ways to create threads in Java: by extending the Thread class or by
implementing the Runnable interface. Both approaches require overriding the run() method to
define the thread’s logic. After creation, calling the start() method begins thread execution. Java
also introduced the Executor Service framework for better thread management in large-scale
applications.

Thread t = new Thread(new MyRunnable()); t.start();

5.14 Thread Control and Priorities:


Java allows developers to control thread execution using methods like sleep() to pause
execution, join() to wait for a thread to finish, and interrupt() to stop a thread. Threads can be
assigned priorities (from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY) to influence
scheduling decisions by the JVM. However, thread scheduling is platform-dependent, so
priorities are not guaranteed to behave consistently across systems. A higher priority thread
usually has a better chance to use the CPU than a lower priority thread.

Example:
// The minimum priority that a thread can have.
public static final int MIN_PRIORITY = 1;

// The default priority that is assigned to a thread.


public static final int NORM_PRIORITY = 5;

// The maximum priority that a thread can have.

public static final int MAX_PRIORITY = 10;


A thread’s priority can be set using the setPriority() method and obtained using the getPriority()
method.

5.15 Thread Synchronization:


When multiple threads access shared data or resources, it can lead to inconsistent or corrupted
data. Synchronization is a mechanism to ensure that only one thread accesses the critical section
at a time. Java provides the synchronized keyword for methods or code blocks to implement
mutual exclusion. Additionally, Java offers higher-level concurrency utilities like Re-entrant,
Semaphore, and Concurrent HashMap to handle synchronization in complex applications.

234
Chapter no 5: JDBC and Multithreading

Example:
synchronized void update() {

// critical section

}
Suppose, we want to maintain a bank account of customers. Several transactions, such as
deposit some amount to an account and withdraw some amount from an account etc. are
possible. Now, for a given account, if two or more transactions come simultaneously then only
one transaction should be allowed at a time instead of simultaneous transaction processing so
that data inconsistency will never occur. So, what we need is to synchronize the transaction.

/* The following Java application shows how the transactions in a bank can be carried out
concurrently. */

class Account {
public int balance;

public int accountNo;


void displayBalance() {

System.out.println("Account No:" + accountNo + "Balance: " + balance);}

synchronized void deposit(int amount){

balance = balance + amount; System.out.println( amount + " is deposited");

displayBalance();}
synchronized void withdraw(int amount){

balance = balance - amount;

System.out.println( amount + " is withdrawn");

displayBalance();}}

class TransactionDeposit implements Runnable{

int amount;
Account accountX;

TransactionDeposit(Account x, int amount){

accountX = x;

this.amount = amount;

new Thread(this).start();}

235
OOPS AND JAVA

public void run(){

accountX.deposit(amount);}}
class TransactionWithdraw implements Runnable{

int amount;

Account accountY;

TransactionWithdraw(Account y, int amount) {

accountY = y;

this.amount = amount;
new Thread(this).start(); }

public void run(){

accountY.withdraw(amount); }}

class Demonstration_119{

public static void main(String args[]) {

Account ABC = new Account(); ABC.balance = 1000;

ABC.accountNo = 111;

TransactionDeposit t1;

TransactionWithdraw t2;

t1 = new TransactionDeposit(ABC, 500);


t2 = new TransactionWithdraw(ABC,900); }}

OUTPUT:
500 is deposited

Account No:111

Balance: 1500
900 is withdrawn

Account No:111
Balance: 600

236
Question Bank

QUESTION BANK

CHAPTER I

PART-A

1.What are the features of java?

• Object-oriented

• Platform-independent

• Simple

• Secure

• Robust

• Multithreaded

• High performance

• Dynamic

2.Difference between JDK, JRE, and JVM.

• JDK: Java Development Kit; includes JRE and development tools.

• JRE: Java Runtime Environment; allows running Java applications.

• JVM: Java Virtual Machine; executes bytecode.

3.What is bytecode?

• Bytecode is an intermediate, platform-independent code generated by the Java compiler,


which the JVM interprets and executes.

4.What is a variable? What are the different types of variables?

A variable is a storage location with a name. Types:

• Local Variables

• Instance Variables

• Static Variables

237
OOPS AND JAVA

5.What is the difference between static variable and instance variable?

• Static Variable: Shared among all instances, belongs to the class.

• Instance Variable: Unique to each instance of the class.

6.What are primitive datatypes in java?

• byte

• short

• int

• long

• float

• double

• char

• boolean

7.List out the operator in Java.

• Arithmetic, Relational, Logical, Bitwise, Assignment, Unary, Ternary

8.What is object?

An object in Java is an instance of a class that encapsulates state (attributes) and behavior
(methods). Objects are used to represent real-world entities in programming.

9.What are the Types of java constructors?

• Default Constructor

• Parameterized Constructor

10.What is the use of ‘this’ Keyword?

The this keyword in Java serves as a reference to the current object within a class. It allows you
to access instance variables and methods of the current object, and it is particularly useful in
situations where there might be naming conflicts or ambiguities.

238
Question Bank

11.What gives java it’s “write once and run anywhere” nature?

• Java achieves its "write once, run anywhere" (WORA) capability through the use of the Java
Virtual Machine (JVM).

• When Java code is compiled, it is transformed into bytecode, which is platform-independent.

• This bytecode can be executed on any device that has a JVM, allowing the same Java program
to run on different operating systems without modification.

12.Why Java is Platform Independent.

• Java is platform-independent because it compiles code into bytecode, which is not specific to
any particular hardware or operating system.

• The JVM interprets this bytecode and translates it into machine code that can be executed on
the host system.

13.Why Java is Architecture-Neutral.

• Java is architecture-neutral because the bytecode generated by the Java compiler is not tied to
any specific hardware architecture.

• This means that the same bytecode can run on any architecture that has a compatible JVM.

14.What is finalize () method?

• The finalize () method in Java is a method of the Object class that is called by the garbage
collector before an object is reclaimed.

• It allows an object to perform cleanup operations, such as releasing resources or closing


connections.

15.What is type conversion in Java?

• Type conversion in Java refers to the process of converting a variable from one data type to
another.

• There are two types of type conversion: implicit (automatic) and explicit (manual).

16.Write the difference between break and continue statements in Java.

break statement

239
OOPS AND JAVA

The break statement is used to exit a loop or switch statement immediately. When a break is
encountered, the control is transferred to the statement following the loop or switch.

continue statement

The continue statement is used to skip the current iteration of a loop and proceed to the next
iteration. When a continue is encountered, the remaining code in the loop for that iteration is
skipped.

17.What are different integer data types in Java?

Java has four integer data types:

• byte: 8-bit signed integer (range: -128 to 127)

• short: 16-bit signed integer (range: -32,768 to 32,767)

• int: 32-bit signed integer (range: -2^31 to 2^31-1)

• long: 64-bit signed integer (range: -2^63 to 2^63-1)

18.Can you make the keyword public to private in main() method? If yes, what will happen?

• Yes, you can change the access modifier of the main() method from public to private.
However, if you do this, the Java Virtual Machine (JVM) will not be able to access the main()
method to start the program, resulting in a runtime error.

• The JVM requires the main() method to be public and static to execute the program.

19. Assess the error in the following array declaration and rectify them.

a.int a[]=new [10]int;

b.float []b=new int[10.5];

a. int a[]=new [10]int;

• Error: The syntax for array declaration is incorrect. The correct syntax does not require square
brackets before the size of the array.

b. float []b=new int[10.5];

• Error: The size of the array must be an integer value. In this case, 10.5 is a floating-point
number, which is not allowed for array sizes.

240
Question Bank

20.Create a java program using control flow statements.

import java.util.Scanner;

public class ControlFlowExample {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (number % 2 == 0) {

System.out.println(number + " is even.");

} else {

System.out.println(number + " is odd.");

switch (number) {

case 0:

System.out.println("You entered zero.");

break;

case 1:

System.out.println("You entered one.");

break;

case 2:

System.out.println("You entered two.");

break;

default:

System.out.println("You entered a number greater than two.");

241
OOPS AND JAVA

break;

System.out.println("Numbers from 1 to " + number + ":");

for (int i = 1; i<= number; i++) {

System.out.print(i + " ");

} scanner.close();

}}

PART-B

1. Explain any four features of java programming.

2. What is type casting? Explain its types with proper syntax and example.

3. State & explain scope of variable with an example.

4. Define a class and object. Write syntax to create class and object with an Example.

5. Write a java program to display all the odd numbers between 1 to 30 using for loop & if
statement.

6. Explain following bitwise operator with an example :

 left shift operator


 right shift operator

7. Explain any two relational operators in Java with example.

8. Write a program to find sum of digit of number entered by user.

9. Write all primitive data types available in Java with their storage sizes in bytes.

10. Write a program to generate Fibonacci series 1 1 2 3 5 8 13 21 34 55 8 9.

11. Why java became platform independent language? Explain.

12. Write a program to check wheater given number is prime or not.

13. Write a program to print the following output:

11111

242
Question Bank

2222

333

44

14. Illustrate with example the use of switch case statement.

15. Explain any four mathematical functions.

16. Explain with example labeled for loop.

CHAPTER II

PART-A

1.Define method overloading.

• Method overloading in Java occurs when multiple methods in the same class have the same
name but different parameter lists (different type, number, or both).

• It allows methods to perform similar functions with different inputs.

2.What is meant by an innerclass?

• An inner class is a class defined within another class. It can access the members (including
private members) of the outer class.

• Inner classes are used to logically group classes that are only used in one place, increasing
encapsulation.

3.What are the uses of the keyword ‘final’?

• The final keyword in Java is used to declare constants, prevent method overriding, and prevent
inheritance of classes.

• A final variable cannot be reassigned, a final method cannot be overridden, and a final class
cannot be subclassed.

4.What are static methods?

• Static methods belong to the class rather than any specific instance of the class.

243
OOPS AND JAVA

• They can be called without creating an object of the class and can only access static variables
and methods directly.

• They are often used for utility or helper methods.

5.What is inheritance?

• Inheritance is a fundamental concept in object-oriented programming that allows a new class


(subclass) to inherit properties and behaviors (fields and methods) from an existing class
(superclass).

• It promotes code reusability and establishes a hierarchical relationship.

6.What is the use of ‘Super’ Keyword?

• The super keyword is used to refer to the immediate parent class object.

• It can be used to access parent class methods and constructors.

7.Difference between method overloading and method overriding in java.

Method Overloading

Occurs within the same class with the same method name but different parameters. It is resolved
at compile time (static polymorphism).

Method Overriding

Occurs in subclasses where a subclass provides a specific implementation of a method that is


already defined in its superclass. It is resolved at runtime (dynamic polymorphism).

8.What is constructor overloading?

• Constructor overloading occurs when a class has more than one constructor with different
parameter lists.

• This allows objects of the class to be initialized in different ways based on the arguments
passed.

9.How to pass object as argument in java?

We can pass an object as an argument to a method by specifying the object type in the method
parameter.

class MyClass {

244
Question Bank

void display(MyObject obj) {

}}

10.What is recursion?

• Recursion is a programming technique where a method calls itself to solve a problem.

• It typically involves a base case to terminate the recursion and a recursive case that breaks
the problem into smaller subproblems.

11.List Access Specifiers in java.

The access specifiers in Java are:

• public: Accessible from any other class.

• protected: Accessible within the same package and subclasses.

• default (no modifier): Accessible only within the same package.

• private: Accessible only within the same class.

12.Define abstract class.

• An abstract class in Java is a class that cannot be instantiated and may contain abstract
methods (methods without a body).

• It is used to provide a base for subclasses to implement specific behaviors while sharing
common functionality.

13.What are the rules for method overriding?

• The method in the subclass must have the same name, return type, and parameters as the
method in the superclass.

• The overriding method cannot be more restrictive than the overridden method (e.g., cannot
change from public to private).

• The method must be marked as virtual in the superclass if using languages that require it (Java
does this by default).

14.What is Static Polymorphism?

245
OOPS AND JAVA

• Static polymorphism, also known as compile-time polymorphism, occurs when multiple


methods have the same name but differ in parameters (method overloading).

• The method to be executed is determined at compile time based on the method signature.

15.What are the 3 ways of Overloading Method?

Different Number of Parameters: Methods with the same name but different parameter
counts.

Different Types of Parameters: Methods with the same name but different parameter types.

Different Order of Parameters: Methods with the same name but different parameter types
in a different order.

16.What are the types of inheritance?

The types of inheritance in Java are:

Single Inheritance: A class inherits from one superclass.

Multilevel Inheritance: A class inherits from a superclass, which is also a subclass of another
class.

Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.

Multiple Inheritance (through interfaces): A class can implement multiple interfaces, allowing
it to inherit behavior from multiple sources.

17.Can you use this () and super () both in a constructor?

• No, We cannot use this() and super() in the same constructor.

If we use one, it must be the first statement in the constructor.

• We can either call another constructor of the same class using this() or call the superclass
constructor using super(), but not both.

18. How can we achieve multiple inheritance in java?

• Java does not support multiple inheritance with classes to avoid ambiguity (the "Diamond
Problem").

• However, multiple inheritance can be achieved through interfaces.

246
Question Bank

• A class can implement multiple interfaces, allowing it to inherit behavior from multiple
sources.

19.How to check the starting and ending point of a string?

To check the starting and ending point of a string in Java, We can use the startsWith() and
endsWith() methods of the String class.

String str = "Hello, World!";

boolean starts = str.startsWith("Hello"); // true

boolean ends = str.endsWith("World!"); // true

20.What value is assigned to String class type when it is automatically initialized and specify
some operations that are performed using string?

• When a String variable is automatically initialized in Java, it is assigned a value of null. This
means it does not reference any string object until explicitly assigned a value.

• Length: str.length()

• Concatenation: str1 + str2

• Substring: str.substring(startIndex, endIndex)

• Character Access: str.charAt(index)

• Comparison: str.equals(otherString) or str.compareTo(otherString)

PART-B

1.Which are the restrictions present for static declared methods?

2.Explain how interface is used to achieve multiple Inheritances in Java.

3.Write a java program to implement multilevel inheritance with 4 levels of hierarchy.

4.Which are the ways to access package from another package? Explain with example.

5.Write a java program to extend interface assuming suitable data.

6.Write a java program to implement runnable interface with example.

7.How to add new class to a package? Explain with an example.

247
OOPS AND JAVA

8.What is single level inheritance? Explain with suitable example.

9.What is package? State how to create and access user defined package in Java.

10.What is meant by interface? State its need and write syntax and features of interface.

11.Explain about java building String and String Buffer class functions with an example

12.What is Iterator class? Give syntax and use of any two methods of Iterator class.

13.Write a program to implement following inheritance: List any four built-in packages from
Java API along with their use.

14.Explain inheritance and polymorphism features of Java.

15.What is the multiple inheritance? Write a java program to implement multiple inheritance.

16.What is package? How do we create it? Give the example to create and to access package.

17.Explain method overriding with suitable example

18.What is importance of super and this keyword in inheritance? Illustrate with suitable
example.

19.Write a single program to implement inheritance and polymorphism in java.

20.Explain concept of nesting of interface.

21.Explain dynamic method dispatch.

22.What is Iterator class? Give syntax and use of any two methods of Iterator class

CHAPTER III

PART-A

1.What is a package?

• A package in Java is a namespace that organizes a set of related classes and interfaces.

• It helps avoid naming conflicts and can control access with access modifiers.

2.Write a note on import statement?

248
Question Bank

• The import statement in Java is used to bring other classes, interfaces, or entire packages into
visibility, allowing the use of their functionalities without needing to specify their full package
names.

3.Explain the usage of Java packages.

• Java packages are used to group related classes and interfaces, manage namespaces, control
access, and facilitate easier maintenance and organization of code.

4.Define interface.

• An interface in Java is a reference type that defines a contract of methods that implementing
classes must provide.

• It can contain method signatures and constants but no method bodies.

5.What is the useful of Interfaces?

• Interfaces allow for abstraction and multiple inheritance in Java, enabling different classes to
implement the same set of methods, promoting loose coupling and flexibility in code design.

6.Define an exception.

• An exception is an event that disrupts the normal flow of a program's execution, indicating an
error or unexpected condition that needs to be handled.

7.What are the types of Exception in Java?

• Exceptions in Java are categorized into two main types: checked exceptions (which must be
declared or handled) and unchecked exceptions (which do not require explicit handling).

8.Difference between Checked and Unchecked Exceptions.

• Checked exceptions are checked at compile-time and must be either caught or declared in the
method signature, while unchecked exceptions occur at runtime and do not require explicit
handling.

9.What is the keyword in Exception?

• The main keywords related to exceptions in Java are try, catch, finally, throw, and throws.

10.What is use of try block?

249
OOPS AND JAVA

• The try block is used to enclose code that may throw an exception, allowing the program to
handle potential errors gracefully.

11.What is catch block?

• The catch block is used to handle exceptions that are thrown by the try block, allowing the
programmer to define how to respond to specific exceptions.

12.What is use of ‘throw statement’ give an example? (or) state the purpose of the throw
statement.

• The throw statement is used to explicitly throw an exception.

• For example: throw new IllegalArgumentException("Invalid argument!");

13.What is throws in java?

• The throws keyword is used in a method signature to declare that the method may throw
certain exceptions, indicating to the caller that they need to handle or declare those exceptions.

14.Difference between throw and throws.

• throw is used to explicitly throw an exception, while throws is used in a method declaration
to indicate that the method may throw exceptions.

15.How can you access the class if it is declared without any access modifiers?

• A class declared without any access modifiers has package-private access, meaning it can be
accessed by other classes in the same package.

16.What is finally in Java with example?

• The finally block is used to execute code after a try-catch block, regardless of whether an
exception was thrown.

17.What is the difference between error and exception?

• An error is a serious issue that a reasonable application should not try to catch (e.g.,
OutOfMemoryError), while an exception is a condition that can be caught and handled by the
application.

18.How does nested try catch work in Java?

250
Question Bank

• Nested try-catch allows a try block to be placed inside another try block, enabling more
granular exception handling for different sections of code.

19.How can you directly access all classes in the packages?

• We can directly access all classes in a package by using the wildcard import statement: import
packageName.*;.

20.State the general form of an exception handling block.

try {

// code that may throw an exception

} catch (ExceptionType e) {

// handle exception

} finally {

// cleanup code (optional)

PART-B

1.Define exception. Why it is needed? Explain the different types of exceptions and the
exception hierarchy with appropriate examples using Java.

2.Define package? How it is created and implemented in JAVA?

3.List the benefits of using packages? Write down the steps in creating a package and using it
in a java program with an example.

4.What is package? How to add a class into a package?

5.Discuss package concept to perform arithmetic operations. Explain how to use it?

6.Illustrate the use of try-catch clauses by sample statements of rare type of run time error.

7.How exceptions are handled in Java? Explain the important methods used to handle
exception.

8.Describe the following concepts with example

i. Try-catch-throw paradigm.

251
OOPS AND JAVA

ii.Exception specification.

9.Discuss in detail about exception handling constructs and write a program to illustrate Divide
by zero exception

10.Assess in detail about the reusable classes in Packages.

11.Evaluate a try block that is likely to generate three types of exception and then incorporate
necessary catch blocks and handle them appropriately

CHAPTER IV

PART-A

1.What are Wrapper Classes in Java?

• Wrapper classes in Java are used to convert primitive data types (like int, char, etc.) into
objects.

• Each primitive type has a corresponding wrapper class (e.g., Integer for int, Character for
char) that provides methods for manipulating the values.

2.What are the Predefined Wrapper Classes in Java?

• Java provides predefined wrapper classes for each primitive data type: Byte, Short, Integer,
Long, Float, Double, Character, and Boolean.

• These classes allow primitives to be treated as objects, enabling the use of methods and
collections.

3.What is Type Conversion in Java?

• Type conversion in Java refers to converting one data type into another.

• It can be implicit (automatic) when converting from a smaller to a larger type (e.g., int to
double) or explicit (manual) when converting from a larger to a smaller type (e.g., double to
int).

4.What is Autoboxing and Unboxing?

• Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class
(e.g., int to Integer).

252
Question Bank

• Unboxing is the reverse process, where a wrapper class is converted back to its primitive type
(e.g., Integer to int)-.

5.What is the Java Collections API?

• The Java Collections API is a framework that provides a set of classes and interfaces for
storing and manipulating groups of objects.

• It includes data structures like lists, sets, and maps, facilitating efficient data management.

6.What is the Collection Framework in Java?

• The Collection framework in Java is a unified architecture for representing and manipulating
collections of objects.

• It includes interfaces like Collection, List, Set, and Map, along with their implementations, to
manage groups of objects.

7.What are Generics in Java?

• Generics in Java allow developers to define classes, interfaces, and methods with a
placeholder for types, enabling type safety and reducing the need for casting.

• For example, List<T> can hold any type specified at instantiation.

8.What are List Implementations in Java?

• The List interface in Java has several implementations, including ArrayList, LinkedList, and
Vector.

• Each implementation has different performance characteristics and use cases, such as dynamic
resizing or thread safety.

9.What are Set Implementations in Java?

• The Set interface represents a collection that does not allow duplicate elements.

• Common implementations include HashSet, LinkedHashSet, and TreeSet, each providing


different ordering and performance characteristics.

10.What are Map Implementations in Java?

• The Map interface maps keys to values and does not allow duplicate keys.

253
OOPS AND JAVA

• Implementations include HashMap, LinkedHashMap, and TreeMap, each offering different


performance and ordering features.

11.What are Functional Interfaces in Java?

• A functional interface in Java is an interface that contains exactly one abstract method.

• They can be used as the basis for lambda expressions and method references, enabling
functional programming in Java.

12.What are Lambda Expressions in Java?

• Lambda expressions are a feature in Java that allows you to write concise, inline
implementations of functional interfaces.

• They provide a clear and expressive way to represent a single method interface.

13.How can you access local variables in Lambda Expressions?

• In lambda expressions, local variables referenced from the enclosing scope must be
effectively final, meaning they cannot be modified after being assigned.

• This ensures thread safety and predictable behavior.

14.How can you access class variables in Lambda Expressions?

• Lambda expressions can access instance variables and static variables of the enclosing class
directly, allowing them to utilize class-level data without restrictions.

15.What are Predicates in Java?

• A Predicate is a functional interface that represents a single argument function that returns a
boolean value.

• It is commonly used for filtering collections based on certain conditions.

16.What are Functions in Java?

• The Function interface represents a function that takes one argument and produces a result.

• It is a generic interface that can be used to transform data in a functional programming style.

17.What are Suppliers in Java?

• A Supplier is a functional interface that represents a supplier of results.

254
Question Bank

• It does not take any arguments and returns a value, making it useful for generating or
providing data on demand.

18.What are Consumers in Java?

• A Consumer is a functional interface that represents an operation that takes a single input
argument and returns no result.

• It is often used for performing actions on elements of a collection.

19.What is the Stream API in Java?

• The Stream API in Java provides a functional approach to processing sequences of elements,
allowing operations like filtering, mapping, and reducing to be performed.

20.What are Parallel Streams in Java?

• Parallel Streams in Java are a feature of the Stream API that allows for parallel processing of
data.

• They enable the execution of stream operations concurrently, utilizing multiple threads from
the Fork/Join framework to improve performance on large datasets.

PART-B

1.Explain how they allow primitive types to be treated as objects.

2.Discuss the methods provided by these classes, such as parsing and conversion methods.

3.Explain type conversion in Java, including implicit and explicit conversion.

4.Explain how Java automatically converts between primitive types and their corresponding
wrapper classes.

5.Explain the core interfaces and classes in the Collections API.

6.Discuss the different types of collections (e.g., List, Set, Map).

7.Explain the role of the Collection interface and its significance in the framework.

8.Compare and contrast different List implementations: ArrayList, LinkedList, and Vector.

9.Explain the differences in ordering, performance, and use cases for each implementation.

10.Discuss how they can be used to manipulate and process data in collections.

255
OOPS AND JAVA

11.Provide examples demonstrating the use of these operations in practical scenarios.

12.Provide an overview of the Stream API and its purpose in Java.

13.Discuss the benefits of using streams for processing collections.

14.Explain the key operations available in the Stream API, such as map, filter, and reduce.

15.Discuss their roles in functional programming and the Stream API.

16.Provide examples of each interface in use, demonstrating their applications in Java.

17.Explain how lambda expressions can access instance and static variables of the enclosing
class.

18.Discuss the implications of accessing class variables in terms of scope and lifecycle.

19.Provide examples illustrating the access of class variables in lambda expressions.

20.Explain the concept of effectively final variables.

CHAPTER V

PART-A

1.What is JDBC?

• JDBC (Java Database Connectivity) is an API in Java that allows Java applications to interact
with databases. It provides methods for querying and updating data in a database, enabling
seamless communication between Java applications and various database management
systems.

2.What is JDBC Driver?

• A JDBC Driver is a software component that enables Java applications to interact with a
database using the Java Database Connectivity (JDBC) API.

• It acts as a bridge between the Java application and the database, translating Java calls into
database-specific calls.

3.What is the purpose of establishing a connection in JDBC?

• Establishing a connection in JDBC is essential for enabling communication between a Java


application and a database.

256
Question Bank

• It involves loading the database driver and using a connection URL to connect to the database,
allowing the application to execute SQL statements.

4.What are the steps to connect to the database in java?

To connect to a database in Java using JDBC, follow these general steps:

• Load the JDBC driver for your specific database.

• Establish a connection using the database URL, username, and password.

• Create a statement object to send SQL queries.

• Execute the SQL queries and process the results.

• Close the connection to free up resources.

5.What are the JDBC API components?

• The JDBC API consists of several key components, including DriverManager, Connection,
Statement, PreparedStatement, ResultSet, and RowSet, which facilitate database interactions.

• JDBC statements include Statement, PreparedStatement, and CallableStatement, each


serving different purposes for executing SQL queries and handling results.

6.How do you execute a query in JDBC?

• To execute a query in JDBC, you create a Statement or PreparedStatement object from the
Connection object and then call the executeQuery() method for SELECT statements or
executeUpdate() for INSERT, UPDATE, or DELETE statements.

7.How do you process results in JDBC?

• Results from a query in JDBC are processed using the ResultSet object, which is returned by
executing a query.

• We can iterate through the ResultSet using methods like next(), and retrieve data using
methods like getString(), getInt(), etc.

8.What is a Prepared Statement in JDBC?

• A PreparedStatement is a precompiled SQL statement that can be executed multiple times


with different parameters.

257
OOPS AND JAVA

• It improves performance and security by preventing SQL injection attacks and allowing
efficient execution of parameterized queries.

9.What is a Callable Statement in JDBC?

• A CallableStatement is used to execute stored procedures in a database.

• It allows you to call a stored procedure with input and output parameters, enabling complex
operations to be performed directly in the database.

10.What are transactions in JDBC?

• Transactions in JDBC are a sequence of operations that are executed as a single unit of work.

• They ensure data integrity by allowing you to commit or roll back changes based on the
success or failure of the operations.

11.What are Meta Data objects in JDBC?

• Meta Data objects in JDBC provide information about the database, such as the structure of
tables, columns, and data types.

• The DatabaseMetaData and ResultSetMetaData interfaces are used to retrieve this


information.

12.What is multithreading in Java?

• Multithreading in Java is the concurrent execution of two or more threads, allowing multiple
tasks to be performed simultaneously within a single program.

• It improves application performance and responsiveness.

13.What is the difference between a Process and a Thread?

• A process is an independent program in execution with its own memory space, while a thread
is a lightweight subprocess that shares the same memory space with other threads in the same
process.

• Threads are more efficient for resource sharing.

14.What is the Thread life cycle in Java?

• The Thread life cycle in Java consists of several states: New, Runnable, Blocked, Waiting,
Timed Waiting, and Terminated.

258
Question Bank

• A thread transitions between these states based on its execution and scheduling by the Java
Virtual Machine (JVM).

15.What is the Thread class in Java?

• The Thread class in Java is a built-in class that represents a thread of execution.

• It provides methods to create, start, and control threads, as well as to manage their life cycle
and state.

16.What is the Runnable Interface in Java?

• The Runnable interface is a functional interface that defines a single method, run(), which
contains the code to be executed by a thread.

• It allows you to create a thread by implementing this interface and passing it to a Thread
object.

17.How do you create a thread in Java?

• A thread can be created in Java by either extending the Thread class or implementing the
Runnable interface.

• After defining the thread's behavior, you can start it using the start() method.

18.What is thread control and priorities in Java?

• Thread control in Java refers to managing the execution of threads, including starting,
pausing, and stopping them.

• Thread priorities determine the order in which threads are scheduled for execution, with
higher priority threads being executed before lower priority ones.

19.What is thread synchronization in Java?

• Thread synchronization in Java is a mechanism that ensures that two or more concurrent
threads do not access shared resources simultaneously, preventing data inconsistency.

• It can be achieved using synchronized methods or blocks, and it helps maintain data integrity
in multithreaded applications.

20.What is the purpose of the DatabaseMetaData interface in JDBC?

259
OOPS AND JAVA

• The DatabaseMetaData interface provides methods to obtain information about the database
as a whole, including its capabilities, supported SQL syntax, and the structure of its tables,
views, and stored procedures.

• It helps developers understand the database environment and make informed decisions in their
applications.

PART-B

1.Discuss the role of JDBC drivers and how they enable communication between Java
applications and databases.

2.Explain the process of loading the JDBC driver.

3.Discuss how to create a connection using DriverManager.

4.Provide an example of a connection string and the parameters involved.

5.Discuss the use of Statement, PreparedStatement, and CallableStatement.

6.Provide examples of executing different types of SQL queries (SELECT, INSERT, UPDATE,
DELETE).

7.Explain the differences between these statement types.

8.Discuss the process of starting a thread using the start() method.

9.Define the Runnable interface and its purpose in multithreading.

10.Discuss the advantages of using Runnable over extending the Thread class.

11.Provide examples of implementing the Runnable interface to create threads.

12.Define the Thread class and its role in creating and managing threads.

13.Discuss the methods provided by the Thread class for thread control.

14.Provide examples of extending the Thread class to create custom threads.

15.Compare and contrast the use of Statement, PreparedStatement, and CallableStatement in


JDBC. When would you use each type?

16.Design a Java application that connects to a database, executes a query, and processes the
results using JDBC. Include error handling and transaction management.

260
Question Bank

17.Demonstrate how to create a thread in Java by implementing the Runnable interface. Provide
a code example.

18.Analyze the thread life cycle in Java. What are the different states a thread can be in, and
how does it transition between these states?

19.Create a multithreaded Java application that simulates a bank account with deposit and
withdrawal operations. Ensure that the operations are synchronized to prevent data
inconsistency.

20.Design a Java application that connects to a database, executes a query, and processes the
results using JDBC. Include error handling and transaction management.

261
OOPS AND JAVA

GLOSSARY

Class: A blueprint for creating objects. It defines fields and methods.

Object: An instance of a class that has state (fields) and behavior (methods).

Encapsulation: Hiding internal data and allowing access via methods (achieved using
private, public).

Abstraction: Hiding complex details and showing only the necessary features. Implemented
using abstract classes and interfaces.

Inheritance: Mechanism where one class inherits the properties of another. Promotes code
reuse.

Polymorphism: Ability of an object to take many forms. Supports method overloading and
overriding.

Method Overloading : Same method name with different parameters (compile-time


polymorphism).

Method Overriding: Redefining a superclass method in a subclass (runtime polymorphism).

Constructor: Special method to initialize objects.

this keyword: Refers to the current object of the class.

super keyword: Refers to the parent class and is used to call superclass methods/constructors.

Final: Used to declare constants, prevent method overriding or class inheritance.

Interface: A contract for what a class can do, without defining how. Supports multiple
inheritance.

Abstract Class: Cannot be instantiated. May contain both abstract and concrete methods.

JVM (Java Virtual Machine): Executes Java bytecode and provides platform independence.

JRE (Java Runtime Environment): Contains JVM and libraries to run Java programs.

JDK (Java Development Kit): Includes JRE + development tools like javac, java.

Bytecode: Intermediate code generated by Java compiler, run by the JVM.

Data Types: Define the type of data (e.g., int, float, char, boolean).

Variables: Containers for storing data values.

262
GLOSSARY

Operators: Symbols used for operations (+, -, ==, &&, etc.).

Type Casting: Converting one data type to another (implicit or explicit).

Access Modifiers: Define visibility (public, private, protected, default).

Packages: Group of related classes and interfaces.

Wrapper Class: Converts primitive types into objects (Integer, Double, etc.).

Collections Framework: Predefined classes/interfaces for storing groups of objects (List,


Set, Map).

Lambda Expression: Concise way to implement functional interfaces.

Stream API: Functional-style operations on collections (filter, map, reduce).

Exception Handling: Mechanism to handle runtime errors (try, catch, throw, finally).

LIST OF ABBREVIATIONS

S.No Abbreviation Full form/Description

1 VM Java Virtual Machine

2 JRE Java Runtime Environment

3 JDK Java Development Kit

4 API Application Programming Interface

5 IDE Integrated Development Environment

6 JAR Java Archive

7 JIT Just-In-Time (Compiler)

8 JSP JavaServer Pages

9 JDBC Java Database Connectivity

10 EJB Enterprise Java Beans

11 RMI Remote Method Invocation

12 AWT Abstract Window Toolkit

13 SWING Set of GUI components for Java

263
OOPS AND JAVA

14 SDK Software Development Kit

15 OOPL Object-Oriented Programming Language

16 GC Garbage Collection

Public Static Void Main (standard main method


PSVM
17 declaration)

Object-Oriented Programming / Object-Oriented


OOP / OOPS
18 Programming System

19 UML Unified Modeling Language

20 IS-A Inheritance Relationship

21 HAS-A Composition / Aggregation Relationship

Single Responsibility, Open-Closed, Liskov


SOLID Substitution, Interface Segregation, Dependency
22 Inversion

REFERENCES

TEXTBOOKS

1. Russell, S., & Norvig, P. (2020). Artificial Intelligence: A Modern Approach (4th ed.).
Pearson.
2. Ertel, W. (2018). Introduction to Artificial Intelligence (2nd ed.). Springer.
3. Rich, E., Knight, K., & Nair, S. B. (2017). Artificial Intelligence (3rd ed.). McGraw-Hill
Education.
4. Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer.
5. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press.
6. Géron, A. (2019). Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow
(2nd ed.). O'Reilly Media.
7. Sutton, R. S., & Barto, A. G. (2018). Reinforcement Learning: An Introduction (2nd ed.).
MIT Press.
8. Jurafsky, D., & Martin, J. H. (2023). Speech and Language Processing (3rd ed.). Pearson.
9. O'Neil, C. (2016). Weapons of Math Destruction: How Big Data Increases Inequality and
Threatens Democracy. Crown Publishing Group.

264
GLOSSARY

10. Tegmark, M. (2017). Life 3.0: Being Human in the Age of Artificial Intelligence. Penguin
Books.

WEBSITES

1. https://www.w3schools.com/java/
2. https://www.oracle.com/java/technologies/
3. https://www.geeksforgeeks.org/java/

SOFTWARES

1. Oracle JDK
2. OpenJDK
3. Eclipse Temurin

265

You might also like