0% found this document useful (0 votes)
37 views29 pages

Unit - 7,8,9 Java PIET

Uploaded by

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

Unit - 7,8,9 Java PIET

Uploaded by

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

UNIT - 7

String Handling in Java

In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string.
For example: String s1 = "Hello"; // Using string literal
String s2 = new String("World"); // Using new keyword

In Java, String is a class in the [Link] package.


 Strings are immutable (cannot be changed once created).
 Java provides many built-in methods to work with strings.

Java String class methods:


Method Description Example Output
Returns string
length() "Hello".length() 5
length
Returns char at
charAt(i) "Java".charAt(2) v
index
Compares
equals(s) "hi".equals("hi") true
content
equalsIgnoreCase(s) Ignores case "Hi".equalsIgnoreCase("hi") true
Lexicographic
compareTo(s) "a".compareTo("b") -1
compare
substring(i,j) Extract substring "coding".substring(1,4) odi
Hello
concat(s) Joins strings "Hello".concat(" World")
World
Converts to
toUpperCase() "java".toUpperCase() JAVA
uppercase
split(" ") Splits string "a b".split(" ") [a, b]

1. Java String charAt()

The Java String class charAt() method returns a char value at the given index
number.
public class CharAtExample {
public static void main(String args[]) {
String name="section";

1|Page By [Link] (Technical Trainer)


char ch=[Link](4);//returns the char value at the 4th index
[Link](ch);
}
}

2. Java String length()

The Java String class length() method finds the length of a string. The length of
the Java string is the same as the Unicode code units of the string.

Syntax: The signature of the string length() method is given below:

public int length()


Example:
public class LengthExample{
public static void main(String args[]){
String s1="Parul";
String s2="University";
[Link]("string length is: "+[Link]());
[Link]("string length is: "+[Link]());
}
}

3. Java String isEmpty()

The Java String class isEmpty() method checks if the input string is empty or
not. Note that here empty means the number of characters contained in a string is
zero.

Syntax: The signature or syntax of string isEmpty() method is given below:

public boolean isEmpty()

Example:
public class IsEmptyExample {
public static void main(String args[]) {
String s1="";
String s2="University";
[Link]([Link]();
[Link]([Link]();
}
}

2|Page By [Link] (Technical Trainer)


4. Java String replace()

The Java String class replace() method returns a string replacing all the old char
or CharSequence to new char or CharSequence.

public class ReplaceExample1{


public static void main(String args[]){
String s1="Java Program";
String replaceString=[Link]('a','e');//replaces all occurrences of 'a' to 'e'
[Link](replaceString);
}
}

5. Java String split() method example

The given example returns total number of words in a string excluding space only. It
also includes special characters.
public class SplitExample{
public static void main(String args[]){
String s1="java string split method";
String[] words=[Link]("\\s");
//splits the string based on whitespace using java
//foreach loop to print elements of string array
for(String w:words){
[Link](w);
}
}
}

6. Java String compare

We can compare String in Java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method),


reference matching (by == operator) etc.
3|Page By [Link] (Technical Trainer)
 By Using equals() Method

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
[Link]([Link](s2)); //true
[Link]([Link](s3)); //true
[Link]([Link](s4)); //false
}
}

Example 2
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
[Link]([Link](s2));//false
[Link]([Link](s2));//true
}
}

 By Using == operator compares references not values.


class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
[Link](s1==s2);//true (because both refer to same instance)
[Link](s1==s3);//false(because s3 refers to instance created in on pool)
}
}

 By Using compareTo() method

The String class compareTo() method compares values lexicographically and


returns an integer value that describes if first string is less than, equal to or greater
than second string. Suppose s1 and s2 are two String objects. If:

o s1 == s2 : The method returns 0.


o s1 > s2 : The method returns a positive value.
o
s1 < s2 : The method returns a negative value.
4|Page By [Link] (Technical Trainer)
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2)); //0
[Link]([Link](s3)); //1(because s1>s3)
[Link]([Link](s1)); //-1(because s3 < s1 )
}
}

