OOPS Through JAVA - Unit5
OOPS Through JAVA - Unit5
Example:
1. String Literal: When you create a string using a string literal, Java checks the string constant pool. If the
string already exists, it reuses the existing string object. Otherwise, it creates a new one.
Example:
2. Using the new Keyword: This approach creates a new string object in heap memory, separate from
the string constant pool.
Example:
In this case, a new string object is created in the heap memory, and the literal "TestString" is placed in
the string constant pool.
• String
• StringBuffer
• StringBuilder
Example:
CharSequence seq = "Hello, World!";
2. String Class: The String class represents immutable sequences of characters. Operations on strings
create new string objects rather than modifying the original string.
Example:
String str = "Immutable";
3. StringBuffer Class: StringBuffer is mutable and thread-safe, making it suitable for use in multi-threaded
environments.
Example:
StringBuffer buffer = new StringBuffer("Mutable");
4. StringBuilder Class: StringBuilder is mutable and not thread-safe. It is used in single-threaded scenarios
for better performance.
Example:
Example:
import java.util.StringTokenizer;
Example:
import java.util.StringJoiner;
Example:
Example:
String demoString = "Test";
Using new Keyword: Creates a new object in the heap memory, separate from the string constant pool.
Example:
To store this string in the constant pool, you can use intern():
Example:
Consider the following scenario:
String s1= "Apple";
String s2= "Mango";
String s3= "Apple";
In this case, "Apple" and "Mango" are stored in the pool as literals. When the third string, also
"Apple," is created, the String Pool returns the reference to the existing "Apple" object rather than
creating a new one.
Immutability of Strings
Unlike other data types in Java, strings are immutable. This means that once a string object is created,
its value cannot be altered. This immutability allows for the sharing of string instances, reducing
memory usage and improving efficiency.
For example:
String str1 = "abc";
is equivalent to:
char[] data = {'a', 'b', 'c'};
String str2 = new String(data);
Both snippets of code result in the creation of the same string object, demonstrating how string
literals and string objects can be used interchangeably.
Practice Programs
Program 1: Count the Number of Words in a String
import java.util.Arrays;
Arrays.sort(arr1);
Arrays.sort(arr2);
Do It Yourself
Quiz
A) combine()
B) concat()
C) append()
D) join()
Answer: B) concat()
A) Hello
B) World
C) Hello World
D) HelloWorld
A) String
B) StringBuilder
C) CharSequence
D) StringBuffer
Answer: B) StringBuilder
5. Which of the following methods is used to split a string into an array of substrings?
A) split()
B) divide()
C) partition()
D) tokenize()
Answer: A) split()
Methods:
1. int length()
CharSequence cs = "Hello";
int length = cs.length(); // 5
CharSequence cs = "Hello";
char ch = cs.charAt(1); // 'e'
CharSequence cs = "Hello";
CharSequence sub = cs.subSequence(1, 4); // "ell"
4. String toString()
CharSequence cs = "Hello";
String str = cs.toString(); // "Hello"
Implementations of CharSequence
1. String
Description: The String class implements CharSequence and represents immutable sequences of characters.
Example:
2. StringBuilder
Description: The StringBuilder class implements CharSequence and represents mutable sequences of
characters.
Example:
3. StringBuffer
4. CharBuffer
Description: The CharBuffer class implements CharSequence and provides a buffer of characters.
Example:
Practice Programs
1. Example Program 1: Length of CharSequence
Quiz
a) String
b) StringBuilder
c) StringBuffer
d) ArrayList
Answer: d) ArrayList
a) A String
b) A CharSequence
c) A char
d) An int
Answer: c) A char
a) String
b) StringBuffer
c) StringBuilder
d) Both b and c
CharSequence cs = "Programming";
System.out.println(cs.subSequence(0, 11));
a) Programming
b) Programmi
c) Programming
d) Programmi
Answer: a) Programming
3. Class String
Class String
Overview: The String class is a final class in Java that represents a sequence of characters. It provides a
rich set of methods to perform operations on strings such as concatenation, comparison, and
searching.
Key Methods:
Syntax:
Example:
Category Methods
charAt(int index)
substring(int beginIndex)
substring(int beginIndex, int endIndex)
Methods for Extracting Characters from getChars(int srcBegin, int srcEnd, char[] dst, int
Strings dstBegin)
equals(Object anObject)
equalsIgnoreCase(String anotherString)
compareTo(String anotherString)
Comparison Methods compareToIgnoreCase(String anotherString)
concat(String str)
replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence
replacement)
toLowerCase()
toUpperCase()
trim()
strip()
Modifying Methods stripLeading()
indexOf(int ch)
indexOf(int ch, int fromIndex)
indexOf(String str)
indexOf(String str, int fromIndex)
lastIndexOf(int ch)
lastIndexOf(int ch, int fromIndex)
lastIndexOf(String str)
lastIndexOf(String str, int fromIndex)
contains(CharSequence sequence)
startsWith(String prefix)
startsWith(String prefix, int toffset)
Searching Methods endsWith(String suffix)
append(String str)
insert(int offset, String str)
delete(int start, int end)
deleteCharAt(int index)
reverse()
replace(int start, int end, String str)
Class StringBuffer Methods toString()
4. Methods for Extracting Characters from Strings
1. charAt(int index)
Example:
Output:
Character at index 7: W
2. substring(int beginIndex)
Example:
Output:
Substring from index 7: World!
substring(int beginIndex, int endIndex)
Example:
Output:
• Syntax: public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
• Description: Copies characters from this string into the specified character array.
• Parameters:
• srcBegin – the starting index, inclusive.
• srcEnd – the ending index, exclusive.
• dst – the destination array.
• dstBegin – the start offset in the destination array.
• Returns: void.
Example:
Output:
Characters copied: World
Explanations
1. charAt(int index):
Retrieves a single character from the string based on the specified index. The index is zero-based, meaning
the first character is at index 0. If the index is out of range (negative or greater than the length of the string),
it throws IndexOutOfBoundsException.
substring(int beginIndex):
Extracts a substring from the specified beginning index to the end of the string. This method is useful when
you need to get a portion of a string starting from a specific point.
Extracts a substring between the specified beginIndex (inclusive) and endIndex (exclusive). This method is
useful for getting a specific range of characters from a string.
Copies a specific range of characters from the string into a character array. This method is useful when you
need to extract multiple characters at once and place them into an existing character array.
Do It Yourself
1. Write a Java program that takes a string input from the user and prints the character at the
index specified by the user.
2. Write a Java program to extract and print the first 10 characters of a given string using substring.
3. Write a Java program that copies characters from index 3 to 8 of a string into a character array and
prints the array.
4. Create a Java program that takes a string and prints all substrings starting from index 2 and ending at
different positions of the string.
5. Write a Java program to extract a substring from the end of a string and print it.
Quiz
A) substring()
B) charAt()
C) getChars()
D) indexOf()
Answer: B) charAt()
2. Which method is used to extract a portion of a string between specified indices?
A) charAt()
B) substring()
C) getChars()
D) contains()
Answer: B) substring()
3. What does the getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method do?
A) ava
B) va
C) va
D) va
Answer: B) va
5. Which method would you use to get a substring from the start to the end of the string?
A) substring(int beginIndex)
B) substring(int beginIndex, int endIndex)
C) charAt(int index)
D) getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Example:
System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // false
}
}
Output:
true
false
2. equalsIgnoreCase(String anotherString)
Example:
System.out.println(str1.equalsIgnoreCase(str2)); // true
System.out.println(str1.equalsIgnoreCase(str3)); // false
}
}
Output:
true
false
3. compareTo(String anotherString)
Example:
Output:
Negative value
0
Positive value
4. compareToIgnoreCase(String anotherString)
Example:
Output:
Negative value
0
Positive value
Explanations:
1. equals(Object obj):
Purpose: Determines if two strings have the same sequence of characters. It checks for case-sensitive
equality.
Usage: Useful for checking if two strings are exactly the same.
equalsIgnoreCase(String anotherString):
Purpose: Compares two strings while ignoring case differences. This method is useful when case-
insensitivity is required.
Usage: Useful for case-insensitive comparisons such as user authentication or case-insensitive searches.
compareTo(String anotherString):
Purpose: Provides a lexicographic comparison between two strings. This method helps in sorting strings and
determining their order.
Usage: Useful for sorting operations and determining the relative order of strings.
compareToIgnoreCase(String anotherString):
Purpose: Compares two strings lexicographically while ignoring case differences. It helps in sorting strings
without case sensitivity.
Usage: Useful for case-insensitive sorting or comparisons.
Do It Yourself
1. Write a Java program to compare two strings using the equals method and print the result.
2. Write a Java program to compare two strings using the equalsIgnoreCase method and print the result.
3. Write a Java program to compare two strings using the compareTo method and display whether the
first string is less than, equal to, or greater than the second string.
4. Write a Java program that sorts an array of strings ignoring case and prints the sorted array.
5. Write a Java program to compare two strings using the compareToIgnoreCase method and print
whether the first string is less than, equal to, or greater than the second string.
Quiz
1. Which method is used to compare two strings for equality considering case sensitivity?
A) compareTo()
B) equalsIgnoreCase()
C) equals()
D) compareToIgnoreCase()
Answer: C) equals()
A) equals()
B) compareTo()
C) compareToIgnoreCase()
D) equalsIgnoreCase()
Answer: C) compareToIgnoreCase()
3. What does str1.compareTo(str2) return when str1 is lexicographically less than str2?
A) 0
B) A positive integer
C) A negative integer
D) Null
4. Which method would you use to perform a case-insensitive comparison of two strings?
A) equals()
B) compareTo()
C) compareToIgnoreCase()
D) startsWith()
Answer: C) compareToIgnoreCase()
Key Methods
1. concat(String str)
Syntax: public String concat(String str)
Description: Concatenates the specified string to the end of the current string.
Parameters: str – the string to be concatenated.
Returns: A new string that is the concatenation of the current string and the specified string.
Example:
Explanation:
Used to combine two strings into one.
Useful for creating a new string that is a combination of existing strings.
replace(char oldChar, char newChar)
Syntax: public String replace(char oldChar, char newChar)
Description: Replaces each occurrence of the specified character in the current string with the new
character.
Parameters:
oldChar – the character to be replaced.
newChar – the character to replace oldChar.
Returns: A new string with all occurrences of oldChar replaced by newChar.
Example:
public class ReplaceCharExample {
public static void main(String[] args) {
String str = "Hello World";
String result = str.replace('o', 'a');
System.out.println(result); // Output: Hella Warld
}
}
Explanation:
Used to replace a specific character in the string with another character.
Useful for making character-based substitutions.
replace(CharSequence target, CharSequence replacement)
Syntax: public String replace(CharSequence target, CharSequence replacement)
Description: Replaces each substring of the current string that matches the specified sequence with the
specified replacement sequence.
Parameters:
target – the sequence to be replaced.
replacement – the sequence to replace target.
Returns: A new string with all occurrences of target replaced by replacement.
Example:
Explanation:
Replaces a substring with another substring.
Useful for making more complex replacements within a string.
toLowerCase()
Syntax: public String toLowerCase()
Description: Converts all characters in the current string to lowercase.
Returns: A new string with all characters converted to lowercase.
Example:
Explanation:
Converts all characters in a string to lowercase.
Useful for standardizing text to a common case for comparison or display.
toUpperCase()
Syntax: public String toUpperCase()
Description: Converts all characters in the current string to uppercase.
Returns: A new string with all characters converted to uppercase.
Example:
Explanation:
Converts all characters in a string to uppercase.
Useful for standardizing text to a common case for comparison or display.
trim()
Syntax: public String trim()
Description: Removes any leading and trailing whitespace from the current string.
Returns: A new string with leading and trailing whitespace removed.
Example:
Explanation:
Removes unnecessary spaces at the start and end of the string.
Useful for cleaning up user input or formatting text.
strip()
Syntax: public String strip()
Description: Removes leading and trailing whitespace from the current string.
Returns: A new string with leading and trailing whitespace removed. This method uses Unicode whitespace
characters.
Example:
Example:
Explanation:
Removes spaces only from the beginning of the string.
Useful for cleaning up leading spaces without affecting trailing spaces.
Practice Program:
import java.util.Scanner;
// 4. Convert to lowercase
String lowerCase = concatenated.toLowerCase();
System.out.println("Lowercase: " + lowerCase);
// 5. Convert to uppercase
String upperCase = concatenated.toUpperCase();
System.out.println("Uppercase: " + upperCase);
sc.close();
}
}
Do It Yourself
1. Write a Java program to concatenate the strings "Hello" and "Java" and print the result.
2. Write a Java program to replace all occurrences of the word "Java" with "Programming" in the
string "Learn Java with Java".
3. Write a Java program to extract the substring "World" from the string "Hello World".
4. Write a Java program to convert the string "Java Programming" to lowercase and uppercase, and
print both results.
5. Write a Java program to remove leading and trailing whitespace from the string " Welcome to Java "
and print the result.
Quiz
Answer: A) concat()
Answer: B) Replaces characters or substrings in the current string with specified replacements.
A) extract()
B) sub()
C) substring()
D) split()
Answer: C) substring()
A) "JAVA"
B) "java"
C) "Java"
D) "jAvA"
Answer: B) "java"
1. indexOf(int ch)
Syntax: public int indexOf(int ch)
Description: Returns the index of the first occurrence of the specified character in the current string.
Parameters:
ch – the character to search for.
Returns: The index of the first occurrence of the character, or -1 if it is not found.
Example:
Explanation:
Useful for finding the position of a character in a string.
Example:
indexOf(String str)
Syntax: public int indexOf(String str)
Description: Returns the index of the first occurrence of the specified substring in the current string.
Parameters:
str – the substring to search for.
Returns: The index of the first occurrence of the substring, or -1 if it is not found.
Example:
Explanation:
Useful for finding the position of a substring within a string.
Example:
Explanation:
Allows starting the search for a substring from a specific position.
lastIndexOf(int ch)
Syntax: public int lastIndexOf(int ch)
Description: Returns the index of the last occurrence of the specified character in the current string.
Parameters:
ch – the character to search for.
Returns: The index of the last occurrence of the character, or -1 if it is not found.
Example:
Explanation:
Useful for finding the last occurrence of a character in a string.
Example:
Explanation:
Allows searching backwards for a character from a specific position.
lastIndexOf(String str)
Syntax: public int lastIndexOf(String str)
Description: Returns the index of the last occurrence of the specified substring in the current string.
Parameters:
str – the substring to search for.
Returns: The index of the last occurrence of the substring, or -1 if it is not found.
Example:
public class LastIndexOfSubstringExample {
public static void main(String[] args) {
String str = "Hello World World";
int index = str.lastIndexOf("World");
System.out.println(index); // Output: 12
}
}
Explanation:
Useful for finding the last occurrence of a substring within a string.
Example:
Explanation:
Allows searching backwards for a substring from a specific position.
contains(CharSequence sequence)
Syntax: public boolean contains(CharSequence sequence)
Description: Checks if the current string contains the specified sequence of characters.
Parameters:
sequence – the sequence to search for.
Returns: true if the sequence is found, otherwise false.
Example:
Explanation:
Determines if a substring exists within a string.
startsWith(String prefix)
Syntax: public boolean startsWith(String prefix)
Description: Checks if the current string starts with the specified prefix.
Parameters:
prefix – the prefix to check.
Returns: true if the string starts with the specified prefix, otherwise false.
Example:
Explanation:
Useful for checking if a string begins with a specific substring.
Example:
Explanation:
Checks if a substring starting at a specific position matches the prefix.
12. endsWith(String suffix)
Syntax: public boolean endsWith(String suffix)
Description: Checks if the current string ends with the specified suffix.
Parameters:
suffix – the suffix to check.
Returns: true if the string
Example:
Explanation:
Determines if a string ends with a specific substring.
Do It Yourself
1. Write a program that finds the index of the character 'a' in the given string and prints it.
2. Write a program that finds the index of the substring "Java" in the given string and prints it.
3. Write a program that checks if the string contains the substring "Programming".
4. Write a program that checks if a given string starts with "Hello" and ends with "World".
5. Write a program that finds the last occurrence of the character 'o' in the given string and prints it.
Quiz
1. Which method returns the index of the first occurrence of a specified character in a string?
A) lastIndexOf()
B) indexOf()
C) contains()
D) startsWith()
Answer: B) indexOf()
2. What will str.lastIndexOf("World") return if str = "Hello World World"?
A) 0
B) 6
C) 12
D) -1
Answer: C) 12
A) startsWith()
B) endsWith()
C) contains()
D) indexOf()
Answer: C) contains()
A) true
B) false
C) 6
D) -1
Answer: B) false
A) startsWith()
B) contains()
C) endsWith()
D) indexOf()
Answer: C) endsWith()
1. append(String str)
• Syntax: public StringBuffer append(String str)
• Description: Appends the specified string to the end of the current StringBuffer object.
• Parameters:
• str – the string to append.
• Returns: The StringBuffer object itself after appending the string.
Example:
Explanation:
The append method is used to add a string to the end of the existing StringBuffer content.
insert(int offset, String str)
Syntax: public StringBuffer insert(int offset, String str)
Description: Inserts the specified string at the specified position in the current StringBuffer object.
Parameters:
offset – the position at which to insert the string.
str – the string to insert.public class InsertExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
sb.insert(6, "Java ");
System.out.println(sb); // Output: Hello Java World
}
}
Returns: The StringBuffer object itself after insertion.
Example:
Explanation:
The insert method allows for inserting a string at a specific position, shifting the existing content.
delete(int start, int end)
Syntax: public StringBuffer delete(int start, int end)
Description: Deletes the characters between the specified start and end indices in the current StringBuffer
object.
Parameters:
start – the starting index (inclusive).
end – the ending index (exclusive).
Returns: The StringBuffer object itself after deletion.
Example:
deleteCharAt(int index)
Syntax: public StringBuffer deleteCharAt(int index)
Description: Deletes the character at the specified index from the current StringBuffer object.
Parameters:
index – the index of the character to delete.
Returns: The StringBuffer object itself after deletion.
Example:
Explanation:
The deleteCharAt method removes a single character at the specified index.
reverse()
Syntax: public StringBuffer reverse()
Description: Reverses the sequence of characters in the current StringBuffer object.
Returns: The StringBuffer object itself with characters reversed.
Example:
Explanation:
The reverse method reverses the entire sequence of characters in the StringBuffer.
Example:
Explanation:
The replace method replaces the content within the specified range with a new string.
toString()
Syntax: public String toString()
Description: Converts the StringBuffer object to a String object.
Returns: A String representing the current StringBuffer content.
Example:
Explanation:
The toString method is used to get the string representation of the StringBuffer content.
Practice program:
// 1. Append
sb.append(" Talk");
System.out.println("After append: " + sb); // Output: Tech Talk
// 2. Insert
sb.insert(5, "y ");
System.out.println("After insert: " + sb); // Output: Techy Talk
// 3. Delete
sb.delete(5, 7);
System.out.println("After delete: " + sb); // Output: Tech Talk
// 4. DeleteCharAt
sb.deleteCharAt(4);
System.out.println("After deleteCharAt: " + sb); // Output: TechTalk
// 5. Reverse
sb.reverse();
System.out.println("After reverse: " + sb); // Output: klaThceT
// 6. Replace
sb.replace(0, 3, "Code");
System.out.println("After replace: " + sb); // Output: CodeThceT
// 7. ToString
String str = sb.toString();
System.out.println("StringBuffer to String: " + str); // Output: CodeThceT
}
}
Do It Yourself
1. Write a program that appends " Java" to the given StringBuffer "Hello".
2. Write a program that inserts "Beautiful " at index 6 in the StringBuffer "Hello World".
3. Write a program that deletes characters from index 6 to 11 in the StringBuffer "Hello World Java".
4. Write a program that reverses the content of the StringBuffer "Java Programming".
5. Write a program that replaces characters from index 0 to 4 with "Hi" in the StringBuffer "Hello
World".
Quiz
A) insert()
B) append()
C) replace()
D) reverse()
Answer: B) append()
2. What will sb.delete(0, 5) return if sb = new StringBuffer("Hello World")?
A) Hello World
B) World
C) World
D) ello World
Answer: C) World
A) deleteCharAt()
B) delete()
C) insert()
D) replace()
Answer: A) deleteCharAt()
Answer: B) avaj
A) toString()
B) toCharArray()
C) substring()
D) append()
Answer: A) toString()
Introduction to Multithreading
Imagine you're juggling multiple tasks at once. You might be cooking dinner, talking on the phone, and
watching TV. Each task is like a separate thread, running independently but within the same context
(your daily life).
In Java, multithreading allows your program to perform multiple tasks simultaneously, just like juggling.
This can make your programs faster and more responsive.
What is Multithreading?
Multithreading is a feature in Java that allows multiple threads to run concurrently within a single process.
This capability enables efficient execution of various tasks and operations in parallel, enhancing the
performance and responsiveness of applications.
Definition: Multithreading is the concurrent execution of two or more threads within a single process. Each
thread shares the same memory space but operates independently, allowing for simultaneous task execution.
Use Cases: Commonly used in applications such as games, animations, and real-time systems where multiple
operations need to be performed concurrently.
Multitasking is the process of performing multiple tasks simultaneously, and it can be achieved in two
primary ways:
1. Process-Based Multitasking (Multiprocessing):
Definition: Involves executing multiple processes simultaneously, where each process has its own memory
space.
Characteristics:
Definition: Involves executing multiple threads within the same process, sharing the same memory space.
Characteristics:
A thread is the smallest unit of processing within a process, also known as a lightweight subprocess. It
represents a separate path of execution within a process.
Characteristics:
Lightweight: Threads share the same memory space and resources of the parent process, reducing
overhead.
Independence: Threads operate independently; an exception in one thread does not affect others.
Shared Memory: Threads share memory and resources, facilitating communication and reducing
memory usage.
Sometimes, the processes might be interdependent for an intermediate result to finish the process.
In Java, threads are the smallest unit of a process, and they can be categorized into two main types
based on how they are created and executed. Each type of thread serves different purposes depending
on the needs of an application.
1. User Threads
User threads are the main type of threads that are created by the application developer to perform specific
tasks. These threads keep running in the JVM until they finish their execution or are explicitly
terminated. If a user thread is running, the Java Virtual Machine (JVM) will not shut down.
• The JVM waits for all user threads to complete before shutting down.
• User threads are used to perform specific tasks such as processing data, handling network connections,
etc.
Example:
2. Daemon Threads
Daemon threads are special types of threads in Java that provide services to user threads. These
threads run in the background to support other user threads. A key characteristic of daemon threads is
that the JVM does not wait for them to finish; when all user threads have finished, the JVM
automatically terminates all daemon threads, even if they are still running.
Daemon threads are generally used for background tasks like garbage collection, monitoring, or
logging, where the task doesn’t need to keep the JVM alive.
• Daemon threads run in the background and provide support to user threads.
• They are terminated automatically when no user threads are left running.
• Daemon threads can be set by calling setDaemon(true) on a thread object.
Example:
class MyDaemonThread extends Thread {
public void run() {
while (true) {
System.out.println("Daemon thread is running");
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyDaemonThread daemonThread = new MyDaemonThread();
daemonThread.setDaemon(true); // Setting thread as daemon
daemonThread.start();
Explanation:
In this example, MyDaemonThread is set as a daemon thread using setDaemon(true). This thread will
run in an infinite loop but will be terminated as soon as the main thread completes. The JVM does not
wait for the daemon thread to finish.
Termination JVM waits for user threads to JVM terminates daemon threads when no
complete. user threads are left.
Creation Created by the developer for Created by the JVM or set by the
specific tasks. developer using setDaemon().
Default User threads are non-daemon Threads are non-daemon by default, must
Behavior by default. be explicitly set as daemon.
Daemon threads can be set using the setDaemon() method before the thread is started. Once a thread
is started, it cannot be changed to a daemon thread.
t.start();
In Java, a thread goes through five distinct stages in its lifecycle. Each stage plays a crucial role in how
the thread is created, executed, and terminated. Let's explore these stages in detail:
1. New
In the initial stage, called "New," the thread is created but has not yet started. At this point, the thread is
instantiated and remains in the new state until it is assigned a task and started.
2. Runnable
Once the thread is assigned a task, it moves to the "Runnable" state. In this stage, the thread is ready to
execute and is waiting for the CPU to schedule it.
3. Running
When the CPU allocates time to the thread, it enters the "Running" stage. At this point, the thread starts
executing its assigned task and continues until the task is completed or paused.
4. Waiting
In certain situations, a thread may need to wait for another process or resource to become available.
When this happens, the thread enters the "Waiting" state, where it halts temporarily until the
dependent process or resource is ready.
5. Dead
The final stage of a thread's lifecycle is the "Dead" state. Once the thread has completed its execution or
has been explicitly terminated, it enters this state. The thread is no longer active, and the JVM
considers it terminated.
After understanding the lifecycle of a thread, you can now explore how multithreading is implemented
in Java to manage multiple threads efficiently.
Multithreading is a core concept in modern programming that involves running multiple threads
concurrently within a single process. Understanding the need for multiple threads is crucial for
developing efficient, responsive, and high-performance applications. Here's a detailed exploration of
why multiple threads are necessary:
1. Improved Performance
a. Concurrent Execution:
Description: Multiple threads allow different tasks to be executed simultaneously, leading to better utilization
of CPU resources.
Example: In a web server, one thread can handle incoming requests, while another processes database
operations concurrently.
Description: Threads share the same memory space and resources of a process, reducing overhead compared
to creating multiple processes.
Example: An application performing multiple calculations simultaneously can utilize threads to distribute the
workload, improving overall performance.
2. Responsiveness
Description: Multithreading ensures that the user interface remains responsive while performing background
tasks, such as loading data or performing long computations.
Example: In a graphical user interface (GUI) application, a background thread can handle time-consuming
tasks, allowing the main thread to update the UI smoothly.
b. Real-Time Processing:
Description: Threads can handle real-time data processing without blocking the main execution flow.
Example: In a video game, separate threads can handle rendering, input processing, and game logic, ensuring
smooth gameplay.
Description: Threads can perform I/O operations concurrently, avoiding blocking and waiting times associated
with single-threaded execution.
Example: A file processing application can use separate threads to read from and write to files
simultaneously, reducing overall processing time.
Description: Servers and networked applications can handle multiple client requests concurrently by assigning
each request to a separate thread.
Example: A web server using threads can handle multiple client connections at once, improving throughput
and response time.
• Description: Large and complex tasks can be broken down into smaller, manageable threads, making the
design and implementation more straightforward.
• Example: A data processing application can divide a large dataset into chunks, with each thread
processing a chunk independently.
b. Asynchronous Operations:
• Description: Threads facilitate asynchronous operations, allowing tasks to run in the background while the
main program continues execution.
• Example: A network application can use threads to perform network communication asynchronously,
enabling other operations to proceed without waiting for the network response.
5. Enhanced Scalability
• Description: Applications designed with multithreading can scale better to handle increased loads by
adding more threads to distribute the workload.
• Example: An e-commerce platform can scale its thread pool to handle a surge in user requests during
peak shopping seasons.
• Description: Multithreaded applications can take advantage of multi-core processors, where each thread
runs on a separate core, improving parallel execution.
• Example: A computationally intensive application can utilize multiple cores by running different threads
on different cores, accelerating processing.
Multithreaded programming is particularly beneficial for taking full advantage of multi-core processors.
Here’s an in-depth look at how multithreading works in the context of multi-core processors, and the
benefits it provides:
a. Multi-core Architecture:
• Description: Multi-core processors have multiple processing units (cores) within a single physical chip.
Each core can execute instructions independently.
• Example: A quad-core processor has four cores, allowing it to execute four threads concurrently.
b. Parallel Processing:
• Description: Multi-core processors can perform parallel processing, where multiple tasks or threads are
executed simultaneously.
• Example: Different cores can handle different parts of a computation or different tasks within a program,
speeding up overall execution.
a. Enhanced Performance:
• Description: Multithreading allows a program to execute multiple threads in parallel, making full use of all
available cores.
• Example: An image processing application can use multiple threads to process different parts of an image
simultaneously, resulting in faster processing times.
b. Improved Responsiveness:
• Description: By running multiple threads concurrently, applications can remain responsive to user inputs
and other tasks even while performing intensive operations.
• Example: A media player can use one thread to handle user interface interactions and another to decode
and play audio/video.
• Description: Multithreading maximizes the utilization of available CPU resources, reducing idle times and
improving throughput.
• Example: A web server can handle multiple client requests concurrently, ensuring that all cores are
utilized effectively.
d. Scalability:
• Description: Multithreaded programs can scale efficiently with the number of cores, providing better
performance as more cores are added.
• Example: A scientific computing application can benefit from additional cores by distributing its
computational tasks across all available cores.
Description: Threads are created and managed using thread libraries and frameworks that allow specifying
the tasks to be executed concurrently.
Example: In Java, you can create threads using the Thread class or implementing the Runnable interface.
b. Synchronization:
• Description: To avoid conflicts and ensure data consistency when multiple threads access shared
resources, synchronization mechanisms are used.
• Example: Java provides synchronized methods and blocks to control access to critical sections of code.
c. Thread Scheduling:
• Description: The operating system or runtime environment schedules threads to run on different cores,
balancing the load and optimizing performance.
• Example: Java’s ExecutorService framework provides advanced scheduling and management of thread
pools.
d. Load Balancing:
• Description: Efficient distribution of tasks among threads to ensure balanced workload across all cores.
• Example: A task manager in an application can dynamically assign tasks to threads based on their current
load and availability.
• Description: Reduce the time threads spend waiting for access to shared resources to improve
performance.
b. Avoid Deadlocks:
• Description: Deadlocks occur when two or more threads are waiting indefinitely for resources held by
each other.
• Example: Ensure a consistent order of acquiring locks and use timeout mechanisms.
• Description: Manage a pool of reusable threads to handle tasks efficiently and avoid the overhead of
creating and destroying threads frequently.
• Example: Java’s ExecutorService provides thread pool management for handling concurrent tasks.
• Description: Ensure that the application design allows it to scale effectively with additional cores and
threads.
• Example: Structure the application to handle a variable number of threads and utilize parallelism where
appropriate.
5. Example Code
// Submitting tasks
executor.submit(() -> System.out.println("Task 1 executed by: " + Thread.currentThread().getName()));
executor.submit(() -> System.out.println("Task 2 executed by: " + Thread.currentThread().getName()));
In Java, multithreading is supported through the Thread class, which allows the creation and
management of threads within a Java program. A thread is a lightweight subprocess, the smallest unit
of processing. Java's Thread class is a part of the java.lang package, and it provides several methods to
create, control, and manage threads in a concurrent program.
To create a thread by extending the Thread class, you need to follow these steps:
• Override the run() method to define the task that will be executed by the thread.
• Create an instance of the new class and call the start() method to begin execution.
Syntax:
• The run() method is where you define the code that the thread will execute.
• The start() method initiates the thread's execution, calling the run() method internally.
sleep(long millis) Puts the current thread to sleep for a specified time.
3. Example Programs
Explanation:
• Two threads (thread1 and thread2) are created, and each thread prints numbers from 1 to 5 along with
the thread name.
• The setName() method assigns names to threads, and getName() is used to retrieve the name of the
current thread.
try {
thread1.join(); // Main thread waits for thread1 to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
• Context Switching: The process of storing the state of a thread and restoring the state of another thread.
Threads share the CPU in time slices.
• Concurrency: Multiple threads executing simultaneously, giving the illusion of parallelism in a single-core
processor.
• Parallelism: Actual simultaneous execution of threads on different processor cores in multi-core systems.
5. Advantages of Using the Thread Class
• Simplicity: Extending the Thread class provides an easy-to-use abstraction for creating threads.
• Control: Methods like sleep(), join(), and interrupt() offer precise control over thread execution.
Understanding the Thread class is essential for mastering multithreading in Java. The class provides all
the necessary tools to create and control threads. By utilizing multithreading, you can write more
responsive and efficient programs, particularly in environments where parallel processing or
concurrency is required.
Do It Yourself
1. Write a program that creates two threads and prints numbers from 1 to 5 in each thread. Ensure that the
main thread waits for the other two threads to complete using join().
2. Explain the difference between the start() and run() methods in the Thread class.
3. Create a thread using the Thread class to print "Hello, World!" five times with a delay of 1 second
between each print.
4. Write a Java program that demonstrates the use of the isAlive() method to check if a thread is still
running.
5. Write a program that creates three threads, each printing a different message. Use the sleep() method to
introduce a delay between messages.
6. Write a program that demonstrates the usage of getPriority() and setPriority() methods of the Thread
class.
Quiz
B. begin()
C. start()
D. init()
Answer: C. start()
B. The method runs in the same thread without creating a new one.
Answer: B. The method runs in the same thread without creating a new one.
3. Which of the following methods makes a thread pause for a specified amount of time?
A. sleep()
B. pause()
C. wait()
D. interrupt()
Answer: A. sleep()
Answer: A. sleep() pauses a thread, while join() waits for a thread to finish.
5. Which method would you use to prevent two threads from executing a critical section of code at the
same time?
A. start()
B. synchronized()
C. sleep()
D. yield()
Answer: B. synchronized()
When a Java program starts, it always runs the main thread by default. This thread is important
because it performs essential tasks such as handling user input, output, and system events. The main
thread is created by the JVM when the main() method is invoked.
• Created by JVM: The JVM automatically creates the main thread when a Java program is executed.
• Entry point: The main() method is the entry point for the main thread.
• Single-threaded execution: By default, all code in the main() method runs in the main thread.
• Control over other threads: The main thread can create and control other threads.
mainThread.setName("Primary Thread");
System.out.println("Renamed Thread: " + mainThread);
Output:
You can create a new thread by extending the Thread class and overriding its run() method. The run()
method contains the code that constitutes the new thread.
Syntax:
System.out.println("Thread is running...");
Example:
Output:
You can also create a thread by implementing the Runnable interface and passing an instance of your
class to a Thread object.
Syntax:
Example:
}
public static void main(String[] args) {
Output:
Here is a simple program that creates two threads by implementing the Runnable interface.
}
}
thread1.start();
thread2.start();
Expected Output:
TaskOne - Count: 1
TaskTwo - Count: 1
TaskOne - Count: 2
TaskTwo - Count: 2
...
TaskOne - Count: 5
TaskTwo - Count: 5
Do It Yourself
1. Write a Java program to create a new thread by extending the Thread class and display a message from the
new thread.
2. Create a Java program using the Runnable interface to print numbers from 1 to 10 in a separate thread.
3. What are the differences between creating a thread by extending Thread and implementing Runnable?
4. Write a Java program that creates two threads using the Runnable interface. One thread should print even
numbers and the other should print odd numbers.
5. Explain the lifecycle of a thread in Java. Provide an example.
Quiz
• a) run()
• b) start()
• c) execute()
• d) begin()
Answer: b) start()
• a) New
• b) Running
• c) Suspended
• d) Terminated
Answer: c) Suspended
5. What is the return type of the start() method in the Thread class?
• a) void
• b) int
• c) boolean
• d) Thread
Answer: a) void
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated
Each state represents a distinct phase in a thread’s life, from creation to execution, pausing, and finally
termination.
1. New State
When a thread is created but not yet started, it is in the New state. At this point, the thread has not started
executing the run() method.
• Syntax:
• Example:
System.out.println("Thread is running...");
}
2. Runnable State
Once the thread's start() method is called, it enters the Runnable state. In this state, the thread is ready to
run but waiting for CPU time to be allocated by the thread scheduler.
• Syntax:
• Example:
System.out.println("Thread is running...");
3. Blocked State
A thread enters the Blocked state when it tries to access a synchronized block or method that another
thread is currently holding. The thread remains blocked until the monitor lock is released by the other
thread.
• Syntax:
synchronized (object) {
// Critical section
• Example:
class SharedResource {
SharedResource resource;
MyThread(SharedResource resource) {
this.resource = resource;
resource.sharedMethod();
t1.start();
4. Waiting State
A thread is in the Waiting state when it is waiting indefinitely for another thread to perform a specific
action. For example, a thread might call the wait() method, waiting for a notification from another
thread.
Syntax:
synchronized (object) {
Example:
class SharedResource {
try {
resource.waitMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
A thread enters the Timed Waiting state when it is waiting for a specified amount of time. This occurs
when methods like sleep(long millis), wait(long millis), join(long millis), or parkNanos(long nanos) are
called.
• Syntax:
• Example:
try {
System.out.println("Thread is awake");
} catch (InterruptedException e) {
e.printStackTrace();
t1.start();
6. Terminated State
Once a thread finishes its execution or is terminated by the stop() method, it moves into the Terminated
state. A terminated thread cannot be restarted.
• Syntax:
• Example:
System.out.println("Thread is executing...");
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
A useful diagram to understand the lifecycle of a thread can be found here. (Note: Replace with actual
link if providing resources.)
Practice Program
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
t1.start();
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
Do It Yourself
1. What are the different states a thread can be in throughout its lifecycle?
2. Write a program to demonstrate the use of sleep() and wait() in Java threads.
3. What is the difference between the Runnable and Blocked states in Java threads?
4. Explain how a thread moves from the Waiting state to the Runnable state.
Quiz
1. Which of the following methods can move a thread from the Timed Waiting state to the Runnable state?
• a) sleep()
• b) notify()
• c) start()
• d) yield()
• Answer: b) notify()
• a) New
• b) Runnable
• c) Terminated
• d) Blocked
• Answer: c) Terminated
• a) sleep()
• b) join()
• c) wait()
• d) start()
• Answer: c) wait()
4. What happens when start() is called on a thread in the New state?
5. Which state does a thread enter when it’s trying to access a synchronized block held by another thread?
• a) Blocked
• b) Timed Waiting
• c) Terminated
• d) Runnable
• Answer: a) Blocked
In Java, threads are assigned priorities to determine the order in which they are scheduled for execution
by the thread scheduler. The thread scheduler uses these priorities to decide when each thread should
run. Thread priorities in Java are integers ranging from MIN_PRIORITY (1) to MAX_PRIORITY (10),
with NORM_PRIORITY (5) as the default.
Threads with higher priority are generally executed in preference to those with lower priority. However,
thread priority does not guarantee the precise order of execution because thread scheduling is platform-
dependent and is controlled by the underlying OS.
Parameters:
• newPriority: This integer value sets the priority of the thread. It must be between 1
(Thread.MIN_PRIORITY) and 10 (Thread.MAX_PRIORITY).
Examples
thread1.setPriority(Thread.MIN_PRIORITY); // Priority 1
thread2.setPriority(Thread.NORM_PRIORITY); // Priority 5
thread3.setPriority(Thread.MAX_PRIORITY); // Priority 10
thread1.start();
thread2.start();
thread3.start();
Output:
Thread-0 - Priority: 1
Thread-1 - Priority: 5
Thread-2 - Priority: 10
}
}
thread1.setPriority(Thread.MIN_PRIORITY); // Priority 1
thread2.setPriority(Thread.NORM_PRIORITY); // Priority 5
thread3.setPriority(Thread.MAX_PRIORITY); // Priority 10
thread1.start();
thread2.start();
thread3.start();
Explanation
• Thread Prioritization: In the above examples, thread1 is given the lowest priority
(Thread.MIN_PRIORITY), while thread3 is assigned the highest (Thread.MAX_PRIORITY). Although
thread priority influences scheduling, it doesn't guarantee that a higher priority thread will always run first.
• Platform Dependence: Thread scheduling and priority management are handled by the OS, and different
operating systems may have different policies on how threads are prioritized and executed.
Practice Program
t1.start();
t2.start();
t3.start();
}
Do It Yourself
1. Write a Java program that creates three threads with different priorities and prints the thread name and
priority.
2. What is the default thread priority in Java, and how can it be changed?
3. Explain how thread priorities influence thread scheduling.
4. How do thread priorities differ across platforms? Give an example of how this can affect program behavior.
5. Modify a multithreaded Java program where all threads have the same priority and observe the execution
order.
Quiz
• A) 1
• B) 5
• C) 10
• D) 0
Answer: B) 5
• A) setPriority()
• B) changePriority()
• C) threadPriority()
• D) updatePriority()
Answer: A) setPriority()
3. Which of the following is the maximum priority that a thread can have in Java?
• A) 10
• B) 5
• C) 1
• D) 100
Answer: A) 10
4. If two threads have the same priority, what decides their execution order?
5. Which of the following constants represents the minimum priority for a thread?
• A) Thread.MIN_PRIORITY
• B) Thread.LOW_PRIORITY
• C) Thread.MIN_PR
• D) Thread.PRIORITY_LOW
Answer: A) Thread.MIN_PRIORITY
4. Synchronization
Synchronization in Java
Introduction
In Java, synchronization is a mechanism that ensures that multiple threads can access shared resources
safely, preventing data inconsistency. When multiple threads access shared data or resources
concurrently, thread interference and memory consistency errors can occur. Synchronization helps by
allowing only one thread to access the resource at a time, maintaining thread safety.
When multiple threads access shared resources (e.g., objects, variables), synchronization is necessary to:
1. Avoid thread interference – This happens when one thread changes the shared data while another
thread is using it.
2. Ensure consistency – Prevents inconsistencies that arise from unsynchronized access to shared data by
multiple threads.
1. Synchronized Method: The entire method is locked for one thread at a time. Once one thread enters
the synchronized method, no other thread can enter any synchronized method of the same object.
2. Synchronized Block: Synchronizes only a specific block of code, allowing finer control over the
synchronization.
Syntax for Synchronization
1. Synchronized Method:
// synchronized code
2. Synchronized Block:
synchronized(object) {
class Table {
System.out.println(n * i);
try {
} catch (InterruptedException e) {
System.out.println(e);
Table t;
MyThread1(Table t) {
this.t = t;
t.printTable(5);
Table t;
MyThread2(Table t) {
this.t = t;
t.printTable(100);
t1.start();
t2.start();
}
Output:
10
15
20
25
100
200
300
400
500
In the above example, the printTable() method is synchronized, so only one thread can execute it at a
time, preventing data inconsistency.
class Table {
void printTable(int n) {
synchronized (this) {
System.out.println(n * i);
try {
} catch (InterruptedException e) {
System.out.println(e);
}
}
Table t;
MyThread1(Table t) {
this.t = t;
t.printTable(5);
Table t;
MyThread2(Table t) {
this.t = t;
t.printTable(100);
t2.start();
In this case, only the critical part of the method (synchronized block) is synchronized, allowing more
granular control over thread access.
Explanation
In Java, synchronization prevents thread interference and provides consistent results when multiple
threads work on shared resources. In the examples above, we use the synchronized keyword to lock the
shared resource (Table object) so that only one thread can access the resource at a time.
Practice Program
class Counter {
count++;
int getCount() {
return count;
MyCounterThread(Counter counter) {
this.counter = counter;
counter.increment();
t1.start();
t2.start();
t1.join();
t2.join();
In this practice program, two threads increment a shared counter. Due to synchronization, the final count
will be 2000, preventing race conditions.
Do It Yourself
1. Write a Java program to demonstrate the use of a synchronized method.
2. Modify the Counter example to demonstrate thread interference by removing synchronization. What issue
arises?
3. Explain the difference between a synchronized method and a synchronized block in Java.
4. Why is thread synchronization necessary? Give an example of thread interference.
5. Write a program using synchronized blocks to achieve thread-safe access to a shared resource.
Quiz
Answer: B) Prevents thread interference by allowing only one thread to execute a block of code at a
time.
3. Which of the following is the correct syntax for a synchronized method in Java?
Introduction
In multithreading, deadlock and race conditions are common problems that can occur when multiple
threads access shared resources. Understanding these issues is crucial for developing robust and reliable
multithreaded applications.
Deadlock in Java
Deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a
resource. It is a state where threads are stuck in a cycle of dependency.
Causes of Deadlock
1. Mutual Exclusion: At least one resource must be held in a non-shareable mode. Only one thread can
access the resource at a time.
2. Hold and Wait: A thread holding a resource is waiting to acquire additional resources held by other
threads.
3. No Preemption: Resources cannot be forcibly taken from threads holding them.
4. Circular Wait: A set of threads is waiting for each other in a circular chain.
Example of Deadlock
Here is a simple example illustrating deadlock:
class A {
b.last();
class B {
a.last();
}
public class DeadlockExample {
In this example, Thread 1 locks A and waits for B, while Thread 2 locks B and waits for A, resulting in a
deadlock.
A race condition occurs when two or more threads try to change shared data at the same time. The final
state of the data depends on the order of execution, which can lead to unpredictable and incorrect results.
void increment() {
count++;
int getCount() {
return count;
counter.increment();
};
t1.start();
t2.start();
t1.join();
t2.join();
}
}
In this example, Counter class is accessed by multiple threads without synchronization, leading to a race
condition. The count variable might not always reflect the expected result due to concurrent
modifications.
Race Condition
Prevention Techniques
Avoiding Deadlock
1. Avoid Nested Locks: Minimize the number of locks and avoid acquiring multiple locks if possible.
2. Lock Ordering: Ensure that locks are acquired in a consistent order across threads.
3. Timeouts: Use timeouts when trying to acquire locks to avoid waiting indefinitely.
4. Deadlock Detection: Implement algorithms to detect deadlock situations and handle them gracefully.
class A {
class B {
class Counter {
count++;
}
int getCount() {
return count;
In this example, the increment() method is synchronized to prevent race conditions by ensuring that only
one thread can execute it at a time.
Do It Yourself
1. Write a Java program that simulates a deadlock situation. Implement a mechanism to detect and recover
from the deadlock.
2. Modify the Counter example to use synchronization to prevent the race condition. Verify that the final
count is always correct.
3. Create a Java program demonstrating deadlock avoidance by enforcing lock ordering.
4. Write a program that uses AtomicInteger to handle increments safely without synchronization.
5. mplement a timeout mechanism to prevent deadlocks in a multi-threaded program.
Quiz
Answer: B) A state where threads are stuck waiting for each other indefinitely.
Answer: C) AtomicInteger
2. Inter-thread Communication
Introduction
In multithreaded programs, threads often need to cooperate with each other, and inter-thread
communication is the mechanism that enables this cooperation. Java provides built-in methods to
facilitate communication between threads using synchronization primitives.
Key Concepts
1. Monitor: A synchronization construct that allows threads to coordinate their activities. Each object in Java
can act as a monitor.
2. Wait/Notify Mechanism: A way to manage the interaction between threads by putting threads into a
waiting state and notifying them when certain conditions are met.
Core Methods
1. wait(): Causes the current thread to wait until another thread invokes notify() or notifyAll() on the same
object.
2. notify(): Wakes up one of the threads that are waiting on the object’s monitor.
3. notifyAll(): Wakes up all the threads that are waiting on the object’s monitor.
Syntax
wait():
synchronized(object) {
object.wait();
notify():
synchronized(object) {
object.notify();
notifyAll():
synchronized(object) {
object.notifyAll();
class SharedResource {
while (isReady) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isReady = true;
System.out.println("Produced");
notify();
while (!isReady) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isReady = false;
System.out.println("Consumed");
notify();
resource.produce();
});
resource.consume();
});
producer.start();
consumer.start();
}
In this example, the produce() method waits if the resource is already produced and the consume()
method waits if the resource is not yet produced. The notify() method is used to signal the other thread
when the resource is ready or consumed.
Inter-thread Communication
Do It Yourself
1. Explain how wait() and notify() work in Java. Illustrate with a simple example.
2. Implement a program that demonstrates the use of notifyAll() to wake up multiple threads.
3. What are the key differences between wait() and sleep()? Provide examples where each would be
appropriately used.
4. Write a program that uses inter-thread communication to solve the producer-consumer problem.
5. Discuss the importance of synchronization when using wait() and notify(). What happens if the
synchronization is not used correctly?
Quiz
C) To release the lock on an object and make the current thread wait.
Answer: C) To release the lock on an object and make the current thread wait.
2. Which method wakes up one of the threads waiting on the object's monitor?
A) notifyAll()
B) resume()
C) notify()
D) wait()
Answer: C) notify()
3. What will happen if notify() is called without any thread waiting on the object's monitor?
4. Which of the following methods should be called from within a synchronized block?
A) wait()
B) notifyAll()
C) sleep()
D) Both A and B
Introduction
In Java, threads are the smallest units of execution within a process. They allow multiple tasks to run
concurrently. Managing the lifecycle of threads—suspending, resuming, and stopping them—can be
crucial in multi-threaded applications. This document provides a comprehensive guide to these concepts,
including explanations, examples, and practice problems.
1. Suspending Threads
Explanation:
In Java, a thread can be temporarily suspended using the suspend() method. However, it's important to
note that this method is deprecated due to potential issues like deadlocks and other synchronization
problems. Instead of suspend(), it's recommended to use other mechanisms like wait() and notify() for
thread communication and control.
Syntax:
Thread.suspend();
Example:
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
t.start();
System.out.println("Thread suspended");
System.out.println("Thread resumed");
}
2. Resuming Threads
Explanation:
A suspended thread can be resumed using the resume() method. Like suspend(), resume() is also
deprecated. It’s better to use wait() and notify() mechanisms to control thread execution.
Syntax:
Thread.resume();
Example:
3. Stopping Threads
Explanation:
To stop a thread, you should use the stop() method. However, this method is deprecated because it can
leave shared resources in an inconsistent state. Instead, use a flag to signal the thread to stop.
Syntax:
Thread.stop();
Example:
while (running) {
System.out.println("Thread running");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Thread stopped");
running = false;
t.start();
Practice Problem
Problem:
1. SuspensionThread - This thread prints numbers from 1 to 10, and after printing 5 numbers, it should be
suspended and then resumed.
2. ResumingThread - This thread should print a message every 1 second, and it should be stopped after 5
seconds.
3. StoppingThread - This thread should run indefinitely until a stop flag is set, then it should stop gracefully.
Code:
while (suspended) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
if (i == 5) {
suspendThread();
suspended = true;
}
suspended = false;
notify();
System.out.println("ResumingThread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("ResumingThread stopped");
System.out.println("StoppingThread running");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("StoppingThread stopped");
running = false;
t1.start();
t2.start();
t3.start();
Thread.sleep(2000);
t1.resumeThread();
Thread.sleep(3000);
t3.stopThread();
Do It Yourself
1. Explain why the suspend() and resume() methods are deprecated. What are the recommended alternatives?
2. Write a Java program using wait() and notify() to demonstrate thread suspension and resumption.
3. Modify the StoppingThread example to use the stop() method and discuss the issues encountered.
4. How can you safely stop a thread without using deprecated methods? Write a sample code to illustrate this.
5. Discuss the impact of thread suspension and resumption on thread safety and synchronization.
Quiz
• a) stop()
• b) suspend()
• c) wait()
• d) sleep()
Answer: b) suspend()
• a) resume()
• b) notify()
• c) start()
• d) continue()
Answer: a) resume()
3. What is a safer alternative to the deprecated stop() method for stopping a thread?
• a) Using Thread.stop()
• b) Using a boolean flag and checking it regularly
• c) Using Thread.interrupt()
• d) Using Thread.suspend()
• a) notifyAll()
• b) interrupt()
• c) notify()
• d) resume()
Answer: c) notify()
while (true) {
// Do something
});
t.start();
t.stop();
a) The thread will stop immediately, potentially leaving resources in an inconsistent state.
Answer: a) The thread will stop immediately, potentially leaving resources in an inconsistent state.
Introduction to JDBC (Java Database Connectivity)
Introduction
Java Database Connectivity (JDBC) is an API that allows Java applications to interact with databases. It
provides a standard interface for connecting to various databases, executing SQL queries, and managing
results. JDBC is essential for enterprise applications that require interaction with relational databases.
Definition of JDBC:
JDBC stands for Java Database Connectivity. It is a Java API used to connect and execute queries with
databases. JDBC is a specification from Sun Microsystems that provides a standard abstraction (API or
Protocol) for Java applications to communicate with various databases. It enables Java applications to
access and manipulate databases and spreadsheets, particularly relational databases (RDBs).
Current Version:
The current version of JDBC is JDBC 4.3, released on September 21, 2017.
Purpose of JDBC:
JDBC is crucial for enterprise applications created using Java EE technology. It provides efficient
database connectivity by enabling Java applications to interact with various databases, such as Oracle,
MS Access, MySQL, and SQL Server. JDBC, combined with database drivers, allows access to and
manipulation of data stored in relational databases.
1. JDBC Components
1. JDBC API
JDBC API provides methods and interfaces for communication with the database. It consists of two
packages:
• java.sql: Contains classes and interfaces for data access and processing in a relational database. Included in
Java Standard Edition (Java SE).
• javax.sql: Extends the functionality of java.sql by providing data source interfaces for connection pooling
and statement pooling. Included in Java Enterprise Edition (Java EE).
The DriverManager class loads database-specific drivers and establishes connections to databases. It
manages a list of database drivers and makes calls to process user requests.
The JDBC Test Suite is used to test operations performed by JDBC drivers, such as insertion, deletion,
and updates.
JDBC-ODBC Bridge Drivers connect database drivers to databases. They translate JDBC method calls
into ODBC function calls and use the sun.jdbc.odbc package, which includes a native library to access
ODBC characteristics.
2. JDBC Drivers
Explanation:
JDBC drivers implement the JDBC API to connect Java applications to databases. There are four types
of JDBC drivers:
1. Type 1: JDBC-ODBC Bridge Driver - Uses ODBC drivers to connect to the database.
2. Type 2: Native-API Driver - Converts JDBC calls into database-specific calls using native libraries.
3. Type 3: Network Protocol Driver - Converts JDBC calls into a database-independent network protocol,
which is then translated into database-specific calls.
4. Type 4: Thin Driver - Converts JDBC calls directly into database-specific calls.
Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
try {
System.out.println("Connection established!");
} catch (SQLException e) {
e.printStackTrace();
Java Database Connectivity (JDBC) is an API that allows Java applications to interact with databases. It
provides a standard interface for connecting to various databases and executing SQL queries.
Application:
Description: A Java application (could be a Java applet or a servlet) that communicates with a data
source.
JDBC API:
Purpose: Provides methods to execute SQL statements and retrieve results from a database.
Important Interfaces:
Important Classes:
DriverManager:
Role: Manages a list of database drivers and establishes a connection between the Java application and
the database.
JDBC Drivers:
Purpose: Translate Java calls into database-specific calls. There are four types:
Two-Tier Model:
Description: Direct communication between the Java application and the database. The JDBC driver
enables this communication.
Example: A Java application on a client machine communicates directly with a database server.
Three-Tier Model:
Description: The application communicates with a middle tier (application server) that then
communicates with the database.
Example: A web application communicates with a middleware server, which then accesses the database.
4. What is an API?
Description: A set of rules and protocols for building and interacting with software applications. It allows
different software systems to communicate with each other without needing to understand each other's
code.
5. Working of JDBC
package com.example.jdbc;
import java.sql.*;
String query = "INSERT INTO students (id, name) VALUES (110, 'Smith')";
try {
Class.forName(driverClassName);
// Establish a connection
// Create a statement
Statement st = con.createStatement();
// Execute the query
con.close();
e.printStackTrace();
Explanation:
This example demonstrates how to use JDBC to insert data into a database. The DriverManager is used
to manage the connection, and the Statement is used to execute the SQL query.
Do It Yourself
Quiz
1. Which JDBC driver type is also known as the "Thin Driver"?
• A. Type-1
• B. Type-2
• C. Type-3
• D. Type-4
Answer: D. Type-4
• A. Driver
• B. Connection
• C. Statement
• D. ResultSet
Answer: C. Statement
• A. DriverManager.loadDriver()
• B. Class.forName()
• C. DriverManager.getConnection()
• D. Connection.createStatement()
Answer: B. Class.forName()
• A. Driver
• B. ResultSet
• C. Statement
• D. Connection
Answer: B. ResultSet
5. Consider the following code snippet:
while (rs.next()) {
Answer: C. Retrieve and display all data from the employees table
This guide will walk you through the process of installing MySQL and MySQL Connector/J, which is
essential for connecting Java applications to MySQL databases.
1. Installing MySQL
1. Setup Type: Choose "Developer Default" or "Server only" based on your needs.
2. Check Requirements: The installer will check for any missing dependencies and guide you through
installing them if necessary.
3. Configuration: Set up MySQL Server:
• Authentication Method: Choose either the default or use the "Use Strong Password Encryption"
option.
• Account Setup: Set up the root user password and create additional user accounts if needed.
• Server Configuration: Configure settings like port number (default is 3306) and character set.
4. Complete Installation: Click "Execute" to begin the installation. Once completed, the installer will provide
options to start MySQL Server and configure MySQL Workbench.
SELECT VERSION();
1. IDE Integration:
• Eclipse:
• Right-click your project in the Project Explorer.
• Select Properties > Java Build Path > Libraries > Add External JARs.
• Navigate to the extracted Connector/J directory and select mysql-connector-java-x.x.x-bin.jar.
• IntelliJ IDEA:
• Right-click on your project and select Open Module Settings.
• Go to Libraries and click + to add the JAR file.
2. Manual Configuration:
• If you are not using an IDE, add the mysql-connector-java-x.x.x-bin.jar file to your classpath manually.
Example Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish the connection
// Create a statement
// Execute a query
String query = "CREATE TABLE test (id INT PRIMARY KEY, name VARCHAR(50))";
stmt.executeUpdate(query);
con.close();
e.printStackTrace();
Explanation:
1. Which of the following is the correct URL format for connecting to a MySQL database?
• A. jdbc:mysql://localhost:3306/mydatabase
• B. jdbc:oracle:localhost:3306/mydatabase
• C. jdbc:sqlserver://localhost:3306/mydatabase
• D. jdbc:postgresql://localhost:3306/mydatabase
Answer: A. jdbc:mysql://localhost:3306/mydatabase
• A. 1433
• B. 1521
• C. 3306
• D. 5432
Answer: C. 3306
• A. Statement
• B. DriverManager
• C. Connection
• D. ResultSet
Answer: B. DriverManager
Answer: C. It contains the JDBC driver for connecting Java applications to MySQL
Setting up a JDBC (Java Database Connectivity) environment involves several steps to ensure that your
Java application can interact with a database. This guide provides detailed instructions for setting up the
JDBC environment, including installation, configuration, and basic usage.
1. Choose the appropriate version of the JDK for your operating system (Windows, macOS, Linux).
2. Download and install the JDK by following the provided instructions.
java -version
SELECT VERSION();
1. IDE Integration:
• Eclipse:
• Right-click your project in the Project Explorer.
• Select Properties > Java Build Path > Libraries > Add External JARs.
• Navigate to the extracted Connector/J directory and select mysql-connector-java-x.x.x-bin.jar.
• IntelliJ IDEA:
• Right-click on your project and select Open Module Settings.
• Go to Libraries and click + to add the JAR file.
2. Manual Configuration:
• If you are not using an IDE, add the mysql-connector-java-x.x.x-bin.jar file to your classpath manually.
In your Java application, you need to load the JDBC driver class. For MySQL Connector/J, this can be
done using Class.forName():
Class.forName("com.mysql.cj.jdbc.Driver");
Once connected, you can create Statement or PreparedStatement objects to execute SQL queries:
Statement stmt = con.createStatement();
while (rs.next()) {
rs.close();
stmt.close();
con.close();
Example Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish a connection
// Create a statement
// Execute a query
while (rs.next()) {
// Close resources
rs.close();
stmt.close();
con.close();
e.printStackTrace();
Explanation:
Do It Yourself
1. Explain the steps involved in installing the JDK and verifying its installation.
2. Describe the process of downloading and adding MySQL Connector/J to a Java project using Eclipse.
3. Write a JDBC program to connect to a MySQL database and create a table named students with columns id
and name.
4. How do you load the JDBC driver for MySQL in a Java application?
5. What is the purpose of DriverManager.getConnection() method in JDBC?
Quiz
• A. DriverManager.getConnection()
• B. Statement.execute()
• C. ResultSet.getString()
• D. Class.forName()
Answer: A. DriverManager.getConnection()
• A. 1433
• B. 3306
• C. 1521
• D. 5432
Answer: B. 3306
• A. Connection
• B. ResultSet
• C. Statement
• D. DriverManager
Answer: C. Statement
while (rs.next()) {
Answer: C. Retrieves and displays all records from the employees table
Establishing JDBC Database Connections
Establishing a JDBC (Java Database Connectivity) connection is a fundamental step in interacting with a
database using Java. This guide covers the steps and key concepts involved in setting up and managing
JDBC connections.
To interact with a database using JDBC, you need to follow these essential steps:
1. Load the JDBC Driver: This step involves loading the JDBC driver class that facilitates communication
between Java and the database.
2. Establish a Connection: Use the DriverManager class to create a connection to the database.
3. Create a Statement: Create a Statement, PreparedStatement, or CallableStatement object to execute SQL
queries.
4. Execute Queries: Run SQL queries using the statement object.
5. Process Results: Retrieve and process the results of the queries.
6. Close Resources: Properly close the ResultSet, Statement, and Connection to free up resources.
Syntax:
Class.forName("com.mysql.cj.jdbc.Driver");
Explanation:
• Class.forName("com.mysql.cj.jdbc.Driver") loads the MySQL JDBC driver class into memory, which is
required to establish a connection to the database.
\
3. Establishing a Connection
Syntax:
Explanation:
url: The URL of the database to connect to. It includes the protocol (jdbc:mysql), the host (localhost), the
port (3306), and the database name (mydatabase).
Syntax:
Explanation:
• Statement: Creates a Statement object for sending SQL statements to the database.
• executeQuery(): Executes a SQL query and returns the result in a ResultSet object.
5. Processing Results
Syntax:
while (rs.next()) {
Explanation:
• ResultSet: Represents the result set of a query. The next() method moves the cursor to the next row.
• getInt("id"): Retrieves the value of the id column.
• getString("name"): Retrieves the value of the name column.
6. Closing Resources
Syntax:
rs.close();
stmt.close();
con.close();
Explanation:
• close(): Closes the ResultSet, Statement, and Connection to free up database resources.
7. Practice Programs
1. Basic JDBC Connection: Write a Java program to connect to a MySQL database and print the current
date using SELECT NOW();.
2. Insert Data: Write a Java program to connect to a MySQL database and insert a new record into a table
named students with columns id and name.
3.Update Data: Write a Java program to connect to a MySQL database and update the name of a student
with a specific id in the students table.
4. Delete Data: Write a Java program to connect to a MySQL database and delete a record from the students
table based on a specific id.
5. Retrieve Data: Write a Java program to connect to a MySQL database, retrieve all records from the
students table, and print them.
Do It Yourself
1. Explain the purpose of loading the JDBC driver class in a JDBC application.
2. How do you establish a connection to a MySQL database using JDBC? Provide a code example.
3. Write a JDBC program to create a table named employees with columns id, name, and salary.
4. What are the steps to execute a SQL query using JDBC and process the results?
5. Why is it important to close JDBC resources like ResultSet, Statement, and Connection?
Quiz
1. Which method is used to load the JDBC driver class in a Java application?
• A. DriverManager.getConnection()
• B. Class.forName()
• C. Statement.executeQuery()
• D. ResultSet.next()
Answer: B. Class.forName()
3. Which JDBC object is used to execute SQL queries and update statements?
• A. Connection
• B. ResultSet
• C. Statement
• D. DriverManager
Answer: C. Statement
Answer: B. Moves the cursor to the next row in the result set
The ResultSet interface in JDBC is used to handle the result set of a query executed against a database. It
allows you to retrieve and manipulate the data returned by a SQL query. This guide covers the essential
aspects of working with the ResultSet interface, including its methods, usage, and best practices.
1. Overview of ResultSet Interface
The ResultSet interface represents a table of data resulting from a query. It provides methods to iterate
through the rows and retrieve data from columns. The ResultSet is automatically created by executing a
SQL query using a Statement or PreparedStatement object.
Key Points:
2. Creating a ResultSet
Syntax:
Explanation:
Statement.createStatement(): Creates a Statement object for sending SQL statements to the database.
Key Methods:
while (rs.next()) {
• previous(): Moves the cursor to the previous row (if the ResultSet type is scrollable).
rs.previous();
• first(): Moves the cursor to the first row (if the ResultSet type is scrollable).
rs.first();
• last(): Moves the cursor to the last row (if the ResultSet type is scrollable).
rs.last();
Key Methods:
int id = rs.getInt("id");
Example:
• Always Check for Valid Data: Use ResultSet methods carefully to avoid SQLException and ensure proper
handling of null values.
• Close ResultSet and Other Resources: Always close ResultSet, Statement, and Connection to prevent
resource leaks.
• Use Column Indexes for Efficiency: In cases where column labels might be subject to change, use column
indexes to access data.
rs.close();
stmt.close();
con.close();
7. Practice Programs
1. Retrieve All Records: Write a Java program to connect to a MySQL database, retrieve all records from a
table named employees, and print each record's id, name, and salary.
2. Process Specific Column Data: Write a Java program to connect to a MySQL database, retrieve and print
the names of all employees who have a salary greater than a specific amount.
3. Retrieve Data Based on Date: Write a Java program to connect to a MySQL database, retrieve all
employees who were hired after a specific date, and display their names and hire dates.
4. Handle Null Values: Write a Java program to handle potential null values when retrieving data from a
ResultSet, and ensure your code does not throw exceptions when encountering nulls.
5. Pagination Example: Write a Java program to fetch a subset of records from the employees table,
implementing pagination to retrieve records in chunks (e.g., 10 records per page).
Do It Yourself
Quiz
1. Which method is used to move the cursor to the next row in a ResultSet?
• A. previous()
• B. first()
• C. next()
• D. last()
Answer: C. next()
• A. rs.getString("columnName")
• B. rs.getInt("columnName")
• C. rs.getDouble("columnName")
• D. rs.getObject("columnName")
Answer: A. rs.getString("columnName")
3. Which method would you use to check if there are more rows in a ResultSet?
• A. rs.isLast()
• B. rs.next()
• C. rs.previous()
• D. rs.first()
Answer: B. rs.next()
4. What does the ResultSet.getObject() method do?
• A. getBoolean()
• B. getDate()
• C. getInt()
• D. getSize()
Answer: D. getSize()
JavaFX Scene Builder is a visual layout tool that allows developers to design JavaFX application user
interfaces (UIs) without writing any code. It provides a drag-and-drop interface for arranging UI
components and creating FXML (FXML is an XML-based language used to define the structure of a
JavaFX user interface). This guide will cover the basics of JavaFX Scene Builder, including its features,
syntax, and usage.
JavaFX Scene Builder is a graphical user interface tool used to design JavaFX applications. It enables
developers to visually build and configure user interfaces for JavaFX applications. Scene Builder
generates FXML files that can be loaded into JavaFX applications at runtime.
Key Features:
• Drag-and-Drop Interface: Allows easy placement of UI elements.
• Real-Time Preview: Provides a real-time preview of the UI as it is designed.
• Property Configuration: Enables configuration of UI component properties through an intuitive interface.
• Event Handling: Allows setting up event handlers for UI components.
• Visit the Scene Builder download page to download the latest version of Scene Builder.
• Follow the installation instructions for your operating system.
• Scene Builder can be integrated with IDEs like IntelliJ IDEA, Eclipse, or NetBeans. This integration allows
seamless opening of FXML files within the IDE.
3. Adding UI Components:
• Drag and drop UI components (e.g., Button, Label, TextField) from the Library panel onto the design
canvas.
• Use the Inspector panel to set properties (e.g., text, size, alignment) for the selected component.
• Select a UI component and go to the Code panel to set up event handlers (e.g., onAction for a
Button).Example: Creating a simple UI with a Button and Label:
• Drag a Button from the Library panel.
• Drag a Label from the Library panel.
• Use the Inspector to set the Button text to "Click Me" and the Label text to "Hello, JavaFX!".
Example Code:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
@Override
primaryStage.show();
launch(args);
}
5. Practice Programs
1. Simple Form Design: Create a form with TextField, PasswordField, Button, and Label. Use Scene Builder
to design the form and set up an event handler for the button to display the entered text.
2. Calculator Layout: Design a simple calculator UI with buttons for digits (0-9), operations (+, -, *, /), and
an TextField for the display. Arrange the buttons in a grid layout.
3. Login Window: Create a login window with TextField for username, PasswordField for password, and
Button for login. Design the UI using Scene Builder and set up an action for the login button.
4. Student Registration Form: Design a registration form with fields for name, email, and phone number,
and a Button for submission. Use Scene Builder to arrange and style the components.
5. To-Do List: Create a simple to-do list application UI with a ListView for tasks and TextField for adding
new tasks. Include Button for adding tasks and removing selected tasks.
Do It Yourself
Quiz
1. Which panel in Scene Builder allows you to add UI components to the design canvas?
• A. Library Panel
• B. Inspector Panel
• C. Code Panel
• D. Preview Panel
Answer: A. Library Panel
2. What file format does Scene Builder use to save user interface designs?
• A. XML
• B. JSON
• C. FXML
• D. HTML
Answer: C. FXML
3. How can you set up an event handler for a button in Scene Builder?
• A. load()
• B. initialize()
• C. FXMLLoader.load()
• D. SceneBuilder.load()
Answer: C. FXMLLoader.load()
JavaFX provides a comprehensive structure for creating graphical user interfaces (GUIs). The structure
of a typical JavaFX application window involves several core elements, including the Stage, Scene, and
Nodes. Understanding how these components interact allows developers to design well-structured and
functional applications.
1. Stage: The Stage class is the top-level container. It represents the window itself. Every JavaFX application
has a primary stage that is automatically created when the application is launched.
You can set the title of the stage, its size, and its visibility.
Syntax:
primaryStage.setTitle("JavaFX Application");
primaryStage.show();
2. Scene: The Scene class represents the content inside the stage. It contains all the UI components (nodes). A
Scene can hold one or more nodes arranged hierarchically.
• You can define different layouts like VBox, HBox, GridPane, etc., inside a scene.
Syntax:
primaryStage.setScene(scene);
3. Nodes: Nodes are the actual UI elements like buttons, text fields, labels, etc., that are added to the scene.
Nodes are part of the Scene Graph, a hierarchical structure where parent nodes can contain child nodes.
Syntax:
root.getChildren().add(button);
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class SimpleWindowApp extends Application {
@Override
root.getChildren().add(button);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
}
Explanation:
JavaFX provides several layout classes to organize the components inside the window:
4. BorderPane: Divides the scene into five regions: top, bottom, left, right, and center.
1. Design a window with a Label and a Button. Clicking the button should change the label's text.
2. Create a login form using VBox. Add TextField for username and PasswordField for password. Include a
Button for login.
3. Design a layout using HBox where you place three buttons side by side.
4. Create a simple calculator using GridPane. Add buttons for numbers and operations.
5. Use BorderPane to create a dashboard with a navigation bar at the top, content in the center, and a footer at
the bottom.
Quiz
• A. Stage
• B. Scene
• C. Node
• D. BorderPane
Answer: A. Stage
• A. HBox
• B. VBox
• C. GridPane
• D. StackPane
• Answer: B. VBox
• A. show()
• B. launch()
• C. display()
• D. setScene()
Answer: A. show()
• A. BorderPane
• B. GridPane
• C. VBox
• D. StackPane
Answer: B. GridPane
Displaying text and images is one of the core functionalities in building JavaFX applications. JavaFX
provides various classes like Label, Text, and ImageView to handle text and images in a user interface
(UI). This material will help engineering students understand how to work with these components to
create visually rich applications.
There are two main ways to display text in JavaFX: using the Label class and the Text class.
1. Label:
• Label is used to display short text or simple information, and it can also hold an image along with text.
• It's often used for UI elements like button labels, headers, etc.
Syntax:
2. Text:
• Text is used when you need more control over how the text is displayed, such as setting the font, color, size,
and alignment.
Syntax:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
@Override
// Creating a Label
text.setFont(new javafx.scene.text.Font(24));
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
Explanation:
• The code demonstrates displaying text using both Label and Text components in a JavaFX application.
• The text is displayed with different formatting, using a VBox layout to arrange them vertically.
To display images in JavaFX, the Image and ImageView classes are used.
1. Image:
• The Image class represents an image that can be loaded from a file, URL, or an input stream.
Syntax:
2. ImageView:
• The ImageView class is used to display the image on the screen. It is a Node that can be resized, rotated,
and manipulated in various ways.
Syntax:
imageView.setFitHeight(200);
imageView.setFitWidth(200);
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
imageView.setFitHeight(300);
imageView.setFitWidth(300);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
Explanation:
• This code displays an image loaded from a file (src/image.png) using ImageView. The image is resized to
fit the specified dimensions.
Picture of Example Output:
JavaFX allows you to display both text and images in the same UI component, like a Label or Button.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
// Loading an image
imageView.setFitHeight(50);
imageView.setFitWidth(50);
// Creating a Label with text and image
label.setContentDisplay(javafx.scene.control.ContentDisplay.TOP);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
Explanation:
• In this example, both an image and text are displayed inside a Label. The ContentDisplay property controls
the position of the image relative to the text (top, bottom, left, or right).
Do It Yourself
1. Create a JavaFX application that displays a welcome message using a Label and a decorative image below
it.
2. Create a simple image gallery with 3-5 images displayed in an HBox or GridPane.
3. Create a button with both an icon (image) and text. When the button is clicked, display a new image.
4. Create a profile card UI with an image (profile picture) and a name (text) below the image.
5. Create an application where the image can be resized dynamically using sliders to control the width and
height.
Quiz
1. Which class in JavaFX is used to display text with more control over its formatting?
• A. Label
• B. Text
• C. ImageView
• D. Button
Answer: B. Text
• A. setImage()
• B. setGraphic()
• C. setView()
• D. loadImage()
Answer: A. setImage()
3. Which property of a Label allows you to position the image relative to the text?
• A. setImagePosition()
• B. setGraphicPosition()
• C. setContentDisplay()
• D. setLabelPosition()
Answer: C. setContentDisplay()
4. How can you resize an image in JavaFX using ImageView?
5. Which of the following is a valid constructor for the Image class to load an image from a file?
• A. new Image("src/image.jpg")
• B. new Image("file:src/image.jpg")
• C. new Image("src/image")
• D. new ImageView("file:src/image.jpg")
JavaFX uses a powerful event-driven programming model. When an event occurs, an object is notified,
and it can respond to the event. There are three main components involved in event handling:
1. Event Source: The object (like a button, text field, etc.) on which the event occurred.
2. Event Object: This encapsulates the details of the event.
3. Event Handler: This handles the event. In JavaFX, it's typically an instance of EventHandler functional
interface.
1. Using setOnAction method: For simple event handling, you can use setOnAction to directly specify what
should happen when an event occurs.
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
});
2. Using Lambda Expressions: Lambda expressions simplify event handling by reducing the code required
to attach an event handler.
button.setOnAction(event -> {
});
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
// Creating a Button
button.setOnAction(event -> {
});
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
Explanation:
• This simple application demonstrates event handling by printing a message to the console when the button
is clicked.
• The event handler is attached using a lambda expression.
4. Handling Mouse Events
Mouse events allow you to respond to actions such as mouse clicks, drags, and movements.
node.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
});
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
// Creating a Label
label.setOnMouseClicked(event -> {
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
Explanation:
• This code demonstrates handling mouse click events. When the label is clicked, it updates the text to show
the x and y coordinates of the click.
Key events occur when the user interacts with the keyboard, such as pressing a key, releasing a key, or
typing.
node.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
});
Example: Handling Key Presses
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
// Creating a Label
label.setOnKeyPressed(event -> {
});
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
Explanation:
• The program listens for key press events. When a key is pressed, the label displays the key code.
Do It Yourself
1. Create a JavaFX application that performs basic arithmetic operations (addition, subtraction, multiplication,
and division) using buttons to trigger the calculations.
2. Create an application where a user can draw on the screen by clicking and dragging the mouse.
3. Create a login form with two text fields for username and password. Use button click events to validate the
credentials.
4. Create a small game where an object moves on the screen based on keyboard arrow key inputs.
5. Create a JavaFX app where clicking a button once prints "Clicked!" and double-clicking the button changes
its background color.
Quiz
A. setOnKeyPressed()
B. setOnAction()
C. setOnMouseClicked()
D. setOnKeyReleased()
Answer: B. setOnAction()
2. Which interface is commonly used for event handling in JavaFX?
A. EventSource
B. EventObject
C. EventHandler
D. EventStage
Answer: C. EventHandler
A. Creating threads
D. Loading images
A. setOnAction()
B. setOnMouseMoved()
C. setOnMouseClicked()
D. setOnMousePressed()
Answer: C. setOnMouseClicked()
A scene graph is a data structure that represents a graphical scene. Nodes in this graph can represent
various UI elements, such as controls, layouts, shapes, and other visual elements. The scene graph starts
with a root node, and all other nodes branch out from this root, forming a tree structure.
1. Leaf Nodes: Represent basic UI components like buttons, labels, text fields, etc.
2. Branch Nodes (Parent Nodes): These nodes group multiple child nodes and are often used to create
layouts. Examples include Pane, HBox, VBox, etc.
JavaFX provides several layout panes that are used to arrange nodes in a scene. Each layout pane
provides a different way of organizing and positioning child nodes.
a) Pane:
Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
@Override
pane.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
b) HBox:
Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
c) VBox:
Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
vbox.getChildren().addAll(btn1, btn2);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
d) BorderPane:
This layout divides the scene into five regions: top, bottom, left, right, and center.
Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
@Override
borderPane.setBottom(bottomButton);
borderPane.setLeft(leftButton);
borderPane.setRight(rightButton);
borderPane.setCenter(centerButton);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
e) GridPane:
This layout allows you to arrange nodes in a grid of rows and columns.
Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
@Override
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
Each layout pane allows you to control how child nodes are arranged through properties like spacing,
alignment, and padding.
• Spacing: Defines the distance between nodes (e.g., VBox and HBox).
• Padding: Defines the space between the content and the edges of the pane.
• Alignment: Determines how nodes are aligned within their pane (e.g., centered, left-aligned, etc.).
Example of Padding and Alignment:
A Scene in JavaFX can be created by placing a node at the root and then adding child nodes to this root
node, forming a tree-like structure (the scene graph).
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
HBox hbox = new HBox(10, btn1, btn2); // Add two buttons in an HBox
VBox vbox = new VBox(20, hbox, btn3); // Add the HBox and another button to a VBox
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
In this example, the layout of nodes in the scene graph is achieved by nesting HBox and VBox layouts.
Do It Yourself
1. Design a form using GridPane layout that collects user details such as name, email, password, and submit it
using a button.
2. Build a calculator interface using GridPane where buttons for numbers and operations (+, -, *, /) are placed
in a grid.
3. Create a JavaFX application using BorderPane where the top, bottom, left, and right regions contain
navigation buttons, and the center displays content.
4. Write a JavaFX app where users can dynamically add buttons to an HBox or VBox by clicking a button.
Quiz
2. Which layout allows nodes to be arranged freely without any predefined structure?
a) GridPane
b) BorderPane
c) Pane
d) HBox
Answer: c Pane
a) Stage
b) Scene
c) Node
d) Parent
Answer: d Parent
5. Which of the following methods is used to add padding around nodes in a layout?
a) setPadding()
b) setSpacing()
c) setAlignment()
d) setMargin()
Answer: a.setPadding()
In JavaFX, mouse events are used to detect and respond to mouse actions such as clicking, pressing,
dragging, or moving the mouse. JavaFX provides a rich API to handle mouse events, allowing
developers to create interactive and user-friendly applications.
The MouseEvent class in JavaFX is used to represent mouse actions, and it provides various methods to
capture information like the mouse's position, button clicks, and whether the mouse is being dragged.
To handle mouse events, you need to register an event handler on the node. This is typically done using
the setOnMouseClicked, setOnMousePressed, and similar methods provided by the node class.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MouseEventExample extends Application {
@Override
});
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
In this example, when the button is clicked, the program prints the coordinates of the click to the
console.
Mouse dragging is another commonly used feature, where actions are performed when the user holds the
mouse button and moves the mouse.
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
@Override
circle.setFill(Color.BLUE);
circle.setCenterX(event.getX());
circle.setCenterY(event.getY());
});
pane.getChildren().add(circle);
primaryStage.setScene(scene);
primaryStage.show();
}
launch(args);
This program allows you to click and drag the circle across the window. The circle’s center moves with
the mouse's movement while the button is pressed.
The MouseEvent class provides several methods to retrieve information about the mouse event:
• getX() and getY(): These methods return the mouse’s x and y coordinates relative to the node.
• getSceneX() and getSceneY(): These methods return the mouse’s coordinates relative to the scene.
• getScreenX() and getScreenY(): These methods return the mouse’s coordinates relative to the screen.
• isPrimaryButtonDown(): This method checks if the primary (usually left) mouse button is pressed.
• isSecondaryButtonDown(): This method checks if the secondary (usually right) mouse button is pressed.
In some cases, you might want to handle multiple types of mouse events for a node, such as
MOUSE_ENTERED and MOUSE_EXITED.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
label.setOnMouseEntered(event -> {
label.setText("Mouse Entered");
});
label.setOnMouseExited(event -> {
});
root.getChildren().add(label);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
In this example, when the mouse enters the label, the text changes to “Mouse Entered,” and when the
mouse leaves, it reverts to “Hover over me!”
Do It Yourself
1. Create a JavaFX application where clicking on different regions of the window changes the background
color of a Pane or Rectangle.
2. Build an application where users can drag multiple shapes (e.g., circles, squares) across the window.
3. Create an application that continuously tracks and displays the current mouse coordinates within a Pane.
4. Build an application where right-clicking an image zooms in, and left-clicking zooms out.
Quiz
1. Which method is used to get the X-coordinate of the mouse relative to the node?
a) getScreenX()
b) getX()
c) getSceneX()
d) getLocalX()
Answer: b. getX()
2. What event is triggered when the user moves the mouse with the button pressed?
a) MOUSE_DRAGGED
b) MOUSE_CLICKED
c) MOUSE_MOVED
d) MOUSE_PRESSED
Answer: a. MOUSE_DRAGGED
a) isPrimaryButtonPressed()
b) isPrimaryButtonDown()
c) isButtonDown()
d) isButtonPressed()
Answer: b. isPrimaryButtonDown()
4. What is the purpose of the setOnMouseDragged() method?
5. Which mouse event is typically used to detect a hover action over a node?
a) MOUSE_CLICKED
b) MOUSE_ENTERED
c) MOUSE_RELEASED
d) MOUSE_DRAGGED
Answer: b,MOUSE_ENTERED
References
Java GUI Mouse event demo - JavaFX GUI - Handling Mouse Event Demos