Java Programming
Java Programming
MONOGRAPH
(Internal Circulation Only)
TABLE OF CONTENTS
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.
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.
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.
The team realized their language could be revolutionary for the emerging World Wide
Web, which needed a platform-independent language.
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.
With the advent of Java 2, new versions had multiple configurations built for
different types of platforms.
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.
With the advent of Java 2, new versions had multiple configurations built for
different types of platforms.
Oracle acquired Sun Microsystems, the company that developed Java, which meant
that Java became part of Oracle.
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.
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.
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
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
1.2.8. Portability
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.
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)..
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
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
Output:
Null
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.
7
OOPS AND 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
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.
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.
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.
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.
These are collections of native libraries required for executing native methods. They
include libraries written in languages like C and C++.
JRE
10
Chapter no 1: Introduction to JAVA
It is a complete software development kit (SDK) for Java, including the compiler
(javac), libraries, and tools needed to develop and run Java applications.
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.
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.
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
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.
Installation of JDK:
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.
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
A Java text file is created and saved it using a user defined name. Here it is saved as
Class Hello
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.
14
Chapter no 1: Introduction to JAVA
JDK contains many useful tools and among them, the most popular after javac is the jar
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.
The -cp stands for classpath which helps to add the jar to the same classpath.
15
OOPS AND JAVA
It includes the JVM and standard libraries but does not contain development tools
It converts Java bytecode (compiled code) into machine code that the operating system
can execute.
16
Chapter no 1: Introduction to JAVA
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.
The implementation of a Java program involves the following steps. They include:
Java programs can be written in a text editor (Notepad, VS Code) or an IDE (IntelliJ,
Eclipse, NetBeans).
17
OOPS AND JAVA
Example:
class HelloWorld
System.out.println(“Hello, World”);
Output:
Hello, World
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
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
Class Declaration
Every Java program starts with a class declaration using the class keyword.
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.
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");
/* The code below will print the words Hello Worldto the screen, and it is amazing */
System.out.println("Hello World");
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;
booleanmyBool = true;
Output:
5.99
true Hello
Figure 1.9 Data Types in Java
21
OOPS AND JAVA
Numbers
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 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
}}
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
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
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
System.out.println(name);
To create a variable that should store a number, look at the following example:
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
To declare more than one variable of the same type, we can use a comma-separated list:
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 {
int m = 60;
System.out.println(minutesPerHour);
System.out.println(m);}}
The general rules for naming variables are:
Names should start with a lowercase letter, and cannot contain whitespace
Reserved words (like Java keywords, such as int or boolean) cannot be used as names
1.9 Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
27
OOPS AND JAVA
Bitwise operators
The assignment operator (=) is used to assign the value 10 to a variable called x.
Example 1:
int x = 10;
28
Chapter no 1: Introduction to JAVA
Example 2:
int x = 10;
x+=10;
= 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
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:
== Equal to x == y
!= Not equal x != y
Logical operators are used to determine the logic between variables or values:
&& Logical Returns true if both statements are true x < 5 && x<
10
and
! Logical not Reverse the result, returns false if !(x < 5 &&
the result is true x < 10)
30
Chapter no 1: Introduction to 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.
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:
& 0111
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:
Bitwise OR
Operation of 5 and
7 0101
| 0111
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:
Bitwise XOR
Operation of 5 and
7 0101
^ 0111
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:
~ 00000101
11111010 = -6 (In decimal)
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
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.
RequiredDatatype=(TargetType) Variable
Example:
import java.io.*;
// Main class
33
OOPS AND JAVA
3.0
3
1.10.2 Type Conversion:
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.
// Main class
34
Chapter no 1: Introduction to JAVA
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 {
35
OOPS AND JAVA
int i = 100;
Widening conversion takes place when two data types are automatically converted.
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.
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
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 {
// The Expression
37
OOPS AND JAVA
byte b = 50;
b = (byte)(b * 2);
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)).
38
Chapter no 1: Introduction to JAVA
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
It is one of the fundamental features of Java, which provides a smooth flow of program.
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
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
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) {
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
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 case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
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.
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 {
int a = 10; if (a == 5) {
46
Chapter no 1: Introduction to JAVA
else {
}}}
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 {
a is not equal to 5 or 10
1.11.3 Loop Statements
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
for loop
while loop
do-while 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 {
}}
Output:
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:
{
//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.
Example:
public class Main {
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.
Example
public class Main {
50
Chapter no 1: Introduction to JAVA
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.
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 {
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
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 {
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 {
53
OOPS AND JAVA
System.out.println(j);
} } } }
Output:
3
5
1
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.
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).
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;
}
System.out.println("Nationality: Foreigner");
55
OOPS AND JAVA
System.out.println("Grade: "+this.grade);
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).
57
OOPS AND JAVA
System.out.println("Grade: "+this.grade);
}}
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;
}
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);
60
Chapter no 1: Introduction to JAVA
}
Output
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.
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{
}
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
Example
class A{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
An array is typically a grouping of elements of the same kind that are stored in a single,
contiguous block of memory.
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.
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.
Disadvantages
Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.
Multidimensional Array
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
cars[0] = "Opel";
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)
Example
public class Main{
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:
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.
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
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
System.out.println();
} } }
66
Chapter no 1: Introduction to 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.
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{
this.name = name;
@Override
{
new Student("Dharma"),new Student("sanvi"), new Student("Rupa"),
67
OOPS AND JAVA
new Student("Ajay")
};
for(Student m:myStudents)
{
System.out.println(m);
}
}}
1.16 Classes and Objects
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.
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
Characteristics of an Object:
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
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.
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.
It is used to achieve the reusability of code. We write a method once and use it many
times.
Reusability
Modularity
Maintainability
Abstraction.
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:
72
Chapter no 1: Introduction to JAVA
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
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
} }
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.
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
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.
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
{
74
Chapter no 1: Introduction to JAVA
int num=scan.nextInt();
//method calling findEvenOdd(num);
}
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
show();
75
OOPS AND JAVA
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.
Example
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.
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
It is a method that returns an object to the class to which it belongs. All static methods are
factory methods.
By reference variable
By method
By constructor
77
OOPS AND JAVA
Example:
class Student{ int id;
String name;
//Creating objects
}
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
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
}
// 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)
{
Class diagrams enable us to model software in a high level of abstraction and without
having to look at 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.
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;} }
81
OOPS AND JAVA
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;
82
Chapter no 1: Introduction to JAVA
return this.name;
}}
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".
public Main(int x) {
this.x = x;
83
OOPS AND JAVA
}}
Output:
Value of x =5
1.22 Encapsulation
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
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.
Example
class Programmer {
private String name;
// Getter and Setter for name
public String getName() { return name; }
84
Chapter no 1: Introduction to JAVA
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
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
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
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:
2. Private
3. Protected
4. Public
86
Chapter no 1: Introduction to JAVA
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.
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
packagep1;
// Class A
classA {
private void display() {
System.out.println("GeeksforGeeks");
}}
// Class B
classB {
87
OOPS AND JAVA
// 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.
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.
classGeek {
void display()
{
System.out.println("Hello World!");
}}
88
Chapter no 1: Introduction to JAVA
Package p2;
classGeekNew {
o.display();
}
}
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.
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
90
Chapter no 1: Introduction to JAVA
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
94
Chapter no 2: Inheritance
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.
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.
97
OOPS AND JAVA
98
Chapter no 2: Inheritance
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
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
103
OOPS AND JAVA
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.
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.
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
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.
public int hashCode() returns the hashcode number for 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).
109
OOPS AND JAVA
110
Chapter no 2: Inheritance
111
OOPS AND JAVA
112
Chapter no 2: Inheritance
113
OOPS AND JAVA
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
117
OOPS AND JAVA
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() {
class Main {
int i;
122
Chapter no 2: Inheritance
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
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
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
130
Chapter no 2: Inheritance
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.
134
Chapter 3: Data Abstraction
• 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.
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.
• 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.
• Java APIs contains the following predefined packages, as shown in the below Figure.3.3:
Predefined packages in Java.
• java.lang: Contains language support classes(e.g classes which defines primitive data types,
math operations). This package is automatically imported.
• java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
• java.awt: Contain classes for implementing the components for graphical user interfaces
(like button;menus etc).
136
Chapter 3: Data Abstraction
list.add("Packages"); System.out.println(list);
}
Output:
[Java, Packages]
• 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.
}
}
137
OOPS AND JAVA
}}
Output:
This is a user-defined package.
Example 2:
Create a package “animals”
package animals;
System.out.println("Mammal eats");
return 0;
m.travel();
interface Animal {
138
Chapter 3: Data Abstraction
• Execute the class file within the package and get the result as shown below
• import packagename.*;
• import package.classname;
• The import keyword is used to make the classes and interface of another package accessible
to the current package.
public class A{
System.out.println("Hello");}
import pack.*;
class B{
obj.msg();
}
139
OOPS AND JAVA
Output:
Hello
public class A{
System.out.println("Hello");}
obj.msg(); } }
Output:
Hello
• It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
• 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.
140
Chapter 3: Data Abstraction
• 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).
• 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.
• 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.
• 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.
141
OOPS AND JAVA
Syntax:
Abstract Class
abstract class ClassName {
// Method body
Example:
abstract class Animal {
System.out.println("Zzz");
System.out.println("Zzz"); }}
{
// The body of animalSound() is provided here in inherited class
142
Chapter 3: Data Abstraction
}}
myPig.animalSound();
myPig.sleep();
}}
Output:
• The pig says: wee wee
• Zzz
Example
//Example of an abstract class that has abstract and non-abstract methods
{
System.out.println("bike is created");
}
// create an abstract method run ()
void changeGear()
System.out.println("gear changed");
}
} // End of abstract class Bike
143
OOPS AND JAVA
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[])
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{
interface A
void a();
void b();
void c();
void d();
144
Chapter 3: Data Abstraction
class M extends B{
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.
• There can be only abstract methods in the Java interface, not method body.
• Interfaces can have abstract methods and variables. It cannot have a method body.
• 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>
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 {
class Main {
public static void main(String[] args) {
147
OOPS AND JAVA
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.
interface Language {
}}
class programMain {
}}
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.
interface A {
// members of A} interface B {
// members of B}
class C implements A, B {
// abstract members of A
// abstract members of B
}
• 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 {
// extending 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.
149
OOPS AND JAVA
interface A {
...
interface B {
...
interface C extends A, B {
...
}
• Level 4 – Final Code / Main Method: It have access of all interfaces data.
Example
// Level 1 interface Bank {
// Level 2
}
abstract class Dev2 extends Dev1 {
150
Chapter 3: Data Abstraction
// Level 3
// Level 4
class exampleMain
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
perimeter += side;
}
class Triangle implements Polygon {
private int a, b, c;
this.a = a;
this.b = b; this.c = c;
s = 0;
s = (double) (a + b + c)/2;
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
class polygonMain
152
Chapter 3: Data Abstraction
t1.getPerimeter(2, 3, 4);
} }
Output
Area: 2.9047375096555625
Perimeter: 9
Example 2:
class Triangle implements Polygon {
private int a, b, c;
// initializing sides of a triangle Triangle (int s1, int s2, int s3) {
a = s1;
b = s2;
c = s3; s = 0;
s = (double) (a + b + c)/2;
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("Area: " + area);
class PolygonMain {
class t1.getArea();
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.
154
Chapter 3: Data Abstraction
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.
o Use an interface when you need to define a contract for behaviour that multiple classes can
implement.
• 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 {
int speed;
int gear;
155
OOPS AND JAVA
gear = newGear;
}
public void applyBrakes(int decrement) {
int speed;
int gear;
}
// Increase speed @Override
public void printStates() { System.out.println("speed: " + speed + " gear: " + gear);
}
156
Chapter 3: Data Abstraction
class VehicleMain
{
public static void main (String[] args)
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);
}}
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.
• 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.
• Class B and C is derived from A and have their own foo() implementation
• 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.
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.
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".
// 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.
• 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.
• 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 .
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.
void bark();
}
class Animal implements Dog, Cat {
160
Chapter 3: Data Abstraction
class Main {
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. *;
161
OOPS AND JAVA
return a+b;
return a-b;
class Main{
// Main Method
Output
Addition: 3
Subtraction: 1
• Without proper exception handling, an error can cause the entire application to crash, leading
to a poor user experience.
162
Chapter 3: Data Abstraction
• finally: An optional block that executes regardless of whether an exception was thrown or
not, typically used for cleanup activities.
• 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.
• 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.
class Main {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
164
Chapter 3: Data Abstraction
catch (ArithmeticException e) {
} }}
Output
ArithmeticException => / by zero
//try-block2 try {
//try-block3 try {
System.out.println(arr[10]);
catch (ArithmeticException e)
{
System.out.print("Arithmetic Exception");
catch (ArithmeticException e)
System.out.print("Arithmetic Exception");
}
}
165
OOPS AND JAVA
System.out.print("Arithmetic Exception");
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
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
• The finally block is optional. And, for each try block, there can be only one finally block.
class ExceptionMain {
try
{
166
Chapter 3: Data Abstraction
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
Output
ArithmeticException => / by zero
• When we throw an exception, the flow of the program moves from the try block to the catch
block.
class ExceptionMain {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
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)
167
OOPS AND JAVA
import java.io.*;
class ExceptionMain {
Output
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
• Custom exceptions can provide more meaningful error messages and handle specific error
scenarios.
168
Chapter 3: Data Abstraction
• InterruptedException
• NullPointerException
• ArrayIndexOutOfBoundsException
• IllegalArgumentException
• NumberFormatException
• ClassCastException
Common Errors:
• OutOfMemoryError
• StackOverflowError
• VirtualMachineError
• AssertionError
Example:
Handling a Built-in Exception
} 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
Java provides automatic conversion between primitive types and their corresponding wrapper
classes through autoboxing and unboxing.
170
Chapter 4: Collection API And Lambda
Collections
ArrayList and HashMap are examples of Java collections that can only contain objects, not
primitives.
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.
Reflection: Wrapper classes play a crucial role in reflection, allowing you to inspect and
manipulate primitive types as objects during runtime.
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
Example:
public class AutoboxingUnboxing
{
Integer integer = 100; // Autoboxing
}}
172
Chapter 4: Collection API And Lambda
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.
For example, the Integer class provides methods to parse a string as an integer
}}
Which of the following is a valid way to create an Integer object with the value 10?
a. Integer val = new Integer(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;
Example: Convert an Integer to a String, and use the length() method of the String class to output
the length of the "string"
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 {
Integer myInt = 5;
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
} }
174
Chapter 4: Collection API And Lambda
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.
1. Interfaces
2. Implementation Classes
3. Algorithms
Types of Interfaces
• Collection Interface
• Set Interface
• List Interface
• Maps
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
175
OOPS AND JAVA
arrList.add("hello");
arrList.add(101);
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
//List of characters
• Generic Method
• Generic Classes
obj.displayData(45.6f, 10);
obj.displayData(10, 10);
obj.displayData("Hi", 'c');
} }
176
Chapter 4: Collection API And Lambda
T obj;
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());
} }
import java.util.*;
public class JavaExample{
hMap.put(101,"Chaitanya");
hMap.put(120,"Carl");
177
OOPS AND JAVA
hMap.put(141,"Aditya");
} } }
Output:
HashMap elements:
key: 101 & Value: Chaitanya key: 120 & Value: Carl
Collections
• Collections with Ordering: Lists
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 insert elements (objects) into a Java List using itsadd() method.
178
Chapter 4: Collection API And Lambda
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.
The List interface has add() method that takes an index as first parameter, and the element to
insert as the second parameter.
The element that had index 0 before the new element was inserted now will get pushed to index
1.
listSource.add("123");
listSource.add("456");
listDest.addAll(listSource);
listA.add("Apple");
179
OOPS AND JAVA
listA.add("Orange");
listA.add("Grapes");
The indexOf() method finds the index of the first occurrence in the List of the given element.
list.add(element1); list.add(element2);
list.add(element1);
list.add(element2);
180
Chapter 4: Collection API And Lambda
list.add(element1);
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);
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.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<>();
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.
181
OOPS AND JAVA
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.
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.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 4");
list.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 3");
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.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
listabc.add("first");
listabc.add("second");
listabc.add("third");
list.add("first");
list.add("second");
list.add("third");
Iterator<String>itr = list.itr();
while(itr.hasNext()) {
String next = itr.next();}
183
OOPS AND JAVA
Create a Set
Create a Set instance:
} }
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.
set.clear();
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.
184
Chapter 4: Collection API And Lambda
set1.add("one");
set1.add("two");
set1.add("three");
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
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.add("456");
set1.add("456");
185
OOPS AND JAVA
list.addAll(set1);
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.
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.
186
Chapter 4: Collection API And Lambda
Example:
import java.util.*; class GFG {
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}
Example:
import java.util.Map; import java.util.TreeMap;
public class CollectionsDemo {
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
187
OOPS AND JAVA
} }
Output
Map Elements
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");
} }
Output
Original Map {1=Learn, 2=in, 3=Scaler}
Example:
import java.util.*; class GFG {
188
Chapter 4: Collection API And Lambda
cg.remove(new Integer(4));
}}
Output:
Original Map {1=Sahil, 2=Vishal, 3=Karan, 4=Nikhil}
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
189
OOPS AND JAVA
Reusability: No need to reinvent data structures like linked lists, hash tables, or trees
java.util.Collection
├── List
│ ├── ArrayList
│ ├── LinkedList
│ └── Vector
│ └── Stack
├── Set
│ ├── HashSet
│ ├── LinkedHashSet
│ └── TreeSet
└── Queue
├── LinkedList
├── PriorityQueue
├── 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
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 LinkedList
//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");
list.remove("C#");
//display the new LinkedList
} }
Output
Size at the beginning 0
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
v.add(88);
v.add(1);
v.add(39);
} }
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.
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
} }
Output
Size at the beginning 0
Top-most element 18
Removing 18
New PriorityQueue after removal[27, 34, 99] Size after removal 3
Function
194
Chapter 4: Collection API And Lambda
In the above example, the interface MyInterface has only one abstract method getValue().
Hence, it is a functional interface.
or
Example
Suppose, we have a method like this:
() -> 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
interface MyInterface
{
// abstract method double getPiValue();
}}
Output:
Value of Pi = 3.1415
Lambda Expression with One Parameter interface cube
{
public static void main(String args[])
196
Chapter 4: Collection API And Lambda
{ int x = 5;
System.out.println(result);
}
public class LambdaMP {
System.out.println(Mul1.Mul(2, 5));
Product Mul2 = (float x, float y) -> (x * y);
System.out.println(Mul2.Mul(100, 200));
}}
interface PrintCoin{
void print();
class Doge{
public void getDoge() {
197
OOPS AND JAVA
doger.getDoge();
} }
Output
Hey ! I see coins. 100
class Doge{
System.out.println(coin);
printingCoin.print();
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
• Consuming
• Filtering
• generating objects
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();
}
}
199
OOPS AND JAVA
Output
5
Example Consumer
public class Student
int rollNo;
{
this.rollNo = rollNo; this.className = className;
this.name = name;
return rollNo;
this.rollNo = rollNo;
return className;
}
public void setClassName(String className)
this.className = className;
}
public String getName() { return name;
200
Chapter 4: Collection API And Lambda
Consumer Code
import java.util.function.Consumer;
{
// Adding data of Student
System.out.println(object.getName());
System.out.println(object.getRollNo());
System.out.println(object.getClassName());
};
consumer.accept(studentOne);
System.out.println("Second student data:");
consumer.accept(studentTwo);
Output
First student data: Ram
1
CSE
201
OOPS AND JAVA
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.
@FunctionalInterface
/**
* Gets a result.
*
* @return a result
*/
T get();
}
Code Snippet
Example Supplier
import java.util.function.Supplier; public class Main {
Supplier<Double>randomValue = () ->Math.random();
System.out.println(randomValue.get());
Output: 0.5685808855697841
202
Chapter 4: Collection API And Lambda
@FunctionalInterface
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 {
System.out.println(lesserthan.test(10));
}}
• 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.
Every class which implements the java.util.Collection interface has a stream method which
allows to convert its instances into Stream objects.
// Create an ArrayList
myList.add(1);
myList.add(5);
myList.add(8);
Lists, use the stream method available in the Arrays class to convert any array into a stream.
Example:
// Create an array
Stream<Integer>myStream = Arrays.stream(myArray);
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
}}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
.collect(Collectors.toList());
Output
Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import java.util.List;
import java.util.stream.Collectors;
public class SortedExample {
}
}
Output:
Original list: [banana, apple, grape, orange, pear]
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;
206
Chapter 4: Collection API And Lambda
Optional<Integer>max = numbers.stream().reduce(Integer::max);
System.out.println("Maximum element: " + max.orElse(0));
Output
Sum of all elements: 15
Maximum element: 5
Concatenated string: Hello world!
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();
listOfNumbers.parallelStream();
4 ForkJoinPool.commonPool-worker-3
2 ForkJoinPool.commonPool-worker-5
1 ForkJoinPool.commonPool-worker-7
3 main
207
OOPS AND JAVA
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.
• JDBC provides a set of interfaces and classes that abstract the details of interacting with
different database systems, making database programming consistent and efficient.
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.
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
A Native Protocol Java Driver converts JDBC calls into the database-specific calls so that the
client applications can communicate directly with the server.
JDBC in Java follows a layered architecture to establish seamless communication between Java
applications and databases shown in the Figure 5.1: JDBC Architecture.
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
{
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();
Example:
// Import JDBC packages
import java.sql.*;
211
OOPS AND JAVA
System.out.println("Connected!");
con.close();
} }
• Using 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.
212
Chapter no 5: JDBC and Multithreading
Example:
Example:
while (rs.next())
{
System.out.println(rs.getString("name"));}
2. Prepare Statement
Instead of hardcoding queries like,
213
OOPS AND JAVA
Set parameter placeholders(use question mark for placeholders) like, select * from students
where age> ? and name = ?
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();
Following are the steps to use Callable Statement in Java to call Stored Procedure:
214
Chapter no 5: JDBC and Multithreading
{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection (“jdbc:mysql://localhost/ root”,
”geek”,”geek”);
}
}
CallableStatement cs = con.prepareCall(sql_string);
Depending upon the data type of query parameters we can set the input parameter by calling
cs.setString(1,”geek1″);
cs.setString(2,”python”);
cs.setString(3,”beginner”);
Example:
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);
// Open a connection
ResultSetrs = stmt.executeQuery(QUERY);) {
} catch (SQLException e) {
e.printStackTrace();
} }}
ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan
Update Records
import java.sql. *;
216
Chapter no 5: JDBC and Multithreading
static final String QUERY1 = "UPDATE Employees SET age=20 where id=100";
static final String QUERY2= "SELECT id, first, last, age FROM Employees";
ResultSetrs=stmt.executeQuery(QUERY2);
// Extract data from result set while (rs.next()) {
} } catch (SQLException e) {
e.printStackTrace();
} }} C:\>java UpdateExample
ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan
Delete Records
import java.sql. *;
217
OOPS AND JAVA
static final String QUERY2= "SELECT id, first, last, age FROM Employees";
stmt.executeUpdate(QUERY1); ResultSetrs=stmt.executeQuery(QUERY2);
} }
catch (SQLException e) {
e.printStackTrace(); } }}
C:\>java DeleteExample
Example:
DatabaseMetaDatadbmd = con.getMetaData();
System.out.println(dbmd.getDatabaseProductName());
218
Chapter no 5: JDBC and Multithreading
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:
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.
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 ThreadC extends Thread{
}
System.out.println("Exiting from Thread C ...");
} }
220
Chapter no 5: JDBC and Multithreading
a.start();
b.start();
c.start();
System.out.println("... Multithreading is over "); }}
OUTPUT:
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
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.
*/
} }
} }
}
System.out.println("Exiting Thread Z ...");
} }
222
Chapter no 5: JDBC and Multithreading
t1.start();
t2.start();
t3.start();
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
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
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.
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.
What is Process?
• Processes are basically the programs that are dispatched from the ready state and are
scheduled in the CPU for execution.
• 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.
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.
• 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
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.
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.
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 ().
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:
LockSupport.park
A thread is in the timed waiting state due to calling one of the following methods with a
specified positive waiting time:
Thread.sleep
LockSupport.parkNanos
LockSupport.parkUntil
5.10.7. Terminated
Thread state for a terminated thread. The thread has completed execution.
try {
228
Chapter no 5: JDBC and Multithreading
} } }
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
if (i==1) yield();
229
OOPS AND JAVA
} }
if (k==3){
try{
sleep(1000);
catch(Exception e){}
}
}
} }
230
Chapter no 5: JDBC and Multithreading
t2.start();
t3.start();
} }
OUTPUT:
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
From Thread B: j = 2
From Thread B: j = 3
From Thread B: j = 4
From Thread B: j = 5
try{
231
OOPS AND JAVA
sleep(10000);
System.out.println (" First thread finishes running" );
catch(Exception e){ }
}}
suspend( );
catch(Exception e){ }
} }
class Demonstration_116{
second.sleep (10000);
232
Chapter no 5: JDBC and Multithreading
catch(Exception e)
{
} }
OUTPUT:
Revive the second thread First thread starts running Second thread starts running
Example:
class MyThread extends Thread {
public void run() {
Example:
class MyRunnable implements Runnable {
}}
233
OOPS AND JAVA
Example:
// The minimum priority that a thread can have.
public static final int MIN_PRIORITY = 1;
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;
displayBalance();}
synchronized void withdraw(int amount){
displayBalance();}}
int amount;
Account accountX;
accountX = x;
this.amount = amount;
new Thread(this).start();}
235
OOPS AND JAVA
accountX.deposit(amount);}}
class TransactionWithdraw implements Runnable{
int amount;
Account accountY;
accountY = y;
this.amount = amount;
new Thread(this).start(); }
accountY.withdraw(amount); }}
class Demonstration_119{
ABC.accountNo = 111;
TransactionDeposit t1;
TransactionWithdraw t2;
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
• Object-oriented
• Platform-independent
• Simple
• Secure
• Robust
• Multithreaded
• High performance
• Dynamic
3.What is bytecode?
• Local Variables
• Instance Variables
• Static Variables
237
OOPS AND JAVA
• byte
• short
• int
• long
• float
• double
• char
• boolean
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.
• Default Constructor
• Parameterized Constructor
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).
• 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.
• 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.
• 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.
• The finalize () method in Java is a method of the Object class that is called by the garbage
collector before an object is reclaimed.
• 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).
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.
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.
• Error: The syntax for array declaration is incorrect. The correct syntax does not require square
brackets before the size of the array.
• 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
import java.util.Scanner;
if (number % 2 == 0) {
} else {
switch (number) {
case 0:
break;
case 1:
break;
case 2:
break;
default:
241
OOPS AND JAVA
break;
} scanner.close();
}}
PART-B
2. What is type casting? Explain its types with proper syntax and 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.
9. Write all primitive data types available in Java with their storage sizes in bytes.
11111
242
Question Bank
2222
333
44
CHAPTER II
PART-A
• 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).
• 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.
• 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.
• 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.
5.What is inheritance?
• The super keyword is used to refer to the immediate parent class object.
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
• 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.
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
}}
10.What is recursion?
• It typically involves a base case to terminate the recursion and a recursive case that breaks
the problem into smaller subproblems.
• 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.
• 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).
245
OOPS AND JAVA
• The method to be executed is determined at compile time based on the method signature.
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.
Multilevel Inheritance: A class inherits from a superclass, which is also a subclass of another
class.
Multiple Inheritance (through interfaces): A class can implement multiple interfaces, allowing
it to inherit behavior from multiple sources.
• We can either call another constructor of the same class using this() or call the superclass
constructor using super(), but not both.
• Java does not support multiple inheritance with classes to avoid ambiguity (the "Diamond
Problem").
246
Question Bank
• A class can implement multiple interfaces, allowing it to inherit behavior from multiple
sources.
To check the starting and ending point of a string in Java, We can use the startsWith() and
endsWith() methods of the String class.
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()
PART-B
4.Which are the ways to access package from another package? Explain with example.
247
OOPS AND JAVA
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.
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.
18.What is importance of super and this keyword in inheritance? Illustrate with suitable
example.
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.
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.
• 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.
• 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.
• 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).
• 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.
• The main keywords related to exceptions in Java are try, catch, finally, throw, and throws.
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.
• 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 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.
• 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.
• The finally block is used to execute code after a try-catch block, regardless of whether an
exception was thrown.
• 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.
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.
• We can directly access all classes in a package by using the wildcard import statement: import
packageName.*;.
try {
} catch (ExceptionType e) {
// handle exception
} finally {
PART-B
1.Define exception. Why it is needed? Explain the different types of exceptions and the
exception hierarchy with appropriate examples using 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.
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.
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
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
• 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.
• 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.
• 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).
• 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)-.
• 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.
• 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.
• 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.
• 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.
• The Set interface represents a collection that does not allow duplicate elements.
• The Map interface maps keys to values and does not allow duplicate keys.
253
OOPS AND 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.
• 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.
• In lambda expressions, local variables referenced from the enclosing scope must be
effectively final, meaning they cannot be modified after being assigned.
• Lambda expressions can access instance variables and static variables of the enclosing class
directly, allowing them to utilize class-level data without restrictions.
• A Predicate is a functional interface that represents a single argument function that returns a
boolean value.
• 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.
254
Question Bank
• It does not take any arguments and returns a value, making it useful for generating or
providing data on demand.
• A Consumer is a functional interface that represents an operation that takes a single input
argument and returns no result.
• The Stream API in Java provides a functional approach to processing sequences of elements,
allowing operations like filtering, mapping, and reducing to be performed.
• 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
2.Discuss the methods provided by these classes, such as parsing and conversion methods.
4.Explain how Java automatically converts between primitive types and their corresponding
wrapper classes.
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
14.Explain the key operations available in the Stream API, such as map, filter, and reduce.
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.
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.
• 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.
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.
• The JDBC API consists of several key components, including DriverManager, Connection,
Statement, PreparedStatement, ResultSet, and RowSet, which facilitate database interactions.
• 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.
• 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.
257
OOPS AND JAVA
• It improves performance and security by preventing SQL injection attacks and allowing
efficient execution of parameterized queries.
• It allows you to call a stored procedure with input and output parameters, enabling complex
operations to be performed directly in the database.
• 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.
• Meta Data objects in JDBC provide information about the database, such as the structure of
tables, columns, and data types.
• Multithreading in Java is the concurrent execution of two or more threads, allowing multiple
tasks to be performed simultaneously within a single program.
• 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.
• 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).
• 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.
• 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.
• 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.
• 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.
• 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.
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.
6.Provide examples of executing different types of SQL queries (SELECT, INSERT, UPDATE,
DELETE).
10.Discuss the advantages of using Runnable over extending the Thread class.
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.
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
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.
super keyword: Refers to the parent class and is used to call superclass methods/constructors.
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.
Data Types: Define the type of data (e.g., int, float, char, boolean).
262
GLOSSARY
Wrapper Class: Converts primitive types into objects (Integer, Double, etc.).
Exception Handling: Mechanism to handle runtime errors (try, catch, throw, finally).
LIST OF ABBREVIATIONS
263
OOPS AND JAVA
16 GC Garbage Collection
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