String Concatenation in Java

In Java, String concatenation forms a new String that is the combination of multiple
strings. There are two ways to concatenate strings in Java:
o By + (String concatenation) operator
o By concat() method
o String Concatenation by + (String concatenation) operator
o Java String concatenation operator (+) is used to add strings.
o For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
[Link](s);//Sachin Tendulkar
}
}
o String Concatenation by concat() method
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);//Sachin Tendulkar
}
}

5|Page By [Link] (Technical Trainer)


 How to reverse String in Java

public class TestStringFormatter {


public static void main(String[] args) {
[Link]([Link]("my name is Ali"));
[Link]([Link]("I am Arshad"));
}
}

Java Package:
 PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It
helps organize your classes into a folder structure and make it easy to locate and
use them. More importantly, it helps improve code reusability.
 Each package in Java has its unique name and organizes its classes and interfaces
into a separate namespace, or name group.
 Although interfaces and classes with the same name cannot appear in the same
package, they can appear in different packages. This is possible by assigning a
separate namespace to each Java package.
Syntax:- package name_of_Package;
To create a package, follow the steps given below:

 Choose a package name according to the naming convention.


 Write the package name at the top of every source file (classes, interface,
enumeration, and annotations).
 Remember that there must be only one package statement in each source file.

Implement a java program to create a package named mypack and import it in circle class.
Step-1: First create a folder for the package and the package_name is mypack.
Step-2: In that mypack folder, create a file_name on [Link].
Step-3: Then write a code for the "circle class'' by using (package mypack;)
source code:
package mypack;
public class Circle {
double r=10;
public void area() {
6|Page By [Link] (Technical Trainer)
[Link]("Area of the circle = " + (3.14 * r * r));
}
}

Step-4: After that create a file for main class for importing it in a circle class by using
(package mypack;)
source code:
package mypack;
public class Main {
public static void main(String args[]) {
Circle c = new Circle();
[Link]();
}
} //Output: Area of the circle = 314.0

Path and Classpath:

• Path: Refers to the directory where Java tools (like javac, java) reside.
• Now, you can simply type:
javac [Link]
java MyProgram
• Classpath: Refers to where the Java compiler looks for classes and libraries.
• Setting Classpath Example (Windows):

set CLASSPATH=C:\myJavaClasses;

Interfaces in Java

An Interface in Java programming language is defined as an abstract type used to


specify the behavior of a class. An interface in Java is a blueprint of a behavior. A
Java interface contains static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction and
multiple inheritance in Java. In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body. Java Interface also represents the
IS-A relationship.

Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).

 Interfaces specify what a class must do and not how. It is the blueprint of the
behaviour.
 Interface do not have constructor.
7|Page By [Link] (Technical Trainer)
Syntax:
interface interface_name{

// declare constant fields

// declare methods that abstract

// by default.

// Java program to demonstrate working of interface

import [Link].*; // A simple interface


interface In1 { // public, static and final
final int a = 10; // public and abstract
void display();
}
// A class that implements the interface.
class TestClass implements In1 {
// Implementing the capabilities of interface.
public void display(){
[Link]("Java Interface");
}
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
[Link]();
[Link](a);
}
}
Output:
Java Interface
10
[Link]. Class Interface
In class, you can instantiate variables and In an interface, you can’t instantiate
1. create an object. variables and create an object.
Class can contain concrete(with The interface cannot contain concrete(with
2. implementation) methods implementation) methods
The access specifiers used with classes are In Interface only one specifier is used-
3. private, protected, and public. Public.

8|Page By [Link] (Technical Trainer)


Relation between Class and Interface:
- class -> implement Interface
- Interface -> never extends a class
Note: Java doesn’t support Multiple Inheritance and Hybrid inheritance.

Enumerations in Java (Enums)


