Learn Java Programming
From
Beginner to Professional
1
Java: Learn Java Programming from Beginner to
Professional
2
<W
Learn Java Programming
From
Beginner to Professional
3
© Copyright Philip Jeff 2024 All rights reserved.
The content contained within this book may not be
reproduced, duplicated, or transmitted without direct
written permission from the author or the publisher.
Under no circumstances will any blame or legal
responsibility be held against the publisher, or author, for
any damages, reparation, or monetary loss due to the
information contained within this book. Either directly or
indirectly. You are responsible for your own choices, actions,
and results.
Legal Notice:
This book is copyright protected. This book is only for
personal use. You cannot amend, distribute, sell, use, quote
or paraphrase any part, or the content within this book,
without the consent of the author or publisher.
Disclaimer Notice:
Please note the information contained within this document
is for educational and entertainment purposes only. All effort
has been executed to present accurate, up to date, and
reliable, complete information. No warranties of any kind are
declared or implied. Readers acknowledge that the author is
not engaging in the rendering of legal, financial, medical, or
professional advice. The content within this book has been
derived from various sources. Please consult a licensed
professional before attempting any techniques outlined in
this book.
By reading this document, the reader agrees that under no
circumstances is the author responsible for any losses,
direct or indirect, which are incurred as a result of the use of
the information contained within this document, including,
but not limited to, — errors, omissions, or inaccuracies.
Table of Content
Contents
Introduction
................................................. 8
Chapter 1
.....................................................10
Introduction to Java Programming
... 10
History of Java
.................................. 10
Chapter 2: Java Basics
.............................. 26
Java Syntax and Structure
................. 26
Practice:
.............................................26
Java Program Structure
...................... 29
Data Types and Variables
..............31
Operators and Expressions
........... 37
Object-Oriented Programming (OOP)
.....................................................................................................91
Classes and Objects
................................. 91
Core Principles of OOP
.................. 93
Encapsulation in Java
.......................... 93
Benefits of
Encapsulation...................................................................................
......................................... 96
Key Concepts of Inheritance
..............99
Abstraction in Java
....................... 118
Chapters 3
................................................ 124
Methods and Constructors in Java
.... 124
Method Overriding
....................... 127
Chapter 4
.................................................. 131
Benefits of Constructor Overloading
138
Chapter 5
.................................................. 152
Encapsulation and Abstraction
.......... 152
Encapsulation in Java
........................ 152
Chapter 6: Basic Data Structures
........ 161
Arrays:
....................................................... 161
Strings:
................................................. 162
ArrayList and LinkedList
.............163
Chapter 7: Exception Handling
.......... 165
Introduction to Exceptions
.............165
Types of Exceptions:
.................... 165
Try, Catch, and Finally
................ 165
Chapter 8: File I/O and Serialization
.. 168
Serialization and Deserialization
... 173
Chapter 9
................................................. 178
Java Collections Framework: List, Set, and Map Interfaces
.................................................................. 178
List Interface:
.......................................... 180
Set Interface
........................................ 184
Map Interface
................................. 189
Chapter 10
................................................ 203
Understanding HashMap, TreeMap, HashSet, TreeSet
......................................................................... 203
HashSet:
.......................................... 223
Chapter 11
................................................. 241
Iterators and Enhanced For-Loop in JavaIterators
...................................................................................241
Chapter 12: Generics
252
Generics in Java
.................................. 252
Benefits of Generics
.......................... 255
Chapter 13
................................................ 270
Multithreading and Concurrency in Java
...................................................................................................270
Implementing the Runnable Interface
....................................................................................................271
Synchronization:
.....................................285
Concurrency Utilities (ExecutorService, Future, Callable)
..............................................................286
Chapter 14: Java
Features
...................................... 288
Default and Static Methods in Interfaces
291
Part III: Advanced Java
.......................... 293
Chapter 15: Java Networking
...............294
Introduction to Networking in Java
294
Networking:
....................................294
Chapter 16: Java Database Connectivity (JDBC)
299
Prepared Statements and Transactions
301
Part III: Advanced Java
.......................... 302
Chapter 17: Java GUI Programming
... 303
Introduction to AWT and Swing
303
Building GUI Applications with Swing
..................................................................................................... 304
6
Event Handling
..............................305
Chapter 18: JavaFX
................................. 307
Introduction to JavaFX
.................... 307
JavaFX Properties and Bindings
. 308
Chapter 19: Web Applications with Java
311
Introduction to Java EE
....................... 311
JavaServer Pages (JSP)
..................... 312
Building Web Applications with Spring Boot
...................................................................................... 313
Chapter 20: Design Patterns
................ 314
Introduction to Design Patterns
......... 314
Chapter 21: Advanced Topics
..............328
Reflection API
......................................... 328
Java Native Interface (JNI)
..............329
Performance Tuning and Profiling
330
Modular Programming with Java
9...........................................................................................................
....... 331
Chapter 22: Testing and Debugging
... 333
Unit Testing with JUnit
.................. 333
Mocking with Mockito
................ 334
Chapter 23: Building and
Deployment......................................................................................
...................... 336
Continuous Integration and Deployment
...................................................................................................338
Dockerizing Java Applications
... 339
Reference
................................................. 340
7
Introduction
Welcome to the world of Java, a language that has shaped
the landscape of modern software development. Whether
you're taking your first steps into programming or you're an
experienced developer looking to sharpen your skills, this
book is your guide on the journey to mastering Java.
Java has been at the heart of the programming world for
over two decades, powering everything from mobile apps to
enterprise-level systems. Its versatility, combined with a
strong community and extensive libraries, makes it a go-to
language for developers of all levels. This book is designed
to be your companion, helping you navigate through the
foundational concepts and guiding you toward advanced
topics with clarity and ease.
As you turn the pages, you’ll discover how Java's powerful
features can be applied to real-world problems, giving you
the tools to create robust, high-performance applications.
We’ll start with the basics—setting up your environment,
understanding syntax, and writing your first lines of code.
From there, we’ll delve into more complex topics like object-
oriented programming, data structures, and multithreading,
ensuring you gain a deep and comprehensive understanding
of the language.
Each chapter is crafted to build on the last, with practical
examples and exercises that reinforce your learning. By the
end of this book, you’ll not only be comfortable writing Java
code, but you'll also be able to think like a developer—
problem-solving with efficiency and creativity.
Unlock the full potential of Java programming and set
yourself on the path to becoming a high-earning developer
with "Java: Learn Java Programming From Beginner to
Professional." Whether you're just starting out or looking to
elevate your skills, this comprehensive guide will empower
you to master Java, one of the most in-demand
programming languages in the world.
This book is more than just a learning tool—it's your
blueprint for success in the competitive tech industry. With
step-by-step instructions, real-world examples, and expert 8
insights, you'll develop the proficiency needed to tackle
complex projects and create robust, scalable applications.
From the basics of syntax and structure to advanced
concepts like multithreading, networking, and JavaFX, each
chapter builds your confidence and capabilities.
But this journey isn't just about learning to code; it's about
transforming your skills into lucrative opportunities. As you
progress through this book, you'll gain the knowledge and
expertise required to land top-tier jobs, secure high-paying
freelance gigs, or even start your own tech venture. The
demand for skilled Java developers is soaring, and with the
right tools and understanding, you could be on your way to
earning six or even seven figures in the industry.
Java is more than just a programming language; it’s a
gateway to innovation, and I’m thrilled to help you on this
exciting journey. So, let’s get started. Your path from
beginner to professional Java developer begins here!
With "Java: Learn Java Programming From Beginner to
Professional," you're not just investing in a book—you're
investing in your future. Ready to turn your passion for
coding into a profitable career? Your journey starts here
9
Chapter 1
Introduction to Java Programming
History of Java
The Java language project was started in June 1991 by
James Gosling, Mike Sheridan, and Patrick Naughton,
according to google. Although Java was initially intended for
interactive television, the digital cable television industry at
the time could not handle its advanced features. Originally
named after an oak tree that stood outside Gosling's office,
the language was known as Oak. Subsequently, the project
was known as Green before being renamed Java after Java
coffee, an Indonesian variety of coffee. Gosling created Java
with a syntax reminiscent of C/C++ for system and
application programmers.
Midway through the 1990s, Sun Microsystems began
developing Java. Although it was too sophisticated for the
digital cable television market at the time, it was initially
intended for interactive television. Originally named after an
oak tree that stood outside the developer James Gosling's
office, the language was known as Oak. The development
team drank a lot of Java coffee, which led to the name
change to Java later on.
Java was originally developed by James Gosling at Sun
Microsystems. It was released in May 1995 as a core
component of Sun's Java platform. The original and
reference implementation Java compilers, virtual machines,
and class libraries were originally released by Sun under
proprietary licenses. As of May 2007, in compliance with the
specifications of the Java Community Process, Sun had
relicensed most of its Java technologies under the GPL-2.0-
only license. Oracle offers its own HotSpot Java Virtual
Machine, however the official reference implementation is
the OpenJDK JVM which is free open-source software and
used by most developers and is the default JVM for almost
all Linux distributions.
Java is a high-level programming language that is class
based, object-oriented, and designed to reduce
implementation dependencies. This general-purpose
programming language allows programmers to write code
once and have it run anywhere. Compiled Java code can run
on any platform that supports Java without the need for
recompilation. Java 10
programs are typically compiled to bytecode.
Java gained popularity shortly after its release, and has
been a very popular programming language since then. Java
was the third most popular programming language in 2022
according to GitHub. Although still widely popular, there has
been a gradual decline in use of Java in recent years with
other languages using JVM gaining popularity.
Key Milestones:
• 1991: Project started by James Gosling, Mike Sheridan,
and Patrick Naughton.
• 1995: Java 1.0 released by Sun Microsystems.
• 1996: First version of Java Development Kit (JDK)
released.
• 1999: Java 2 (J2SE 1.2) released with significant
improvements.
• 2004: Java 5 (J2SE 5.0) introduced new features like
generics, annotations, enumerated types, and the enhanced
for loop.
• 2009: Oracle Corporation acquired Sun Microsystems,
including Java.
• 2014: Java 8 released with lambda expressions, the
Stream API, and the new date-time API.
11
Features of Java
Key Features
1. Simple: Java's syntax is easy to learn and use, with a
clean and straightforward design because of following
reasons:
• Java comprises the same syntax as C, and C++.
• It holds automatic garbage collection features.
• Java eliminated its unused features.
• It keeps bringing regular updates for better performance.
• Java has its own community to make learning and using
Java easy.
2. Object-Oriented: Java is based on the principles of
objects and classes, which makes it modular, flexible, and
scalable.
Almost everything written in Java is object and class,
making it a true object-oriented programming (OOP)
language. The basic concept of OOP is:
• Object: Object is a real-world entity in Java that
encompasses state, functionality, and identity.
• Class: Class is a logical entity which includes a group of
objects with common properties. It contains fields, methods,
constructors, blocks, nested classes and interfaces.
• Inheritance: It’s a concept in Java through which
developers can create new classes built upon existing
classes to achieve runtime polymorphism.
• Polymorphism: A Mechanism in Java through which you
can perform a single action in multiple ways. Polymorphism
can be of two types- Compile time and runtime.
• Abstraction: It’s a method to hide internal processing and
show only essential things to the users.
12
3. Platform-Independent: Java programs can run on any
device with the Java Virtual Machine (JVM). This feature is
known as "write once, run anywhere."
Unlike other languages, Java is not limited to any specific
machine and dependent on other factors to run. The Java
platform is independent because:
• It uses a runtime environment of its own, i.e. JVM.
• It is a write-once, run-anywhere language.
• It is a software-based platform that runs on top of other
hardware-based platforms.
• Its code can be executed on multiple platforms, including
Windows, Linux, Sun Solaris, and Mac/OS.
The Java code is compiled by the compiler and converted
into bytecode.
4. Secure: Java provides a secure environment for
developing applications by including features like bytecode
verification and a security manager.
Java programming language is known for its security. With it,
you can create virus-free systems because:
• Java programming language runs inside a virtual machine.
• It uses its own runtime environment- JVM.
• Java includes a security manager, which determines what
resources a class can access, such as reading and writing to
the local disk.
• In Java run time, a class loader separates the package for
the classes of the local file system from the files imported
from network sources.
Java also consists of Bytecode Verifier, which checks the
code fragments for illegal code.
5. Robust: Java has strong memory management,
exception handling, and type-checking mechanisms to
create reliable applications.
Automatic memory management is a crucial feature of Java
programming. It helps in:
• Create high-performance system.
• Automatically allocate and free up space for objects.
• Eliminating the worries about memory management.
• Issues like object destruction don’t occur.
13
There is no need to add memory management logic.
6. Multithreaded: Java supports concurrent execution of
multiple threads, making it possible to perform many tasks
simultaneously.
Multithreading is an essential feature of Java that makes
Java programming exclusive. It offers several benefits:
• It lets Java developers execute multiple threads at the
same time.
• It’s used to achieve multitasking.
• It saves time.
• It’s mostly used in games and animation.
Threads work independently and don’t impact other
threads, even if created simultaneously.
7. High Performance: Java achieves high performance
through Just-In-Time (JIT) compilers and efficient garbage
collection.
Java is a programming language with a high-performance
rate. It is because:
• Java uses bytecode that can be easily translated into
native machine code.
• It has multiple easy-to-use frameworks.
• It is compatible with multiple platforms, including
Windows, Linux, Sun Solaris, and Mac/OS.
• It is a write-once, run-anywhere language.
Java also automatically clears the garbage to enhance its
performance.
8. Distributed: Java supports distributed computing,
allowing developers to create applications that can run on
different systems across a network.
Java offers its users scalability, which means it can deal with
more and more users and works. It is so because:
• Java is an object-oriented programming language.
• It has the ability to handle large databases.
• Java doesn’t require multiple resources while running.
14
// Simple Java program to demonstrate object-oriented principles
class Animal {
void makeSound() {
System.out.printIn( Animal makes a sound );
}
}
class Dog extends Animal {
^Override
void makeSound() {
System.out.printIn( Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Outputs: Dog barks
}
} o
• It uses multithreading and multiprocessing.\
Java includes a higher volume of code.
9. Dynamic: Java can dynamically load classes, even if they
are not known at compile time, which makes it flexible and
adaptable.
Example:
15
Setting up Java Environment: Step-by-Step Guide
Step 1: Download and Install JDK
1. Visit the Official Oracle JDK Download Page: Go to
the Oracle JDK download page.
2. Select and Download the Appropriate JDK Version:
Choose the appropriate JDK
version for your operating system (Windows, macOS, or
Linux) and click the download link.
3. Accept the License Agreement: Accept the license
agreement and download the installer.
4. Run the Installer: Locate the downloaded installer file
and run it. Follow the on-screen instructions to complete the
installation.
Step 2: Set Up JAVA_HOME Environment Variable
1. Locate the JDK Installation Directory: After
installation, locate the directory where JDK was installed.
The default installation path is usually:
o Windows: C:\Program Files\Java\jdk-<version>
o macOS: /Library/Java/JavaVirtualMachines/jdk-
<version>.jdk/Contents/Home o Linux: /usr/lib/jvm/jdk-
<version>
2. Set JAVA_HOME on Windows:
o Right-click on "My Computer" or "This PC" and select
"Properties".
o Click on "Advanced system settings".
o Click on the "Environment Variables" button.
o Under "System variables", click "New" to add a new
variable.
o Set the variable name to JAVA_HOME and the variable
value to the JDK
installation path (e.g., C:\Program Files\Java\jdk-<version>).
o Click "OK" to save the changes.
3. Set JAVA_HOME on macOS:
o Open a terminal window.
o Edit the ~/.bash_profile file (or ~/.zshrc if using zsh) using
a text editor: 16
export 2AVA_HDME=/Libr a ry/J av a/3 avaVi rtuaiMa chines/j dk -<version>. j dk/Content s/Horne
nano -/.bashre
export JAVA_H0ME=/usr/1ib/jvm/jdk-<ve rsio n >
Add the following line to the file
Save the file and reload the shell configuration
Set JAVA_HOME on Linux:
• Open a terminal window.
• Edit the ~/.bashrc or ~/.profile file using a text editor:
Set JAVA_HOME on Linux:
• Open a terminal window.
• Edit the ~/.bashrc or ~/.profile file using a text editor:
Add the following line to the file:
Save the file and reload the shell configuration:
17
Step 3: Add JDK's bin Directory to System PATH
1. Add to PATH on Windows:
o In the "Environment Variables" window (same as where
you set JAVA_HOME), find the "Path" variable under "System
variables" and select it.
o Click "Edit" and then "New".
o Add the path to the bin directory of the JDK installation
(e.g., C:\Program Files\Java\jdk-<version>\bin).
o Click "OK" to save the changes.
2. Add to PATH on macOS and Linux:
o Open a terminal window.
o Edit the ~/.bash_profile or ~/.bashrc (or ~/.zshrc for zsh)
file Add the following line to the file:
Save the file and reload the shell configuration
18
java -version
java version "17, " - - LTS
Java(TM) SE Runtime Environment (build . + -LTS- )
Java Hots pot (TH) -Bit server VM (build . + -LTS- , mixed inode., sharing)
javac -version
javac 17.0.2
Step 4: Verify the Installation
1. Open a Command Prompt or Terminal: Open a new
command prompt (Windows) or terminal window
(macOS/Linux).
2. Check Java Version: Run the following command to
check the installed Java version:
You should see output similar to:
3. Check Java Compiler Version: Run the following
command to check the installed Java compiler version:
You should see output similar to:
19
javac Hellaworld.java
java HelloWorld
HellOj World I
Step 5: Write and Run Your First Java Program
1. Create a New Java File: Create a new text file named
HelloWorld.java and open it in a text editor. Write the
following code:
2.Compile the Java Program: Open a command prompt
or terminal, navigate to the directory containing
HelloWorld.java, and run:
Run the Compiled Java Program: Run the compiled Java
program with the following command: You should see the
output:
By following these steps, you have successfully set up your
Java development environment and run your first Java
program.
20
*/jdk
export JAVA_HOHE=/path/to/your
export PATH=$JAVA_HOME/bin:$PATH
Summarized Steps to Set Up Java Environment
1. Download and Install JDK:
o Visit the official Oracle website and download the Java
Development Kit (JDK) appropriate for your operating
system.
o Follow the installation instructions to install JDK on your
system.
2. Set Up Environment Variables:
o For Windows:
1. Right-click on 'My Computer' or 'This PC' and select
'Properties'.
2. Click on 'Advanced system settings'.
3. Click on the 'Environment Variables' button.
4. Under 'System variables', click 'New' and add a new
variable with the name JAVA_HOME and the path to your JDK
installation directory.
5. Find the Path variable, click 'Edit', and add
%JAVA_HOME%\bin.
o For Mac/Linux:
1. Open the terminal.
2. Open or create the .bash_profile file in your home
directory.
3. Add the following lines:
21
$ java -version
java version "17.0.2" 2021-12-14 LTS
Java(TM) SE Runtime Environment (build 17.0.2+8-LTS-86)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.2+8-LTS-86, mixed mode, sharing)
1. Save the file and run source ~/.bash_profile to apply the
changes.
2. Verify Installation:
o Open a command prompt or terminal window.
o Type java -version and javac -version to verify that Java is
installed and configured correctly.
Example:
22
Writing Your First Java Program
Steps to Write and Run a Java Program:
1. Create a Java Source File:
o Open a text editor and create a new file named
HelloWorld.java.
o Write the following code in the file
Compile the Java Source File:
• Open a command prompt or terminal window.
• Navigate to the directory where HelloWorld.java is saved.
• Run the following command to compile the file
• This will generate a HelloWorld.class file in the same
directory.
23
java HelloWorld
Hello, World!
// HelioWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.printIn( Hello, World );
}
}
Run the Compiled Java Program:
• In the same command prompt or terminal window, run the
following command This will execute the program and
display the output
Example:
24
public class Sum {
public static void mai (String[] args) {
int numl = 10;
int num2 = 20;
int sum = numl + num2;
System.out.printIn( The sum is: + sum);
Practice Exercise:
1. Task: Modify the HelloWorld program to print your name
instead of "Hello, World!".
Solution:
2. Task: Create a new Java program that prints the sum of
two numbers.
Solution:
25
public class HelloWorld {
public static void main(String[] args) {
System.out_println( Hello, World );
Chapter 2: Java Basics
Java Syntax and Structure
Java programs are written in plain text files ending with the
.java extension. These files contain one or more classes and
their definitions.
Example of a Basic Java Program:
Explanation:
• public class HelloWorld: Defines a public class named
HelloWorld.
• public static void main(String[] args): The main method,
which is the entry point for any Java application.
• System.out.println("Hello, World!");: Prints "Hello, World!"
to the console.
Practice:
1. Write a Java program that prints your name.
2. Write a Java program that prints the sum of two numbers.
26
public class Print lame {
public static void main(String[] args) {
System-out.printIn( Craig );
}
}
Solution:1
Explanation:
• The PrintName class contains a main method, which is the
entry point of the program.
• System.out.println("Craig"); prints the name "Craig" to the
console.
27
public class SumOfTwoNumbers {
public static void niain(String[] args) {
int numl = 10; // First number
int num2 = 20; // Second number
int sum = numl + num2; // Calculate the sum
System.out.println("The sum of " + numl + " and " + num2 + " is: " + sum);
Solution: 2
Explanation:
The SumOfTwoNumbers class contains a main method.
• Two integer variables, num1 and num2, are declared and
initialized with the values 10
and 20, respectively.
• The sum variable is calculated by adding num1 and num2.
• System.out.println("The sum of " + num1 + " and " +
num2 + " is: " + sum); prints the result of the sum to the
console in a formatted string.
These examples help in understanding the basics of Java
syntax and the use of variables and operators. By modifying
and experimenting with these programs, you can get more
comfortable with writing and running Java code.
28
□ackage com.example.«yapp;
public class Helloworld {
// Fields, constructors, methods go here
}
public static void main(string[] args) {
System.out.println{ Hello, Wor ).;
}
Java Program Structure
1. Package Declaration (Optional):
o Packages are used to group related classes. The package
declaration is the first line in a Java source file.
Import Statements (Optional):
• Used to import other Java classes into your code.
Class Declaration:
• The class is the fundamental unit of Java programs. Every
Java application has at least one class.
Main Method:
• The entry point of any Java application.
29
package com.example.myapp;
inport java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
system.out.printing Hello, arid );
}
}
Example:
30
=
double salary = 50000.75;
char grade = ;
boolean IsEaployed = true;
Data Types and Variables
Java is a strongly typed language, which means every
variable must have a data type.
Primitive Data Types:
int: Integer (e.g., int age = 25;)
double: Double-precision floating-point (e.g., double price =
19.99;) char: Character (e.g., char grade = 'A';)
boolean: Boolean (e.g., boolean isJavaFun = true;)
1. byte: 8-bit integer (-128 to 127)
2. short: 16-bit integer (-32,768 to 32,767)
3. int: 32-bit integer (-2^31 to 2^31-1)
4. long: 64-bit integer (-2^63 to 2^63-1)
5. float: 32-bit floating point
6. double: 64-bit floating point
7. char: 16-bit Unicode character
8. boolean: true or false
Example:
31
String narne = ''3ofin Dae1';
ir [] numbers = { 2, a, +,
int num = 10;
double salary = 3500.59;
= ;
boolean isActive = true;
String name = "John";
Reference Data Types:
String: Sequence of characters (e.g., String message =
"Hello";)
• Classes, arrays, interfaces, etc.
Example:
Variable Declaration and Initialization:
32
Practice:
1. Declare and initialize variables of different types and print
them.
2. Write a program to swap two numbers using a temporary
variable.
33
public class VariableTypes {
public static void main(String[] args) {
int num = 25; // Integer variable
double price = 19.99; // Double variable
char grade = 'A'; 11 Char variable
boolean islavaFun = true; // Boolean variable
String message = "Hello, World!"; // String variable
System.out.printIn( Integer: " + num);
System.out.printin("Double: " + price);
System.out.println( Char: + grade);
System.out.println( Boolean: " + isJavaFun);
System.out.println('String: ' + message);
}
}
Practice Exercise Solutions 1
Explanation:
• The VariableTypes class contains a main method.
• Different types of variables are declared and initialized
with values.
• System.out.println is used to print each variable to the
console
34
public class SwapNumbers {
public static void main(String[] args) {
int numl = 10; // First number
int num2 = 20; // Second number
System.out.printIn( Before swapping: );
System-out.printIn( numl - + numl);
System.out.printIn( ium2 = + num2);
// Swapping logic using a temporary variable
int temp = numl;
numl = num2;
num2 = temp;
System-out.printIn( After swapping: );
System.out.printIn( numl + numl);
System.out.printIn('num2 = 1 + num2);
1
}
Practice Exercise Solutions 2
Explanation:
• The SwapNumbers class contains a main method.
• Two integer variables, num1 and num2, are declared and
initialized with values 10
and 20, respectively.
• The original values of num1 and num2 are printed to the
console.
• A temporary variable temp is used to hold the value of
num1 during the swap.
• The values of num1 and num2 are swapped using the
temporary variable.
• The swapped values of num1 and num2 are printed to the
console.
35
These examples illustrate how to declare and use different
types of variables, as well as how to perform basic
operations like swapping values using a temporary variable.
By practicing these concepts, you'll strengthen your
understanding of variable manipulation in Java.
36
int sum =10+5;
int difference =10-5;
int product = 10 * 5;
int quotient =10/5;
int remainder = IS % 5;
int a = IB;
int t = 2?;
int sum = a + b; // 38
Operators and Expressions
Operators are used to perform operations on variables and
values.
Arithmetic Operators:
• + Addition
• - Subtraction
• * Multiplication
• / Division
• % Modulus
Example:
Arithmetic Operators:
+ (addition), (subtraction), * (multiplication), / (division), %
(modulus) Example:
37
boolean isEqual = (IS — 5);
boolean isNotEqual = (10 != 5);
boolean isGreater = (10 > 5);
boolean isLessen = (10 < 5);
boolean result = (a > b); // false
Relational Operators:
• == Equal to
• != Not equal to
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to
Example:
Relational Operators:
• == (equal to), != (not equal to), > (greater than), < (less
than), >= (greater than or equal to),
<= (less than or equal to)
Example:
38
boolean result = (a > 5 &S b < // true
- ;
X += ! ; // 15
Logical Operators:
• && Logical AND
• || Logical OR
• ! Logical NOT
Logical Operators:
• && (logical AND), || (logical OR), ! (logical NOT)
Example:
Assignment Operators:
• =, +=, =, *=, /=, %=
Example:
39
public class Rectangle {
public static void main(String[] args) {
double length = 5.0; // Length of the rectangle
double width = 3.0; // Width of the rectangle
double area = length * width; // Calculate the area
double perimeter = 2 * (length + width); // Calculate the perimeter
System.out.println("Area of the rectangle: " + area);
System.out.println("Perimeter of the rectangle: " + perimeter);
}
Practice:
1. Write a program to calculate the area and perimeter of a
rectangle.
2. Write a program to check if a number is even or odd.
Practice Exercise Solutions 1
1. Write a program to calculate the area and
perimeter of a rectangle.
Solution:
Explanation:
• The Rectangle class contains a main method.
• Two double variables, length and width, are declared and
initialized with values.
• The area is calculated by multiplying length and width.
• The perimeter is calculated by adding length and width
and then multiplying by 2.
• System.out.println is used to print the area and perimeter
to the console.
40
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(Systeni.in); // Create a Scanner object for user i
System.out.print("Enter a number: ");
int number = scanner.nextlnt(); // Read an integer from the user
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
scanner.close(); // Close the scanner object
}
}
Practice Exercise Solutions 2
Write a program to check if a number is even or odd.
Solution:
Explanation:
• The EvenOrOdd class contains a main method.
• A Scanner object is created to read input from the user.
• The user is prompted to enter a number using
System.out.print.
• The entered number is read using scanner.nextInt.
• An if-else statement is used to check if the number is even
or odd using the modulus operator %.
• If the remainder when number is divided by 2 is 0, the
number is even; otherwise, it is odd.
41
• The result is printed to the console.
• The scanner.close() method is called to close the scanner
object.
These examples demonstrate basic calculations and control
flow using if-else statements.
Practicing these exercises will help you understand how to
perform arithmetic operations and handle user input in Java.
42
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
Control Flow Statements
Control flow statements determine the order in which
statements are executed. They allow for branching and
looping, providing the ability to execute code conditionally
or repeatedly.
if Statement:
If-Else Statement
The if-else statement allows you to execute code based on a
condition.
Syntax:
43
public class IfElseExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.printIn(number + ’ is positive.1);
} else {
System.out.printin(number + ' is negative or zero. );
}
}
}
if (a > b) {
System.out.printIn( is greater than b );
} else {
Systeni.oirt.printLn("a is not greater than b");
}
Example:
44
Practice
1. Write a program to check if a given number is positive,
negative, or zero.
Practice: Check if a Given Number is Positive, Negative, or
Zero Solution
Explanation:
• The CheckNumber class contains a main method.
• A Scanner object is created to read input from the user.
• The user is prompted to enter a number using
System.out.print.
• The entered number is read using scanner.nextDouble.
• An if-else-if statement is used to check if the number is
positive, negative, or zero: 45
javac CheekNumber.java
java CheckNumber
Enter a number: 1?
I0.0 is positive.
o If the number is greater than 0, it is positive.
o If the number is less than 0, it is negative.
o If the number is equal to 0, it is zero.
• The result is printed to the console.
• The scanner.close() method is called to close the scanner
object.
Test the Program
You can compile and run this program to see how it works
with different inputs: Sample runs:
46
Enter a number:
-5.0 is negative.
Enter a number: 0
The number is zero.
By practicing and running this program, you can see how
control flow statements like if-else-if can be used to make
decisions based on user input in Java.
47
switch (expression) {
case valuel:
// Code to execute if expression == valuel
break;
case value?:
// Code to execute if expression == value?
break;
// You can have any number of case statements.
defauli :
// Code to execute if expression does not match any case
}
Switch Statement
The switch statement allows you to execute one block of
code among many based on the value of an expression.
Syntax:
48
public class SwitchExample {
public static void main(string[] args) {
int daj = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "invalid day";
break;
}
System.out.println("Day " + day + " is " + dayName);
}
Example:
49
= j
switch (day) {
case 1:
System.out.print Ln( one );
breal;
case 2:
System.out.print Ln( Tuesd i );
breal;
case 3:
System.out.printlnf Wednesday );
breal;
default:
System.out.printlnf Other : );
}
50
Practice:
1. Write a program to print the name of the month based on
the month number (1-12).
51
import Java.util.Scanner;
public class MonthName £
public static void mair (String!] args) £
scanner scanner = nevi Scanner(System.in); // create a Scanner object for user inp
System.out.print("Enter the month number (1-12): );
int nonttiNumber = scanner _ nextlnit( ) ; // Read an integer froa the user
String monthName;
switch (monthNumber) £
case 1:
monthName = "January";
break;
case 2:
monthName = "February”;
break;
case 3:
monthName = "March";
break;
case 4-:
monthName = "April”;
break;
case 5:
monthName = "May”;
break;
case s:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case le:
monthName = "October";
break;
case 11:
monthName = "November”;
break;
case 12:
monthName = "December”;
break;
de-Fault:
monthName = "invalid month number. Please enter a number between 1 and 12.
break;
System, out .printLn( lonth: " * monthName);
scanner.close(); // Close the scanner object
Solution
52
Explanation:
• The MonthName class contains a main method.
• A Scanner object is created to read input from the user.
• The user is prompted to enter a month number using
System.out.print.
• The entered month number is read using scanner.nextInt.
• A switch statement is used to determine the name of the
month based on the month number:
o Each case corresponds to a month number (1-12), setting
the monthName variable to the appropriate month name.
o The default case handles invalid month numbers by
setting monthName to an error message.
• The result is printed to the console.
• The scanner.close() method is called to close the scanner
object.
53
javac MonttiName. java
java MonthName
Enter the month number (1-12): 3
Month: March
Enter the month number (1-12): 11
Month: November
Enter the month number (1-1 ): 15
Month: Invalid mo-ith number. Please enter a number bet. een 1 and 12.
Test the Program
You can compile and run this program to see how it works
with different inputs: By practicing and running this
program, you can see how control flow statements like
switch can be used to handle multiple conditions in Java.
54
for (initialization; condition; update) -[
// Code to be executed repeatedly
}
For Loop
The for loop in Java is used to execute a block of code a
fixed number of times. It consists of three parts:
initialization, condition, and update. These parts control the
number of iterations the loop will execute.
Syntax
Initialization: This part is executed only once, at the
beginning of the loop. It typically declares and initializes
loop control variables.
Condition: This is evaluated before each iteration. If the
condition is true, the loop's body is executed. If false, the
loop terminates.
Update: This part is executed after each iteration of the
loop's body. It typically updates the loop control variables.
55
public class ForLoopExainple {
public static void mainfstringl] args) ■£
for ( = ; i <= ■ i+
*
) {
System.out.printing i = " + i);
Example: Print Numbers from 1 to 5
Explanation:
• The for loop starts with i initialized to 1.
• The condition i <= 5 ensures that the loop runs as long as
i is less than or equal to 5.
• After each iteration, i is incremented by 1 using i++.
56
public class FirstTenNaturalNunibers {
public static void main{String[] args) {
for ( = i i c= ; i++) {
System.out.printin(i);
Practice
1. Write a Program to Print the First 10 Natural
Numbers
Solution:
57
javac F irstTenNat uraiNum bers.java
java FirstTenMaturalNumbers
1
2
3
4
5
B
7
3
9
10
Test the Program
You can compile and run this program to see how it works:
Expected output:
Explanation:
• The loop initializes i to 1 and increments i by 1 in each
iteration.
• The condition i <= 10 ensures that the loop runs ten
times, printing the numbers from 1
to 10.
58
public class SumOfFirstTenNumbers {
public static void (string[] args) {
= j
for (int i = 1; i <= 1®; i++) {
sun += i;
}
system.out.printing lie sum of the first 10 natural ruroers is ' + sum);
)
}
2. Write a Program to Print the Sum of the First 10
Natural Numbers
Solution
Explanation:
• The loop initializes i to 1 and increments i by 1 in each
iteration.
• The condition i <= 10 ensures that the loop runs ten
times.
• The sum variable accumulates the sum of i in each
iteration.
• The final sum is printed after the loop completes.
59
javac SumOfFirstTenMumbers.java
java SumOfFlrstTenNumbers
The sum of the first IE natural numbers is: 55
I-lie (condition) {
if Code to be executed repeatedly
}
Test the Program
You can compile and run this program to see how it works:
Expected output:
By practicing these examples, you'll become comfortable
using for loops to perform repetitive tasks in Java.
While Loop
The while loop in Java is used to repeatedly execute a block
of code as long as a specified condition is true. It is
particularly useful when the number of iterations is not
known beforehand.
Syntax
Condition: This is evaluated before each iteration. If the
condition is true, the loop's body is executed. If false, the
loop terminates.
60
public class WhileLoopExample {
public static void main(String[] args) {
int 1 = 1; // Initial izartion
while (i <= 5) { H condition
system.out.println( i = + i);
i++; fl update
Example: Print Numbers from 1 to 5
Explanation:
• The loop initializes i to 1.
• The condition i <= 5 ensures that the loop runs as long as
i is less than or equal to 5.
• After each iteration, i is incremented by 1 using i++.
61
int i = ;
while (i < E) {
system.a nt.printIn( + i);
public class SiimofFirstTenNiintierswtiile {
public static void (string[] args) {
int sum = 0;
= j // Initialization
while (i <= 10) { // Condition
sum += i; // Add i to sin
i++; // update
}
Systea.out.print 1ji("The sum of the first IB natural nuntiers is ' +■ sum);
}
}
while Loop:
Practice
1. Write a Program to Print the Sum of the First 10
Natural Numbers Using a While Loop
Solution:
62
The sum of the first if natural numbers, is: 55
Explanation:
• The loop initializes i to 1.
• The condition i <= 10 ensures that the loop runs as long
as i is less than or equal to 10.
• The sum variable accumulates the sum of i in each
iteration.
• The final sum is printed after the loop completes.
Test the Program
You can compile and run this program to see how it works:
Expected output:
63
public class FirstTenEvenNumbers {
public static void (String[] args) {
int i=l; // Counter for even numbers
int num = 2; // Start with the first even number
while (i <= 10) { // condition to print IB even numbers
System.out.p rintin(n urn);
num += 2; // Move to the next even nuaber
i++; ft increment the counter
}
}
3. Write a Program to Print the First 10 Even
Numbers Using a While Loop
Solution
Explanation:
• The loop initializes i to 1 and num to 2.
• The condition i <= 10 ensures that the loop runs 10 times.
• num starts at 2 and is incremented by 2 in each iteration
to get the next even number.
• The first 10 even numbers are printed to the console.
64
javac FirstTenEvenNumbers.java
java FirstTenEvenNumbers
2
4
S
8
10
12
14
IS
IS
20
Test the Program
You can compile and run this program to see how it works:
Expected output:
By practicing these examples, you'll become comfortable
using while loops to perform repetitive tasks in Java,
especially when the number of iterations isn't
predetermined.
65
do {
H Code to be executed repeatedly
} ihile (condition);
Do-While Loop
The do-while loop in Java is similar to the while loop, but it
guarantees that the loop's body is executed at least once.
This is because the condition is evaluated after the loop's
body has been executed, not before.
do-while Loop:
Syntax
• Code Block: The code inside the do block is executed at
least once and then repeatedly until the condition evaluates
to false.
• Condition: This is evaluated after each iteration of the
loop. If the condition is true, the loop continues; otherwise,
it terminates.
66
public class DoKiile Loo pExample {
public static void ■ain(£tring[] args) ■[
int i = 1; H initialization
de {
System.out.println( + i);
i++; H Update
} while (i <= 5); // Condition
}
}
Example: Print Numbers from 1 to 5
Explanation:
• The loop initializes i to 1.
• The code inside the do block executes, printing the value
of i.
• After printing, i is incremented by 1.
• The condition i <= 5 is checked after the loop's body
executes. As long as i is less than or equal to 5, the loop
continues.
67
Practice
1. Write a Program to Print the Sum of the First 10
Natural Numbers Using a DoWhile Loop
Solution
Explanation:
• The loop initializes i to 1.
• The code inside the do block adds i to sum and increments
i by 1.
• The condition i <= 10 ensures that the loop runs as long
as i is less than or equal to 10.
• The final sum is printed after the loop completes.
68
javac SumOfFirstTenMumbersDoWbile.java
java suniof Firs ttenN umber soowhile
The sum of the first ie natural numbers is: 55
Test the Program
You can compile and run this program to see how it works:
Expected output:
69
public class FirstTenodcKumbers {
public static aid (String[] args) {
int i = 1; f! Counter for odd numbers
int count = 0; ! I Count of odd numbers printed
de {
System.out.println(i);
i += 2; // Move to the next odd number
count+4-i // Increment tbe count
} while (count < 10}; // Condition to print 19 odd nurters
}
}
2. Write a Program to Print the First 10 Odd Numbers Using
a Do-While Loop Solution:
Explanation:
• The loop initializes i to 1 and count to 0.
• The code inside the do block prints i (the current odd
number) and increments i by 2
to get the next odd number.
• count is incremented each time an odd number is printed.
• The loop continues until count reaches 10.
70
javac FirstTenOddNumbers.java
java FirstTenDddNuabers
1
3
5
7
9
11
13
15
17
19
Test the Program
You can compile and run this program to see how it works:
Expected output:
By practicing these examples, you'll understand how do-
while loops work and see their advantage in scenarios
where the loop's body must be executed at least once
regardless of the condition
71
Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming
paradigm based on the concept of
"objects," which can contain data in the form of fields (often
known as attributes or properties) and code in the form of
procedures (often known as methods). Java is an object-
oriented language that leverages this paradigm to structure
programs in a modular and reusable way.
Core Concepts of OOP
Class in Java
A class in Java is a blueprint or template for creating
objects. It defines a type of object by specifying its
properties (fields) and behaviours (methods). Classes
encapsulate data for the object and methods to manipulate
that data.
Structure of a Class
A class typically consists of the following components:
1. Fields (Attributes or Properties): Variables that hold
the data of the object.
2. Methods: Functions that define the behaviour of the
object.
3. Constructors: Special methods used to initialize new
objects.
4. Access Modifiers: Keywords that control the visibility of
the class and its members (e.g., public, private, protected).
72
public class lyclass {
// Fields (attributes or properties)
int myNuaber;
string mystring;
// Constructor
HyClassfini numberj String text) {
myNunber = number;
mystring = tert;
U Methods.
void displa; () {
System.out.println( umber: + myNumber);
System.out.printlnf ytring: + mystring);
// Method with return value
int get\umi'er() {
return myNumber;
public class lain {
p.iblic static void (string[] args) {
ll create an object of Myclass
ij class : = new cless( j Hello world");
11 Access fields and methods
obj.display{); // calls the display method
int number = obj.getNurt>er(); // calls the getNLmiber method and stores the result
System.out.printlnf jmber fror getmaber() + number);
}
Syntax of a class
Example of Creating and Using a Class
73
Explanation:
1. Class Definition: MyClass defines two fields (myNumber
and myString), a constructor, and two methods (display and
getNumber).
2. Constructor: Initializes myNumber and myString with
values provided when creating an object.
3. Methods: display prints the values of myNumber and
myString. getNumber returns the value of myNumber.
4. Object Creation: In the Main class, MyClass obj = new
MyClass(10, "Hello World"); creates a new object of MyClass,
initializing its fields using the constructor.
5. Method Calls: obj.display(); calls the display method on
the object obj.
obj.getNumber(); calls the getNumber method to retrieve
the value of myNumber.
74
public class -.ccess'dodifiersExample {
public int pub Lie Fie Id; // Accessible -from anywhere
private int privateField; // Accessible only within this class
protected int protectedField; // Accessible within the sawe package and subclasses
int defaultField; // Accessible only within the sawe package
// Constructor
AccessMfldifiersExample( publicvalue, privatevalue, protectedvalue, defa
publicField = publicvalue;
privateField = privatevalue;
protectedField = protectedvalue;
defaultField = defaultvalue;
}
H Method
public void displa.() {
System.out.printing iblic Fiel + publicField);
System.out.printing Private Fiel + privateField);
System.out.printing Protected Fielt + protectedField);
System.out.printing Default Fi + defaultField);
}
}
Access Modifiers
Access modifiers control the visibility and accessibility of
classes, fields, constructors, and methods:
• public: The member is accessible from any other class.
• private: The member is accessible only within the class
itself.
• protected: The member is accessible within the same
package and by subclasses.
• Default (no modifier): The member is accessible only
within the same package.
Example of Access Modifiers:
75
public class MyClass {
// Fields
int myNumber;
string aystring;
H Constructor
MyClass(iit number, string text) {
myNumber = number;
myString = text;
}
// Method
void display() {
System.out.printLnf N.irber: ' + myNumber);
system.out.printLnf string: + mtystring);
}
}
Creating and Using a Class
1. Create a Class File: Save the class definition in a .java
file.
2. Compile: Use javac ClassName.java to compile the class.
3. Run: Use java Main to run the Main class that utilizes the
defined class.
A class in Java is a fundamental construct that allows you to
create objects with specific attributes and behaviors. By
defining fields, methods, and constructors, you can model
real-world entities and organize code in a modular and
reusable way. Experiment with creating your own classes to
gain a deeper understanding of their functionality and
usage.
Class
o A class is a blueprint or template for creating objects. It
defines a type of object by bundling data and methods that
operate on that data.
Syntax
76
Practice Examples
1. Creating a Person Class
Objective: Define a Person class with attributes for name
and age. Include methods to display person details and
check if the person is an adult.
77
public class Person {
// Fields
private String name;
private int age;
// Constructor
public Perse (String name, int age) {
this.name = name;
this.age = age;
}
// Method to display person details
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: + age);
}
// Method to check if the person is an adult
public boolean isAdult() {
return age >= IS;
}
// Main method to test the Person class
public static void main(string[] args) {
Person personi = new Person(“Alice", 30);
Person person2 = new Person(“Bob", 15);
personi.d isplayDetails();
System.out.println("ls Adult: + personi .isAdultQ);
person2.d isplayDetails();
System.out.println("ls Adult: + person2 .isAdultQ);
}
1
Solution:
Explanation:
• Fields: name and age.
• Constructor: Initializes the name and age fields.
78
• Methods: displayDetails prints the person’s name and
age, isAdult returns whether the person is an adult.
• Testing: In the main method, two Person objects are
created and their details and adulthood status are
displayed.
2. Creating a BankAccount Class
Objective: Define a BankAccount class with attributes for
account number and balance.
Include methods to deposit, withdraw, and check balance.
79
public class BankAccount ■{
ff Fields
private String accountNumber;
private double balance;
// Constructor
public BankAccount(String accountNiumberj double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
ff Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" +■ amount);
} else {
System.out.println("Deposit amount must be positive. );
}
ff Method to withdraw money
public void withdraw(double amount) [
if (amount > 0 && amount <= balance) {
balance -= amount;
System .out .print ln( "withd rev.: $" •+■ amount);
} else {
System.out.println("insufficient balance or invalid amount.-);
}
ff Method to check balance
public -double getBalance() £
return balance;
ff Main method to test the BankAccount class
public static void wait (String[] args) {
BankAccount account = new BankAccount(“123456789", 50-0.00);
System.out.printing initial Balance: $■" +■ account.getBalance());
account.deposit(15©.00};
account.witMraw(280 -00);
System.out.println( "Final Balance: $" +■ account.getBalanceQ);
Solution:
80
Explanation:
• Fields: accountNumber and balance.
• Constructor: Initializes the account number and balance.
• Methods: deposit adds money to the balance, withdraw
deducts money from the balance, and getBalance returns
the current balance.
• Testing: In the main method, a BankAccount object is
created and deposit, withdrawal, and balance checking are
demonstrated.
81
public class Rectangle {
// Fields
private width;
private double height;
H Constructor
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
// Method to calculate area
public double grtAreaQ -[
return width * height;
}
// Method to calculate periBeter
public double getFerimeterO £
return • (width + height);
}
H Hain Bethod to test the Rectangle class
public static void (String[] args) {
Rectangle rect = new Rectangle(5.e, 3.0);
system.out.printlnf widt + rect.width);
System.out.printlnf Heigh + rect.height);
System.out.printlnf rea + rect.getArea());
System.out.printlnf Perijnete + rect.getPerimeter());
}
}
3. Creating a Rectangle Class
Objective: Define a Rectangle class with attributes for
width and height. Include methods to calculate the area and
perimeter of the rectangle.
Solution
82
Explanation:
• Fields: width and height.
• Constructor: Initializes width and height.
• Methods: getArea returns the area of the rectangle,
getPerimeter returns the perimeter.
• Testing: In the main method, a Rectangle object is
created and its area and perimeter are calculated.
These practice examples cover creating classes, initializing
objects, and using methods. By experimenting with these
examples, you'll better understand how to define and use
classes in Java. Feel free to modify and extend these
examples to further your learning!
83
Objects in Java
In Object-Oriented Programming (OOP), objects are
instances of classes. They are the fundamental building
blocks of a program and represent real-world entities or
concepts. An object encapsulates both data and behavior
related to that data.
Key Concepts of Objects
1. Creating Objects
2. Accessing Object Fields and Methods
3. Object Initialization
4. Object References
Creating Objects
To create an object in Java, you use the new keyword
followed by the class constructor. This process allocates
memory for the object and initializes it using the
constructor.
84
public class car {
// Fields (attributes)
String model;
year;
// constructor
public . (String models year} {
this.model = model;
this.year = year;
}
H Method
public void displayInfo() {
system.out.printlnf + model);
System.out.printlnf Year + year);
}
}
// Main, class to create and use objects
public class lain {
public static void i (String[] args) {
// Creating an object of Car
Car myCar = new Car("Toyota Caary", 2622);
// Accessing object methods
my Ca r. d isp 1 ay Inf o( );
}
}
Example
85
public class Person {
H Fields
String name;
int age;
!/ Constructor
public Perse (String name, int age) {
this.name = name;
this.age = age;
H Method
public void greet() {
System, out. print Ln ["Hello, my name is ' + name +■ " and I am " + age + 11 years old.
)
}
U Hain class to create and use objects
public class lain {
public static void i (string[] args) {
11 Creating an object of Person
= new ( > )j
// Accessing object fields
System.out.printLn[person.name);
System.out.printLn[person.age);
ll Accessing object method
person.greet()i
)
}
2. Accessing Object Fields and Methods
Once an object is created, you can access its fields and
methods using the dot (.) operator.
Example:
86
public class Eook {
// Fields
string title;
String author;
H Parameterized constructor
public (String title, String author) {
this.title = title;
this.author = author;
3. Object Initialization
Objects can be initialized using constructors, which can be
parameterized or default. If no constructor is explicitly
defined, Java provides a default constructor.
Parameterized Constructor Example:
87
public class Book: {
// Fields
String title;
String author;
U Default constructor
public Hoolc() {
this.title = "Unknown Title";
this.author = "unknown Author";
}
}
Default Constructor Example:
88
public class Main {
public static void (String[] args) {
// Creating two references to the sane object
car carl = new car("Honcla civic", 2021>;
Car car2 = carl; // car2 references the same object as carl
// Modifying the object through one reference
carl.year = 202 ;
// Both references reflect the change
System.out.printing Car 1 Year + carl.year); // Outputs: 2023
system.out.printing car 2 Year + car2.year); H outputs: 2023
4. Object References
In Java, variables that hold object references are used to
refer to objects. These references point to the memory
location where the object is stored.
Example:
89
public class Main {
public static void (String[] args) {
// Creating an object
:ar aycai = net ( :ord Focus"., );
// Reassigning reference, the previous Car object is eligible for garbage collect!
mycar = ne Cai ("Chevrolet l ie Lib'. , 1020);
// At this point, the previous car object is no longer referenced and will be coll
}
}
5. Garbage Collection
Java uses automatic garbage collection to manage memory.
When objects are no longer referenced by any part of the
program, they become eligible for garbage collection, which
reclaims their memory.
Example:
• Creating Objects: Use the new keyword and a
constructor to create an object.
• Accessing Fields and Methods: Use the dot (.) operator
to interact with an object’s data and behavior.
• Initialization: Objects can be initialized using
constructors with or without parameters.
• Object References: Variables hold references to objects,
and multiple references can point to the same object.
• Garbage Collection: Java automatically reclaims
memory used by objects that are no longer referenced.
Understanding and practicing these concepts will help you
effectively use and manage objects in your Java programs.
90
public class car {
1! Fields (attributes)
String color;
String model;
int year;
// Methods (behaviors)
void drivef) {
System.out.printLn( he ci r is driving );
}
}
Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming
paradigm that uses "objects" and their interactions to
design and implement software. Java is a classic object-
oriented language that leverages OOP principles to organize
and manage code effectively. Here’s an overview of the core
principles of OOP and how they are implemented in Java:
Object-Oriented Programming (OOP) in Java uses classes
and objects to structure and organize code. By employing
the principles of encapsulation, inheritance, polymorphism,
and abstraction, you can create robust, maintainable, and
reusable code. Understanding these principles and
practicing them through coding exercises will help you
become proficient in OOP.
Classes and Objects
Class Definition:
• A blueprint for creating objects.
91
Creating Objects:
• Instances of a class.
92
Core Principles of OOP
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Encapsulation in Java
Encapsulation is a fundamental concept in Object-Oriented
Programming (OOP) that is used to bundle data (attributes)
and methods (functions) that operate on the data into a
single unit or class. Encapsulation also involves restricting
direct access to some of the object's components, which
helps in protecting the integrity of the data.
Key Aspects of Encapsulation
1. Private Fields: Attributes of a class should be marked as
private to restrict direct access from outside the class.
2. Public Methods: Provide public methods to get (access)
and set (modify) the private attributes. These methods are
known as getters and setters.
3. Data Hiding: Prevent direct modification of the fields
from outside the class to ensure the object's state is
controlled and validated.
Implementing Encapsulation
Here’s a step-by-step guide to implementing encapsulation
in Java: 1. Define Private Fields: Use the private access
modifier to define fields within a class.
This restricts access to these fields from outside the class.
2. Provide Public Getter and Setter Methods: Define
public methods to provide controlled access to the private
fields. The getter method allows reading the value, and the
setter method allows modifying it.
93
public class Employee [
// Private fields
private String name;
private double salary;
// Constructor
public Enployee(String name, double salary) {
this.name = name;
this.salary = salary;
// Getter for name
public String :et:jame() {
return name;
// Setter for name
public void setName(String name) £
this.name = name;
// Getter for salary
public double getSalar () {
return salary;
// Setter for salary
public void setsalary(double salary) {
if (salary > ) £ // Validation to ensure salary is positive
this.salary = salary;
} else £
System.out.println( salary must be positive. );
}
// Method to display employee details
public void displayDetails() {
System.out.printin("Name: " + name);
System.out.println("Salary: $" ♦ salary);
Example of Encapsulation
Class Definition with Encapsulation:
94
public class lain {
public static void (string[] args) {
// Creating an Employee object
Employee emp = new E^loyee("iohn Doe", 50000};
// Accessing and modifying data using getter and setter methods
System.out.printlnf"Initial Details );
emp.displayDetails();
// updating salary with valid value
emp. setsalary {SE:?:);
system.out.printing updated salar );
emp.displayDetails();
// Attempting to set an invalid salary
emp.setsalary{-1000)i // outputs: salary must be positive.
System.out.printlnf --ter Invalid lalar L ate );
emp.displayDetails();
// Accessing name using getter method
System, out. printlnf'En 1: ee lame + emp.getNamef));
// changing name using setter method
emp.setName{"Jan£ Doe");
System.out.printlnf Updated Name: ' + emp.getNamef));
}
}
Using the Encapsulated Class:
95
Benefits of Encapsulation
1. Control: Encapsulation allows control over the data by
providing methods to access and modify it. This ensures
that the data is always in a valid state.
2. Flexibility: Internal implementation can be changed
without affecting other parts of the code that use the class.
3. Maintainability: Encapsulation helps in keeping code
organized and makes it easier to manage and maintain.
4. Increased Security: By hiding the internal state of the
object, encapsulation reduces the risk of unintended
interference and misuse.
Encapsulation in Java is implemented by using private fields
and public getter and setter methods. This approach
ensures that the internal state of an object is protected from
unauthorized access and modification. Encapsulation
enhances the security, maintainability, and flexibility of
code by providing controlled access to the object's data and
behavior.
96
Java Implementation
• Private Fields: Use private fields to protect data from
outside access.
• Public Methods: Use public getter and setter methods to
access and update the private fields.
Example:
97
public class Person £
// Private fields
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter for name
public String ;etn? e() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge() {
return age;
}
// Setter for age
public void setAge(int age) {
Llii^.dge = dge;
}
// Method to display details
public void displayDetails() {
System.out.println( Name: + name);
System.out.println( Age: + age);
}
}
98
Inheritance in Java
Inheritance is one of the core principles of Object-Oriented
Programming (OOP). It allows a new class to inherit the
properties and methods of an existing class. The new class
is known as the subclass or derived class, and the class it
inherits from is known as the superclass or base class.
Inheritance promotes code reuse and establishes a natural
hierarchy between classes.
Key Concepts of Inheritance
1. Superclass and Subclass
2. The extends Keyword
3. Constructor Inheritance
4. Method Overriding
5. Accessing Superclass Methods
6. The super Keyword
7. Type Casting
99
public class Aniaal {
// Fields
string name;
age;
// Constructor
public -.rl'i (String name, int age} {
this.name = name;
this.age = age;
}
// Method to display animal details
public void displs; () {
system.oiit.println( ante + name + + age);
}
// Method to make sound
public void makescundf) ■[
system.oiit.println( 1 makes a sou };
}
}
Example of Inheritance
Let's consider a basic example where a superclass Animal is
inherited by a subclass Dog.
Superclass: Animal
100
public class Dog extends Animal -[
U Additional field specific to Dog
String breed;
H Constructor
pitjlic (string nante, age, string breed) {
super(name, age); // Call the constructor of the superclass
this.breed = breed;
}
H overriding the makesound method
^override
public void makeSoun() ■[
System.out.printIn( Dog barks );
// Method to display dog details
public void displi () {
super.display(); // call the display method of the superclass
System.out.printlnf reed + breed);
H Main class
public class Hain {
piiilic static void (String[] args) {
Dog dog = new Dog("Buddy", 5, "Golden Retriever");
dog.display(); // Outputs: Name: Buddy, Age: 5, Breed: Golden Retriever
dog.aakeSound(); // Outputs: Dog barks
Subclass: Dog
Detailed Explanation
1. Superclass and Subclass
Superclass: The class whose properties and methods are
inherited.
Subclass: The class that inherits the properties and methods
from the superclass.
• Superclass (Animal in this case) is the class whose
properties and methods are inherited.
101
// superclass
public class Animal {
void eat() {
Sy stem. out. print Ln ( is a mal earts foot );
}
}
// subclass
public class Dog extends Animal {
void Lark() {
system.out.printing he dog barks );
}
}
// Main class
public class lair {
public static void (String[] args) {
= new . ();
myDog.eatf); // Method inherited from Animal
myDog.bark(); // Method of Dog class
1
}
• Subclass (Dog in this case) is the class that inherits
properties and methods from the superclass
Example:
102
public class ■efiicle {
H Superclass method
public void start{) {
System, out.println(''Vehicle is starting.");
}
}
public class Car extends Vehicle {
// Subclass method
public void drive{) {
system.out.printing car is c-: he );
}
}
// Main class
public class lair {
public static void main{String[] args) {
tar myca = nen ();
myCar. startOi 11 Inherited method
myCar.drive(); I! Method of Car class
}
}
public class Dog extends Animal {
11 class body
}
2. The extends Keyword
In Java, inheritance is specified using the extends keyword.
A subclass inherits all accessible properties and methods
from its superclass. The extends keyword is used to
establish an inheritance relationship between the superclass
and the subclass.
Example:
103
public class Animal {
Animal() {
System.out.printlnf"Animal constructor called.");
}
}
public class Dag extends Anima] {
D0g() -L
superf); // Calls the superclass constructor
System.out.printing Dog constr ctor Called );
}
}
H Main class
public class 'lair {
public static void (String[] args) {
Deg myDog = new ();
// Outputs:
// Animal constructor called.
// Dog constructor called.
1
}
3. Constructor Inheritance
Constructors are not inherited. However, a subclass can call
the constructor of its superclass using the super keyword.
Example:
104
public class Anil 1 {
void soundO {
System.out.printing nimal m=<es a sou ).;
}
}
public class Cat extends Animal {
^Override
void soundO <
System.ant.printing tat wows, );
}
}
// Hain class
public class lain {
public static void (String[] args) {
Cat -/Cc = nei ();
myCat.saund(); // Outputs: Cat meows.
}
}
^override
public void makesoundO {
system.out.printing rDog barks' );
}
4.Method Overriding
A subclass can provide a specific implementation for a
method that is already defined in its superclass. This is
known as method overriding.
Method overriding allows a subclass to provide a specific
implementation of a method already defined in its
superclass. The overridden method must have the same
name, return type, and parameters.
Example:
4. The super Keyword
105
public D (String name, age, Stripg breed) {
super(na»e, age); // Call the constructor of the superclass
this.breed = breed;
public void displa.() {
super.display(); // Call the display method of the superclass
System.out.printinf Breed + breed);
}
The super keyword is used to refer to the immediate
superclass. It can be used to:
• Call the constructor of the superclass.
• Access superclass methods and fields.
Calling the superclass constructor:
Calling a superclass method:
. Types of Inheritance
• Single Inheritance: A subclass inherits from one
superclass.
• Multilevel Inheritance: A subclass inherits from another
subclass.
• Hierarchical Inheritance: Multiple subclasses inherit
from one superclass.
Inheritance in Java enables the creation of a new class
based on an existing class. It facilitates code reusability,
logical class hierarchy, and method overriding. Using the
extends keyword and super keyword, Java provides a clear
and straightforward way to implement inheritance.
This allows subclasses to inherit and enhance the
functionality of their superclasses, leading to a more
modular and maintainable codebase.
Mechanism where one class inherits the fields and methods
of another class.
106
public class Animal -[
void eat() {
system.out.println("This animal eats food.");
}
}
public class Dog extends Animal {
void bark() {
system.out.printing The dog barks. );
}
}
public class ain {
public static void main{String[] args) {
Dog myOog = nes ();
myDog.eat(); // Inherited method
myDog.bark{); // own method
}
}
Example:
107
public class Person -[
String name;
int age;
public Perse (string name, int age} ■[
this.name = name;
this.age = age;
}
public void displs. (} {
System.out.printing ante + name + , Age: + age);
}
}
Practice Example
Practice 1:
Create a superclass Person with fields name and age and
methods to display the details.
Then, create a subclass Student that adds a field studentID
and overrides the display method to include the student ID.
Person.java:
108
public class student extends Person {
String studentID;
public 51 (String name, age, String studentID) {
super(name, age);
this.studentID = studentID;
}
^override
public void displr; () (
super.display();
System.out.printlnf Student IE + studentID);
}
}
H Main class
public class lai' {
public static void r (string[] args) {
Student student = new 5tudent("Alice", "512345"};
student.display();
// Outputs:
// Name: Alice, Age: 20
// student ID: si2345
}
}
Student.java:
This example demonstrates how inheritance can be used to
build a class hierarchy, allowing subclasses to extend and
customize the behavior of their superclasses.
109
public class Animal {
void sound() {
System.ant.printing makes a sc.. n );
}
}
public class cat extends Animal {
^Override
void sound() {
super. soundQj // Calls the superclass method
system.out.printing cat meows );
}
}
H Main class
public class lair {
public static void main(String!] args) {
Cat nyCa = nei ();
myCat.sound()j
// Outputs:
// Animal makes a sound.
// Cat meows.
}
}
5. Accessing Superclass Methods
A subclass can access methods of its superclass using the
super keyword. This is useful when you need to call the
superclass method that has been overridden in the
subclass.
Example:
110
public class Animal -[
= ;
void displayColor() {
System.out.printLn("Animal color: + color);
}
}
public class Dog extends Animal {
String color = "Black";
void display Color () {
System.out.printlnf"Dog color: " + color);
Syste«.out.println("Superclass color: " * super.color); // Access superclass field
}
}
H Main class
public class Iain {
public static void (string[] args) {
= ne ();
myDog.displaycolor();
// outputs:
// Dog color: Black
// Superclass color: White
}
}
6. The super Keyword
The super keyword is used to refer to the immediate parent
class object. It can be used to:
• Access superclass methods.
• Call superclass constructors.
• Access superclass fields.
111
public class Animal {
void eat() {
System.out.printLnf limal is eating. J;
}
}
public class Dog extends Animal ■{
void bark() {
system.out.printing is barking );
}
}
U Main class
public class lain {
public static void mair(String[] args) {
Animal animal = new Dog()j // Upcasting
animal.eat{); // Works fine
// Downcasting
if (animal instanceo- Dog) {
= (Dog) animal^
dog.bark(); H Works fine
}
}
}
7. Type Casting
Java supports type casting between related classes. This
involves converting a subclass reference to a superclass
reference and vice versa.
Example:
112
• Inheritance allows a class to inherit properties and
methods from another class, promoting code reuse.
• Use the extends keyword to create a subclass.
• Subclasses can inherit methods but not constructors from
the superclass.
• Method Overriding allows a subclass to provide a
specific implementation of a method already defined in the
superclass.
• Use the super keyword to access superclass methods,
fields, and constructors.
• Type Casting enables converting between superclass and
subclass references.
By understanding and applying these concepts, you can
create a well-structured and reusable codebase using
inheritance in Java.
113
public class Animal {
void sound [) {
system.out.printLnf flakes a sol );
}
J
public class Cat extends Animal ■{
^Override
void sound{) {
super.sound()j // Calls the superclass method
System.out.printLn( Cat ■ );
}
}
!l Main class
public class lair {
public static .'cic (String[] args) {
Cat tayCat = new ()j
mycat.soundOs
// outputs:
// Animal makes a sound.
// Cat meows.
}
}
114
public class Animal ■[
void sound() -[
System.out.printing make$ a sc.
}
}
public class Cat extends Anina1 {
^Override
void sound() -[
super.sound()s H Calls the superclass method
System.out.printing Cat aeoNS. );
}
}
U Hain class
public class lair {
2.islic static void (string[] args) {
Cat '/Cat = nei ();
myCat.sound()i
// Outputs:
// Animal makes a sound.
// Cat meows.
}
}
115
public class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
H Method to add three integers
public int add(int a, in- b_, i'lt c) {
return a + b + c;
}
}
H Main class
public class lain {
public static void (string[] args) {
Calculator calc = new calculator^;
System.out.println(calc.add( , IB]); // Outputs: 15
System.out.printIn(calc.add( , } )); // Outputs: 30
}
}
Polymorphism
Polymorphism allows methods to do different things based
on the object it is acting upon.
This can be achieved through method overloading (compile
time polymorphism) and method overriding (runtime
polymorphism).
Java Implementation:
• Method Overloading: Multiple methods with the same
name but different parameters within the same class.
• Method Overriding: A subclass provides a specific
implementation for a method already defined in its
superclass.
Example:
Method Overloading:
116
// superclass
p .rLie class . {
■ ".3 r ■ ■ ■:. O {
System.out.println( ■
>
1
H Subclass
public class extends {
^override
void sliest {) {
System.out.printlnf );
}
}
H Main class
. ilic class {
public static void main (string! ] dl"gs) -[
= ■■■ Oj
myCat.makeSoijndQ; Zutpucr: Ce~
}
}
Method Overriding:
117
Abstraction in Java
Abstraction is a key concept in Object-Oriented
Programming (OOP) that allows you to hide the complex
implementation details of a system and expose only the
essential features.
The goal of abstraction is to reduce complexity and allow
the programmer to focus on interactions at a higher level
without needing to understand the intricate details of each
component.
In Java, abstraction is achieved through:
1. Abstract Classes
2. Interfaces
1. Abstract Classes
Definition: An abstract class is a class that cannot be
instantiated on its own and may contain abstract methods
that must be implemented by subclasses. Abstract methods
are methods without a body, meant to be overridden in
derived classes.
Features:
• Can have abstract methods (methods without a body).
• Can have non-abstract methods (methods with a body).
• Can have fields and constructors.
• Can be extended by other classes.
118
abstract class Shape {
w[);
*
abstract void dr // Abstract method
void printShapeTypeO {
System.out.printLn( rhis is a shape };
1
}
class Circle extends Shape {
^override
void drav() {
System.out.printing 'awing ■ • );
1
}
H Main class
public class lain {
public static void (string[] args) {
= new ();
myCircle.draw(); // Outputs: Drawing a circle
myCircle.printShapeTypef); If Outputs: This is a shape
1
}
Example:
Abstract Class
119
if Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void makeSound();
// Hon-abstract method
void sleep() {
System.out.printing Phis a ncl is sleeping );
}
}
ff concrete subclass
class Dog extends Ari- al (
// Providing implementation for the abstract method
^Override
void ■ rkeSound{) {
system.out.printing rhe dog barks };
}
}
H Main class
public class lain {
public static void (String[] args) {
= iew ()j
myDog.makesound(); // Outputs: The dog barks.
myDog.sleep()j ff Outputs: This animal is sleeping.
120
interface Cratable £
void dra. (}; // Abstract wethod
}
class Rectangle implements Drawable {
^Override
public void draw() {
system.out.printIn( a Ing a rectangle' )j
}
}
H Main class
public class 'lai- £
public static void (String[] args) £
Drawable myRectangle = new RectangleQi
myRectangle.draw(); // Outputs: Drawing a rectangle
}
}
Interfaces
An interface in Java is a reference type, similar to a class,
that can contain only constants, method signatures, default
methods, static methods, and nested types. Interfaces
cannot contain instance fields or constructors. A class
implements an interface, thereby inheriting the abstract
methods of the interface.
Features
• Cannot contain instance fields or constructors.
• Can contain abstract methods and default/static methods.
• A class can implement multiple interfaces.
Interface
121
// Interface
interface -ri~ial -[
// Abstract method
void makeSoun {).;
H Default method
default void eat() {
System.out.printlnf is animal eats foot ];
}
J
H Concrete class implementing the interface
class cat implements Animal -[
// Providing implementation for the abstract method
^Override
public void makessundf) {
system.out.printing he ce );
}
}
H Main class
public class Main {
public static void (String[] args) {
= i£- ()>
myCat.makeSound(}; // Outputs: The cat meows.
myCat.eatf); // Outputs: This animal eats food.
122
Benefits of Abstraction
1. Simplifies Code: Abstraction helps in reducing
complexity by hiding implementation details and showing
only the necessary features.
2. Improves Maintainability: Code becomes easier to
manage and maintain since changes in the implementation
details do not affect the external interface.
3. Promotes Code Reusability: By defining common
functionality in abstract classes or interfaces, you can reuse
code across multiple classes.
4. Enhances Flexibility: Allows you to change the
implementation without affecting the code that uses the
abstracted components.
Choosing Between Abstract Classes and Interfaces
• Use an Abstract Class When:
o You have a base class that should not be instantiated.
o You want to share common code among related classes.
o You need to provide some method implementations but
also require some methods to be abstract.
• Use an Interface When:
o You want to define a contract that can be implemented by
any class.
o You need to define methods that must be implemented by
multiple classes from different hierarchies.
o You want to support multiple inheritance of type (a class
can implement multiple interfaces).
Abstraction in Java helps manage complexity by allowing
you to focus on the interactions at a high level while hiding
the implementation details. You achieve abstraction using
abstract classes and interfaces. Abstract classes provide
a way to share code among related classes and define
abstract methods that must be implemented by subclasses.
Interfaces define methods that must be implemented by
any class that chooses to implement the interface,
promoting a flexible and reusable design.
123
Chapters 3
Methods and Constructors in Java
In Java, methods and constructors are fundamental
components of classes. They define the behaviour of objects
and how they are initialized.
Methods
Methods are blocks of code that perform a specific task.
They are used to define the behaviour of objects created
from a class. Methods can have parameters, return types,
and can be called to perform actions on objects.
Key Concepts
1. Method Declaration
2. Method Overloading
3. Method Overriding
4. Static Methods
5. Instance Methods
6. Method Parameters and Return Types
1. Method Declaration
A method is declared within a class and consists of the
following components:
• Access Modifier: Defines the visibility of the method (e.g.,
public, private).
• Return Type: Specifies the type of value the method will
return (e.g., int, void).
• Method Name: The name of the method.
• Parameters: Optional values passed to the method.
• Method Body: The block of code that executes when the
method is called.
124
public class Calculator {
H Method to add two numbers
public int adi (ent a± ir b) -[
return a + b;
H Method to subtract two numbers
public int subtracts int aj int b) {
return a - b;
// Method with no retuirn value
public void display•essege() {
system.out.printlnf his is a calculator );
H Main class
public class Main {
public static void (string[] args) {
calculator ta = new calculate ();
// calling methods
= calc.addf , );
= caic.subtractt , );
system.out.printIn(*su 1 + sum); // outputs: sum: s
System.out.print ln("Difference: " +■ difference); // Outputs: Difference: G
calc.displayMessageOi H outputs: This is a calculator.
Example:
Methods:
125
public class Calculator ■{
int add(int a, int b) ■{
return a + b;
public class Displa; {
H overloaded method with one parameter
public void sb (int number} {
System.out.printing umber: " + number);
}
H Overloaded method with two parameters
public void . (string text, number) {
System.out.printlnf Text + text + t Number + number);
)
}
H Main class
public class lair {
public static void (string[] args) {
Displa; displa; = new Displa; ();
display.sbow( ); // Outputs: number: 10
display.shorn("Value", 20); // Outputs: Text: value, Nutter: 20
}
}
• Blocks of code that perform specific tasks.
2. Method Overloading
Method Overloading occurs when multiple methods have
the same name but different parameters (type, number, or
both). It allows methods to perform similar functions with
different input.
Example:
126
// Superclass
public class -.ninal {
void BakeSDimdO ■[
systein.out.println( makes a sol );
}
}
H subclass
public class Dog extends Animal ■{
^Override
void ■ -keSourid{) {
Systern.aut.printlnf );
}
}
H Hain class
public class lair {
public static void (String[] args) {
Animal myDog = new Dog();
myDog.makeSoLind(); // Outputs: Dog barks.
}
}
Method Overriding
Method Overriding occurs when a subclass provides a
specific implementation for a method that is already defined
in its superclass. The overridden method must have the
same name, return type, and parameters as the method in
the superclass.
Example:
127
public class Mathirtils {
// Static method
public static int multiply ( nt a, int b) {
return a * b;
}
}
H Main class
public class lain ■£
public static void (string[] args) {
= MathlTtils .aultiply J , );
System.out.println("Product + result); // Outputs: Product: 15
}
}
4. Static Methods
Static Methods belong to the class rather than to any
specific instance. They can be called without creating an
instance of the class and can only access static fields and
methods.
Example:
128
public class tectangle {
width;
in height;
// Instance method to calculate area
public int calculateArea() {
return width * height;
}
}
H Main class
public class lair {
public static old (string[] args) {
Rectangle rect = new RectangleO;
rect.width = ie;
rect.height = 5;
= rect.calculateArea{);
system.out.printInf rea + area); // outputs: Area: 50
}
}
5. Instance Methods
Instance Methods operate on instances of a class and can
access instance fields and methods. They require an object
of the class to be called.
Example:
129
6. Method Parameters and Return Types
Methods can take parameters and return values to perform
operations and provide results.
• Parameters: Passed into the method to provide input
data.
• Return Type: Specifies what type of value the method
will return. If a method doesn’t return a value, its return
type is void.
Example:
130
public class Person {
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Main class
public class Main (
public static void main(String[] args) {
Person person = new Person("Alice", 30);
System.out.println("Maine: " + person.name); // Outputs: Name: Alice
System.out.println("Age: " + person.age); // Outputs: Age: 30
}
1
Chapter 4
Constructors
Constructors are special methods used to initialize objects
when they are created. They have the same name as the
class and no return type.
Key Concepts
1. Constructor Declaration
2. Default Constructor
3. Parameterized Constructor
4. Constructor Overloading
5. Constructor Chaining
1. Constructor Declaration
A constructor is declared with the same name as the class
and has no return type. It initializes the object's state when
it is created.
Example:
131
public class car {
string model;
irt year;
if Default constructor provided by Java
}
ff Main class
public class lain {
public static void (string[] args) {
= ne(};
System.out.printing od + car.ntodel); ff Outputs: Model: null
System.out.printlnf Yee- + car.year); ff Outputs: Tear: 0
}
}
2. Default Constructor
If no constructor is defined, Java provides a default
constructor that initializes instance variables to their default
values (e.g., null for objects, 0 for numeric types).
Example:
132
public class look {
String title;
dcuble price;
!l Parameterized constructor
public (string title, price) {
this.title = title;
this.price = price;
}
}
U Main class
public class Mai' {
public static void (string[] args) {
= new ( Java Programming", 29. );
System.out.println( ritle + book.title); // Outputs: Title: Java Programming
Systeiu.out.printlnf r ce + book.price); // Outputs: Price: $29.99
}
}
3. Parameterized Constructor
A parameterized constructor allows you to initialize objects
with specific values.
Example:
133
4. Constructor Overloading
Constructor Overloading is a technique in Java that
allows a class to have more than one constructor with
different parameter lists. Each constructor performs a
different task but constructs objects of the same class.
Overloaded constructors provide flexibility in object creation
by allowing different ways to initialize an object.
Key Concepts
1. Same Class, Different Parameters
2. No Return Type
3. Different Initialization Option
Example of Constructor Overloading
Let's consider a Rectangle class that demonstrates
constructor overloading: 134
public class Rectangle {
int width;
int height;
// Constructor with no parameters
public Rectangle() {
this.width = 05
this.height = ©.;
// Constructor with one parameter
public Rectangle(int side) {
this.width = side;
this.height = side;
>
// Constructor with two parameters
public Rectangle(in~ width,, int height) {
this.width = width;
this.height = height;
// Method to calculate the area
public int calculateArea() {
return width * height;
// Method to display the dimensions
public void displayDimensionsO {
Sy stem. out. print In ("Width: + width +■ “j. Height: + height);
// Main class
public class Main {
public static void mairn(string[ ] args) {
// Using the constructor with no parameters
Rectangle recti = new RectangleO;
rectl.displayDimensionsC); // Outputs: width: Height: 0
System.out.println("Area: ■+■ recti.calculateArea()); // Outputs: Area: 0
H using the constructor with one parameter
Rectangle rect2 = new Rectangle(S);
rectZ.displayOimensionsC); // Outputs: width: Height: 5
System.out.println("Area: ■+■ rect2.calculateArea()); // Outputs: Area: 25
// Using the constructor with two parameters
Rectangle rect3 = new Rectangle(4, 7)5
rect3.displayDi«nensions(); // Outputs: width: Height: 7
System.out.println("Area: ■+■ rect3.calculateAreaf)); // Outputs: Area: 28
135
public Rectanglef) {
this.width = ;
this.height = ;
}
Detailed Explanation
1. Constructor with No Parameters:
o This constructor initializes both width and height to 0. It’s
useful when you want to create a Rectangle object without
specifying any dimensions.
Constructor with One Parameter:
• This constructor initializes both width and height to the
same value, which is useful for creating square Rectangle
objects.
136
public Rectangle{int width, int height) {
this.width = width;
this.height = height;
}
Constructor with Two Parameters:
• This constructor initializes the width and height to the
specified values, allowing you to create rectangles of any
dimension.
137
Benefits of Constructor Overloading
• Flexibility in Object Creation: Users can create objects
with different initial values based on the parameters passed.
• Code Readability and Maintenance: Overloading
constructors with meaningful parameters can make the
code more readable and maintainable.
• Default and Specific Initialization: Allows providing
both default and specific ways to initialize an object.
Constructor overloading enhances the flexibility of object
creation in Java. By providing multiple constructors with
different parameters, you can initialize objects in various
ways while maintaining a clean and organized code
structure. This technique is widely used in Java to provide
multiple options for initializing objects, making classes more
versatile and easier to use.
138
public class Rectangle £
ini width;
int height;
// Constructor with no parameters
public Rectan§le() {
this.width = e;
this, height = ?;
}
ll Constructor with parameters
puslic Rec £ width, height) {
this.width = width;
this.height = height;
}
}
H Hain class
public class Iain £
public static void (string[] args) {
Rectangle rect. = new Rec ();
Rectangle rect. = hew Rec ( , 5);
Systeiu.out.printlnf Recti - Width + recti.width + Heigh + recti.height);
System.out.printLn("Rect2 - Width: " + recta.width + ", Height: " + rect2.height);
11 Outputs:
// Recti - width: e, Height: &
// Recta - width: io, Height: 5
}
}
Constructor Overloading allows a class to have more
than one constructor with different parameter lists.
Example:
139
Constructor Chaining in Java
Constructor Chaining in Java is a process of calling one
constructor from another constructor within the same class
or from a constructor in a subclass. This allows for a more
efficient way to initialize an object with multiple
constructors, reducing code duplication and enhancing
maintainability.
Types of Constructor Chaining
1. Within the Same Class: Using this()
2. From a Subclass: Using super()
1. Constructor Chaining Within the Same Class
When you have multiple constructors in the same class, you
can call one constructor from another using the this()
keyword. This approach helps in reusing constructor code
and keeping initialization logic in one place.
140
public class Circle {
radius;
string color;
H Constructor with no parameters
public Circled {
this(l.f); H calls the constructor with one parameter
}
H Constructor with one parameter
public Circle(rouble radius) ■[
this(radius, "red"); !I calls the constructor with two parameters
}
// Constructor with two parameters
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
}
H Main class
public class ain {
public static void (String[] args) {
= ne ();
= ne ( );
= re ( j );
System.out.printing Circlel Radius +■ circlel.radius + . Cola + circle!.a
system.out.printlnf zirclea Radius +■ circlel.radius + , eclo + circles.o
System.out.printing Circles - Radius +■ circles.radius + . Colo + circles.o
// Outputs:
// Circlel - Radius: l.fl, color: red
// Circlel - Radius: 1.5, color: red
// Circles - Radius: 3.8, color: blue
}
}
Example:
In this example:
• The Circle() constructor with no parameters calls the
Circle(double radius) constructor.
141
• The Circle(double radius) constructor calls the
Circle(double radius, String color) constructor.
• The Circle(double radius, String color) constructor
initializes the instance variables radius and color.
142
H Superclass
public class Animal {
String name;
H Superclass constructor
public LTal(string name) {
this.name = name;
}
}
H Subclass
public class Dog extends -.nimal {
string breed;
!/ Subclass constructor
public [>og(string name, string breed) {
super(name); // calls the constructor of the superclass
this.breed = breed;
}
}
H Hain class
public class lain ■{
public static: void (string[] args) {
Dog dog = new Dog("Buddy", "Golden Retriever'1);
system.out.printing ante + dog.name); // outputs: Name: Euddly
System.out.printlnf"Breed: " + dog.breed); H Outputs: Breed: Golden Retriever
}
}
2. Constructor Chaining from a Subclass
When you have a subclass that extends a superclass, you
can use the super() keyword to call a constructor from the
superclass. This ensures that the superclass is properly
initialized before the subclass adds its own initialization.
Example:
In this example:
• The Dog class extends the Animal class.
• The Dog constructor calls the Animal constructor using
super(name), initializing the name field in the Animal class
before initializing the breed field in the Dog class.
143
public class car {
string color;
String model;
i’t year;
// Constructor
public i (string color, string model, year) ■[
this.color = color;
this.model = model;
this.year = year;
}
}
Constructor chaining is a powerful technique in Java that
allows constructors to reuse code and ensure proper
initialization by calling other constructors within the same
class or from a superclass. This helps to reduce redundancy
and maintain a clean and organized codebase.
Using this() for chaining within the same class and super()
for chaining from a superclass ensures that objects are
constructed correctly and efficiently.
• Special methods used to initialize objects.
Example:
144
public class at hope ration!; {
// Method to add two integers
public int addfint aj int b) {
return a + b;
}
// Method to add three integers
public int addfint a, int b_, int c) -[
return a + b + c;
}
if Method to add two double values
public : ble (double a^, cubic b) {
return a + b;
}
public static void i (String[] args) {
= " (>;
System.out.printlnf sum of 2 integers + math.add( , )); if outputs: sum of 2 i
System.out.println("Sum of 3 integers: " + math.add(2j 3, 4}); // Outputs: Sum of
system.out.println("sum of 2 doubles: " * aath.add(2.5, 3.5)); // outputs: sum of
}
}
Polymorphism in Java
Polymorphism is one of the four fundamental concepts of
Object-Oriented Programming (OOP). It allows objects to be
treated as instances of their parent class rather than their
actual class. The two main types of polymorphism in Java
are:
1. Compile-Time Polymorphism (Method Overloading)
2. Run-Time Polymorphism (Method Overriding)
Key Concepts
1. Method Overloading
2. Method Overriding
3. The instanceof Keyword
4. Dynamic Method Dispatch
1. Method Overloading (Compile-Time Polymorphism)
Method overloading allows a class to have more than one
method with the same name, but different parameters. The
methods are resolved at compile time.
Example:
145
public class Animal {
void soLndQ {
System.out.printLn("This animal makes a sound.");
}
}
public class Dog extends Animal {
^Override
void soundQ {
System.out.printLn( he dog barks };
}
}
public class lain {
public static void (String[] args) {
Animal myAnimal = new Pog();
myAnual.soundO; // outputs: The dog barks.
}
}
Polymorphism:
• Ability to take many forms, typically through method
overriding and method overloading.
Method Overriding:
• Redefining a method in a subclass.
Example:
146
class Arimal (
// Method in superclass
public void nakesoundO <
System.out.printing niaal m kes a sc, ■; };
}
}
class Dog extends Animal {
H Overridden Berthed in subclass
^Override
public void ntakesoundO <
System.out.printing log ba );
}
}
class Cat extends Animal {
H Overridden Bethod in subclass
^Override
public void nakesoundf) {
system.out.printing cat bec );
}
}
public class lair {
public static void Bain{String[] args) {
= new ();
= new ()±
myDog.BakeSoLindf}; // Outputs: Dog barks
myCat.BakeSound(); // Outputs: Cart aeows
}
}
2. Method Overriding (Run-Time Polymorphism)
Method overriding allows a subclass to provide a specific
implementation of a method that is already defined in its
superclass. The method to be executed is determined at
runtime.
Example:
147
public class -in {
pjslic static void (String[] args) {
MathUtils math = new MathUtilsO;
System.out.printLn(math.add( , )); // Outputs: 15
system.out.println(math.add( , J.5)}; // outputs: 16.0
}
}
public class 5in {
public static void(String[] args) ■(
= new ()J
if (myDog instancecf Dog) {
system.out.println( Dog is an instance );
}
if {myDog instances- Animal) {
system.out.printIn(''■/Dog is an instance of Animal");
}
}
}
3. The instanceof Keyword
The instanceof keyword is used to test whether an object is
an instance of a specific class or a subclass thereof.
Example:
148
class Aninal {
public void nakeSoundf) {
System.out.printing makes a sol );
}
}
class Dog extends Animal {
^Override
public void rtakcScundO {
System.out.printing Dog );
}
}
class Cat extends Animal {
^Override
public void makescund0 ■[
system.out.printing cat );
}
}
public class lain {
public static void (String[] args) {
Animal myAnimal;
myAnimal = ie i»gO;
myAnimal .ma keSou nd O; // outputs: Dag barks
myAnimal = ne 0;
myAnimal.makesound0; // outputs: cat meows
}
}
4. Dynamic Method Dispatch
Dynamic method dispatch is the mechanism by which a call
to an overridden method is resolved at runtime rather than
compile time. It allows Java to support run-time
polymorphism.
Example:
149
Benefits of Polymorphism
• Code Reusability: Methods can be used in multiple
forms.
• Maintainability: Simplifies code maintenance and
readability.
• Extensibility: New functionalities can be added with
minimal changes to the existing code.
Practice Example
Practice 1:
Create a superclass Shape with a method draw(). Then,
create subclasses Circle and Rectangle that override the
draw() method. Demonstrate polymorphism by calling the
draw() method on objects of these classes.
Shape.java:
Circle.java:
150
public class Main {
public static void (5tring[] args) {
Shape mySiiape;
mystiape = new {);
niystiape.drawO j H outputs: Drawing a circle
mystiape = new ();
mySliape.drawf) j // Outputs: Drawing a rectangle
}
J
Rectangle.java:
Main.java:
This example illustrates how polymorphism allows a single
method draw() to have different implementations depending
on the actual object type (Circle or Rectangle). This
flexibility is one of the core strengths of OOP and enhances
the modularity and scalability of the code.
151
Chapter 5
Encapsulation and Abstraction
Encapsulation in Java
Encapsulation is one of the fundamental principles of
object-oriented programming (OOP).
It refers to the bundling of data (fields) and methods
(functions) that operate on the data into a single unit or
class. Encapsulation also involves restricting direct access to
some of the object's components, which is a means of
preventing unintended interference and misuse of the data.
This is typically achieved using access modifiers.
Key Concepts
1. Data Hiding
2. Access Modifiers
3. Getter and Setter Methods
Example of Encapsulation
Let's consider an example of a Person class that
demonstrates encapsulation.
152
public class Person ■[
// Private fields (data hiding)
private String name;
private ind age;
// constructor
public Perse (String name, int age} {
this.name = name;
this.age = age;
}
// Getter method for name
public String () {
return name;
// Setter method for name
public void setNamefString name) {
this.name = name;
// Getter method for age
public int getAgef) ■{
return age;
I/ Setter method for age
public void setAge(int age) {
if {age >•){// Validation
this.age = age;
Person.java
153
public class Main {
public static void (string[] args) {
H Creating an object of Person class
= fie ( ce", );
// Accessing private fields using getter methods
System.out.printlnf ante + person.getNamef)); // Outputs: Name: Alice
System.out.println("Age: " + person.getAge{))s // Outputs: Age: 3B
// Modifying private fields using setter methods
person.setNamef Eob );
person.setAge( );
// Accessing modified fields
System.out.println("updated Naae: " + person.getNamef)}; // outputs: updated Na«e:
System.out.println("Updated Age: " + person.getAge{)); Outputs: Updated Age: 35
pri ate string name;
private int agjei
Main.java
Detailed Explanation
1. Data Hiding
Data hiding is achieved by declaring the class variables as
private. This restricts direct access to the fields from outside
the class.
154
// Getter method for name
public string get ameO {
returr name;
// Setter method for name
public void setName(String name) {
this.name = name;
}
H Getter method for age
public int get Age () {
returr age;
}
// Setter method for age with validation
public void setAge(int age) {
if (age > e) {
this.age = age;
}
}
2. Access Modifiers
Access modifiers in Java control the visibility of class
members. The primary access modifiers are:
• private: The member is accessible only within the same
class.
• default (no modifier): The member is accessible only
within the same package.
• protected: The member is accessible within the same
package and subclasses.
• public: The member is accessible from any other class.
3. Getter and Setter Methods
Getter and setter methods provide a controlled way to
access and modify the private fields.
These methods allow for validation, if necessary, before
setting a value.
155
Benefits of Encapsulation
• Improved Control: Provides control over the data by
restricting direct access and allowing controlled
modifications.
• Increased Flexibility: Allows changes in the
implementation without affecting other parts of the code.
• Enhanced Maintainability: Makes the code easier to
maintain and understand.
• Data Integrity: Helps in protecting the data from
accidental or unauthorized modification.
Practice Example
Practice 1:
Create a class BankAccount with private fields
accountNumber, balance, and accountHolderName.
Implement getter and setter methods for these fields, and
include a method to deposit and withdraw money with
validation.
BankAccount.java:
156
public class BankAccount {
private String accountNumber;
private double balance;
private String accountHolderName;
// Constructor
public BankAccoun-(string accountNumber, double balance, String accountHolderName) {
this.accountNumber = accountNumber;
this.balance = balance;
this.accountHolderName = accountHolderName;
// Getter for accountNumber
public String getAccountNumber() {
return accountNumber;
// Getter tor balance
public double getBalance() {
return balance;
// Getter for accountHolderName
public String getAccountHoIderName() {
return accountHolderName;
// Setter for accountHolderName
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
// Method to deposit money
public void deposit(double amount) ■(
if (amount > 9) {
balance ■+= amount;
// Method to withdraw money with validation
public void withdraw(double amount) {
if (amount > e && amount <= balance) {
balance -= amount;
Solution
157
public class aim {
public static void (String[] args) £
I) Creating an object of BankAccount class
BankAccount account = new Ba nkAccountf'12345 6788", ieee.e, "Alice"};
// Accessing private fields using getter methods
Sy stem. out. printing count Number: + account.getAccountNumberf));
System.out.println{ Eclaice : + account.getBalancef));
System.out.printing zcount Holder laue + account.getAccountHolderMame{});
// Depositing money
account .deposit (S3'. );
System.out.printlnf Jpdated Balance after deposit: + account.getEalance{));
// Withdrawing money
account.withdraw(3 };
System.out.printing fated Balance after withdr 1: + account.getBalancef));
// Trying to withdraw more than the balance
account, withdr aw{i5£.: };
Systeu .out. print Ln{"Updated Balance after failed withdrawal: " + account.getBalanc
}
}
Main.java:
This example demonstrates how encapsulation allows you
to create classes with private fields that can only be
accessed and modified through public methods. This
ensures that the internal state of the object is protected and
can only be changed in a controlled manner.
158
public class Person {
private String name;
public String getNameQ {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class lain {
public static void main(String[] args) {
Person person = new Perso-();
person.setNamef );
Encapsulation:
• Bundling data (fields) and methods into a single unit
(class) and restricting direct access to some of the object's
components.
Example:
159
abstract class Animal {
abstract void makesound
}
class Dog extends Animal ■{
void ciakeSoundO {
System.out.printlnf he dog barks );
}
}
public class lain {
public static void (String[] args) {
= new [ ();
my Dog. Bakesoimd (); // outputs: The dog barks.
}
}
Abstraction:
• Hiding complex implementation details and showing only
the necessary features.
Example:
160
int[] runbers = new int[5]i // Declaration with size
int[] BDreNuBbers = 2, 3, 4t 5); H Declaration with initialization
public class Main {
public static void mair(string[] args) {
int[] numbers = (1, 2, 3, 4, 5};
for (int i = ; i < numbers.length; i++) {
System.out.println("Element at index " + i + : " + numbers[i]);
}
}
Chapter 6: Basic Data Structures
Arrays:
• Arrays are a collection of elements of the same type,
stored in contiguous memory locations.
• Arrays have a fixed size once they are created.
Declaration and Initialization:
Accessing Elements:
Example:
161
String greeting = "Hello, World!";
string name = new string("John Doe");
public class lain {
public static void (String[] args) {
String greet.' = "Hello, .-Jorld ;
Sy stem. out. printing Lengt + greet ing.lengtfiQ);
system.out.printing char cter at index 1: + greeting.cliarAt{ ));
system.out.printing substring: + greeting.substring( , )};
System, out. printing ipercase: + greeting. tolipperCase());
}
}
Strings:
• Strings are objects in Java that represent sequences of
characters.
• Strings are immutable, meaning their value cannot be
changed once created.
Declaration and Initialization:
Common String Methods:
• length(): Returns the length of the string.
• charAt(int index): Returns the character at the specified
index.
• substring(int beginIndex, int endIndex): Returns a
substring.
• equals(Object another): Compares two strings for equality.
• toUpperCase(): Converts all characters to uppercase.
Example:
162
import java.util.ArrayList;
public class Hair {
prtlic static void (String[] args) {
ArrayListcString> list = te <>();
list.add( ole");
list.add( );
list.add( Orange");
for (String fruit : list) -[
System.out.println(fruit);
}
}
J
ArrayList and LinkedList
ArrayList:
• A resizable array implementation of the List interface.
• Allows duplicate elements and maintains insertion order.
Example:
163
import java.util.LinkedList;
public class lain {
public static void (String[] args) {
Linked List <:String:> list = new LinkedListof);
list.add( pie );
list.add( );
list.add( Orange"};
for {string fruit : list) ■[
system.out.println(fruit);
}
}
LinkedList:
• A doubly linked list implementation of the List and Deque
interfaces.
• Efficient for insertions and deletions at both ends.
Example:
164
try {
ll Code that may throw an exception
} catch (ExceptionType e) {
!l Code to handle the exception
} finally {
I! Code that will always execute, regardless of whether an exception was thrown
}
Chapter 7: Exception Handling
Introduction to Exceptions
Exceptions:
• An exception is an event that disrupts the normal flow of a
program.
• Java provides a robust mechanism to handle runtime
errors through exception handling.
Types of Exceptions:
• Checked Exceptions: Subclasses of Exception (except
RuntimeException). Must be either caught or declared in the
method signature.
• Unchecked Exceptions: Subclasses of
RuntimeException. Not required to be declared or caught.
• Errors: Subclasses of Error. Indicate serious problems that
applications should not try to catch.
Try, Catch, and Finally
Syntax:
165
public class ain (
public static void (String[] args) {
try {
= / j
} catch (ArithmeticException e) {
system.out.println( ’ error occur + e.getMessage());
} finally {
System.oLit.prirrtln('rThis block is always execute:.');
}
}
Example:
Custom Exceptions
Creating Custom Exceptions:
• Extend the Exception class (for checked exceptions) or
RuntimeException class (for unchecked exceptions).
Example:
166
class CustoBException extends Exception {
public Cu [String message) {
super(message);
}
}
public class lain {
public static old (string[] args) {
try {
throw new CustomException("This is a custom exception"};
} catch (customException e) {
System.out.p rintln(e.getMe s s age{));
}
}
}
167
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReadExample {
public static void rain(String[] args) {
String filePath - "example.txt";
try (Buf-FeredReader reader = new BufferedReader(new FileReader(-filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.printIn(line);
}
} catch (lOException e) {
e.printStackTrace();
}
Chapter 8: File I/O and Serialization
File I/O (Input/Output) is a fundamental part of Java
programming, allowing you to read from and write to files.
Serialization is a mechanism of converting the state of an
object into a byte stream, which can then be saved to a file
or sent over a network. Deserialization is the reverse
process where the byte stream is converted back into an
object.
1. Reading and Writing Files
Reading Files
To read files in Java, you can use classes such as FileReader,
BufferedReader, or Scanner.
• Using FileReader and BufferedReader:
The FileReader class is a simple way to read characters from
a file. To improve efficiency, you often use it in conjunction
with BufferedReader, which buffers the input to make
reading more efficient.
Example: Reading a File Line by Line
168
import java.io.BufferedReader;
i■pcrt j ava.io.File Reade r;
import j ava.io.IOExc eption
public class Nail {
public static void *ing[]
(Str args) {
try (BufferedReader br = new BufferedReader(new File Reader ("file, txt"))) ■[
String line;
while ({Line = br.readLinef)) != null) {
System.out.printLn(line);
}
} catc- (lOException e) {
e.printStackTrace();
Explanation:
FileReader is used to read the file "example.txt".
BufferedReader wraps FileReader to allow efficient reading
of lines.
The program reads and prints each line from the file until
the end.
Reading from a File:
169
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Filel-.'riteExample {
public static void main(String[] args) {
String filePatk = "example.txt";
String content = "Hello, World!\nWelcome to File I/O in Java.";
try (Bufferedh'riter writer - new BufferedWriten(new FileWriter(filePath))) {
writer.write(content);
} catch (lOException e) {
e.printStackTrace();
}
}
}
Writing Files
To write to files, you can use FileWriter or BufferedWriter.
• Using FileWriter and BufferedWriter:
The FileWriter class allows you to write characters to a file,
and BufferedWriter can be used to write text to a character
output stream, buffering characters to provide efficient
writing.
Explanation:
• FileWriter is used to write to the file "example.txt".
• BufferedWriter wraps FileWriter to allow efficient writing.
• The program writes the string content to the file.
170
impart java.io.Bijfferedwriter;
import java.io.Filewriter;
inpci i*t j ava.io. IQExc eption;
public class lair {
public static void (stringf] args) {
try (BufferedWTiter bw = new BufferedWriter(new FileWriter("file.txf})) -{
bw. write f dello, );
} cacc- (IQException e) {
e.printstackTrace();
Writing to a File:
Practice Exercise:
Task: Create a Java program that reads from a file named
"input.txt" and writes the content to another file named
"output.txt". Add some additional text like "Processed by
Java program" to the end of the output file.
171
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileCopyExample {
public static void nain(String[] args) {
String inputFilePath = "input.txt";
String outputFilePath = "output.txt";
try (BufferedReadi r reader — new BufferedReader(new Fi' (inputFilePath));
BufferedWriter writer — new BufferedWriter(new Fi lei-, r iter (outputFilePath))) •{
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
// Adding additional text
writer.write("Processed by lava program");
.11 o
} catch (TOException e) {
e.printStackTrace();
Solution:
Explanation:
• The program reads each line from "input.txt" and writes it
to "output.txt".
• After copying all the content, it adds "Processed by Java
program" to the end of the output file.
172
* va. io. FiltChit putstreaa;
J
lB'raaltj. r-OEscceptiijri;
Ja?a;io. ObJetkDutputSt reae;
1 a'ra. io. Serlall labia;
■ ■ ■ {
■ - iLa: i.L ■ l=:_ L ' .■ ■ " ■ Lj
String nanw;
■ . ate age;
(String name, age) {
= iiwtie;
ili;>.a£e r age;
}
i i String () {
rrLu ■ n ' n-: =. + naae + agt ■ + age + J' ■;
}
. -I'. . -. . {
(String[] args) {
» ■ (' ’■ I ■ I ' t );
( - ( ))
- (-FiieObt)) {
cot□ -BriteOtjJ eet (person);
Sy 5 tfrB □dGt.printJ.rtf j;
} (rflEkteption e) {
prints La eklraeef);
}
}
Serialization and Deserialization
Serialization is the process of converting an object into a
byte stream, so it can be easily saved to a file or
transmitted over a network. Deserialization is the process of
converting the byte stream back into an object.
Serialization
To serialize an object, the class must implement the
Serializable interface. This interface is a marker interface,
meaning it doesn’t have any methods to implement but
indicates that the class can be serialized.
Example: Serialization
173
import java.io.
*;
class Person implements serializable {
private static final long serialversicmulD = 1L;
string name;
int age;
public Persc (string name, int age} {
this.name = name;
this.age = age;
public class ' ain {
public static void (String[] args) {
= new ( , );
// serialization
try (objectoutpiitstream oos = new objectoutputstreamfnew FileDutpiitstreaBeperscin.
oos.writeobjectfperson);
} catch (lOException e) {
e.printstackTrace();
// Deserialization
try (objectlnputstream ois = new objectinpwtstrearn(new Filelnputstream("person.ser
= (Person) ois.readobject{);
System, out. printin ("Na me: " + deserializeciPerson.name + ", Age: " + deserializ
} catch (lOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
Explanation:
• Person class implements Serializable, making it eligible for
serialization.
• An instance of Person is created and serialized to a file
named "person.ser" using ObjectOutputStream.
Serialization:
• Process of converting an object into a byte stream.
Deserialization:
• Process of converting a byte stream back into an object.
Example:
174
import java.io.Fileinputstream;
import java.io.IOException;
import java.io.Objectinputstream;
public class DeserializationExample {
public static void mair(String[] args) {
Person person « null;
try (Fileinputstream -fileln - new FileInputStream("person.ser");
ObjectlnputStream in = new ObjectlnputStream(fileln)) {
person « (Person) in.readObject();
System.out.println('Deserialized Person: );
System.out.println(person);
} catch (lOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Deserialization
To deserialize an object, you use ObjectInputStream to read
the object from the file and convert it back into an instance
of the class.
Example: Deserialization
Explanation:
The program reads the "person.ser" file and deserializes the
byte stream into a Person object.
It then prints the deserialized object.
175
Practice Exercise:
Task: Create a Java program that serializes an object
representing a book (with attributes like title, author, and
price) and then deserializes it from the file, printing the
book details.
176
i-: Java.io.
*
;
tlJSS let:. iniilrneiti £
1V .1 •• s'.K .L -I; ll . a ;
String title;
- 4i' String author;
iv. : ■ price;
(String title. String author, price) {
this.title = title;
th is.author a author;
this.price = price;
String () {
। -tuT’i -i _i- + title +• + author -+ -+■ price +
}
>
pub. r. : ..- {
j: : . i . (String[) args) {
// Create a Book object
= ti- i • ('Ef+i?<t r. ■ i", ji-.i:.- i .'j. , );
// Serialize the book object
(r a net. ( t'uu . sei J;
= (fileOut)) (
out.MriteObject(book);
SyStea.out.println( );
} (lOExce ption e) •{
e.printStackTrace();
// Deserialize the book object
try (Pilelnputitrean fllelii a new FileInputStrear«(''book. ser’*
);
= (ifileln)> {
= (Book) ln.read06ject();
SyStea.out.println( );
Systea.out.println(deserlalizedBook);
} (lOExceptian | ClassMotFoundExceptIon e) {
e.printStackTrace();
> o
Solution:
177
Chapter 9
Java Collections Framework: List, Set, and Map Interfaces
The Java Collections Framework (JCF) provides a set of
interfaces and classes for storing and manipulating groups
of data as a single unit—a collection. The primary interfaces
in the JCF are List, Set, and Map. Each of these interfaces
defines different ways to store and access elements.
1. List Interface
The List interface extends the Collection interface and
represents an ordered collection (also known as a
sequence). Lists can contain duplicate elements, and
elements can be accessed by their index.
Key Implementations:
• ArrayList: A resizable array implementation.
• LinkedList: A doubly-linked list implementation.
• Vector: A synchronized resizable array.
• Stack: A subclass of Vector representing a LIFO stack.
Common Methods in List:
• add(E e): Appends the specified element to the end of the
list.
• add(int index, E element): Inserts the specified element at
the specified position in the list.
• get(int index): Returns the element at the specified
position in the list.
• remove(int index): Removes the element at the specified
position in the list.
• indexOf(Object o): Returns the index of the first
occurrence of the specified element in the list.
• size(): Returns the number of elements in the list.
178
i-ipur t Java.utLl.ArrayLLst;
i-ipu-L java.ut LL.Listi
public class Llstlx-aaipli {
public static void 1 (String[j args} {
List<String> list = pew - ayLi
i! Adding elenwnts to the list
list.add( Apple };
list.add( Baria ju'};
list.add( "CHhIy ■);
H Accessing elements by index
Sy stem, out-prlotlnj "I t ■ ■. + l±st.get( JJ; !j Banana
It Iterating over the list
Sy steffi, out. print in ( Li--. ■iMtenl );
for- (String fruit : list) {
Systea.nut.printing fruit
}
Reffioving an elenent
list.receive( ■ ..i,l );
f! Checking the size of the list
Systeffi,out.printing list Lze rfter ■■ novel: + UstxSize^));
1
}
Element at index 1: Banana
List elements:
Apple
Banana
Cherry
List size after removal: 2
Example using ArrayList
Output:
179
The List, Set, and Map interfaces are part of Java's
Collections Framework, providing powerful tools for handling
groups of objects (collections) with different behaviors and
characteristics. Below, we'll explore each of these interfaces
in detail, including their key characteristics, usage, and
examples. We'll also include practice exercises with
solutions.
List Interface:
Overview:
• Ordered Collection: List maintains the order of elements in
which they are inserted.
• Duplicates Allowed: List can contain duplicate elements.
• Indexed Access: Elements can be accessed by their index
position.
Common Implementations:
• ArrayList
• LinkedList
• Vector (Less commonly used)
180
Example
181
Element at index e: Apple
Iterating over the list:
Apple
Banana
Cherry
Apple
After removing elenent at index 1: [Apple, Cherry, Apple]
List contains 'Apple': true
Output
Key Methods:
• add(E e): Adds an element to the list.
• get(int index): Retrieves the element at the specified
index.
• remove(int index): Removes the element at the specified
index.
• contains(Object o): Checks if the list contains the specified
element.
• size(): Returns the number of elements in the list.
182
impart java.util.ArrayList;
import java.util.List;
public class lair {
public static void mair(string!] args) {
ListcString> list = neh rrayListoO;
list.add( >ple");
list.add( );
list.add("Apple"); // Allows duplicate
for {string fruit : list) ■[
system.out.p rintln(fruit);
}
}
}
Example:
183
Set Interface
The Set interface extends the Collection interface and
represents a collection that cannot contain duplicate
elements. It models the mathematical set abstraction.
Key Implementations:
• HashSet: Stores elements in a hash table and does not
guarantee any specific order of elements.
• LinkedHashSet: Maintains a linked list of the entries in
the set, in the order in which they were inserted.
• TreeSet: Implements the NavigableSet interface, using a
tree for storage. The elements are ordered using their
natural ordering or a custom comparator.
Common Methods in Set:
• add(E e): Adds the specified element to the set if it is not
already present.
• contains(Object o): Returns true if the set contains the
specified element.
• remove(Object o): Removes the specified element from
the set if it is present.
• size(): Returns the number of elements in the set.
• isEmpty(): Returns true if the set contains no elements.
Overview:
• Unordered Collection: Set does not maintain any order
of elements.
• No Duplicates: Set does not allow duplicate elements.
Common Implementations:
• HashSet
• LinkedHashSet (Maintains insertion order)
184
i-ipu"L Java.util.Hashset;
import Java, at 11 ..Set;
putdi'L ClBSS '? . “.KdllLlt {
1L Static void i . jr(String[] args} {
Set<Strlng> set - new HiiahSc is(Ji
H Adding elements to the set
set.addf 'Dog J;
set.add( 'CaL');
set.addf 'Fie );
set.addf 'Dog J; if Duplicate element
ff Checking if an element exists
Sy s tern, ou t. print In ('■'.■ eon ■ !■ Ca + set. contains (■£ ))j
ff Iterating over the set
Sy stem, out. printing Se. elt is: };
■for (String anlaal : set) {
Systea.ant.printlnfanlNalJj
ff Removing an elenent
set.remowe('Cat' );
ff Checking the size of the set
Sy stem. out. printing Set size after • .■ vai: + set., size (J);
>
}
Set contains 'Cat': true
Set elements:
Dog
Elephant
Cat
Set size after renewal: 2
TreeSet (Maintains sorted order)
Example: Using HashSet
185
import java.util.Hashset;
Lwport java.util.Set;
public class lain {
public static void (string[] args) {
set<string> set = ieu Hashse <>();
set.addf 'Apple");
set.add('Banana" );
set.add("Apple"); // Does not allow duplicate
for (String fruit : set} (
System.out.println(fruit);
}
}
}
Example 1
186
import java.util.Hashset;
iaport java.util.Set;
public class SetExample {
public static void (String[] args) {
Set<String> set = iej Hash c>{);
// Adding elements to the set
set.addf 'Apple");
set.addf 'Banara");
set.addf 'Cierr );
set.add("Apple"); // Duplicate, will not be added
// Iterating over the set
System.out.printing derating over the set );
for (String fruit : set} {
System.out.printin(fruit);
}
// checking if the set contains an element
boolean containsBanana = set.contains("Banana");
System.out.printing Set contains 'Banarc' + containsBanana);
H Removing an element
set. removef'Cher ry' );
System.out.printing ftep rent ug therri + set);
// checking the size of the set
system.out.printing set size + set.sizeO);
}
}
Example 2
187
Iterating over the set:
Apple
Banana
Cherry
Set contains 'Banana': true
After removing 'Cherry : [Applej Banana]
Set size: 2
Output:
Key Methods:
• add(E e): Adds an element to the set.
• remove(Object o): Removes the specified element from
the set.
• contains(Object o): Checks if the set contains the specified
element.
• size(): Returns the number of elements in the set.
• isEmpty(): Checks if the set is empty.
188
Map Interface
The Map interface represents a collection of key-value pairs,
where each key is unique. Maps are not part of the
Collection interface.
Key Implementations:
• HashMap: A hash table-based implementation that allows
null values and keys.
• LinkedHashMap: Extends HashMap and maintains a
linked list of the entries, preserving insertion order.
• TreeMap: Implements the NavigableMap interface and
uses a tree to store the keys in a sorted order.
• Hashtable: Similar to HashMap, but synchronized and
does not allow null keys or values.
Common Methods in Map:
• put(K key, V value): Associates the specified value with
the specified key in this map.
• get(Object key): Returns the value to which the specified
key is mapped, or null if this map contains no mapping for
the key.
• remove(Object key): Removes the mapping for a key from
this map if it is present.
• containsKey(Object key): Returns true if this map contains
a mapping for the specified key.
• keySet(): Returns a Set view of the keys contained in this
map.
• values(): Returns a Collection view of the values contained
in this map.
Overview:
• Key-Value Pair Collection: Map stores elements as key
value pairs.
No Duplicate Keys: Each key in a Map must be unique.
• Keys and Values: Values can be duplicated, but keys
cannot.
Common Implementations:
• HashMap
• LinkedHashMap (Maintains insertion order)
• TreeMap (Maintains sorted order by keys)
189
i-ipur-L Java.util.HasriHap;
import Jna^utU.Mp;
public Class HapE ‘ Lit {
public st; ic void । . (String[J args} {
HapcString, Integers map - new II : <>(.};
fl Adding key-value pairs to the nap
nap.putf ‘Apple „ 16);
nap.putf'Bins , M);
nap.putf ‘Orange a );
fl Accessing a value by key
Sy stem, out. print in (' I - tee u- Apple: ' + wap. get ( 'Apple-));
fl Iterating over the map
Sy stem, out. printing p entrlei };
for (Map. Entry (String,. Integers entry : nap.entrySet {
Systen.enrt, printing entry. getKeyf) + -> " + entry .getValueO);
}
fl Removing a key-value pair
nap. remove(' lanane-);
ft Checking if a key exists
Sy stem. out. printing contains lanaia' + nap. con tain EKey ( it ana'1'));
J
}
Example Using HashMap
190
Price of Apple: 1&
Map entries:
Apple -> 16
Banana -> 26
Orange -> 30
*:
Map contains 'Banana false
Output
Summary:
• List: An ordered collection that can contain duplicate
elements. Elements can be accessed by their index.
• Set: A collection that cannot contain duplicate elements. It
is not ordered by default (except in the case of
LinkedHashSet or TreeSet).
• Map: A collection of key-value pairs, where each key is
unique. It allows you to quickly retrieve a value based on a
key.
191
import java.util.HashMap;
import java.util,Map;
public class ■ lapExample {
public static void (String[] args) {
Mapcstring, lnteger> map = new -as- <>();
// Aciding key-value pairs to the map
map.put( Apple 'j B)[
map.putf Banana j 5);
map.put( cherry ± 7);
H Accessing value by key
System.out.println( "value for key 'Apple' : " + map.get("Apple")); // outputs: 3
ll Iterating over the map
System.out.printIn( erating over t ■ );
for {Map.Entrycstring, integers entry : map.entry5et()) {
System.out.println(entry.getkeyQ + + entry.getvalue());
11 Checking if a key exists in the map
boolean containsBanana = map.containskey( anana );
System.out.printing C tains key \ + containsEanana);
11 Removing a key-value pair
map.remove( Cherry');
System.out.println["After removing 'cherry': " + map);
// Checking the size of the map
System.out.printing ap size + map.size());
Example 1
192
Value for key 'Apple': 3
Iterating over the map:
Apple: 3
Banana: 5
Cherry: 7
Map contains key 'Banana': true
After removing 'cherry': {Apple=3, Banana=5}
Map size: 2
Output
Key Methods:
put(K key, V value): Adds a keyvalue pair to the map.
• get(Object key): Retrieves the value associated with the
specified key.
• remove(Object key): Removes the keyvalue pair for the
specified key.
• containsKey(Object key): Checks if the map contains the
specified key.
• size(): Returns the number of keyvalue pairs in the map.
193
import java. util.HashHap;
import java.util.Map;
public class lain {
public static veld (string[] args) £
nape integer, string) map = net <>();
map.put(1, *);
Apple
map.putfl, "Banana");
for {Hap.EnitrycInteger, String) entry : map.entrySet()) £
Sy stem. out. printing + entry.getKeyf) + + entry. getvalueQ);
}
}
}
Example 2
194
import java.util.ArrayList;
ir.po"t java.util.List;
public class List-'ractice {
public static void (String[] args) {
Listclnteger> numbers = ne <>();
// Aciding numbers to tbe list
numbers.add(1 );
numbers.add(2:);
numbers.add{? );
numbers.add{- );
numbers.add{: );
// Removing a nuaber by its value
numbers.remove(Integer.valuedf(3( ));
// Checking if tbe list contains a specific number
= numbers.contains( );
System.out.printing List contains le + contains29);
// Printing all the eleaents of the list
System.out.printlnf Eleaents in the lisi );
for (ire number : numbers) {
System.out.println(number);
}
}
Practice Examples
Practice 1: Working with List
Task: Create a List of integers and perform the following
operations: 1. Add numbers to the list.
2. Remove a number by its value.
3. Check if the list contains a specific number.
4. Print all the elements of the list.
Solution:
195
Practice 2: Working with Set
Task: Create a Set of strings representing colors and
perform the following operations: 1. Add colors to the set.
2. Check if a specific color is in the set.
3. Remove a color.
4. Print all the colors in the set.
Solution:
196
import java.util.ArrayList;
import java.util.List;
public class StudentList {
public static void mair(String[] args) {
List<String> students = new ArrayList<>();
// Add students
students.add("John );
students.add("Alice');
students.add("Bob );
// Display the list
System.out.println('Students: + students);
// Remove a student
students.renove( Alice );
// Display the list after removal
System.out.println( Students after removal: ’ + students);
}
} *
.1.
Practice Exercises:
1. Task:
o Create an ArrayList of student names. Add names, remove
a specific name, and display the list.
o Solution:
197
import java.util.HashSet;
import java.util.Set;
public class BookSet {
public static void mair(String[] args) {
Set<String> books = new HashSet<>{);
// Add books
books.add("The Great Gatsby');
books.add( Moby Dick");
books.add("1984 );
// Check if a book exists
System.out.println("Contains 1984': + books.contains( "1984"));
// Display all books
System.out. println(''Books : ' + books);
}
}
2. Task:
Create a HashSet of book titles. Add titles, check if a specific
title exists, and display all titles.
Solution:
198
import java.util.HashHap;
import java.util.Map;
public class ProductMap {
public static void main(String[] args) {
Map<String, Double) products « new HashMap<>();
// Add products
products.put("Laptop", 799.99);
products.put("Smartphone , 499.99);
products.put("Tablet", 299.99);
// Update product price
products.put("Smartphone", 450.06);
// Remove a product
products. rei»ove( "Tablet" ) ;
// Display all products
■for (Map.Entry<String, Double) entry : products.entrySet()) {
System.out.println(entry.getKey() +":$”+ entry.getValue());
}
}
}
3.Task:
• Create a HashMap to store product names as keys and
prices as values. Add, update, remove products, and display
all entries.
• Solution:
These exercises help solidify your understanding of List, Set,
and Map interfaces and their common implementations.
Understanding these concepts is crucial for efficient and
effective Java programming.
199
Practice : Working with Map
Task: Create a Map of employee names (keys) and their
salaries (values) and perform the following operations:
1. Add employees and their salaries to the map.
2. Update the salary of a specific employee.
3. Remove an employee from the map.
4. Print all the employees and their salaries.
Solution:
200
import java.util.HashMap;
import java.util.wap;
public class I apPractice (
public static: void (String[] args) {
MapcString., Integer> employeesalaries = net <>{);
// Adding employees and their salaries to the map
employeeSalaries.put( lice , =■: );
employeeSa1a ries.put( , )j
employeeSalaries.put( 'C'ar lie1’, );
// Updating the salary of a specific employee
employeeSalaries.put ("Alice", 55804); // Update Alice's salary
Removing an employee from the map
employeesalaries.remove{ );
// printing all the employees and their salaries
System.out.printIn( loyees and their salaries );
for (Hap.Entryestring, Integers entry ; employeesalaries.entry5et()} (
System.out.println(entry.getKey() + + entry.getValue());
}
}
Summary
List: Ordered collection that allows duplicates. Commonly
implemented by ArrayList and LinkedList.
Set: Unordered collection that does not allow duplicates.
Commonly implemented by HashSet and TreeSet.
Map: Collection of key-value pairs, with unique keys.
Commonly implemented by HashMap and TreeMap.
201
These interfaces and their implementations provide the
foundation for working with collections in Java, enabling
developers to choose the most appropriate data structure
based on their specific needs.
202
Chapter 10
Understanding HashMap, TreeMap, HashSet, TreeSet
The Java Collections Framework (JCF) provides powerful data
structures to store and manipulate data efficiently. Four
commonly used data structures in this framework are
HashMap, TreeMap, HashSet, and TreeSet. Each of these
structures has unique characteristics, advantages, and
trade-offs, which make them suitable for different scenarios.
1. HashMap
Overview:
• HashMap is a data structure that implements the Map
interface and stores key-value pairs.
• It uses a hash table for storage, providing fast lookups,
insertions, and deletions.
• The keys are hashed into buckets, and the position of the
bucket in the hash table is determined by the hash code of
the key.
Key Characteristics:
• Order: HashMap does not guarantee any specific order of
the elements.
• Null Values: Allows one null key and multiple null values.
• Performance: Average time complexity for operations
like get(), put(), remove() is O(1).
Common Methods:
• put(K key, V value): Associates the specified value with
the specified key in this map.
• get(Object key): Returns the value to which the specified
key is mapped.
• remove(Object key): Removes the mapping for the
specified key.
• containsKey(Object key): Returns true if this map contains
a mapping for the specified key.
• keySet(): Returns a Set view of the keys contained in this
map.
• values(): Returns a Collection view of the values contained
in this map.
203
inpurt java.LitLL. HashMap;
i-ipurt java.trtLL.Map;
public class .. ■ e .
public static void ulm (String[] args} {
MapcStrlng, Integers hashMap = new <>tJ»
ff Adding key-value pairs to the HastiHap
hashMap, put( Apple"; H|;
hashMap, put( anena'', 13);
hashMap, put( Orange"; 3);
fj Accessing a value by key
System,out.printin( rice of Apple * hashMap. get( Apple ));
H Iterating over the HashMap
System,out.printin( ashflap t rie«: );
foi (Map.Entry<stridfi± Integers entry : hastiHap.entrySet(}) {
Sy Stea, cut ,prlntla( entry. getKey(} + -> + entry, get Value-J }};
}
ff Removing a key-valoe pair
hashMap,re«ave( Bena };
ff Checking if a key exists
System,out .prlntln( I 'Lp coi lbIhs ' Sanaru + hashMap. contains Key ( ■■}};
}
}
Example Using Hashmap
204
Price of Apple: IB
HashMap entries:
Apple -> 1©
Banana -> 20
Orange -> 30
HashMap contains 'Banana
:
* false
Output
205
import java.util.HashMap;
import java.util.wap;
public class I-ash-'a pEx ample -[
public static void i (string[] args) {
MapcStringj Integers hashMap = new Hash p<>();
// Aciding key-value pairs to the HashMap
hashMap.put{ Alice", 30);
hashMap.put( BOb", 2 );
hashMap.put(rcharLie , 35);
hashMap.put{ David , );
// Accessing a value by key
system.out.println( Lice s age: + hashMap.get{ Alice1')); !! outputs: 30
// Iterating over the HashMap
system.out.println("All key-value pairs in the HashMap:1');
for (Map.Entrycstring, integer} entry : hashMap.entrysetf)) {
system.out.printin(entry.getKey{) + + entry.getvaluef));
}
// checking if a key exists
= hashMap.containsKey( );
System.out.println( HashMap contains Bob + hasKey);
// Removing a key-value pair
hashMap.remove( Charlie');
// Feinting the HashMap after removal
system.out.println("HashMap after removing 'Charlie': “ + hashMap);
}
}
Example:
206
Alice's age: 39
All key-value pairs in the HastiMap:
Alice: 39
Bob: 25
Charlie: 35
David:
HashMap contains 'Bob': true
HashMap after removing 'Charlie': tAlice=30, Bob=25, David=4B}
Output
207
Practice Exercise 1
• Task: Create a HashMap that stores the names of
students and their grades. Write methods to:
1. Add a student and their grade.
2. Retrieve a grade by the student's name.
3. Update a student's grade.
4. Remove a student from the HashMap.
5. Print all students and their grades.
Solution 1
The solution includes methods to add a student and their
grade, retrieve a grade by the student's name, update a
student's grade, remove a student, and print all students
and their grades.
208
Java.util .nastMap;
import Java.util.Map;
public class Studsec tfirades {
7/ HashMap to store student naeas. as keys and their grades as values
KapcStrlng. Integer) studon-tGradas;
7/ Constructor to Initlaliio the MashMap
public StuderctGradesQ {
studertfiradus - non k./ajooO;
>
7/ Hethod to add a student and their grade
public void addstuo. :{String name, ini grade) £
studertfiradus-pert (name, grade);
System.out.printing Mac e nene e " eith grad. ” ♦ grade);
>
// Hotrod to retrieve a student's grade by their name
* (String name) £
public Integer jettc ad
studuntfirade s-get(naae);
>
7/ Hotrod to update a student's grade
public void updatofii . . (String name, newGrade) (
(studMtfirades .cental ns Key (nancy) £
studamtfirades .put (naan. eufirade);
System.out -print In ( ipdat e name • -d. t-_ a newfirade);
} else <
System.out -print In ( itwknt e naee • doc . rot u.lsj;
>
>
7/ Hotrod to remove a student from the HashMap
public void , (String ninny (
if (studemtfirades .c ootalnsteyt nancy) £
stbdsntfirades .rMOTt(naie);
System.out .print In ( <urx». sd e naee • fren the luuords. " )J
} else <
System.out .print In ( iti.lt t e naee • doc. tot «uist.')g
>
>
7/ Hotrod to print all students and! their grades
public void prierukl lStudonts{) (
System .out.printing -.dents and their grad. . );
f< (Hap.EntryoStrlng, Int«gpr> entry : studentGrados.amtrySet( )) {
System.out-prlnt In (entry, get Key( ) e • entry. gctValueQ );
>
>
7/ Hain eottod to deenxistrate the Functionality
public static void . (String(J argsy (
Studentfirades studsn(Grades - now £tuden<Gra4tes(>;
// Adding students and their grades
studentfirades . addSt udemt ( . .. ' , ) ;
studartfirades .addStudemt ( t-'. ;>;
Studertfirades. addSt udeart ( carl 1 e' , i>;
// Retrieving a grade
System .out.printing radu oF Adi. «■ studentGrados, getCrade ( All.- '));
7/ Updating a grade
Studertfirades-Mpdatofiradex tot.", 82);
77 Ranoving a student
studertfirades.raecovaStmdent <■ haril.
// Printing all studsects and their grades
Studertfirades . prlnCAl IStudents( );
>
>
209
Explanation:
1. studentGrades HashMap:
o The HashMap is used to store the names of students (as
keys) and their grades (as values).
2. Methods:
o addStudent(String name, int grade): Adds a student's
name and their grade to the HashMap.
o getGrade(String name): Retrieves the grade of the student
with the specified name.
o updateGrade(String name, int newGrade): Updates the
grade of the specified student.
o removeStudent(String name): Removes the specified
student from the HashMap.
o printAllStudents(): Prints all students and their grades.
3. Main Method:
o Demonstrates the functionality by adding students,
retrieving a grade, updating a grade, removing a student,
and printing all students and their grades.
210
Added ALlti grade
Added Bob grade
Added Charlie grade
Grade Alice:
Updated Bob's grade to B2
Renewed Charlie the records.
All students their grades:
Alice: es
Bab: 32
Output:
When you run the program, the output will be:
This program provides a clear demonstration of how to use
a HashMap for managing a collection of students and their
grades in Java.
211
impart java.util.HashMap;
import java.util.Map;
public class lain {
public static void (String[] args) {
Map<stringj integers map = new Hash <>();
map.put('Apple , 1);
■ap.put("Banana", 2);
System.out.printLn(map.get( pie")); // Outputs: 1
}
}
Example 2
Implements the Map interface.
Uses a hash table for storage.
Allows null keys and values.
212
2.TreeMap:
Overview:
• TreeMap is a data structure that implements the
NavigableMap interface and stores key-value pairs.
• It uses a Red-Black tree to maintain the order of keys.
• The elements are sorted according to their natural
ordering or by a custom comparator provided at map
creation time.
Key Characteristics:
• Order: TreeMap maintains the elements in ascending
order of the keys.
• Null Values: Does not allow null keys (throws
NullPointerException) but allows multiple null values.
• Performance: Operations like get(), put(), remove() have
a time complexity of O(log n) due to the tree structure.
Common Methods:
• put(K key, V value): Associates the specified value with
the specified key.
• get(Object key): Returns the value associated with the
specified key.
• remove(Object key): Removes the mapping for a key.
• firstKey(): Returns the first (lowest) key.
• lastKey(): Returns the last (highest) key.
• subMap(K fromKey, K toKey): Returns a view of the portion
of this map whose keys range from fromKey to toKey.
213
]*va. util .flap j
j a va. ut 11 l TneeMa p j
l.i.l. l J1 Class '; . । .:. .. -[
public static v&id h^Ibi (String£) args} 4
flapcstrlng, integers treeflap - <s():
i! Adding key-iralue pain to the TreeMap
treeHap.put( , . );
treeMap.put( >.. ( . );
treeMap. put-( ■ . ):
i! Accessing a value by key
System,out.printing . + treeHsp.g±t( '■Apple" ));
I! Iterating ever the TreeMap
System,out.print in( I । ■ i- .
(K^p>EntryxString.j Integers entry : trteHap.EhtrySet(}} {
Sy steti .nut .printing entry .get key () + + entry .getValuefj ) j
}
f! RetHPVirig n key-value pair
treeMap.rehuve( ■ J;
if Checking Uie first and last key
System,out.priiitln( . i treeJIap.fLrstKeyf))j
System,out.printing t treeMap. Last Key(J};
}
}
214
Output:
Overview:
• Purpose: TreeMap is a Map implementation that
maintains a sorted order of keys.
• Ordering: Natural ordering (according to the keys'
Comparable implementation) or a custom Comparator.
• Nulls: TreeMap does not allow null keys but allows
multiple null values.
• Performance: Provides O(log n) time complexity for basic
operations.
Internal Working:
• TreeMap uses a Red-Black Tree, a self-balancing binary
search tree, to maintain the sorted order of the keys.
• This ensures that the entries are always sorted based on
the natural ordering of the keys or the order specified by a
Comparator.
215
impart java.util.Map;
irport java.util.Treenap;
public class l ain {
public static void (string[] args) {
Mapcstringj integers map = new Tr <>Oj
map.putf Applt" j l)j
map.putf Earana"j 2);
System.out.printLn(map.get( ople )); // Outputs: 1
}
}
Example
• Implements the Map interface.
• Uses a red-black tree for storage.
• Does not allow null keys.
Example 1
216
1-ava.utlluMap;
java.irtll .TreeHap:
। ub. . ■ :. ■ ■ {
(String^] argsj
Hap<Strlng, Integery treeMap ■ <■'()>
ff Adding key-value pairs to the TreeHap
treeRap.putf , t)j
treeRap.put( ,
treeRap.put( f
treeRap.put( , Ij
If Aoiessing a value fay key
System,out. prIntln( + treeMap..get( )); n r 21
If Iterating over the- Tree
*Gp (Nate: The nut put is sorted by
Systert.outLprlrttln( ■ ' . };
(Map.Entry<Stringy Integers entry : tre<sHBp.entrySet) -[
Sy stei □ aut .printlbf entry^aetKeyO + + entry. getValue());
J
If LtietkLng if a key exists
bu : .■■ I = treeHap. ccuitel riskeyf );
System, out .print In ( ■* hasJCey);
ff Reaving a key'-value pair
treeRap.renuve( );
ff Printing the TreeHap after renuval
System.out.printIn( * treeHap);
}.
J
Example 2
217
gub’ L. drgc! ZE
ley-
All *
dlLH piiri 1ft the TteeMjIpl
Alite *
!
Bub: 25
LhdrUe: 35
Udvlit 41!
Treeftjth itunLdlii.s AJ-lUe
* Ldue
Freefldu 31 LeJ' resIUvlr11[ '□dvlit' {AlJi^-ldj Clkdrlle= 35}
Output
218
Practice Exercise:
• Task: Create a TreeMap that stores product names and
their prices. Write methods to:
1. Add a product and its price.
2. Retrieve the price of a product.
3. Update a product's price.
4. Remove a product from the TreeMap.
5. Print all products and their prices in ascending order of
product names.
Solution
The solution includes methods to add a product and its
price, retrieve the price of a product, update a product's
price, remove a product, and print all products and their
prices in ascending order of product names.
219
java.utll_Map;
1.,port Java. util. TreeMap;
public class ProductCatalog (
f! TreeMap to stare product naeos as keys and ‘their prices as values
MapcStrlng. Doubles productprices ;
H Constructor ta initialise the JrsulUp
public f-ruduttCatalogf) (
productPrices - now Ti Upo();
I
rr Matted to add a product and Its price
public void uio.vucJuct(String producthaaM, ubl. *)prix f
productf-rices.pwt(protectMaae. price);
Systaa.OMt-prlntlnC Aided * • productteM a -1th prl» v S~ a price):
I
rr tettod to retrieve the price of a product by its tuee
pub 1 . Double- (String prodLkCthane) {
productPrices.get(prodwctMaae);
)
rr Matted to update a protect's price
public void updatePr i< (String prcdctkai. out- nesdr-lce) (
(protectPricos.containsKeyfproductteee)) (
pratectPrices.putCproductMaM, amdrloe);
Sy stem,out .print la( । a productNaee *■ • MoPrice);
> else £
Sy stem .out.printle( u<t ' a productMase a does nut c.L . .
>
rr Matted to reaove a protect froo the TrwoMap
public void r—nveProduv:(String productNaae) (
(pratectPrlces.contalnsKey(produ<-t«K»ee)) (
pratectPricas.reteverprotectMaae) :
Sy Stea .out.printle( 'I sed v productteee *■ Frew. the catalog. );
> rise £
Sy stem .out.printle( ' a produc tteee * does not e«L. );
}■
rt Matted to print all products aad tbelr prices In ascending order of product nae.
public void printAllProducts(> <
Systee.oet.prlntlnf All protects and their prices In ascending ocde< );
Pc- (Map. EntrycStrlng. Doubles entry : products'rices . entrySetC)) {
Sy stem.aut.printInfantry.getteyt) e ♦ entry.gatV3Luo()>;
rr Malm eatbod ta daaanstrata the Functionality
public static void -.’ (Strlngf] arUsJ (
ProtectCatalog catalog — now ProductCart al m();
rr Adding products and their prices
*,
catalog.addprodact( tptop
catalog.addprodact( >a tphe . . 1M.4P);
catalog. addProd«ct( -Lluf, Ate .fid))
catalog.addProdect( itor’.
ff Retrlanrlng the price of a product
:Systee.CMt.printIn( . - lai - ’ ♦ catalog.gptPrlce( apt ■. )):
ft Updating a product's price
catalog.tedatePr£ce( -cptcou’. ■. tie);
ft Renavieg a product
catalog. reaaweProductC >blet ' Jj
ft Printing all products and their prices in ascending order
catalog. prin tAHProducts (>;
I
)
220
Explanation:
1. productPrices TreeMap:
o The TreeMap is used to store the names of products (as
keys) and their prices (as values). The TreeMap ensures that
the products are stored in ascending order of their names.
2. Methods:
o addProduct(String productName, double price): Adds a
product and its price to the TreeMap.
o getPrice(String productName): Retrieves the price of the
product with the specified name.
o updatePrice(String productName, double newPrice):
Updates the price of the specified product.
o removeProduct(String productName): Removes the
specified product from the TreeMap.
o printAllProducts(): Prints all products and their prices in
ascending order of product names.
3. Main Method:
o Demonstrates the functionality by adding products,
retrieving a product's price, updating a product's price,
removing a product, and printing all products and their
prices in ascending order.
221
Added Laptop with price $1200.3
Added Smartphone iitt price $ e.0
Added Tablet with price $ B0.0
Added Monitor dtf price (250
Price of Laptop: S
Updated Smartphone s price to $850.0
Removed Tablet frcm the catalog.
All products and their prices in ascending ordei :
Laptop: $_200.0
Dfiitor: (2W 0
Smartphone: $858.0
Output:
When you run the program, the output will be:
This program provides a clear demonstration of how to use
a TreeMap for managing a collection of products and their
prices in Java, ensuring the products are maintained in
ascending order of their names.
222
HashSet:
Overview:
• HashSet is a data structure that implements the Set
interface and stores unique elements.
• It is backed by a HashMap (the elements are stored as
keys in the underlying HashMap).
• Order: Does not guarantee any specific order of the
elements.
Key Characteristics:
• Duplicates: Does not allow duplicate elements.
• Null Values: Allows a single null element.
• Performance: The average time complexity for
operations like add(), remove(), contains() is O(1).
Common Methods:
• add(E e): Adds the specified element to this set if it is not
already present.
• remove(Object o): Removes the specified element from
this set if it is present.
• contains(Object o): Returns true if this set contains the
specified element.
• size(): Returns the number of elements in the set.
• isEmpty(): Returns true if this set contains no elements.
223
i-ipur L lava.utIL.HashSet;
inpurt lava.irt LL.Set;
public class HashSi {
public static vtlld Mlh (String[] args} {
SetcStrlng? hashSet = new :hSet<i()i
i! Adding elements to the Hashset
hashSet. add("D.: j };
hashset. add("Cr. };
hashSet. add ("E le pl ran I.") ;
hashSet. add("D.: g U Duplicate element
!f Checking If an element exists
Sys tern, out .printing sitset contains 'Cat . + hashset .cantaLns( C. J};
if Iterating over the HashSet
System.out.println["Ha:.hS^L ele-ienLc: }j
fur (String anlaal : lushSet} {
Sy ste
* . out, print 1 n( anlnal);
}
if Removing an eienent
hashSet.rennve( 'Cat');
I! Checking the size of the HsshSet
System, out .print In ( shSet size aft ■■ re . . + hashSet. size tJ->>
1
}
224
HashSet contains 'Cat': true
HashSet elements:
Dog
Elephant
Cat
HashSet size after removal: 2
Output:
Overview:
• Purpose: HashSet is a Set implementation that stores
unique elements in an unordered manner.
• Ordering: Does not maintain any order.
• Nulls: Allows a single null element.
• Performance: Provides O(1) time complexity for basic
operations.
Internal Working:
• HashSet uses a HashMap internally, where the elements of
the set are stored as keys in the HashMap, and the
associated values are a constant object.
225
Example:
226
All elements in the Hashset:
Apple
Banana
cherry
Hashset centalns 'Banana': true
Hashset after removing Cher : [AppleBanana]
impart java.util.Hashset;
iaport java.util.Set;
public class lain {
public static void i (String[] args) {
set<string> set = new Hashse <>{);
set.add('Apple");
set.add( 'Earana''};
set.add("Apple"); // Duplicate, will not be added
Systea.out.println{set); // Outputs: [Bananaj Apple]
}
}
Output:
• Implements the Set interface.
• Uses a hash table for storage.
• Does not allow duplicate elements.
Example:
227
Practice Exercise:
• Task: Create a HashSet to store unique cities visited by a
user. Write methods to: 1. Add a city.
2. Check if a city has been visited.
3. Remove a city from the set.
4. Print all visited cities.
Solution for the practice exercise that involves working
with a HashSet to store unique cities visited by a user. The
solution includes methods to add a city, check if a city has
been visited, remove a city from the set, and print all visited
cities.
228
import ja^a.iitll.HashSe't;
import java.uttl.Set;
public class CltyVlslts {
// HashSet to stone unique cities visited by the user
private Set<Strlng> vlsltedCitles;
// Constructor to Initialize the HashSet
public cityvisitsO <
vlslte-dCitles ■ new Hash£et<>()•
}
// Method to add a city to the set
public void addCitj(String city) {
1-F (visitedCltles.add (city) ) {
Sy st esa. out .prlntln( city ■+■ ’ added to visited cities.
> else <
Systea.out.prlntln(clty ■+• • has already been visited."J;
}
}
// Method to check i-F a city has been visited
public boolean hasVlsltec (String city) ■{
retut n visltedCltles.contalnsfcity};
}
// Method to renove a city froa the set
public void retsoveCLty<String city) {
i-F (visitedClties.refi>ove(clty)) {
Sy st esa. out. prlntln( city ■+• " reaoved frora visited cities. ) ;
> else <
Sy st esa. out .printing city + " was not -Found in the visited cities.”);
// Method to print all visited cities
public void prlntAllCities() {
System, out. pr-intlnC ’Visited cities: >;
-For- (String city : visltedCltles) {
Sy st esa. out .printing city );
>
J
// Main method to dieaonstrate the -functionality
public static void aalr (Strlng( ] args) -{
CityVlsits cityvisits - new CityVlsits();
// Adding cities
cltyVisits.addCity(•Hew York");
cltyVlslts.addCity(” os Angeles);
cltyVisits.addCity( Chicago >;
cltyVisits.addCity(•Hew York"); // Duplicate city
// Checking i-F a city- has been visited
System.out.prlntln< • i las visited Chicago ' ■+■ cityVlsits.hasVisitedf ’ Chicago”)) ;
System.out.prlntln< • i las visited Miami? -» cltyVisits.hasVisitedlC ’ Mi-ami " )>;
f/ Removing a city
cityVisits.refl»veClty( Los Angeles");
cltyVisits.removedtyC'Miaai"); // City not in the set
// Printing all visited cities
cltyVisits . pr-ln-tAll Citi es( ) ;
}
229
Explanation:
1. visitedCities HashSet:
o The HashSet is used to store the names of cities visited by
the user. Since HashSet only allows unique elements, it
automatically prevents duplicate cities.
2. Methods:
o addCity(String city): Adds a city to the HashSet. If the city
is already in the set, it will not be added again, and a
message will indicate that the city has already been visited.
o hasVisited(String city): Checks if a city is in the HashSet,
returning true if it is, and false otherwise.
o removeCity(String city): Removes a city from the HashSet.
If the city is not found, it will indicate that the city was not
found.
o printAllCities(): Prints all the cities that have been added
to the HashSet.
3. Main Method:
o Demonstrates the functionality by adding cities, checking
if a city has been visited, removing a city, and printing all
visited cities.
230
Neu Wk added to visited cities .
Las Angeles added tu visited cities.
Chicago added to visited cities.
New York, has already been visited.
Has visited Chic ago
* true
Has visited Miami? false
Las Angeles removed from visited cities.
Hia«l was not found i- the visited cities.
Visited citiesl
New York
Chicago
Output:
When you run the program, the output will be:
This program shows how to use a HashSet to manage a
collection of unique cities, ensuring that no duplicates are
stored and providing basic operations like adding, checking,
removing, and listing the cities.
231
TreeSet:
Overview:
• TreeSet is a data structure that implements the
NavigableSet interface and stores unique elements.
• It is backed by a TreeMap, meaning elements are stored in
a Red-Black tree.
• Order: Maintains elements in ascending order.
Key Characteristics:
• Duplicates: Does not allow duplicate elements.
• Null Values: Does not allow null elements.
• Performance: Operations like add(), remove(), contains()
have a time complexity of O(log n).
Common Methods:
• add(E e): Adds the specified element to this set if it is not
already present.
• remove(Object o): Removes the specified element from
this set if it is present.
• contains(Object o): Returns true if this set contains the
specified element.
• first(): Returns the first (lowest) element.
• last(): Returns the last (highest) element.
• subSet(E fromElement, E toElement): Returns a view of
the portion of this set whose elements range from
fromElement to toElement.
232
i-ipur L 1-Bva.Util.Set;
inpurt Java.<rtll.TreeSet;
public class TreeSt le {
public static void । ir (String [J args} {
Set<Strlng> treeSet = at TreeSe o(};
if Adding elements to the TreeSet
treeSet. add("D.:;" };
treeset.add("Cdt"};
treeset. add ("Elcplidril.");
if Checking if an element exists
System.out.prlntlh('”■ eeSeL contains 'Cal + tr eeSet. contains ("C. }};
ff Iterating over ttie TreeSet
Sy stem. out. printing' Ti eelet elements nr ted}: j;
fur- (String anlaal : treeset} {
Systea.nut,printlanlwal)j
}
ft Removing an element
treeSet.mow( 'Cat "J;
if Checking the first and last element
System.out.prirttlriFi-tie t treeSet.first(}J;
System.out.printIn( st eler + treeSet.last());
1
}
Example Using Treeset
233
Tr«5et untilns Tat'i true
TreeSet elements (sorted):
Cat
Dog
EleplLdftt
First elenert: Dog
Lui-t element: Elephant
Output:
Key Differences:
• Order:
o HashMap and HashSet do not guarantee order.
o TreeMap and TreeSet maintain elements in sorted order.
• Performance:
o HashMap and HashSet offer average O(1) time complexity
for basic operations.
o TreeMap and TreeSet provide O(log n) time complexity for
operations.
• Null Handling:
o HashMap: Allows one null key and multiple null values.
o TreeMap: Does not allow null keys.
234
o HashSet: Allows one null element.
o TreeSet: Does not allow null elements.
Conclusion:
Choosing between these data structures depends on the
requirements of your application.
Use HashMap or HashSet when you need fast access to
elements without worrying about order. Opt for TreeMap or
TreeSet when you need elements to be sorted.
Understanding these differences is crucial for optimizing
performance and functionality in Java applications.
Overview:
• Purpose: TreeSet is a Set implementation that stores
unique elements in a sorted manner.
• Ordering: Maintains a natural order or a custom order
specified by a Comparator.
• Nulls: Does not allow null elements.
• Performance: Provides O(log n) time complexity for basic
operations.
Internal Working:
• TreeSet uses a TreeMap internally to store its elements.
The elements are stored as keys in the TreeMap, ensuring
that they are sorted.
235
jaua.utiliSrt;
. ■ i Java.trt-lluTreeSet;
plibJl cless It . . ■{
:- ' . ■ (String!J ergs} 4
5et<Strlng> treeSet = <>()>
it iddlng element; to the TreeSet
treeset.add(
treeset.add( );
treeset.addt
treeset.add( ); ■ Duplicate, mill ■ : be added
it Iterating aver tlie TreuSet (Note: The output Is sorted)
system.out. prijHin{ ■
(String fruit : treeSetJ -[
System, out .prlritlnf fruit);
I
it Checking If an element exists in the set
■ treeSet uCMttainsf );
Systwh.out.prljHln( 4 codtalniCherry);
it Removing an elenent
treeset.reao^e( );
tf prittting the Tree
Example:
• Implements the Set interface.
• Uses a red-black tree for storage.
• Does not allow duplicate elements and maintains sorted
order.
236
import java.util.Set;
iaport java.util.Treeset;
public class lair {
public static void (String[] args) {
Set<String> set = new TeeS± o();
set.add( "Banana");
set. add( cple");
set.addf 'o-ange");
Systea.out.println(set ); // outputs: [Apple, Banana, orange]
}
}
Example:
Solution for the practice exercise that involves working
with a HashMap to store students'
names and their grades. The solution includes methods to
add a student and their grade, retrieve a grade by the
student's name, update a student's grade, remove a
student, and print all students and their grades.
237
J awa . irt££ .Map ;
✓ / HashKap to ator« student n<acae-s. as keys and R»xt£r grades as. values
*
Map<String3 Integer studentGrades;
✓ / Constructor to InltMllre thee HashHap
< > -{
studentGrades ।
1
✓ / Method tc add a student and Utter£r~ grade
CString namej grade) £
studentGrades.put(name, grade);
System.out .printing -+- nime •+• -+■ grade);
1
✓ / Method tc retrieve a student's grade t>y *their <iaae
Integer (String nene) £
stodentGrades.get(name);
1
✓ / Method tc update a student's grade
(String name, newGrade) £
(studentGrades .comtainsKey(na«e) ) -[
studentGrades.put(name, newGrade);
Syctaai . out . printing ' n.a»m * -4- n*wCrad») -
> --- <
System .out prlntln( ' ♦ name ♦ );
>
1
✓ / Method to renove a student from the HasJvMap
(String ruamej ■{
(studentGrades .comtainsKey(name) ) -[
studentGrades.reroove(name)j
System .out .prlntln( ♦ name * J-
> --- <
System.out.prlntln( ' ♦ name ♦ );
>
1
// Method to print all students and their grades
( ) •(
System.out .printing >;
(Map. EntryoString, Integers entry : studentGrades. entrySetf J ) •£
System .out println(entry. getKey £> -t- -+• entry .getValue()) ;
>
1
✓ / Main method to demonstrate the functionality
(String £ J args ) £
« * Os
// Axl<l£/ig students amt their grades
studentGrades.addStudent< ' , i r);
studentGrades. addStudent( i >3
studentGrades.addStudent<
// Retrieving u grade
System .out .printlnj studentGrades. getGrade( J >S
/✓ Updating a grade
srudenturaoes.updateuraaei
// Reflaowlinig o student
studentGrades. removeStudent( J;
// Printing ail students and their grades
studentGrades.printAllStudents();
238
Explanation:
1. studentGrades HashMap:
o The HashMap is used to store the names of students (as
keys) and their grades (as values).
2. Methods:
o addStudent(String name, int grade): Adds a student's
name and their grade to the HashMap.
o getGrade(String name): Retrieves the grade of the student
with the specified name.
o updateGrade(String name, int newGrade): Updates the
grade of the specified student.
o removeStudent(String name): Removes the specified
student from the HashMap.
o printAllStudents(): Prints all students and their grades.
3. Main Method:
o Demonstrates the functionality by adding students,
retrieving a grade, updating a grade, removing a student,
and printing all students and their grades.
239
Added Alice grade
Added teb grade
Added Charlie &rwt
Grade Allee:
Updated Bob
Removed Charlie the records.
All .students i their grades:
Alite-: SS
Bbta: nJ
Output:
When you run the program, the output will be:
240
Chapter 11
Iterators and Enhanced For-Loop in JavaIterators
In Java, Iterator and the enhanced for-loop (also known as
the "for-each" loop) are tools that allow developers to
traverse or iterate over collections such as List, Set, Map,
and arrays.
Understanding how to use these effectively is key to
managing collections in Java.
1. Iterators
Overview:
• An Iterator is an interface in Java that provides a way to
traverse through elements in a collection, one element at a
time.
• Iterator is a universal cursor for the Collection framework.
• It is particularly useful when you need to remove elements
from a collection while iterating over it.
Key Methods in Iterator Interface:
• hasNext(): Returns true if there are more elements to
iterate over in the collection.
• next(): Returns the next element in the iteration.
• remove(): Removes the last element returned by the
next() method from the collection.
241
i- port java.utLL.ArrayList;
import J ava. at iL. Iterator;
import Java.atiL.List;
public class IteratorEscaflple {
public static void ■ . (String[) args} {
LiStcStrihg? iiames = itW ArrayLi: <>();
na«es.add( Alict" };
Fiawes.add( “lob"};
naNes.aJdl rC ji lie' );
LteratorcStringj iterator = names.iteraterf);
while iflterator.hasF
*ext(; } {
String ■ant = lteratar.rtext( }■;
System.out.print1n(nane);
// Raativirig an element
If (nane.equals( ■D-.L }) {
iteratorremove (J;
}
}
Sy stem. out. printing List rftei i + ruaes};
}
}
Example Using Iterator With a List
242
Alice
Bob
Charlie
List after removal: [Alice, Charlie]
Output:
Advantages of Using Iterator:
• Removal During Iteration: Iterator allows safe removal
of elements while iterating, which is not possible with the
enhanced for-loop.
• Universal Cursor: Iterator works with most collection
classes (List, Set, Map, etc.).
Disadvantages of Using Iterator:
• Verbosity: More code is required compared to the
enhanced for-loop.
• One-Way Traversal: Iterator can only move forward in
the collection. If backward traversal is needed, a ListIterator
should be used.
• Used to traverse collections.
243
import java.util.ArrayList;
import j ava.util.Iterate r;
import java.util.List;
public class lain {
public static void nair(String!] args) {
*
List<String> list = ne rrai List<>();
list.add( pie };
list.acid( );
Iterator<String> iterator = list.iteratorO;
while (iterator.hasNext()) {
System.out.println(iteratnr.inextO);
}
}
}
Example:
244
■fur ^Type element : ealteetlon) {
ti Use element
}
public class 5in {
public static void main(£tring[] args) {
[] numbers = { , };
for (int number : numbers) -[
System.out.p rintin(n umber);
}
}
J
Enhanced ForLoop (ForEach Loop)
Overview:
• The enhanced forloop is a simplified loop for iterating over
arrays and collections.
It is introduced in Java 5 as a more readable and less
errorprone way of iterating over elements in a collection.
Syntax:
Type: The data type of the elements in the collection or
array.
element: The variable that holds the current element in the
iteration.
collection: The collection or array being iterated over.
Enhanced For-Loop:
• Simplifies iteration over collections and arrays.
Example:
245
■ . ; : :: ■ {
(String[] -args) {
[] nuabers x. {1, t r , J;
If UiLrig enhanced for-locp tn iterate- oirfr the array
( number : ruurberi) {
Sy 5 teia □ dkit, priritliif huhbe-r):
1
}
}
1
2
3
4
5
Example: Using Enhanced ForLoop with an Array
Output:
246
j-awa. dtH .Array List;
■ jBtfa.util.LlSt J
l-'UL'uJ. kLi-z i I ■ !fl- : ' ■ ' . . . ■ ■" £
puhllk ±.LdE..lL VCJlifl |I (String[] args} {
List<5tringj fraits - <>■()»
fruits ..add ( );
fruits >-sdd( ■ );
fruits tidd( );
it iJblug enhai^ed ft: -it>up to iterate a
*
er tns: list
(String fruit : fruits} ■[
Sys cm. out. prlntlnff rul t};
Apple
Banana
Cherry
Example: Using Enhanced ForLoop with a List
Output:
247
Advantages of Using Enhanced For-Loop:
• Simplicity: Less code to write and more readable.
• Less Error-Prone: No need to manage the loop counter
or handle IndexOutOfBoundsException.
Disadvantages of Using Enhanced For-Loop:
• No Access to Index: You cannot get the index of the
current element during iteration.
• No Modification: You cannot modify the collection (e.g.,
remove elements) during iteration. Doing so will result in a
ConcurrentModificationException.
3. Iterators vs Enhanced For-Loop:
Use Iterator when:
• You need to remove elements from a collection while
iterating.
• You want to traverse over a Map. While the enhanced for-
loop can be used to iterate over Map's entry set, Iterator
provides more control.
Use Enhanced For-Loop when:
• You are simply reading the elements of a collection and do
not need to modify the collection.
• You want a concise and readable way to iterate over
arrays or collections.
248
1*73. Lit 11 .ArrayLl & t;
. i .■ l jB7a.irt.ll.Iteritiir;
: port Jfl7a.krt.il .Lilt)
pllbJ 1 kd .■. : ..7:": -: I {
fStririg[J args} {
LlstiStrlngj fiamts = <^0;
nanes.addf };
hanes^addf . );
hanti.add^ Jj;
I Lera tortstrIngi Iterator = rt
*mes.iterator^ );
(iterator.hasHAXtiJ J |
= 1 terator. h£d(};
(riaae.startsWltti^ }) -{
iterator.readvefJ;
}
}
Systerti.eut □prlfttln( ■ । ■:■ + rttees};
}
}
Example: Removing Elements with Iterator vs
Enhanced For-Loop
Using Iterator to Remove Elements
Output
249
Lilt after renoval:
i-ipur-L Jdva.utLL.ArrayList;
. iport
public clan FnharicedrorLc>cjf>Readliig {
publie italic wold train (String[] args} {
ListcString? ruaM = im Array Lis <>();
names..-Bdd( "A. Ice"
names.add( Cj }j
names...add( l lai-lie' );
for (String ruse : noaeM) {
*
Syste .not,prlntld(name J ;
}
Using Enhanced ForLoop to Read Elements
250
Alice
Bob
■Charlie
Output
Conclusion:
• The enhanced for-loop is best for simple iterations where
you just need to read and process elements without
modifying the collection.
• Iterator provides more control and is necessary when you
need to remove elements during iteration. Understanding
both tools will allow you to choose the most appropriate one
for your specific needs.
251
import java.util.ArrayList;
import java.util.List;
public class lair {
public static void main(String!] args) {
List<String> list = nen rrai List<>();
list.add( jplE1');
list.add( );
for (String fruit : list) {
System.out.p rintin(fruit);
}
}
Chapter 12: Generics
Generics in Java
Generics in Java allow you to write flexible, reusable, and
type-safe code. Introduced in Java 5, generics enable
classes, interfaces, and methods to operate on types
specified by the programmer, enhancing the language's
expressiveness and robustness.
1. What are Generics?
Generics provide a way to parameterize types, enabling you
to create classes, interfaces, and methods that can operate
on any specified data type. This removes the need to write
multiple versions of the same code for different data types,
thus promoting code reusability and type safety.
Enable types (classes and interfaces) to be parameters
when defining classes, interfaces, and methods.
Example:
252
Jftva^utlL.ArrayLlst;
■ ■ ■ ■ {
(String[] args) {
■■ ■ = 'in ();
Ust.adtf( Hel );
list.add{ ); ... . I : r. = $—
(Object c
*1 : list) (
Str11it ■ (String.) abj; If Cluses CLsssCastExuptlan at runtlae
Sy stea □ cut. printl iif str )■;
1
}•
}
Example Without Generics:
In this example, list is an ArrayList that can store any type
of object. If you accidentally add an Integer to this list and
later try to cast it to a String, you'll get a
ClassCastException at runtime.
253
Example With Generics:
Here, ArrayList<String> specifies that the list can only
contain String objects. Any attempt to add an incompatible
type will cause a compile-time error, preventing potential
runtime exceptions.
254
Benefits of Generics
• Type Safety: Ensures that only a specific type of data is
added to a collection or used in a method.
• Elimination of Casts: No need to cast objects when
retrieving them from a collection.
• Code Reusability: Write general algorithms that work on
various types without code duplication.
3. Generic Classes
A generic class is defined with a type parameter. This type
parameter can be used as a placeholder for any data type.
Syntax
T is a type parameter that can be replaced by any class or
interface type.
255
l: <r> <
. :■ 1 value;
. fT value J {
Lh Is □value = value;
J
■ 1 1 O {
return value;
pdhliL stat It VQld tuiirl (stringL) args} {
tku0iIhfcegB££ IrttBox - <>{);
IntB&K.setValoaf );
Systert.out.printint + mt Hot. jjetvalue-i J};
Box<Strlng> strSov -
strB&K. setvalij-ef );
Systerf. .out. print In t + strHci
* *{
, g±tValu J j;
>
J
Integer .j±j 12
String Value: Helle
Example: Generic Box Class
Output:
In this example, Box<T> is a generic class that can hold any
type T, which is specified when creating an instance of Box.
256
<T> (T p-aranj ■[
l( Method twdy
}
4. Generic Methods
A generic method is a method that can operate on objects
of various types while being declared in a generic or
nongeneric class.
<T>: Denotes the type parameter. This can be any name
but typically uses single letters like T, E, K, or V.
257
li . . : : (
■ -■ ' *£> (T[ ] array, i, Jj f
- array]!];
array]1] = JFWtftjjl
array]j] ■ temp;
}
(String!] args) t
Integer] ] IntArray - { , , > };
swap (JjitArray, , )j
■ ■ [ i i UitArray) {
Sys tea □ nut .print (L);
}
System.odt.prlrttln{
String.]] str Ar ray = ■{ * f , };
swaptstrArray., . };
(String s i strArray) {
Sy51ea.out .print(s +■ );
}
}•
}
*
32
1
C B A D
Example: Generic Method for Swapping Two Elements
Output:
258
<T tfctsriil-i- SuperCLin-ii fi 1 nuit be a subeless &f Sk^terOais
<T s -[
T njlue;
(T 'raluej {
Ui-b.veLue - vftluie;
}
jjjlli ■■■■_! I : () {
Systeffl.Gut.pflfltlnf + valuejj;
}
puh±lL. static vdld Halt (String[j args) f
Buutjid'E>.-iBple<lntegei-!> intObj = <>( );
iritDbj L<Jisplav():
li BMHBlEiaHpilecStrlhg> StFCbj - flew JLUUbd Ek ditip] e<>('Mellb" , fi Cbtn|H4e-Limit erra
}
)
The swap method works with any array type, whether it's an
Integer[] or a String[].
5. Bounded Type Parameters
Sometimes, you want to restrict the types that can be used
as arguments in a generic class or method. Bounded type
parameters allow you to enforce such constraints.
Syntax:
Example: Bounded Type Parameter in Generic Method
259
Value; L0
public void print List(Lists J> liit) -[
for (Object elea : list) {
Sy Eten.out.pr1ntln(elem};
>
}
Output:
In this example, the class BoundExample<T> only accepts
types that are subclasses of Number, such as Integer or
Double.
6. Wildcards in Generics
Wildcards are used in generics to represent an unknown
type. They are particularly useful when you want to express
that a method can accept or return multiple types of
objects, but the exact type isn't known.
Types of Wildcards:
1. Unbounded Wildcard (?): Represents any type.
2.Upper Bounded Wildcard (<? extends T>):
Represents a type that is a subclass of T.
260
(LlSKi
* Mrt^fkds Number> Hit) {
- (Humber n ; List) ■{
Sys tea L tiut □ printInfn};
>
}
public i/oid addNufftersfLlatsJ supti- Integer; list) -{
llst.£dd(10};
3.Lower Bounded Wildcard (<? super T>): Represents a
type that is a superclass of T.
261
: port lava.utLL.Array List;
. ipuit Java.utlLAist;
public class WildcardExample {
public static void prlntList(Llst<?> list) {
for (Object tie
* : list J {
SystM.aut. printingelen);
}
}
public static void dal (String[] args} {
List<liiteger> intLlst =. new Arr yLli <>();
intLlst,add(i);
intLlst,Bdd(l);
intList,add( );
List<String> strLlst - irn ArriyLis
strLlst,Bdd( };
strLlst,add(
strLlst,add("C ]j
prlntLlst{iritLlst}; a Mirka with a list of any type
print L Lst( str List};
}
}
Example: Using Wildcards
262
Output:
263
<k. v> -[
K j.eLKeyO;
Cldi S Cird«-«Btaik'<KJ V> InplemelltS P
*
ir<kj V> {
K key;
V value;
. i.. ff key, V value) {
this,key r key;
thlj
*e
yal ■ value;
}
.i K () -{ - ei. key; }
.i V .■ () { :■'. ■ valoe; }
.i ■ t£ J. (String^] args} ■[
Palr<Stririg, Integers pl = <>( Ji , jt;
5y st ere. cut. printing + pl. getKey{ J + ..■■ + pl.getValue()) ;
Palr<Stririg, Strings pl = <>( , );
Sy st ere. cut. printing + pl. getKey{ J + alu t pl.getValue()};
}
}
Generic Interfaces
Just like classes and methods, interfaces can also be
generic.
Example: Generic Interface
264
Output
8. Type Erasure
Java generics are implemented via type erasure, which
means that the type parameter information is removed
during compilation. This process ensures backward
compatibility with non-generic code.
• Consequences of Type Erasure:
o You cannot use primitive types as type parameters. Use
wrapper classes like Integer, Double, etc.
o You cannot create instances of a generic type (e.g., new
T() is not allowed).
o Runtime exceptions related to generics, such as
ClassCastException, can still occur.
265
LlSt< > list = H <>Oi i.Cirrq l-t-: lii...........■
I[] array ■ new T[10]; H Coepile-tine error
Limitations of Generics
• No Primitive Types: You cannot use primitives as type
arguments.
No Generic Arrays: You cannot create an array of a generic
type.
Type Erasure: Generic types do not retain their type
information at runtime, which may lead to some issues
when working with reflection or serialization.
266
public class lain {
public static <T> void printArray(T[] array) {
for (T element : array) {
system.out.p rintin(element};
1
}
public static void (String[] args) {
Integer[] irrtArray = { , , };
String[] strArray = { ■ 3ple,’J ■Banana11};
printArray{intArray); // outputs: 123
printArray(strArray); H Outputs: Apple Banana
}
}
Generic Methods and Classes
Generic Method:
267
public class Bax<T> {
private T item;
public void sei (T item) {
this.item = item;
}
public T getltem() {
return item;
}
}
public class 'lair {
public static void i (string[] args) {
Box<String> stringBoK = new Box<>();
stringBox.set!tem( 'Apple );
System.out.println(stringBox.getItea()); H Outputs: Apple
*
BoxcInteger: intBox = new <>();
intEox.set!tem( ?);
System.out.println(intEox.getltemO); // Outputs: 123
Generic Class:
268
public class Hain {
public static <T extends Nimber> void printDoubleVal (T number) (
System.out.printLn(number.doubleValue());
}
public static void (string[] args) {
printDoublevalue(123).; // outputs: 123.0
printDoubleVailue(-E , j }; // Outputs: 45,67
}
}
Bounded Types
Bounded Type Parameters:
• Use bounded type parameters to restrict the types that
can be used as type arguments.
Example:
269
Chapter 13
Multithreading and Concurrency in Java
Multithreading and concurrency are critical concepts in Java
that enable the execution of multiple tasks simultaneously,
improving application performance and responsiveness.
Java provides robust support for multithreading and
concurrency, allowing developers to write applications that
can efficiently manage multiple tasks.
1. Introduction to Multithreading
Multithreading refers to the ability of a CPU (or a single
core in a multi-core processor) to provide multiple threads of
execution concurrently, supported by the operating system.
Each thread represents a separate path of execution.
Key Concepts:
• Thread: A lightweight process that can run concurrently
with other threads within a single process.
• Concurrency: The ability of a program to execute
multiple tasks simultaneously.
• Parallelism: The simultaneous execution of multiple
tasks, often on different processors or cores.
2. Creating Threads in Java
Java provides two primary ways to create and start a thread:
2.1. Extending the Thread Class
The simplest way to create a thread is by extending the
Thread class and overriding its run() method.
270
■ " {
^thierrLde
i O ■{
Sy sterti. out. print in ( 1;
}
pulkltt itaLLe Wflld rjjlr (StringEJ argij {
- 0;
thread.itart(>; ■:■•: .■■ '. th« tnrejd
}
}
.. : . ..11.. . {
eoverrldfr
■ □: ! - ■ . () {.
System,out.prlfltln^ . );
}
PJul-ILl blzatlc void u (StringE] args) {
ThnSjid :iir-eUI " hew Tfii'elid(rt£»l NyHlMttubl'.()))
threadjitiftO; Star ■. the thread
}
}
Implementing the Runnable Interface
Another common way to create a thread is by implementing
the Runnable interface, which has a single run() method.
271
3. Thread States and Lifecycle
A thread in Java can be in one of several states during its
lifecycle:
• New: A thread that has been created but not yet started.
• Runnable: A thread that is ready to run or currently
running.
• Blocked: A thread that is waiting for a monitor lock to
enter a synchronized block/method.
• Waiting: A thread that is waiting indefinitely for another
thread to perform a particular action.
• Timed Waiting: A thread that is waiting for another
thread to perform a specific action within a time limit.
• Terminated: A thread that has completed its execution.
4. Synchronization in Java
Synchronization is the process of controlling access to
shared resources by multiple threads to prevent race
conditions.
4.1. Synchronized Methods
You can synchronize a method by using the synchronized
keyword. When a method is synchronized, only one thread
can execute it at a time for a given object.
272
{
P’lvdte 1’il UMJtflt ■ tJJ
p'j-Ll.. .- ■* »!."
*• « i. . () {
tOLint-H-J
}
(J {
taunt;
}
}
: 1 I v.; Lt . a ;
: j1 ! . ■ (} {
.ip ■ -iLzclJ (this} {
c&uflt-w;
}
}
. {J {
il- ib count;
}
]
Synchronized Blocks
For more finegrained control, you can synchronize a specific
block of code within a method.
273
Inter-Thread Communication
Java provides several ways for threads to communicate with
each other: 5.1. wait(), notify(), and notifyAll()
Methods
These methods are used for communication between
threads. They must be called from within a synchronized
block or method.
• wait(): Causes the current thread to wait until another
thread invokes notify() or notifyAll() on the same object.
• notify(): Wakes up a single thread that is waiting on the
object's monitor.
• notifyAll(): Wakes up all threads that are waiting on the
object's monitor.
274
(
Itoa;
1 vale
( Itea) Intarruptedtxceptlon {
(available) (
->«();
)
thls.lUa - Itea;
available - ;
Systee.out.printing * Itea);
notifyC);
() IntarmptedEueptlaa {
(1available) {
)
available - ;
Systee.out.prlntln< * ItM);
Itea;
■ ;.... . «r i.-oi.• (
SfiareeRatouroa r-eiource;
(SharodResar-ce resource) (
■ bi. .rescarce • resource.;
)
^Override
..<.<• 11. H. Id <) (
( - ; 1 < ; !>♦> (
try (
resource. prodace-( 1);
) <Interruptedfxceptlon o) {
nroad.arrentThreadO .lnt«m(it();
)
}
)
>
< ............... Uvl. • .' i {
ShareCRaeourcai resource;
(SharedReuiurce resource) (
ihls.rasMrce • resource.;
)
(Dv urrlde
«ut>ll. ..Id <) (
( - 1 < ; 1h) (
Uv (
resource. constevO;
) < InterruptadtxceptAon e) (
Tbread.current Thread!) -Interrupt!);
1
)
)
>
Example: ProducerConsumer Problem
275
(SETlngn args] (
- C frMourcaJiJj
■ C (resource));
pradtacarHbftiad .ttar£< j.
CDMuaflrTOniMi.-Lt a"tC);
1
}
Deadlock
A deadlock occurs when two or more threads are blocked
forever, waiting for each other to release resources. To avoid
deadlocks:
• Acquire resources in a consistent order.
• Use tryLock with a timeout to prevent indefinite waiting.
276
£
-synchronised void method <B b) £
System, out .prlntln( -z-_ );
try £
Thread.sleep(. );
} _ (InterruptedExceptiom e) £
>
b.last();
J
i I .1 1 nil. : ,'U id () £
System.out.prlntln( );
J
i.ass • {
(A a) £
System.out.prlntln( -z-_ );
try £
Thread.sleep(. );
} _ (InterruptedExceptiom e) £
>
a.last();
J
. 1 i uni . .. . - () £
System.out.prlntln( >;
J
>
pubi 1: tl . !'ps.......... ■- Hli: ' {
= '» 0;
: = nt-w B();
DeadlockExaapleO {
= (this);
t.start();
a.methodA(b);
J
UUt’IiL . () £
b.method0(a);
(String[J args) {
J o
}
Example of a Deadlock
277
i' part lava.ut 11 lcancurrent.ExecutarServlet;
. ipoi-t Java.utlL.concurrent. Executars;
public class ExecutorExample {
public static wold । . (String[] args} {
r -. । S-.- : ■ e - Exeeutar-i.fteuFl»edThreadPMl(2);
Runnable taskl ■ (} -> Systen.aut.prlntlri("'ra£k 1 «j<acuted");
Runnable task! ■ (} -> Sy&ten.aut. printing'"Task 2 ejeecuted");
eveeutcr. submit^ taskl^
executor.submit^task!)j
executor.shutdown^};
>
}
7. Concurrency Utilities
Java provides a java.util.concurrent package that includes
high-level concurrency utilities, such as:
7.1. Executor Framework
The Executor framework provides a way to manage a pool
of threads to execute tasks asynchronously.
• ExecutorService: Interface that provides methods to
manage the termination and track the progress of
asynchronous tasks.
• Executors: Factory methods for creating thread pools.
278
iaport Java.util.concurrent.Callable;
poi t J ava.utLl.concurrent. Execu tloiiExcept ion;
pui L Java.util.concurrentsExecutertervice;
. ipurL Java.util.concurrents Executors;
pui L Java.util.concurrents Future;
publ1c Clal; . .a {
public it.Lj.ic void . (String[] -args} {
I r Se e = Executors.neNFlxeafThreadPoolf 2);
Callableclntegerj task *
{}-;{
return 121;
i;
Future<Tnteger> future ■ executor.iuL
*ilt( task) [
try {
Systeu.out. printing r.Hi... + futuresget;)};
} eatt (InterruptedException | ExecutlonException e) {
e.printstacklrace{);
} finally {
exec utor. shutdowii ();
}
1
}
Future and Callable
The Callable interface is similar to Runnable, but it can
return a result and throw checked exceptions.
The result can be retrieved using a Future.
279
* a. util. eancurr an t»lock 5. Lack;
ja
■ J a*. util, concurrent .leeks,-Reentrant Lock;
I2i_! □ j . l i . {
□ ■TlVdte ■,l"jll . = ll?H - Sr -: 1 l :.l : !.i (
:!,LVolK ™ ;
: ji: J 11 - :: . - i (} {
lockul<Kk(};
■r. <
*-]';
count
1 {
lrMk..uhl«k( ) p
}
J
() {
eaurit;
J
}
Locks
ReentrantLock provides explicit lock management, with
more advanced features compared to synchronized blocks.
280
Java□u tilL concurrent□ atonic. fit curl clntegtr;
i-l:- .. . . ■ . . {
■ ■ ■ ■ ■ ■ ■ ()j
ptfbll lj () -[
count j IrtCreftwimridGetO;
}
■ I (J {
count.get-();
}
}
■Ik
Atomic Variables
Atomic variables like AtomicInteger provide a lock-free and
thread-safe mechanism to perform atomic operations.
281
Conclusion
Understanding multithreading and concurrency in Java is
essential for building high-performance applications. Java
provides a rich set of APIs and utilities to help you manage
threads effectively, ensuring your programs run smoothly
even when performing complex, concurrent tasks. By
leveraging these tools and techniques, you can avoid
common pitfalls such as race conditions, deadlocks, and
inefficient thread management.
Threads:
• A thread is a lightweight process.
• Java provides built-in support for multithreading through
the java.lang.Thread class.
Creating Threads (Runnable and Thread Class)
Using Runnable Interface:
282
class MyRunnable implements Runnable {
public void rur() {
System.out.printIn( mead is running );
1
}
public class lair {
public static void (String[] args) {
Thread thread = new Thread (new MyRunnableQ);
thread.start()j
1
}
Using Thread Class:
283
class HyTtiread extends Thread {
public void rur() {
System.out.printlnf i is rurr );
}
}
public class Hair {
public static void ■ain(string[] args) {
My Thread thread = new M/Threadf);
thread.start();
1
J
284
class Counter {
private int count = 0;
public synchronized void increment() {
*-;
count-
>
public int getcount() {
return count;
public class Main {
public static void nair.(String!] args) <
Counter counter = new Counter();
Thread tl = new Thread(() -> <
for (int i = e; i < 1006; i+-+) <
counter.increment();
}
});
Thread t2 = new Thread(() -> <
for (int i = e; i < 1006; i-*•) <
counter.increment();
}
});
tl.start();
t2.start();
try {
tl.join();
tz.join();
} catch (interruptedException e) {
e.printStackTrace();
}
System.out.println( Count: " + counter.getCount()); // Outputs: 2000
Synchronization:
• Ensures that only one thread can access a resource at a
time.
Example:
285
inport j ava.util.co ncurre nt.Exec utorSe rvice;
i--port java .util.toneurrent.Execiitars;
public class lain {
public static void (string[] args) {
= Executors.newFixedThreadPooH );
= ()->{
System.out.println( . running");
>;
= ()->{
System.out.printin( ask 2 is runnin );
>;
executor.exe c ute{t askl);
executor.exe c ute(t ask2);
executor.shutdown{);
Concurrency Utilities (ExecutorService, Future, Callable)
ExecutorService:
• A higherlevel replacement for managing threads.
Example:
Callable and Future:
• Callable can return a result and throw a checked
exception.
286
import java.util.concurrent.callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executorservice;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class lain {
public static: void (String[] args) {
= Executor s. new FixedTtire ad Poo );
Callable<Integer> task =()->{
return 12Z;
Future<lnteger> future = executor.submit(task);
try {
= future.get();
Systern.out.prirrtln("Result: " +■ result); // Outputs: Result: 123
} catch (interruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
• Future represents the result of an asynchronous
computation.
Example:
287
(parameters) -> expression
(parameters) -> { statements; }
import java.util.Arrays;
inport java. util.List;
public class lair {
public static old (string[] args) {
List<String> list = Arrays.asList( Lile"j j );
// Using a lambda expression to iterate over the list
list.forEach(fruit -> system.out.printin(fruit));
}
Chapter 14: Java Features
Lambda Expressions:
• Provide a clear and concise way to represent a method
interface using an expression.
• Enable treating functionality as a method argument or
treating a code as data.
Syntax:
Example:
288
import java.util.Arrays;
irport java. util.List;
irport java. util.stream.Collectors;
public class lair {
public static void (String[] args) {
Listcstring> list = Arrays.asList( pie", , ige );
// Using Streams to filter and collect
ListcString> filteredList = list.streamf)
.filter(fruit -> fruit.startswith( ))
.collect(Collectors.toList());
System.out.printLn(filteredList); H Outputs: [Apple]
Streams API:
• Provides a new abstraction to process sequences of
elements.
• Supports operations such as filter, map, and reduce.
Example:
289
gFunctionaiInterface
interface h'.yFuncticriallnterface {
void p : (string message);
}
public class Main {
public static void (string[] args) {
// Using a lambda expression with a functional interface
= message -> system.out.printin{message);
printer.printMessage( HellOj World! );
}
}
Functional Interfaces:
• An interface with exactly one abstract method.
• Used as the basis for lambda expressions and method
references.
Example:
290
interface r-‘. Interface {
default void defaulf.ethod() {
system.out.printing rhis is a default metho );
}
}
class MyClass implements Mylnterface {
// Myclass can override def a Lilt Met tod if needed
}
public class lair {
public static void (String[] args) {
Myclass clas = new ' classQj
my Class, defa Lilt Het hod(); // Outputs: This is a default method
}
}
Default and Static Methods in Interfaces
Default Methods:
• Allow adding new methods to interfaces without breaking
the existing implementation.
Example:
291
interface MjIrcerface {
static void staticr-ethcc () {
System.out.printing is is a static " );
}
}
public class Hain {
public static void (string[] args) {
My In ter face, st at icMettiodOs H Outputs: This is a static method
}
}
Static Methods:
• Can be defined in interfaces and accessed without an
instance.
Example:
292
Part III: Advanced Java
293
import j ava.net.MaIformedURLExc eptio n;
irport java.net.URL;
public class Mair {
public static void (String[] args) {
try {
URL url = new url("https://www.example.com");
System.out.printing Pre oc + url.getProtocol());
System.out.p rintin( + url.getHost());
system.out.p rintin( + u rl. get Port ());
System.out.println( File + url.getFilef));
} catch (HalformedURLException e) {
e.printstackTrace();
}
}
Chapter 15: Java Networking
Introduction to Networking in Java
Networking:
• Java provides support for networking through the java.net
package.
• Commonly used classes include URL, URI, Socket,
ServerSocket, and DatagramSocket.
Working with URLs and URIs
URLs and URIs:
• URL represents a Uniform Resource Locator, a pointer to a
resource on the web.
• URI represents a Uniform Resource Identifier, a string of
characters used to identify a resource.
Example:
294
Sockets and ServerSockets
Sockets:
• Provide a way for communication between two machines.
• Socket class is used for clientside, and ServerSocket class
is used for serverside.
Example (ClientServer Communication):
Server:
295
import java.io.
*;
inport java.net.serversocket;
import java.net.socket;
public class Ser.er {
public static void (String[] args) {
try (serversocket serversocket = new serversocket(izz-)) {
System.out.printing er is listening on port 123- J;
while (true) {
socket sock; = serversocket.accept();
new serverTtiread(socket).start();
}
} catch (lOException e) {
e.printstackTrace ();
}
}
class ser.erThread extends Thread {
private socket socket;
public Ser erThrea (socket socket) {
this.socket = socket;
}
public void rur() {
try (BufferedReader input = new BufferedReader(new lnputstreamReader(socket.getlnp
Printwriter output = new Printwriter(5ocket.get0utputstream(), )) {
string message;
while {(message = input.readLine{)) 1= mil) {
System.out.printin( deceived: + message);
output.printin("Echo: ‘ + message);
}
} catch (lOException e) {
e. printstackTra ce ();
}
}
}
296
import java.io.
*;
inport j ava.net.So c ket;
public class Client {
public static void i (string[] args) {
try (socket socket = new socket("localhost \ 1234);
Printwriter output = new PrintWrite r( socket. getOutputStreami(), true);
BufferedReader input = new Buffered Reader (new lnputstreamReader(socket.getlnp
BufferedReader console = new Euffe red Reade r( new InputStreamReade'(System.in))
string userinput;
rhile {{userinput = console.readLine()) != null) {
output.println(userlnput);
System.out.printin(input.readLine());
}
} catch (lOException e) {
e.printStackTrace();
}
}
Client:
297
impart j ava.net.Datagram Packet;
iaport java.net.Datagramsocket;
iaport java. net. met Address;
public class lain £
public static void (String[] args) £
try {
DartagramSocket socket = new DatagramGocketO;
= ello, world ;
byte[] buffer = message.getBytesO;
inetAddress address = InetAddress.getByName{ calhost1");
DartagramPacket packet = new Datagrampacket(buffer, buffer, length address., 123
soc ket.send(pa c ket);
H Receive response
buffer = new byt [ B24];
packet = new DatagramPacI (buffer, buffer.length);
socket.receive(packet);
= lew (packet.getDataQ, , packet.getLength());
System.out.println('Receive + received);
soc ket.closed;
} catch (Exception e) £
e.printst ackTra ce();
}
}
}
Datagrams and Multicast Sockets
Datagrams:
• Used for sending and receiving packets.
• DatagramSocket is used to send and receive datagram
packets.
Example:
298
import j ava.sql.connection;
iapcrt java.sql.DriverManager;
iaport java.sql.SQLException^
public class Main {
public static void (String[] args) {
String iirl = "jdbc:mysql://localhost :B306/n<ydataba5e";
string use = root'j
string pass = passwo ;
tr { = DriverManager.getccinnectionfurlj user, password)) {
System.out.printlnf netted to the data! J;
} catci (SQLException e) {
e.printstackTrace();
}
}
}
Chapter 16: Java Database Connectivity (JDBC)
Introduction to JDBC
JDBC:
• Java API for connecting and executing queries with
databases.
• Consists of interfaces such as Connection, Statement,
PreparedStatement, and ResultSet.
Connecting to a Database
Example:
299
import java.sql.connection;
import j ava.sql.Dr iverMa n ager;
i■port j ava.sql.Re 5ultSet;
uport java.sql.SQLException;
import j ava.sql.st atement;
public class lair {
public static Void (String[] args) {
String url = "jdtic:mysql://localhost:330E/nydatatiase";
string user = "root";
String = cis. : ;
try { = DriverManager.getconnectionfurl, user, password)y
= connection. createstatenient()) {
H Execute a query
Resultset resultset = statement. executeQueryf"SELECT * FROM mytable");
H Process the result set
while (resultset.nextf)) {
System.out:.println("ID +■ resultset. getlntf id ));
Sy stem. out:, printin J ai"; + resultset. getstring( name ));
}
} Catch (SQLException e) {
e.printstackTrace();
}
Executing SQL Queries
Example:
300
import java.sql.Connection;
inport j ava.sql.Dr iverMa n ager;
import j awa.sq1.Fre pa redst a terne nt;
inport java.sql.SQLException;
public class Mair {
public static void ■ain{String[] args) {
String url = ''jdbcimysql://localhost:330
Prepared Statements and Transactions
Prepared Statements:
• Used to execute parameterized queries.
• Prevents SQL injection attacks.
Example:
301
Part III: Advanced Java
302
import javax.swing.
*;
public class 'lair {
public static void (String[] args) {
IFrame frame = new JFrameC'HellQ Swing");
JLabel label = new ILabelfHellOj World!");
frame.add(label);
frame.setsizef ± );
frame.setDef amltCloseOpe ration (3 Franie.EXIT_ON_CLCSE);
frame.setvisible{true);
}
}
Chapter 17: Java GUI Programming
Introduction to AWT and Swing
AWT (Abstract Window Toolkit):
• Part of Java Foundation Classes (JFC).
• Provides a set of APIs for creating graphical user
interfaces.
• Components are heavyweight.
Swing:
• Extension of AWT.
• Provides a richer set of GUI components.
• Components are lightweight.
Example:
303
import javax.swing.*
;
irport java.awt.
*;
public class lair {
public static void (String[] args) {
IFraae fra«e = new 1 Fir ante ("Calculator");
frame. set Layout (-e.. ());
JTextField display = new 3TextField();
frame.add(display, BorderLayout.NORTH);
= ();
panel, set Layout s (-j -));
String[] buttons = {
"7", "S", T,
"4", "5n, "6",
"I", "2", "3",
nr n if_ii bi .if
J "J — J
>;
for (String text : buttons) {
panel.add(ne.. lEutto (text));
1
frame.add(panel, BorderLayout.center);
frame.setSize( , };
frame.setDefaultCloseOpe ration{JFran
*e.EXIT_OM_CLOSE );
frame.setvisible(true);
}
}
Building GUI Applications with Swing
Example:
304
Event Handling
Event Handling:
• Mechanism to handle events like button clicks.
• Uses event listeners and event sources.
Example:
305
*;
import javax.swing.
import java.awt.
*;
public class lain {
public static void (String[] args) {
OFraae frame = new J Frame("Layout Manager Example");
frame. setLayaut(-e'.. ());
frame. add(ne.. ( ~tn ), BorderLayout.NORTH);
frame. add(ne.. ( 'Sou ), Border Lay out. SOUTH);
frame. add(ne.. ( 'East"), BorderLayout.EAST);
frame.add(nt . JEuttonf .est"), BorderLayout.WEST);
frame.add(nc.. 3El ('Teirter ), EorderLayout.CENTER);
frame.setSizef , );
frame.setDefault€loseoperation{JFrame.exit_on_clcse);
frame.setvisible(trLE);
}
}
Layout Managers
Layout Managers:
• Used to arrange GUI components in a container.
• Common layout managers include BorderLayout,
FlowLayout, GridLayout, and BoxLayout.
Example:
306
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.stage;
public class Main extends Application {
^Override
public void start(stage stage) {
Label label = new Label("Hello, DavaFX!");
Scene scene = new Scene(label, 300, 200);
stage.setscene(scene);
stage.setTitle("JavaFX Example');
stage.show();
}
public static void main(string[] args) {
launch(args);
}
Chapter 18: JavaFX
Introduction to JavaFX
JavaFX:
• Modern Java framework for building rich GUI applications.
• Replaces Swing and AWT.
• Supports 2D and 3D graphics, audio, and video.
Building GUI with JavaFX
Example:
307
import javafx.application.Application;
import j avaf x. bean s. prope rt y. Do u blePro perty;
iaport j avafx.bean s.prope rty.SiapleDo u bleProperty;
inport javafx.scene.Scene;
inport j avaf x. s c ene. c ontrol.slider;
irport javafx.scene.control.TextField;
inport javafx. scene. layo lit. VBox;
inport javafx.stage.Stage;
public class Main extends Application {
^Override
public void st^'t{Stage stage) {
= , );
TextField textField = new Tex±Field();
DoubleProperty sliderValue = new SiBpleDoublePropertyO;
slidervalue.bind(slider.valueProperty ());
text F ield.textproperty().bind(slide rvalue.a sStri ng( ’f ));
= c (slider, tertField);
scene scene = ne.. see (root, 3( , 2fl );
stage.s ets ce ne(s ce ne);
stage.setTitle("lavaFK Properties and Bindings");
stage.show{};
pitolic static void (String[] args) {
launch(args);
JavaFX Properties and Bindings
Properties and Bindings:
• JavaFX properties enable observing changes to an object's
state.
• Bindings connect properties so changes in one reflect in
another.
Example:
308
impart javafx.application.Applic atio n;
iaport j avafx.fxml.fxml Load er;
iaport javafx.scene.Parent;
iaport javafx.scene.Scene;
iaport javafx.stage.Stage;
public class Main extends Application {
^override
public ■. :id stpitfstage stage) throws Exception {
Parent = FXMLLoader.load(getClass().getResoiirce( lyoiit.fxrtl });
Scene scene = ne1 (root);
stage.setscene(scene);
stage.setTitle( FX L Example );
stage.show();
public static void (string!] ares) {
launcliCargs};
}
}
FXML and Scene Builder
FXML:
• XMLbased language to define the user interface.
• Scene Builder is a visual layout tool for designing JavaFX
applications.
Example:
• Main.java:
309
ckxiol ¥ersion="1.0" encoding="UTF-8"?>
c’import javafx.scene.control.Label’1}
c’import j av afx.see n e.layout.VEox ’ >
cvbox : :fx=" http://javafK.coa/fxnil" fx:controLler='rcontroller,'>
(Label = F />
</VEOX>
c’xnd version="l.e“ encoding="UTF-8"’>
<’import jav afx. see n e. co nt r ol. L a bel ?>
<? import javafx. scene.layout.VEox ? >
<ybox i :fx="http://javafx.coa/fxml" fx: controlLer='rcontroller,'>
<l_abel texU'HellO; FXHL!" />
</VB0X>
public class Controller ■{
// controller logic can be added here
}
layout.fxml:
Controller.java:
310
inport java.io.10Exception;
inport javax.servlet.servletException;
inport javax.servlet.annotation.webservlet;
iaport javax.servlet.http.Httpservlet;
iaport javax.servlet,http.HttpServletRequest;
iaport javax.servlet,http.HttpservletResponse;
gwebservlet("/hello")
public class HelioServlet extends HttpServlet {
protected void oGet(HttpservletRequest request, HttpservletResponse response) throws
response.eetwriter().println( -ello, servlet );
}
}
Chapter 19: Web Applications with
Java
Introduction to Java EE
Java EE (Enterprise Edition):
• Set of specifications extending Java SE with specifications
for enterprise features such as distributed computing and
web services.
Servlets:
Java programs that run on a server and handle client
requests.
Extend the capabilities of servers that host applications
accessed by means of a requestresponse model.
Example:
311
page language="java" coirtentType="text/ht«l; charset-UTF-s" pageEncoding^'UTF-S"I>
<! DOCTYPE
<head>
<title>Hello JSP</titLe>
</head>
<body>
■thliHellOj 0SP!</hl>
</body>
JavaServer Pages (JSP)
JSP:
• Technology that helps create dynamically generated web
pages based on HTML, XML, or other document types.
• Allows embedding Java code directly in the HTML.
Example:
• index.jsp:
312
import org.s pringfr a mewo rk.boot.SpripgAppli cation;
import org.Spring-Framework.boot.autoconrfigure.SpringBootApplication;
iaport org.springfranework.web.bind.annotation.GetMapping;
import org.s pringf ramework.web.bind.a nnotat io n.Restcontro'ller;
gspringBootApplication
public class Application (
public static void (String[] args) {
Spri ngAppli c a tio n.run(Application.classa rgs);
}
}
^RestControl1er
class Hellocontroller {
@GetMapping("/hello")
public String () {
return "HellOj Spring Boot J"j
1
J
Building Web Applications with Spring Boot
Spring Boot:
• Framework for building production-ready applications
quickly.
• Simplifies the configuration and setup of Spring
applications.
Example:
• Application.java:
313
Chapter 20: Design Patterns
Introduction to Design Patterns
Design Patterns:
• Solutions to common problems in software design.
• Can be classified into creational, structural, and behavioral
patterns.
Creational Patterns
Singleton:
• Ensures a class has only one instance and provides a
global point of access.
Example:
314
interface Shape {
void drav();
}
class Circle implements Shape {
public void draw() ■[
System, out. println("’Dra..ing circle");
class square implements Shape {
public void draw() ■[
System.out.println("Drawing Square );
}
}
class ShapeFactory {
public Shape getshaoe(String shapeType) {
if (shapeType.equals("ClRC_ ")) {
return new Circle();
> else if (shapeType.equals("SQUARE )) {
return new Square();
return null;
}
}
public class Main {
public static void main(string[] args) (
ShapeFactory ShapeFactory = new ShapeFactory();
Shape s = ShapeFactory.getshape( CIRCLE );
shapel.draw();
Shape shape2 = ShapeFactory.getshape( square );
shape2.draw();
}
Factory:
• Defines an interface for creating an object but lets
subclasses alter the type of objects that will be created.
Example:
Builder:
315
• Separates the construction of a complex object from its
representation. Example: 316
class User £
private final String firstMame;
private -Final String LastNaoe;
private -Final int age;
private -Final String address;
private user(userBuilder builder) £
this .firstNanie = builder.firstName;
this.lastName = builder.LastName;
this.age = builder.age;
this.address = builder-address;
public static class userBuilder £
private String firstName;
private String lastName;
private ini age;
private String address;
public UserBuilder setFirstNane(String firstName) £
tliis.firstNa»e = firstName;
return this;
Il-
public UserBuilder setLastNarne(String lastName) £
this-lastName = lastName;
return this;
Il-
public UserBuilder setAge(int age) £
this-age = age;
return this;
Il-
public UserBuilder setAddress(String address) £
this-address = address;
return this;
Il-
public user build() £
return new user(this);
public class Main £
public static void main(string!] args) £
User user = new user.UserBuilder()
.setFirstName( John")
.setLastName £"Doe”)
.setAge(36)
.setAddress<”123 Main St”>
.build(>;
Sy stem, out .print In £ "User created: " ■+■ user);
317
Structural Patterns
Adapter:
• Allows incompatible interfaces to work together.
Example:
318
m
t
{
£
))
<J 3
xJ>;
M M
< );
* 41 I 41 b
4- >
a 0
i f ( a u d ic T y p e .e < iu a ls lg n o r e C a s e - (
«it
a
*
4J
•J
•1
3
14rJ 4- a
M -
4-
U
V M
L
fi
fi
4i
fl 7. u.
vi s
-
fl
rtfl 41 fl
>
•
4 H tt Ji fl 4-
0 H e
a d v a n c e a M u s ic P ia y e r =
a d v a n c e d H u s lc P la y e r =
fl
s *av *flV i
M
I4
£ a
<1
fl
«
H 5 2
fl fl
fl
3
u
*4
u
*< 2
p
14
r u1
i 3
u1
1 1111
& Cl Cl Cl
£ 2 2
a u
c
a
u
c
5 fl fl
5
0 3
a
<0
v <0
E fl % uu
li
i
Mfl! 4 (0
u
3 1
a a
a
319
Composite:
• Composes objects into tree structures to represent
partwhole hierarchies.
Example:
320
Jawa-utll-Arraysist;
Java-uitll-List;
tatar-fttca tasptovu.. <
■ uiil na^apln/aaOatall•<};
. >-■ - -•.■-••■i. • •- .t
Strlag naae;
sapid;
Strlag position;
C . sapid. String naan. Strlag position} (
ttai.-oapld - oapld;
thls-naaa - naan;
•- fils-position - position;
>
gOMorrSAa
pabLlx void .i«Mrqr.trlxuDuiaLJ af) f
Systaa.awt_prlntln<anpld ■» ♦ <un);
b
Man agar lacfaaants SapliryM (
Strlag naan;
sapid;
String position;
( sapid- String naan. String position} ■{
t_hAW_o«pZi3 • oapld;
- na«t;
LPks-posltlon - position;
b
pOMurrlds
<) (
SysLaa-UMU-prlaiLlrafanntal * •
. ........ . tary laplBMSU E•*!)<•; mt (
LlstcEaployM* aaployoauist - <>O1
pOxarrSAa
i.l.S. vu: J .0 f
CEoployao anp : aa^JoyoM. 1st) f
aap. sJacatEaployaoCntadl a ( ) ;
>
F
{EaployM *ap) C
cnployoou1st.add(aap);
b
(taplcyaa nap) £
<MapEcyouList.r«eovo<anp);
b
............. (
<Strlng{] args} (
- ( . . ):
tMaalilOMI- d
*Ml lup«^l«L,
*
— lira b»i * Jan». *.Lz.Ltli *l> );
Nanaaai- anal - -ana Ka I lapar (1M, *MUs satui.Mi
** "SSO MaaMg );
Ciaw-anySiruiXiira airxur, a Mx Citapaayblrat tis>(bS
dLrsKXorx.addEaployoe(davl};
dlractor)r-addEMployM(aa^2 };
dLraKXorx-ddd£aployoe(aanl);
dlraotorx-ShCMEnployaaOita 1 Is( );
b
)
321
Decorator:
• Attaches additional responsibilities to an object
dynamically.
Example:
322
inter--ac- C.-tr -{
••■old ;>-r • I . ( );
>
class &.at ..nplcn . t ■* {
public vale! . sei>bb.’() -{
System,o at. pr±nt('t .!c );
3
>
class Curl-.-, .-rjti..- 1ft :> 1 i-nent ■. Car {
atec ted Car car;
.. ... 1 .1 _c i (Car c) <
this.car = c;
public vale . b) -(
this..car. asseort>le() ;
3
>
Class Spin •. .11 e-xten.!:. Cjri.cee.'jtur {
public : _ It- (<j»r c) {
super(c);
public vale! .p».b )•.'() -(
super.asse<sble( ) ;
System .oat.print( -- r - Spui ■. c.:. >;
3
>
Class . . mi exteUs Cai ■■..... _i tar f
- Jbllc LaXf.1 '.•■.! (Car c) {
super(c);
P-Jblle vale! .sw.b)•.-() -(
super.asseable();
Sy stem .oat. print ( ■•-r..»irt - Lu.-u-. Cai >;
3
>
publ 1C class. M.t 1 fl {
..r . (String[J args} ■{
C.: s. .1 t .C t « new (i rw : . ()>;
sportsCar. assemt>le( >;
System.out.println( >;
Car spot ..a • * ihm Spa« •. -..Car(i>e^« LuxaryCtir (new BaslcCar()JJ;
sportsLuxuryCar.assemble<);
3
>
323
Behavioral Patterns
Strategy:
• Defines a family of algorithms, encapsulates each one,
and makes them interchangeable.
Example:
324
<
( i—t);
v XapLa—ns •. rijwnJUmcgy £
Strlag car<
*»«<iar ;
(String cardMfTnr) (
lii l .candMjatwr — carcMjaber;
3
( a—t) (
Syt—.oert .prlrrtln<a—t ■» • card—bar) ;
3
<
*
Stria aaaallld;
{String, — nil Fd} {
i .uillXd -
3
( —out It ) (
Syctan. occt . prlntln<a«o«irbt ■» • —nil rd J;
3
>
I 1 - •■ ‘ (
listen—} It—s;
Pa y—
।tStratagy pay—tStratogy;
CPay—ntS-trutogy pay—tS trat agy ) (
* -it—« -
ttil <>();
*
tStratogy
. - .pay it - pay—tSXratagy;
3
(it—। it—> {
It—c. add (it—) ;
3
CXt— it—) {
t r
i ia .r—<»«(11—iJj
3
-uiii.- • .; J i' C> <
(Tt— it— : it—&) (
total ♦- lua.gatprlca();
J
pay—tStracogy -pay {total};
3
{
String naaa;
pa-lea;
(String ai — . prlcaj {
thl. .na— — a nn n;
■ lui.prlc
* - prKa;
3
Str*lr« (> {
' • ruaa;
3
c-uUlje.......................... C3 <
-' prlc a;
3
Ind.;:- (
{String!] args) {
- ( (
cartl. add 11-— ( ( ■■ - -5>J
cam.ad<Lt— < ( . >);
cam.pajrO;
- ( ■ < "3>J
cartl. addit—< ( ■ ■ . »;
cartl. addlt— < ( ■ ■ . - •
carta.pay();
3
325
. Java-iAil-Uftj
J-'1- ■-■ (
(String Hkuags);
}
l.lrfii ; . idl Al.' Ll J.:. !_■ ! 11 [
Sli'lflft maw;
*
l}
fEtfrlJlg U f
'lilu.naM - naa
*;
piiMirrUi
EyctM.orft-prliTtlnfnaM . * kjii.ij'i,
1
}
Li„. [
LiEtiChUHW-li DbfitrarE - <>(}■
t'.Lis. i.J J . fQbMFtw etjswwr-} f
jdd(dHarMif-) £
Li.iiUi i.Id I (fifetUHW dhfiMWr) f
QtrtOi
*Vd Pt. *0^) _■
V* £ Otl £4^
1
i-i.lillL ..id .LJ> -i (S-TFij^i ULMg?> f
COfaM^riJ1 !: BfcEfiirrtPCj {
■tfi-itfniH'. updatD(auuig6}:
}
I
j
■ ■'■■ - {
. *1S (
■kavlMiUilW tauf-1'immh.riJ;
- ( i;
. : ( )J
ptfallfhvr _MtSC
*[0ilIirtUr ,.2}J
UifaUsbw.MitldF*Ct»ap««H4 );
pifaLifbwr .dillC
*[atlIirtUr4} I
UifaUsbw.MitldF*Ct»ap««H4 ).;
I
1
Observer:
• Defines a onetomany dependency between objects so that
when one object changes state, all its dependents are
notified.
Example:
Command:
• Encapsulates a request as an object, thereby letting you
parameterize clients with queues, requests, and operations.
Example:
326
{
O:
i.liu.. u £
■i.l............. (> (
SystM.-<Mt.println< >;
>
. ..L1U . ..1 £) (
>
i Im;. - 1 ..... ul . . £
tight light;
(Light light) (
•.HL..ll^it - light;
>
. 4.1U . ..I £) (
light. tunaOnO;
>
i.la». . • • , mu .1 t> (
light light;
*
<ll
>t ll^t) f
•.lils.ll^t - light;
>
. 4.1U . ..I £) (
light. turwOfFO;
>
i Im;. . 1 £
fn—wt ciMBUnd;
(rr»ind owund) (
i
till, .tam nd - commmI;
>
•J.1U . 14 <) (
coBund .*x«cutaC );
)
1. Im.. (
■ 1.. <$tring(] args) £
- ();
• (light);
- niahtv
“ (J:
rcnota. Mt CoMued (1 ightOn);
rcaota. pr«cautt:cn<>;
rcaota. MtCoaaandClt^btOff) ;
cmo ts. pr«sButton< );
>
>
327
public class iuln [
public stacic uold sab fEcringl] args} thruns ticapElen {
Claitch clazz - Claes_fi3rtia
*ft[ ..lafijg.Sti j-i. )■
Jud - £lazz .g^titattad("tcbppiii<aiu '’)i;
Etriag str - hflJlii”-
EtrlJbg result » (String) Mited.iinKi»(Etr);
EyKtafl .£Kjt..prlritJn4i'iKEiIt}j
I
}
0£AtariFa<4 JtyhwtaElfn {
String valuatJ;
}
pt^uvtttaEinMvaiLi^ - 'Eriaapla')
public class Hiulii [
public static vuid 1 (Strict] vgs} (
■ .- ui <:iz - JtalA.class .gatAmutatl£«(I^AnretaTlc6.claE£):
Eyfitaa .out.print!H<anutat ion.Maluo( ))j
1
I
Chapter 21: Advanced Topics
Reflection API
• Allows inspection and modification of classes, methods,
and fields at runtime.
Example:
Annotations:
• Provide metadata for code.
• Can be used for compiler instructions, runtime processing,
or generating code.
Example:
328
f
.1.. {
puhlJi uJLln vuiJ r.l lih"^l ^.ilQ :
p.i.i if .uld «x. /Styln^[] [
*
() .i«tlw
wthirf[ );
J
}
JHHXPMT 3HUJU.L [JMIfM 'tilW. ;iiHl>et Qti]l {
Hi'. ■r( I:
}
Java Native Interface (JNI)
JNI:
• Enables Java code to interact with native applications and
libraries written in other languages like C/C++.
Example:
nativeLib.c:
329
f
csiU'ifta]'] apj [
- S^scM.curfMftTi^Cllisni
// Ydiir COd
* hfirtf
- 5^t^.CHrrwitTlMMUll£(};
iyttjM.l*jc-prlniJrtHf 4- (ariTLtt - rtartTiaa} « J;
T
}
Performance Tuning and Profiling
Performance Tuning:
• Process of making your Java application run faster and
more efficiently.
Profiling Tools:
• Tools like JVisualVM, YourKit, and JProfiler help in
identifying performance bottlenecks.
Example:
330
_^lu -jr_ 1UJ.K <
ilM-BjnC OBpyflhrpf- J
}
CM . 1 n. fcys Lfd l13* ■.
Modular Programming with Java 9
Modules:
• Introduced in Java 9 to create more manageable and
scalable applications.
Module Declaration:
• moduleinfo.java:
Example:
• moduleinfo.java:
331
Main.java:
332
!• org.Junlt.Tast;
org.Junit.Assart_as&artEqualt;
public class MalnlMt (
gTast
public void testAdd() (
assartEquals( , ♦ );
)
Chapter 22: Testing and Debugging
Unit Testing with JUnit
JUnit:
• Framework for writing and running unit tests in
Java.
Example:
333
*1L_
IILJL> LlaU F-lLjllakt |
STwbt
111.Li. .i Id () {
Llst<5rria^.> iixM
*
dLitt - •oci[Lirt.EljfitJ:
}). tJUlttCtliHlf " . J?
s&MncEqHalKf . HKkftdLLH
Mocking with Mockito
Mockito:
• Framework for creating mock objects.
Example:
334
Debugging Techniques and Tools
Debugging Techniques:
• Breakpoints, stepping through code, and inspecting
variables.
Debugging Tools:
• IDEs like IntelliJ IDEA, Eclipse, and NetBeans provide
powerful debugging tools.
Example:
335
JpaCht-Dr^/POV-^ Mliljfit!M£iA’lrtTp.!//m
*»_wi-iW 1g/'M&Lil'WiiLSC
htcpj//My«A.jpa<ihft.iicg/i£d/iiakW
ItftKLDA>4-& .fc/KMtaIViSr-i 10A>
c gr lmj pId> c cd. ti aap 1
* < / graypl dfr
■zor 11 fac 11 d >>>-app</art 1 f a ctl d>
CMfir & lm.1-1. B-5WP£tiQ7</MBnicn>
c/pra]ort>
Chapter 23: Building and Deployment
Build Tools (Maven, Gradle)
Maven:
• Build automation tool used primarily for Java projects.
Example:
• pom.xml:
336
pJjMglni (
Id 'jawT
gr&MP1 1 cM_raiMp]er
MbPiSiNi ' 1.0-SHM5HH'
F«pUJtOrlJr£ {
■WAnCMtralO
dtiKTiikiriLifi-i {
Gradle:
• Build automation tool that builds upon the concepts of
Apache Ant and Apache Maven.
Example:
• build.gradle:
337
4 .trwlfi.yil to- Trarfi CI
Ja«a
- ivaLl^dl^
« ./gradLaw build
Continuous Integration and Deployment
Continuous Integration (CI):
• Practice of merging all developers' working copies to a
shared mainline several times a day.
Tools:
• Jenkins, Travis CI, CircleCI.
Example:
338
FROM openjdk:8-jdk-alpine
COPY target/myapp.jar myapp.jar
entrypoint ["java", "-jar", ’myapp.jar"]
# Build Docker image
docker build -t myapp .
# Run Docker container
docker run -p 3BM:E880 myapp
Dockerizing Java Applications
Docker:
• Platform for developing, shipping, and running
applications inside containers.
Dockerfile:
Example:
339
Reference
• Arnold, K., Gosling, J., & Holmes, D. (2005). The Java
programming language (4th ed.).
Addison-Wesley Professional.
• Bloch, J. (2018). Effective Java (3rd ed.). Addison-Wesley.
• Sierra, K., & Bates, B. (2005). Head first Java (2nd ed.).
O'Reilly Media.
• Lippman, S. B. (2012). C++ primer (5th ed.). Addison-
Wesley.
• Horstmann, C. S. (2013). Core Java Volume I-
Fundamentals (9th ed.). Prentice Hall.
• Eckel, B. (2006). Thinking in Java (4th ed.). Prentice Hall.
• Schildt, H. (2014). Java: The complete reference (9th ed.).
McGraw-Hill Education.
• Goetz, B. (2006). Java concurrency in practice. Addison-
Wesley Professional.
• Fowler, M. (2003). Patterns of enterprise application
architecture. Addison-Wesley.
• Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1994).
Design patterns: Elements of reusable object-oriented
software. Addison-Wesley.
• Joshua, J., & Eckstein, R. (2007). Java SE 6 programming.
McGraw-Hill.
• Vermeulen, M. (2013). Java 7 new features cookbook.
Packt Publishing Ltd.
• Yoon, H. (2007). Java SE 6: What's new? . Pearson
Education.
• Liang, Y. D. (2020). Introduction to Java programming and
data structures (12th ed.).
Pearson.
• Bates, B. (2008). SCJP Sun certified programmer for Java 6
study guide (CX-310-065).
McGraw-Hill Education.
• Mak, G., & Russell, G. (2004). Java server pages. McGraw-
Hill Education.
• Gupta, A. (2017). Spring 5 design patterns. Packt
Publishing Ltd.
• Nguyen, D. H., & Johnson, K. (2018). Mastering
Microservices with Java. Packt Publishing Ltd.
• Niemeyer, P., & Knudsen, J. (2005). Learning Java (3rd ed.).
O'Reilly Media, Inc.
• Lefranois, S. (2018). Mastering Java for data science. Packt
Publishing Ltd.
340
• Butch, S., & Zakhour, S. (2013). The Java tutorial: A short
course on the basics (6th ed.).
Addison-Wesley Professional.
• Keogh, J. (2005). J2EE: The complete reference. McGraw-
Hill Education.
• Richards, M. (2015). Software architecture patterns.
O'Reilly Media, Inc.
• Sedgewick, R., & Wayne, K. (2011). Algorithms (4th ed.).
Addison-Wesley Professional.
• Sonmez, J. (2015). Soft skills: The software developer's life
manual. Manning Publications.
• Pramod, S., & Mak, G. (2002). JSP: The complete
reference. McGraw-Hill Education.
• Vasudevan, V. (2005). Java EE 5: The complete reference.
McGraw-Hill Education.
• Raj, S. (2019). Microservices architecture. Packt Publishing
Ltd.
• Pilone, D., & Pitman, N. (2005). UML 2.0 in a nutshell.
O'Reilly Media, Inc.
• Kousen, K. (2013). Making Java Groovy. Manning
Publications.
341