MODULE 4 PYQ
a) Illustrate the usage of the following methods related to String with
appropriate sample code. (i) length( ) (ii) charAt( ) (iii) equalsIgnoreCase( )
b) Discuss the need for thread synchronization. Explain how a method can be
synchronized with an example.
Why Thread Synchronization is Needed:
In Java, multithreading allows multiple threads to access shared resources
(like variables or methods) simultaneously. If threads are not properly
coordinated, data inconsistency and race conditions may occur.
Example Problem Without Synchronization:
If two threads update a shared variable at the same time, their operations may
interfere, leading to incorrect or unpredictable results.
Solution: Thread Synchronization
Java provides a mechanism called synchronization to ensure that only one
thread can access a method or block of code at a time. This prevents data
corruption and ensures consistency.
Explain the characteristics of the List interface in Java and its implementation
by classes such as ArrayList and LinkedList. Provide examples demonstrating
list operations.
Sure! Let’s break this down into easy parts so you can understand and
remember it well.
1. What is the List Interface in Java?
• List is a part of the Java Collections Framework.
• It represents an ordered collection (also known as a sequence).
• Allows duplicate elements.
• Elements can be accessed by their index (position).
• Commonly used classes that implement List:
o ArrayList
o LinkedList
o Vector
o Stack
2. Key Characteristics of List Interface
Feature Description
Ordered Maintains the insertion order
Index-based You can use get(index) to access items
access
Allows You can store the same element multiple times
duplicates
Grows/shrinks as elements are added/removed
Resizable (unlike arrays)
Null values Allows null values
3. ArrayList vs LinkedList
Feature ArrayList LinkedList
Structure Uses a dynamic array Uses a doubly linked list
Access Slower for access
Faster for get(index)
speed
Slower (elements need Faster (just changes links)
Insert/Delete
shifting)
Frequent
Best for Random access insertions/deletions
4. Example: Using ArrayList
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Banana"); // Duplicates allowed
// Access element by index
System.out.println("First fruit: " + fruits.get(0));
// Remove an element
fruits.remove("Banana"); // Removes first "Banana"
// Loop through list
System.out.println("All fruits:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Check if list contains an item
System.out.println("Contains Apple? " + fruits.contains("Apple"));
}
}
5. Example: Using LinkedList
import java.util.*;
public class LinkedListExample {
public static void main(String[] args) {
List<Integer> numbers = new LinkedList<>();
// Add elements
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Add element at start and end
((LinkedList<Integer>) numbers).addFirst(5);
((LinkedList<Integer>) numbers).addLast(40);
// Remove element
numbers.remove(Integer.valueOf(20));
// Print all elements
System.out.println("Numbers in list:");
for (int num : numbers) {
System.out.println(num);
}
}
}
6. Summary Points to Remember
• Use ArrayList when you need fast access.
• Use LinkedList when you need frequent insert/delete.
• Both implement List, so you can use common methods like:
o add(), remove(), get(), size(), contains(), etc.
Let me know if you want a table with methods and meanings or a practice
question!
Write a Java program to reverse a given string.
Explain how to concatenate two String objects in Java. Provide syntax and an
example. 3 8 Describe the sleep(), wait() and suspend() methods in a thread.
Explain how to concatenate two String objects in Java. Provide syntax and an
example. 3 8 Describe the sleep(), wait() and suspend() methods in a thread.
Sure! Let’s break down both your questions into clear, easy-to-study sections:
7. Concatenating Two Strings in Java
What is Concatenation?
Concatenation means joining two strings together.
Ways to Concatenate Strings in Java:
Method Description
+ operator Most common and simple
concat() method Built-in method of the String class
StringBuilder or Useful when joining many strings inside
StringBuffer loops
Syntax and Example
➤ Using + Operator:
String s1 = "Hello ";
String s2 = "World";
String result = s1 + s2;
System.out.println(result); // Output: Hello World
➤ Using concat() Method:
String s1 = "Good ";
String s2 = "Morning";
String result = s1.concat(s2);
System.out.println(result); // Output: Good Morning
8. Thread Methods: sleep(), wait(), suspend()
Let’s look at each one clearly:
1. sleep() Method
• Belongs to the Thread class.
• Makes the thread pause for a specified time (in milliseconds).
• Does not release the lock if the thread is holding one.
Syntax:
Thread.sleep(milliseconds);
Example:
try {
System.out.println("Sleeping for 2 seconds...");
Thread.sleep(2000); // 2000 ms = 2 seconds
System.out.println("Awake!");
} catch (InterruptedException e) {
e.printStackTrace();
}
2. wait() Method
• Defined in the Object class (not Thread).
• Causes the thread to wait until another thread calls notify() or notifyAll() on
the same object.
• Releases the lock during waiting.
Syntax:
synchronized (object) {
object.wait();
}
Example:
Used in thread communication – not usually shown alone.
3. suspend() Method (Deprecated)
• Suspends a thread’s execution until resumed.
• Deprecated due to the risk of deadlocks (it doesn’t release locks).
• Avoid using it. Use wait() or other safer techniques instead.
Example (Not recommended):
thread.suspend(); // Deprecated
thread.resume(); // Deprecated
Summary Table
Release Status
Method Class Usefulness
s Lock
Threa Pause Safe
sleep() No
d thread
Thread
wait() Object Yes coordinatio Safe
n
Release Status
Method Class Usefulness
s Lock
suspend( Threa Deprecate
No Old method
) d d
Let me know if you'd like visu
Draw and Explain the lifecycle of a thread showing the different states and
methods invoked.
Sure! Here's a clear explanation and diagram of the Thread Lifecycle in Java,
broken into parts for easy studying.
Thread Lifecycle in Java
A thread in Java goes through various states from creation to termination.
States of a Thread:
1. New
2. Runnable
3. Running
4. Blocked/Waiting
5. Timed Waiting
6. Terminated (Dead)
Lifecycle Diagram of a Thread
Let me describe it visually first (text-based) — I can also provide a proper
diagram image if you'd like.
+---------+ start() +-----------+
| New | ---------------------------> | Runnable |
+---------+ +-----------+
|
| (Scheduler picks thread)
v
+-----------+
| Running |
+-----------+
/ | \
/ | \
sleep()/wait() | completed/stop
/ |
+------------+<-----+ +-----------+
| Timed Wait | | Terminated|
+------------+ +-----------+
1. New State
• Thread is created but not started yet.
• Code:
• Thread t = new Thread();
2. Runnable State
• Thread is ready to run, waiting for CPU time.
• It may be picked anytime by the thread scheduler.
• Code:
• t.start();
3. Running State
• Thread is currently executing.
• Only one thread runs at a time on a single core.
• Comes here from Runnable when scheduler picks it.
4. Blocked / Waiting / Timed Waiting
Thread temporarily stops execution:
Type Method Description
synchronized Waiting to acquire a
Blocked lock
block/object
Waiting wait() Waiting indefinitely
Timed Waits for a specific
sleep(ms), join(ms) time
Waiting
5. Terminated (Dead) State
• Thread has finished execution or was stopped.
• Code:
o After run() method ends.
o Or when stop() (not recommended) is called.
Summary Table
State Trigger / Method Description
New new Thread() Thread created
Runnable start() Ready to run
Running CPU assigned Executing
Waiting wait() Waiting to be notified
Timed Waiting sleep(), join() Paused for a time
Blocked Enters locked block Waiting for lock
Terminated run() ends Finished
Would you like me to generate a neat diagram image for this thread lifecycle?
Sure! Here's a clear explanation and sample code for each of the String
methods you mentioned in Java. I've divided it into parts so it's easy to study.
(i) substring() Method
Purpose:
Extracts a portion of a string based on start and end index.
Syntax:
string.substring(startIndex); // from startIndex to end
string.substring(startIndex, endIndex); // from startIndex to endIndex-1
Example:
public class SubstringExample {
public static void main(String[] args) {
String text = "HelloWorld";
System.out.println(text.substring(5)); // Output: World
System.out.println(text.substring(0, 5)); // Output: Hello
}
}
(ii) replace() Method
Purpose:
Replaces one character or substring with another.
Syntax:
string.replace('oldChar', 'newChar');
string.replace("oldString", "newString");
Example:
public class ReplaceExample {
public static void main(String[] args) {
String text = "Java is fun";
System.out.println(text.replace("fun", "powerful")); // Output: Java is
powerful
}
}
(iii) equals() Method
Purpose:
Checks if two strings are exactly equal (case-sensitive).
Syntax:
string1.equals(string2)
Example:
public class EqualsExample {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // Output: false
}
}
(iv) toLowerCase() Method
Purpose:
Converts all characters in the string to lowercase.
Syntax:
string.toLowerCase()
Example:
public class ToLowerCaseExample {
public static void main(String[] args) {
String text = "JAVA Programming";
System.out.println(text.toLowerCase()); // Output: java programming
}
}
Summary Table:
Method Description Example Output
Extracts part of a "HelloWorld".substring(5) →
substring() "World"
string
Replaces
replace() characters or "fun".replace("f", "r") → "run"
substrings
Compares two
equals() strings (case- "Hi".equals("hi") → false
sensitive)
Converts to "HELLO".toLowerCase() →
toLowerCase() "hello"
lowercase
Let me know if you'd like all these in a combined runnable Java file!
Write a java program to count the occurrence of a particular word within a
sentence using string handling methods.
Here's a simple Java program that counts the occurrence of a particular word
within a sentence using String handling methods like split(), equals(), and
toLowerCase():
Java Program: Count Word Occurrence in a Sentence
import java.util.Scanner;
public class WordCountExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input sentence
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
// Input word to search
System.out.print("Enter the word to count: ");
String word = sc.nextLine();
// Convert both to lowercase to ignore case differences
String[] words = sentence.toLowerCase().split(" ");
String target = word.toLowerCase();
int count = 0;
for (String w : words) {
if (w.equals(target)) {
count++;
}
}
System.out.println("The word '" + word + "' occurs " + count + " time(s).");
sc.close();
}
}
Sample Output:
Enter a sentence: Java is easy. Java is powerful. Java is everywhere.
Enter the word to count: Java
The word 'Java' occurs 3 time(s).
String Methods Used:
• split(" ") → Splits sentence into words.
• equals() → Checks word match.
• toLowerCase() → Case-insensitive comparison.
Let me know if you’d like a version that removes punctuation as well.
Describe the different character extraction methods of String class along with
their syntax. 3 8 Write notes on Array List in java.
Sure! Here's a concise 3-mark answer for each question as per typical exam
expectations:
1. Character Extraction Methods of String Class in Java
Java’s String class provides several methods to extract characters from a
string:
(i) charAt(int index)
• Returns the character at the specified index (0-based).
• Syntax:
• char ch = str.charAt(2);
(ii) getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
• Copies characters from the string into a character array.
• Syntax:
• str.getChars(0, 4, charArray, 0);
(iii) toCharArray()
• Converts the entire string into a character array.
• Syntax:
• char[] chars = str.toCharArray();
These methods are useful when individual characters or sub-parts of a string
need to be accessed or manipulated.
2. Notes on ArrayList in Java
• ArrayList is a resizable array implementation of the List interface in Java.
• It is present in java.util package and allows dynamic memory allocation.
Features:
• Can store duplicate elements.
• Maintains insertion order.
• Allows random access via index.
• Automatically resizes when elements are added/removed.
Example:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list); // [Apple, Banana]
}
}
ArrayLists are widely used for managing lists of data where resizing is
required frequently.
Let me know if you want these formatted for handwritten notes or flashcards!
Write short note on any four methods of String class.
Sure! Here's a short note on four commonly used methods of the String
class in Java, suitable for a 3-mark answer:
Short Note on Four String Methods:
1. length()
• Returns the number of characters in the string.
• Syntax: str.length();
• Example: "Hello".length() → 5
2. charAt(int index)
• Returns the character at the specified index (0-based).
• Syntax: str.charAt(2);
• Example: "Java".charAt(1) → 'a'
3. substring(int beginIndex, int endIndex)
• Returns a part of the string from beginIndex to endIndex - 1.
• Syntax: str.substring(0, 4);
• Example: "HelloWorld".substring(0, 5) → "Hello"
4. toLowerCase()
• Converts the entire string to lowercase.
• Syntax: str.toLowerCase();
• Example: "JAVA".toLowerCase() → "java"
Let me know if you want two more for a 5-mark question!
Write any three constructors of String class.
Here are three constructors of the String class in Java:
Three Constructors of the String Class:
1. String()
• Purpose: Creates an empty string (a string with no characters).
• Syntax:
• String str = new String();
• Example:
• String emptyStr = new String(); // Creates an empty string
• System.out.println(emptyStr); // Output: (empty string)
2. String(String original)
• Purpose: Creates a string that is a copy of the given string.
• Syntax:
• String str = new String("Hello");
• Example:
• String str = new String("Hello");
• System.out.println(str); // Output: Hello
3. String(char[] value)
• Purpose: Creates a string from an array of characters.
• Syntax:
• String str = new String(char[] value);
• Example:
• char[] chars = {'J', 'a', 'v', 'a'};
• String str = new String(chars);
• System.out.println(str); // Output: Java
These constructors are helpful in creating strings in different ways depending
on the available data (empty, copied, or from a character array).