An enumeration in Java (created using the enum keyword) is a special data type that
represents a group of constants (unchangeable values).

Key Points about Enum


1. Defined using the enum keyword.
2. Enums are type-safe (you cannot assign values other than those defined).
3. Each enum constant is implicitly public, static, and final.
4. Enums can have:
o fields
o methods
o constructors (private by default).
Example 1: Simple Enum
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY
}

public class EnumExample {


public static void main(String[] args) {
Day today = [Link];

switch (today) {
case MONDAY:
[Link]("Start of the week!");
break;
case FRIDAY:
[Link]("Weekend is near!");
break;
case SATURDAY:
case SUNDAY:
[Link]("It's weekend!");
break;
9|Page By [Link] (Technical Trainer)
default:
[Link]("Midweek day!");
}
}
} //Output: It's weekend!

Example 2: Enum with Fields & Methods


enum Season {
WINTER("Cold Season"),
SPRING("Pleasant Season"),
SUMMER("Hot Season"),
FALL("Cool Season");

private String description;

// Constructor
Season(String description) {
[Link] = description;
}

// Method
public String getDescription() {
return description;
}
}

public class EnumWithMethods {


public static void main(String[] args) {
for (Season s : [Link]()) {
[Link](s + ": " + [Link]());
}
}
}
Output:
WINTER: Cold Season
SPRING: Pleasant Season
SUMMER: Hot Season
FALL: Cool Season

Advantages of Enum
 Improves readability and maintainability of code.
 Prevents invalid values (only predefined constants allowed).
 Can be used in switch-case statements.

10 | P a g e By [Link] (Technical Trainer)


Assignment Questions - industry-relevant practice questions:

Q1. String Handling (Real-time Example), Problem Statement:


In a text-processing company, you are tasked with writing a program that checks if a given
sentence is a pangram (i.e., contains every letter of the English alphabet at least once).
 Use Java String handling functions (toLowerCase(), charAt(), contains(), etc.).
Requirements:
 Input: A sentence (String).
 Output: "Yes, it is a Pangram" OR "No, it is not a Pangram".

Q2. Package Creation & Classpath, Problem Statement:


Your company is modularizing code. You are asked to create a custom package named
utilities that contains a class MathUtils with a method isPrime(int n) returning true/false.
 In another class (outside the package), import this package and check whether a
given number is prime.
 Demonstrate compilation and execution using classpath.

Q3. Class vs Interface in Industry Scenario, Problem Statement:


In a payment system, there are different payment methods (CreditCard, UPI, NetBanking).
 Define an interface Payment with a method pay(double amount).
 Implement the interface in multiple classes (CreditCardPayment, UPIPayment,
NetBankingPayment).
 Write a test class where the user selects a payment method and processes a transaction.
Question Part:
Also explain why an interface is more suitable than an abstract class in this case.

Q4. Interface + Enumeration (Real-world Use Case), Problem Statement:


A logistics company wants to assign package delivery priorities (LOW, MEDIUM, HIGH,
URGENT).
 Create an enum Priority with these values.
 Define an interface Shippable with method ship(Priority p).
 Implement this in Courier class, where shipping time is decided based on priority.
o Example: URGENT → “Delivery in 1 Day”, LOW → “Delivery in 5 Days”.

Q5. String Functions + Packages Integration


Problem Statement:
You are building a text analytics tool for social media posts.
 Create a package textutils containing a class TextAnalyzer with methods:
1. int countWords(String text) – returns number of words.
2. boolean containsHashtag(String text) – returns true if # present.
3. String reverseText(String text) – returns reversed string.
 In the main class, import this package and analyze multiple sample posts.

11 | P a g e By [Link] (Technical Trainer)


UNIT - 8
Exception Handling Overview:
 Exception is an abnormal condition that arises in a piece of code.
 Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
 Exceptions can be caught and handled by the program.
 Exception Handling in Java is one of the effective means to handle the runtime errors
so that the regular flow of the application can be preserved.
 Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
 Major reasons why an exception Occurs:
o Invalid user input
o Device failure
o Loss of network connection
o Physical limitations (out of disk memory)
o Code errors, Opening an unavailable file

 Checked Exceptions: These are exceptions that are checked at compile-time. For
example, IOException, SQLException.
 Unchecked Exceptions: These exceptions are not checked at compile-time but at
runtime. For example, ArithmeticException, NullPointerException.
 Errors: These are serious issues not intended to be caught by the application. For
example, OutOfMemoryError, StackOverflowError.

12 | P a g e By [Link] (Technical Trainer)


Hierarchy of Standard Exception Classes:
All exception classes inherit from the Throwable class. Here's the hierarchy:

Keywords in Exception Handling:

1. try Block: The code that might throw an exception is placed inside the try block.
2. catch Block: It catches and handles the exception thrown by the try block.
3. finally Block: This block always executes whether an exception is handled or not,
making it ideal for cleanup code like closing file streams or database connections.
4. throw Keyword: Used to explicitly throw an exception.
5. throws Keyword: Used to declare an exception that might be thrown by a
method but is not handled within the method itself.

Basic Structure of Exception Handling:


try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute (optional)
}

13 | P a g e By [Link] (Technical Trainer)


try, catch, and finally Blocks:
The basic structure for exception handling includes:

• try block: Code that may throw an exception is placed inside this block.
• catch block: It catches the exception thrown by the try block.
• finally block: This block will execute whether an exception is handled or not.

Example:
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
[Link](result);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
} finally {
[Link]("Finally block executed.");
}
}}

Output:

Exception caught: / by zero Finally block


executed.

Multiple Catch Blocks:

You can catch multiple types of exceptions by using multiple catch blocks.

Example:
public class MultipleCatchExample { public static void
main(String[] args) { try {
int[] arr = new int[5];
arr[5] = 10; // Throws ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
[Link]("ArithmeticException caught."); } catch
(ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException caught.");
} catch (Exception e) {
[Link]("General Exception caught.");
}
}}

Output:

ArrayIndexOutOfBoundsException caught.

14 | P a g e By [Link] (Technical Trainer)


throw Keyword:

• The throw keyword is used to explicitly throw an exception.

• It is mainly used to throw custom exceptions.

Example:
public class ThrowExample {
public static void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible for voting");
} else {
[Link]("Welcome to vote");
}
}
public static void main(String[] args) {
validateAge(16); // This will throw an exception

}}

Output:

Exception in thread "main" [Link]:

Not eligible for voting

throws Keyword:
• The throws keyword is used to declare exceptions.

• It indicates that a method can throw an exception, which must be handled by the
calling method.

Example:
import [Link].*;
public class ThrowsExample {
public static void method() throws IOException {
throw new IOException("File error");
}
public static void main(String[] args) {
try {
method(); // Calling method that throws an exception
} catch (IOException e) {
[Link]("Exception handled: " + [Link]());
}
}}

Output:
Exception handled: File error

15 | P a g e By [Link] (Technical Trainer)


finally Block:
• The finally block is executed whether or not an exception occurs.
• It's typically used to release resources (like closing files or database connections).

Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Exception caught.");
} finally {
[Link]("This will always be executed.");
}
}}

Output:

Exception caught. This will always be


executed.

Custom Exceptions:

You can create your own exception classes by extending the Exception class or
RuntimeException.

Example:
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age less than 18");
} else {
[Link]("Valid age.");
} }
public static void main(String[] args) {
try {
checkAge(16); // Throws custom exception
} catch (AgeException e) {
[Link]("Caught: " + [Link]());
}}}

Output:

Caught: Age less than 18

16 | P a g e By [Link] (Technical Trainer)


Checked vs. Unchecked Exceptions:
1. Checked Exceptions:

 checked at compile time.


 The programmer must either handle these exceptions using a try-catch block or
declare them using the throws keyword.
 Like: IOException, SQLException.

Example:
import [Link];
import [Link];
import [Link];

public class CheckedExceptionExample {


public static void main(String[] args) {
try {
File file = new File("[Link]");
FileReader fr = new FileReader(file); // Checked exception
[Link]("File exists!");
} catch (FileNotFoundException e) {
[Link]("File not found.");
}
}
}

Creating Text File of name “[Link]”:


“Hello Parul University AIML students”

Output: File exists!

If the file does not exist, the output will be: File not found.

2. Unchecked Exceptions:
 These exceptions subclasses of RuntimeException. They are not checked at compile
time, meaning the programmer is not forced to handle them.
 Like: NullPointerException, ArithmeticException.

Example:

public class UncheckedExceptionExample {


public static void main(String[] args) {
String str = null;
[Link]([Link]()); // This throws NullPointerException
}
}

17 | P a g e By [Link] (Technical Trainer)


Output:

Exception in thread "main" [Link]: Cannot invoke


"[Link]()" because "<local1>" is null at
[Link]([Link])

Class Throwable:

 The Throwable class is the superclass of all exceptions and errors in Java.

 It provides methods to print stack trace, get error messages, etc.

Example:
public class ThrowableExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (Exception e) {
[Link]("Message: " + [Link]());
[Link](); // Prints the stack trace
}
}}

Output:

Message: / by zero
[Link]: / by zero
at [Link]([Link])
Summary:
• Exception handling allows us to gracefully handle runtime errors and maintain the
normal flow of the application.
• Key concepts include try, catch, finally, throw, and throws.
• You can handle multiple exceptions using multiple catch blocks.
• You can create custom exceptions by extending the Exception class.
• Checked exceptions must be declared or caught, while unchecked exceptions do not
require explicit handling at compile-time.

18 | P a g e By [Link] (Technical Trainer)


Assignment Questions - industry-relevant practice questions:

Q1. File Handling with Exceptions


Write a Java program to read data from a text file and display it on the console.
 Handle the case when the file does not exist using FileNotFoundException.
 If the file is empty, throw a custom exception EmptyFileException.

Q2. Banking System with Exception Handling


Create a BankAccount class with methods for deposit and withdraw.
 Throw an IllegalArgumentException if the deposit amount is negative.
 Throw an InsufficientFundsException (custom exception) if withdrawal amount
is greater than balance.
 Demonstrate proper handling of both exceptions in a main program.

Q3. Command-Line Calculator


Write a Java program that accepts two numbers and an operator (+, -, *, /) from the
command line.
 Handle the following exceptions:
o NumberFormatException if invalid input is entered.
o ArithmeticException for division by zero.
 Ensure program doesn’t terminate abruptly but displays user-friendly messages.

Q4. Online Shopping Cart Simulation


Develop a Java program for a shopping cart.
 Throw OutOfStockException if a user tries to add more quantity than available.
 Throw InvalidProductException if the product ID does not exist.
 Demonstrate how to catch multiple exceptions and continue execution gracefully.

Q5. Multiple Exception Handling in Student Result Processing


Write a program that accepts student marks and calculates the grade.
 Throw NegativeMarksException if marks entered are less than 0.
 Throw MarksOutOfRangeException if marks exceed 100.
 Use finally block to display a message "Result processing completed" regardless
of exceptions.

19 | P a g e By [Link] (Technical Trainer)


UNIT - 9
Introduction to Multithreading
 Multithreading in Java enables multiple threads to run concurrently, sharing the same
memory space but executing different tasks.
 This enhances performance, especially in applications with long I/O waits or those that
need to handle multiple tasks at once (e.g., web servers, gaming engines).
 Thread: A lightweight process that runs independently and concurrently with other
threads.
 Multithreading: Refers to executing multiple threads at the same time.

Need for Multiple Threads


Java applications, especially those with user interfaces or server-side processes, benefit
from multithreading to maintain responsiveness.

Use Cases:
• Web Servers: Handle multiple client requests simultaneously.
• Media Players: Play audio while performing other tasks like UI updates.
• Video Games: Separate logic for game mechanics, rendering, and user input.
• Data Processing: Execute heavy computational tasks without blocking the UI.

Thread Class
Java provides the Thread class, which you can extend to create a new thread. The run()
method contains the code that the thread will execute.

Example: Creating a thread using Thread class


class MyThread extends Thread { public void run() {
for (int i = 0; i < 3; i++) {
[Link]("Thread is running: " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
[Link]();
//start() method invokes the run() method of Thread class
}
}

20 | P a g e By [Link] (Technical Trainer)


Explanation:

The start() method is used to start a thread, which internally calls the run() method.

Output:
Thread is running: 0
Thread is running: 1
Thread is running: 2

Creating New Threads

You can create threads in Java either by:

1. Extending the Thread class.


2. Implementing the Runnable interface.

Example: Creating a thread using Runnable interface


class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Runnable thread is running: " + i);
} }
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
[Link]();
}
}
21 | P a g e By [Link] (Technical Trainer)
Explanation:
The Runnable interface is preferred in cases where your class is already extending
another class (since Java doesn’t support multiple inheritance).

Output:
Runnable thread is running: 0
Runnable thread is running: 1
Runnable thread is running: 2
Runnable thread is running: 3
Runnable thread is running: 4

Thread Lifecycle (Thread States)


Java threads have several states they move through during their lifecycle:

1. New: When a thread object is created but not started.


2. Runnable: The thread is ready to run but waiting for CPU time.
3. Running: The thread is actively executing.
4. Blocked: The thread is waiting for a resource.
5. Terminated: The thread has finished execution.

Thread Priority
 Thread priority helps to manage the execution order of threads.
 Java assigns a priority from 1(MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5
being the default (NORM_PRIORITY).
 Higher-priority threads are executed before lower-priority ones.

Example: Setting Thread Priority


class MyThread extends Thread {
public void run() {
[Link]([Link]().getName() + ": Priority is " + getPriority());
} }
public class PriorityExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
22 | P a g e By [Link] (Technical Trainer)
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
} }
Output:
Thread-1: Priority is 10
Thread-0: Priority is 1

Synchronization
 When multiple threads access shared resources (like variables, files, or databases), you may
encounter inconsistency in the data.
 Synchronization ensures that only one thread can access a critical section of code at a time,
avoiding race conditions.

Example: Synchronized Block


class Counter {
int count = 0;
public void increment() {
synchronized(this) {
count++;
}
}
}
class MyThread extends Thread {
Counter counter;
MyThread(Counter counter) {
[Link] = counter;
}
public void run() {
for (int i = 0; i < 1000; i++) {
[Link]();
}
}
}
public class SyncExample {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
MyThread t1 = new MyThread(counter);
MyThread t2 = new MyThread(counter);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Final count: " + [Link]); // Output: 2000
}
}

Explanation: The synchronized block ensures that only one thread can increment the
counter at a time.

23 | P a g e By [Link] (Technical Trainer)


Inter-thread Communication

Java provides wait(), notify(), and notifyAll() methods for threads to communicate with each
other.

Producer-Consumer Problem using wait/notify


class Queue {
int value;
boolean valueSet = false;
synchronized void put(int value) throws InterruptedException {
while (valueSet) {
wait();
}
[Link]("Produced: " + value);
[Link] = value;
valueSet = true;
notify();
}
synchronized int get() throws InterruptedException {
while (!valueSet) {
wait();
}
[Link]("Consumed: " + value);
valueSet = false;
notify();
return value;
}
}
class Producer implements Runnable {
Queue q;
Producer(Queue q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while (true) {
try {
[Link](i++);
[Link](1000);
24 | P a g e By [Link] (Technical Trainer)
} catch (InterruptedException e) {
[Link]();
}
}
}
}
class Consumer implements Runnable {
Queue q;
Consumer(Queue q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while (true) {
try {
[Link]();
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
Queue q = new Queue();
new Producer(q);
new Consumer(q);
}
}

Explanation:

 The producer thread puts values into the queue, while the consumer thread retrieves them.
 Both threads use wait() and notify() to communicate and ensure synchronization.

Output:
Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4

25 | P a g e By [Link] (Technical Trainer)


Thread Methods

1. isAlive(): Checks if the thread is still running.


2. join(): Waits for the thread to finish before proceeding.
3. sleep(): Pauses the thread for a specific time.
4. yield(): Temporarily pauses the thread to give other threads a chance to execute.

26 | P a g e By [Link] (Technical Trainer)


Example of join() and isAlive():
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread running: " + i);
try { [Link](500); }
catch (InterruptedException e) { }
}
}
}
public class ThreadJoinExample {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
[Link]();
[Link](); // Wait for t to finish
if (![Link]()) {
[Link]("Thread has finished.");
}
}}
Output:
Thread running: 1
Thread running: 2
Thread running: 3
Thread running: 4
Thread running: 5 Thread has
finished.

Daemon Threads
 Daemon threads provide background services for user threads.
 They terminate automatically when all user threads finish.

Example of Daemon Thread:


class DaemonThread extends Thread {
public void run() {
while (true) {
[Link]("Daemon thread running...");
try { [Link](500); }
catch (InterruptedException e) { }
}
}
}
public class DaemonThreadExample {
public static void main(String[] args) {
DaemonThread daemon = new DaemonThread();

27 | P a g e By [Link] (Technical Trainer)


[Link](true); // Mark this thread as daemon
[Link]();
try { [Link](2000); }
catch (InterruptedException e) { }
[Link]("Main thread finished.");
}
}

Explanation:

The daemon thread runs in the background, and when the main thread finishes, the
JVM automatically stops the daemon thread.

Output:
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Main thread finished.

Conclusion
• Java multithreading enables efficient task management, especially in applications
requiring parallel execution.
• By understanding thread creation, synchronization, communication, and handling
common issues like deadlocks and race conditions, you can build robust, concurrent
applications suitable for modern multi-core processors.
• The thread management methods (join(), isAlive(), daemon threads) provide further
control, allowing precise coordination between threads.

28 | P a g e By [Link] (Technical Trainer)


Assignment Questions - industry-relevant practice questions:
Q1. Ticket Booking System (Race Condition Demonstration)
Write a Java program to simulate a ticket booking system where multiple users (threads) try to
book tickets simultaneously.
 Use multiple threads to represent different users.
 Demonstrate what happens without synchronization (race condition).
 Apply synchronization (synchronized block/method) to fix the issue.

Q2. File Download Manager (Multi-threading Simulation)


Create a Java program that simulates downloading multiple files at the same time using threads.
 Each file should be downloaded by a separate thread.
 Display the progress of each file download.
 Use [Link]() to simulate time taken for downloading.

Q3. Producer-Consumer Problem (Inter-thread Communication)


Implement the Producer-Consumer problem using threads.
 Producer thread should generate random numbers and place them in a shared buffer.
 Consumer thread should read numbers from the buffer and display them.
 Use wait() and notify() methods for communication.

Q4. Banking Transactions with Daemon Threads


Write a Java program for a banking system:
 One thread handles deposit and withdrawal operations.
 Another thread (daemon thread) continuously logs all transactions to a file (simulation).
 Demonstrate how daemon threads work differently from user threads.

Q5. Real-Time Chat Simulation (Thread Priorities)


Design a program where multiple users are chatting in real-time:
 Each user runs as a separate thread.
 Assign different priorities to threads to simulate message handling.
 Show how thread priorities affect execution order.

29 | P a g e By [Link] (Technical Trainer)

You might also like