java
count NO Question Repeats Chapter Page No
1 Differentiate/compare features of Java and C++; explain
1 4 Ch-1
features of Java.
2 16 Explain bitwise operators. 3 Ch-1
3 17 Explain shift operators with examples. 1 Ch-1
4 10 Explain the super keyword; explain super and this keywords. 2 Ch-2
5 11 Explain the final keyword. 1 Ch-2
6 Write programs for command-line operations (e.g.,
23 2 Ch-5
displaying digits with delays, counting vowels).
7 What is inheritance? Types of inheritance not supported in
6 2 Ch-2
Java; explain constructors in inheritance.
8 What is an interface? Why do we need it? Explain differences
7 1 Ch-2
between interface and abstract class.
9 Explain static method, static variable, and static block;
12 2 Ch-2
explain the static keyword.
10 Explain method overloading and overriding; differentiate
21 3 Ch-2
between overloading and overriding.
11 Explain runtime polymorphism with examples, including
22 3 Ch-2
runtime polymorphism using interfaces.
12 27 Explain constructor overloading in Java. 1 Ch-2
13 Explain try, catch, and finally blocks/keywords with
2 2 Ch-3
examples.
14 3 Differentiate between final, finalize, and finally. 1 Ch-3
15 Explain exception handling and user-defined exceptions with
5 3 Ch-3
examples.
16 Differentiate between String and StringBuffer; explain
24 2 Ch-3
methods of String and StringBuffer classes.
17 Explain methods of the String and StringBuffer classes; list
25 3 Ch-3
methods and explain selected ones.
18 Explain multithreading, thread states, and thread lifecycle
15 4 Ch-4
with examples; explain thread lifecycle.
19 Explain package creation and importing with examples;
18 4 Ch-4
create a subpackage and import it.
20 Explain linked lists, circular linked lists, and singly linked
13 3 Ch-5
lists with examples.
21 Explain applet lifecycle; discuss <applet> tag, Graphics
20 4 Ch-5
methods, and parameter passing in applets.
1 Differentiate between features of Java and C++. -ch-1
Compare features of Java and C++. -ch-1
Compare features of Java with any other object-oriented programming language.
ch-1
Explain features of Java. -ch-1
→
Features of Java Programming Language
1. Simple
o Java is easy to learn, with clean and simple syntax.
o Its syntax is similar to C++, making it easier for C++ programmers.
o Complex features like pointers and operator overloading are removed.
o Java has Automatic Garbage Collection, so it manages memory itself.
2. Object-Oriented
o Everything in Java is an object (it contains both data and behavior).
o It follows Object-Oriented Programming (OOPs), which helps in software
development.
o OOPs concepts in Java:
▪ Object
▪ Class
▪ Inheritance
▪ Polymorphism
▪ Abstraction
▪ Encapsulation
3. Platform Independent
o Unlike C and C++, Java can run on any platform (Windows, Linux, Mac, etc.).
o Java code is compiled into bytecode, which can be run anywhere.
o This is called Write Once, Run Anywhere (WORA).
o Java runs on a software-based platform with two parts:
▪ Runtime Environment
▪ API (Application Programming Interface)
4. Secured
o Java is safe from viruses and security threats.
o It does not use explicit pointers, which prevents hacking risks.
o Java programs run inside a virtual machine sandbox for safety.
o Java has:
▪ Classloader (separates local and network-imported classes).
▪ Bytecode Verifier (checks for illegal access).
▪ Security Manager (controls resource access like disk read/write).
o Additional security tools: SSL, JAAS, Cryptography.
5. Robust (Strong & Reliable)
o Uses strong memory management to prevent crashes.
o No pointers, which avoids security problems.
o Automatic Garbage Collection removes unused objects.
o Exception Handling helps handle runtime errors.
o Type checking ensures correct data types are used.
6. Architecture-Neutral
o Java programs work the same on any computer architecture.
o Example: In C, an int can take 2 bytes (32-bit) or 4 bytes (64-bit), but in
Java, it always takes 4 bytes.
7. Portable
o Java bytecode can be moved and run on any platform without changes.
8. High-Performance
o Java is faster than other interpreted languages.
o Java bytecode is close to native code, making it efficient.
o However, it is a bit slower than compiled languages like C++.
9. Distributed
o Java allows the creation of distributed applications (apps running across
networks).
o Technologies like RMI (Remote Method Invocation) and EJB (Enterprise
Java Beans) help in this.
o Java programs can access files or methods from other computers on the
internet.
10. Multi-threaded
• Java supports multi-threading, which allows multiple tasks to run at the same time.
• It shares memory between threads, making it efficient.
• Useful for multimedia, web applications, and more.
11. Dynamic
• Java supports dynamic loading of classes (loaded only when needed).
• It can use functions from C and C++.
• Java supports dynamic compilation and automatic memory management.
No. Topic C++ Java
1 Platform Works only on the system Works on any system with Java
where it is compiled (platform-independent).
(platform-dependent).
2 Usage Mostly used for system Mostly used for making
programming. applications (Windows, web,
mobile, etc.).
3 goto Supports the goto Does not support the goto
statement. statement.
4 Multiple Supports multiple Does not support multiple
Inheritance inheritance. inheritance directly. Uses
interfaces instead.
5 Operator Supports operator Does not support operator
Overloading overloading. overloading.
6 Pointers Uses pointers. You can Uses pointers internally but
write pointer programs. does not allow writing pointer
programs.
7 Call by Value Supports call by value and Only supports call by value (no
& Reference call by reference. call by reference).
8 Structures & Supports structures and Does not support structures and
Unions unions. unions.
9 Hardware More connected to Less connected to hardware.
Interaction hardware.
10 virtual Uses the virtual keyword Does not have virtual, but all
Keyword to decide function behavior. non-static methods act like
virtual functions by default.
-------------
16 Explain bitwise operators. -ch-1
Bitwise operator. -ch-1
Explain bitwise operators. -ch-1
7. Bitwise Operators
Perform bit-level operations.
Operator Symbol Uses
Bitwise AND & op1 & op2
Bitwise NOT ^ op1 ^ op2
Bitwise OR | op1 | op2
Bitwise Compliment ~ ~ op
Bitwise left shift << op1 << op2
Bitwise right shift >> op1 >> op2
1. Bitwise AND (&)
o Compares each bit of two numbers; result is 1 only if both bits are 1.
o Example: 6 & 3 → 0110 & 0011 → 0010 (2).
2. Bitwise XOR (^) (Not Bitwise NOT!)
o Compares bits; result is 1 if bits are different, 0 if same.
o Example: 6 ^ 3 → 0110 ^ 0011 → 0101 (5).
3. Bitwise OR (|)
o Compares each bit; result is 1 if at least one bit is 1.
o Example: 6 | 3 → 0110 | 0011 → 0111 (7).
4. Bitwise Complement (~)
o Inverts all bits (flips 0 to 1 and 1 to 0), using two’s complement.
o Example: ~6 → 0110 → 1001 (Output: -7).
5. Bitwise Left Shift (<<)
o Shifts bits left, multiplying the number by 2^n.
o Example: 6 << 1 → 0110 → 1100 (12).
6. Bitwise Right Shift (>>)
o Shifts bits right, dividing the number by 2^n (preserving sign).
o Example: 6 >> 1 → 0110 → 0011 (3).
Example :
int a = 6, b = 3; // BINARY: 6 = 0110, 3 = 0011
// Bitwise AND
System.out.println(a & b); // (6 = 0110 & 3 = 0011) → ANS = 2 = 0010
// Bitwise OR
System.out.println(a | b); // (6 = 0110 | 3 = 0011) → ANS = 7 = 0111
System.out.println(Integer.toBinaryString(a | b)); // Binary Output: 111
// Bitwise XOR
System.out.println(a ^ b); // (6 = 0110 ^ 3 = 0011) → ANS = 5 = 0101
// Bitwise Complement
System.out.println(~a); // 6 = 0110 → ~6 = -7 (Two's complement)
// System.out.println(Integer.toBinaryString(~a)); // Uncomment to see binary
representation
// Left Shift (a << b) = a * 2^b
System.out.println(a << 1); // 6 = 0110 << 1 → 6 * 2^1 = 12 = 1100
System.out.println(a << 2); // 6 = 0110 << 2 → 6 * 2^2 = 24 = 11000
// Right Shift (a >> b) = a / 2^b
System.out.println(a >> 1); // 6 = 0110 >> 1 → 6 / 2^1 = 3 = 0011
System.out.println(a >> 2); // 6 = 0110 >> 2 → 6 / 2^2 = 1 = 0001
-------------
17 Explain shift operators with example. -ch-1
Bitwise Shift Operators in Java
Shift operators move the binary digits (bits) of a number left or right. They are used for
fast calculations and bit-level operations.
Types of Shift Operators
1. Left Shift (<<) → Moves bits left and adds 0s on the right.
2. Right Shift (>>) → Moves bits right and keeps the sign bit (0 for positive, 1 for
negative).
3. Unsigned Right Shift (>>>) → Moves bits right and always fills 0s on the left (even
for negative numbers).
Operator Description Example Result
<< Left Shift 5 << 2 20
>> Right Shift 20 >> 2 5
>>> Unsigned Right Shift -20 >>> 2 Large positive number
1. Left Shift (<<)
• Moves all bits to the left by the given number of positions.
• Adds 0s on the right.
• Formula: a << b → a * 2^b (Multiplies the number by 2 for each shift).
Example:
int num = 5;
int result = num << 2;
System.out.println(result); // Output: 20
How it works:
• 5 in binary → 0000 0101
• 5 << 2 → 0001 0100 (Shifted left, added 00 on the right)
• Final value = 20
2. Right Shift (>>)
• Moves all bits to the right by the given number of positions.
• Keeps the sign bit (0 for positive numbers, 1 for negative numbers).
• Formula: a >> b → a / 2^b (Divides the number by 2 for each shift).
Example (Positive Number):
int num = 20;
int result = num >> 2;
System.out.println(result); // Output: 5
How it works:
• 20 in binary → 0001 0100
• 20 >> 2 → 0000 0101 (Shifted right, removed last 2 bits)
• Final value = 5
Example (Negative Number):
int num = -20;
int result = num >> 2;
System.out.println(result); // Output: -5
3. Unsigned Right Shift (>>>)
• Moves all bits to the right, but always fills 0s on the left (even for negative
numbers).
• No sign bit is copied.
Example (Positive Number):
int num = 20;
int result = num >>> 2;
System.out.println(result); // Output: 5
How it works:
• 20 in binary → 0001 0100
• 20 >>> 2 → 0000 0101 (Shifted right, filled 00 on the left)
• Final value = 5
Example (Negative Number):
int num = -20;
int result = num >>> 2;
System.out.println(result); // Output: 1073741819
How it works:
• -20 in binary (Two’s complement) → 1111 0110
• -20 >>> 2 → 0011 1111 1111 1111 1111 1111 1111 1011 (Shifted right,
filled 00 on the left)
• Final value = 1073741819 (Huge positive number)
15 What is multithreading? Explain thread states with diagram. -ch-4
Write a short note on Thread Life Cycle. -ch-4
What are threads in Java? List two ways to use threads in a class and explain one
with example. -ch-4
What is a thread? Explain thread lifecycle. -ch-4
Multithreading in Java (Simple Explanation)
Multithreading means running multiple tasks (threads) at the same time. A thread is a
small part of a program that runs separately. It is faster and uses less memory than
running multiple full programs (processes).
Multithreading is used in games, animations, and real-time applications to improve
speed and performance.
Advantages of Multithreading in Java
1. Smooth User Interface – Multiple tasks can run together without slowing down the
UI.
2. Faster Execution – Different tasks run at the same time, saving time.
3. Independent Threads – If one thread has an error, other threads keep working.
Life Cycle of a Thread (Thread States)
A thread goes through different states in its life, controlled by the Java Virtual Machine
(JVM):
1. New – Thread is created but not started yet.
2. Runnable – Thread is ready to run but waiting for CPU time.
3. Running – Thread is running after getting CPU time.
4. Blocked (Non-Runnable) – Thread is waiting, like during input/output operations.
5. Terminated (Dead) – Thread has finished running.
Methods to Control Thread States
• start() – Moves thread from New to Runnable.
• run() – Runs the thread’s task.
• sleep(milliseconds) – Pauses the thread for a given time.
• join() – Makes one thread wait until another thread finishes.
• interrupt() – Stops or interrupts a thread.
Thread Class Constructors (Ways to Create a Thread)
• Thread() – Creates a thread with no name.
• Thread(String name) – Creates a thread with a name.
• Thread(Runnable r) – Creates a thread with a task to run.
• Thread(Runnable r, String name) – Creates a thread with a task and a name.
Commonly Used Thread Methods
1. run() – Defines the task to be executed by a thread.
2. start() – Starts the thread, JVM runs the run() method.
3. sleep(milliseconds) – Pauses the thread for some time.
4. join() – Makes a thread wait until another thread dies.
5. join(milliseconds) – Makes a thread wait for a specific time.
6. getPriority() – Gets the thread’s priority.
7. setPriority(int priority) – Sets the thread’s priority.
8. getName() – Gets the thread’s name.
9. setName(String name) – Sets the thread’s name.
10. isAlive() – Checks if the thread is still running.
-Extra-
What are Threads in Java?
A thread in Java is a small, independent part of a program that runs separately. It helps
in multitasking, meaning multiple tasks can run at the same time. Java provides a built-
in Thread class to create and manage threads.
Two Ways to Use Threads in a Class:
1. Extending the Thread class
2. Implementing the Runnable interface
Explanation of Implementing the Runnable Interface:
This method is preferred because Java does not support multiple inheritance (a class
cannot extend multiple classes). Using the Runnable interface allows the class to extend
another class if needed.
Steps to Use Runnable Interface:
1. Create a class that implements the Runnable interface.
2. Override the run() method and write the task inside it.
3. Create a Thread object and pass the class object as an argument.
4. Start the thread using start().
Example:
class MyThread implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String args[]) {
MyThread obj = new MyThread();
Thread t = new Thread(obj); // Passing object to Thread class
t.start(); // Starting the thread
}
}
Explanation:
• Step 1: MyThread class implements Runnable.
• Step 2: run() method contains the task to be executed.
• Step 3: Thread t = new Thread(obj); creates a thread.
• Step 4: t.start(); starts the thread, and run() executes.
-----------
18 Explain package creation and importing with example. -ch-4
What is a package? How can we create a subpackage and import it into another
package? -ch-4
What is a package? How can we create a subpackage and import it into another
class? -ch-4
What is a package? Explain package creation and import in detail with example. ch-4
Packages in Java: Creation and Importing
1. What is a Package?
• A package in Java is a collection of related classes, interfaces, and sub-packages.
• It helps in organizing the code, preventing name conflicts, and providing access
control.
• Java provides built-in packages (java.util, java.io, etc.), and we can also create
user-defined packages.
2. How to Create a Package?
• A package is created using the package keyword at the beginning of a Java file.
• The file should be saved in a directory matching the package name.
Syntax:
package mypackage; // Declaring a package
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in mypackage!");
}
}
Steps to Compile and Run a Package:
1. Save the file as MyClass.java inside a folder named mypackage.
2. Compile the package:
3. javac -d . MyClass.java
o The -d . option tells Java to create the necessary package directories.
4. Run the class using its fully qualified name:
5. java mypackage.MyClass
3. How to Create a Subpackage?
• A subpackage is a package inside another package.
• It is created using dot (.) notation.
Example: Creating a Subpackage
package mypackage.subpack; // Declaring a subpackage
public class SubClass {
public void show() {
System.out.println("Hello from SubClass in
mypackage.subpack!");
}
}
Compiling the Subpackage:
javac -d . SubClass.java
4. How to Import a Package into Another Package?
• To use a class from one package in another package, import it using the import
keyword.
Example: Importing a Package into Another Package
package anotherpackage;
import mypackage.MyClass; // Importing MyClass from mypackage
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Compiling and Running:
1. Compile both packages:
javac -d . MyClass.java
javac -d . Test.java
2. Run the program:
java anotherpackage.Test
5. How to Import a Subpackage into Another Class?
• A subpackage can be imported into another class using:
o Specific Import:
o import mypackage.subpack.SubClass;
o Wildcard Import (to import all classes in a package):
o import mypackage.subpack.*;
Example: Importing a Subpackage into Another Class
package anotherpackage;
import mypackage.subpack.SubClass;
public class TestSub {
public static void main(String[] args) {
SubClass obj = new SubClass();
obj.show();
}
}
Compiling and Running:
1. Compile both files:
javac -d . SubClass.java
javac -d . TestSub.java
2. Run the program:
java anotherpackage.TestSub
-----------
13 What is a linked list? Give its advantages. Give differences between singly and singly
circular linked lists. -ch-5
What is a linked list? Explain circular linked list in Java with example. -ch-5
What is singly linked list? Write a program to create and display a singly linked list.
- ch-5
Linked List – Explanation, Advantages, Types, and Java Programs
What is a Linked List?
A Linked List is a data structure where elements (called nodes) are connected using
pointers. Each node contains:
1. Data – The value stored in the node.
2. Pointer (Next) – A reference to the next node in the sequence.
Unlike arrays, linked lists do not have a fixed size and allow dynamic memory allocation.
Advantages of Linked List
1. Dynamic Size – Can grow or shrink dynamically.
2. Efficient Insertions/Deletions – Faster than arrays for adding/removing elements,
as no shifting is required.
3. Memory Utilization – Uses memory efficiently since extra space is allocated as
needed.
4. No Wastage of Space – Unlike arrays, no need to pre-allocate memory.
5. Easy to Implement Data Structures – Used for stacks, queues, and graphs.
6. Efficient for Large Data Sets – Suitable when frequent insertions and deletions are
required.
Difference Between Singly Linked List and Singly Circular Linked List
Feature Singly Linked List Singly Circular Linked List
Last Node NULL (marks the end) First node (forms a loop)
Points To
Traversal Stops when reaching NULL Continues infinitely unless controlled
Insertion at Requires finding last node and Requires finding last node and linking it
End updating its next to new node to the new node, which then points to
the head
Deletion If the last node is deleted, no If the last node is deleted, the second
special handling is needed last node must be updated to point to
the head
Memory Less, as no extra pointer is Slightly more, as last node stores a
Usage needed for circular connection pointer to the first node
Efficiency Faster termination as it ends May cause infinite loop if not handled
at NULL properly
Use Cases Used in stacks, queues, and Used in round-robin scheduling,
simple data storage multiplayer games, and circular buffers
Reversing the More complex, as we need to Even more complex due to circular
List maintain multiple pointers connection
Accessing Can be done using head Always accessible from any node in the
First Node pointer list
Flexibility Good for simple data storage Better when cyclic operations are
and one-way traversal needed, like in scheduling
Circular Linked List in Java with Example
In a Circular Linked List, the last node’s next pointer points back to the first node,
forming a loop.
Java Program for Circular Linked List
class CircularLinkedList {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
Node head = null, tail = null;
// Insert at end
void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
newNode.next = head; // Circular link
} else {
Node temp = head;
while (temp.next != head) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = head;
}
}
// Display Circular Linked List
void display() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node temp = head;
do {
System.out.print(temp.data + " -> ");
temp = temp.next;
} while (temp != head);
System.out.println("(Back to head)");
}
public static void main(String[] args) {
CircularLinkedList cll = new CircularLinkedList();
cll.insert(10);
cll.insert(20);
cll.insert(30);
cll.insert(40);
System.out.println("Circular Linked List:");
cll.display();
}
}
Output:
Circular Linked List:
10 -> 20 -> 30 -> 40 -> (Back to head)
Singly Linked List in Java
A Singly Linked List consists of nodes where each node points to the next node, but the
last node points to NULL.
Java Program for Singly Linked List
class SinglyLinkedList {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
Node head = null;
// Insert at end
void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}
// Display Singly Linked List
void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
SinglyLinkedList sll = new SinglyLinkedList();
sll.insert(10);
sll.insert(20);
sll.insert(30);
sll.insert(40);
System.out.println("Singly Linked List:");
sll.display();
}
}
Output:
Singly Linked List:
10 -> 20 -> 30 -> 40 -> NULL
Easiest Explanation of Singly Circular Linked List
A linked list is a way to store data in a sequence. It has nodes, and each node has two
parts:
1. Data – The value stored in the node.
2. Pointer – A link that connects the node to the next one.
Unlike arrays, linked lists don’t have a fixed size. You can easily add or remove
elements without shifting others. But to find a specific value, you must follow links from
one node to the next, which takes time.
Think of a linked list like a chain, where each link (node) knows where the next one
is.
Head and Tail in a Linked List
• Head: The first node in the list.
• Tail: The last node, which usually points to NULL (no next node).
• Example: A train is like a linked list. The engine (head) is the starting point, and
each coach (node) is connected to the next one.
Singly Circular Linked List
A Singly Circular Linked List is a special type of linked list where:
• The last node does not point to NULL. Instead, it points back to the first (head)
node.
• This creates a loop, making the list circular.
• It still has a head node, which is the entry point.
• If you start from the head and keep moving, you will come back to the head again.
Advantages
✔ Useful when you need a continuous loop (e.g., round-robin scheduling, circular
buffers).
✔ No need to check for the end of the list; it keeps looping.
Disadvantages
❌ More complex than normal linked lists.
❌ Inserting and deleting nodes needs extra care to keep the circular connection intact.
Creating a Node in a Circular Singly Linked List
1. If the list is empty:
o Create a new node with data.
o Make it point to itself (since it's the only node).
o Update the last node pointer to refer to this new node.
This ensures the circular structure is maintained.
24 Give difference between String and StringBuffer. Explain any 3 methods of
StringBuffer. - ch-3
Give difference between String and StringBuffer. Explain any 4 methods of String
class. - ch-3
And
25 Explain any four methods of StringBuffer class. -ch-3
Explain various methods of the String class. -ch-3
List methods of the String class. Explain any two methods. -ch-3
3.1.2 String Methods
Method Description
charAt(int index) Returns the character at the specified index.
compareTo(String anotherString)
Compares two strings lexicographically.
concat(String str) Concatenates the specified string to the end of this string.
equals(Object anObject) Compares this string to the specified object.
equalsIgnoreCase(String Compares this string to another string, ignoring case
anotherString) considerations.
Returns the index within this string of the first occurrence of the
indexOf(int ch) specified character.
Returns the index within this string of the first occurrence of the
indexOf(String str) specified substring.
isEmpty() Returns true if, and only if, length() is 0.
length() Returns the length of this string.
replace(char oldChar, char Returns a new string resulting from replacing all occurrences of
newChar) oldChar in this string with newChar.
Splits this string around matches of the given regular
split(String regex) expression.
substring(int beginIndex) Returns a new string that is a substring of this string.
toLowerCase() Converts all of the characters in this String to lower case.
toUpperCase() Converts all of the characters in this String to upper case.
Returns a string whose value is this string, with any leading and
trim() trailing whitespace removed.
Example
import java.util.*;
class StringMethodsDemo {
public static void main(String[] args) {
// Creating a string
String s = "LetsLearnJava";
System.out.println("String = " + s);
// Finding length of the string
System.out.println("String length = " + s.length());
// Getting a character at a specific position
System.out.println("Character at 3rd position = " + s.charAt(3));
// Extracting substring from an index to end
System.out.println("Substring = " + s.substring(3));
// Extracting substring from index 2 to 5 (excluding 5)
System.out.println("Substring (2 to 5) = " + s.substring(2, 5));
// Concatenation of two strings
String s1 = "Java";
String s2 = "LetsLearn";
System.out.println("Concatenated string = " + s1.concat(s2));
// Finding index of a word
String s3 = "Learn Share Learn";
System.out.println("Index of 'Share' = " + s3.indexOf("Share"));
// Finding index of a character from a specific position
System.out.println("Index of 'a' after index 3 = " + s3.indexOf('a', 3));
// Comparing two strings
System.out.println("Checking Equality (Java vs java) = " + "Java".equals("java"));
System.out.println("Checking Equality (Java vs Java) = " + "Java".equals("Java"));
System.out.println("Checking Equality (Ignoring Case) = " +
"Java".equalsIgnoreCase("jAvA "));
// Comparing ASCII values of two strings
int diff = s1.compareTo(s2);
System.out.println("ASCII difference (Java vs LetsLearn) = " + diff);
// Converting to lower case
String word1 = "LeaRnJava";
System.out.println("Lowercase: " + word1.toLowerCase());
// Converting to upper case
String word2 = "HeLLoHowRu";
System.out.println("Uppercase: " + word2.toUpperCase());
// Trimming extra spaces
String word3 = " Learn Share Learn ";
System.out.println("Trimmed string = " + word3.trim());
// Replacing characters
String str1 = "JavaForBeginners";
System.out.println("Original String = " + str1);
System.out.println("Replacing 'n' with 'O' -> " + str1.replace('n', 'O'));
}
StringBuffer Class and Its Constructors
The StringBuffer class in Java is a mutable sequence of characters. It is part of the
java.lang package and is used when a lot of modifications are required on a string (like
appending, inserting, deleting, etc.). Unlike String, which is immutable, StringBuffer
allows direct modification of the object without creating a new one.
Key Features of StringBuffer:
• Thread-safe: All methods are synchronized, making it safe to use in multi-
threaded environments.
• Resizable: Its capacity grows automatically when needed.
• Performance: Slower than StringBuilder due to synchronization.
Constructors in StringBuffer
The StringBuffer class provides several constructors to create and initialize objects:
1. Default Constructor:
Syntax:
StringBuffer()
Description:
Creates an empty StringBuffer with an initial capacity of 16 characters.
2. Constructor with Initial Capacity:
Syntax:
StringBuffer(int capacity)
Description:
Creates an empty StringBuffer with the specified initial capacity.
3. Constructor with String:
Syntax:
StringBuffer(String str)
Description:
Creates a StringBuffer initialized with the given string. The capacity is str.length() +
16.
4. Constructor with CharSequence:
Syntax:
StringBuffer(CharSequence cs)
Description:
Creates a StringBuffer initialized with the specified CharSequence (like a String or
StringBuilder).
Example
public class StringBufferExample {
public static void main(String[] args) {
// Default constructor
StringBuffer sb1 = new StringBuffer();
System.out.println("Default Capacity: " + sb1.capacity()); // 16
// Constructor with initial capacity
StringBuffer sb2 = new StringBuffer(30);
System.out.println("Initial Capacity: " + sb2.capacity()); // 30
// Constructor with String
StringBuffer sb3 = new StringBuffer("Java");
System.out.println("Content: " + sb3); // Java
System.out.println("Capacity: " + sb3.capacity()); // 20
// Constructor with CharSequence
CharSequence cs = "Programming";
StringBuffer sb4 = new StringBuffer(cs);
System.out.println("Content: " + sb4); // Programming
3.1.4 StringBuffer methods :
(append(),insert(),update(),delete(). reverse(),capacity())
Method Description Syntax Example
append() Adds data to the end of StringBuffer sb.append("Java"); →
the StringBuffer. append(DataType data) "Hello Java"
insert() Inserts data at the StringBuffer insert(int sb.insert(5, " World"); →
specified position. offset, DataType data) "Hello World"
replace() Replaces a substring StringBuffer replace(int sb.replace(6, 11, "Java");
with the given string. start, int end, String str) → "Hello Java"
Deletes characters StringBuffer delete(int
delete() between the start, int end) sb.delete(5, 11); → "Hello"
specified indices.
reverse() Reverses the sequence StringBuffer reverse() sb.reverse(); → "dlroW
of characters. olleH"
Method Description Syntax Example
Returns the
capacity() current capacity of int capacity() sb.capacity(); → Default 16
the StringBuffer.
Ensures the minimum void ensureCapacity(int
ensureCapacity() capacity is at least the minimumCapacity) sb.ensureCapacity(50);
specified value.
Example
public class StringBufferMethods {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
// Append
sb.append(" World");
System.out.println("After append: " + sb); // Hello World
// Insert
sb.insert(6, "Java ");
System.out.println("After insert: " + sb); // Hello Java World
// Replace (Update)
sb.replace(6, 10, "C++");
System.out.println("After replace: " + sb); // Hello C++ World
// Delete
sb.delete(6, 10);
System.out.println("After delete: " + sb); // Hello World
// Reverse
sb.reverse();
System.out.println("After reverse: " + sb); // dlroW olleH
// Capacity
System.out.println("Capacity: " + sb.capacity()); // Default 16, increases as needed
}}
Here is the easiest explanation with simple words while keeping all points:
String vs. StringBuffer
Feature String StringBuffer
Mutability Cannot change: Once made, its Can change: You can modify its
value stays the same. value without making a new
object.
Performance Slow: Every change creates a new Fast: Changes happen in the
object, making it slower. same object, so it works faster.
Thread Safety Not safe for multiple threads: Safe for multiple threads: Has
Needs extra coding for safety in built-in safety, so it works well
multi-threading. in multi-threading.
Memory Usage Uses more memory: Because new Saves memory: Works on the
objects are created for changes. same object, so it uses less
memory.
Usage Scenario Best for fixed text: Use when the Best for changing text: Use
value does not change much. when making many changes to
the text.
String Pool Supports string pool: Saves Does not support string pool:
memory by reusing string values. Always creates objects in heap
memory.
Methods Examples: concat(), Examples: append(),
Available substring(), toUpperCase(), insert(), replace(),
toLowerCase(), trim(), etc. delete(), reverse(), etc.
Synchronization No built-in safety for multi- Has built-in safety for multi-
threading. threading.
-----------
5 Explain Exception handling in Java with example. -ch-3
What is Exception? Explain user-defined Exception with example. -ch-3
→
Exception Handling in Java
What is an Exception?
An exception is an error that occurs during program execution and disrupts the normal
flow of instructions. It happens when the program encounters unexpected situations like:
• Dividing by zero (ArithmeticException)
• Accessing an invalid array index (ArrayIndexOutOfBoundsException)
• Trying to open a file that doesn’t exist (FileNotFoundException)
If exceptions are not handled properly, the program may crash or behave unexpectedly.
Why Handle Exceptions?
Exception handling is necessary because:
✔ It prevents program crashes.
✔ It helps find errors easily.
✔ It makes the program more reliable.
Exception Handling in Java
Java provides a structured way to handle exceptions using the try, catch, finally,
throw, and throws keywords.
Basic Syntax:
try {
// Code that might cause an exception
}
catch (ExceptionType e) {
// Code to handle the exception
}
finally {
// Code that always runs (optional)
}
Example of Exception Handling:
public class ExceptionExample {
public static void main(String[] args) {
try {
int num = 10 / 0; // Division by zero will cause an
exception
}
catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
finally {
System.out.println("Execution completed.");
}
}
}
Output:
Error: Cannot divide by zero!
Execution completed.
✔ try block: Contains the code that might cause an error.
✔ catch block: Catches the error and prevents program termination.
✔ finally block: Always executes, whether there is an error or not.
Types of Exceptions in Java
1️ Checked Exceptions – These are checked at compile-time.
• Example: FileNotFoundException, IOException
2️ Unchecked Exceptions – These occur at runtime and are not checked by the compiler.
• Example: NullPointerException, ArithmeticException
3️ Errors – Serious problems that cannot be handled by the program.
• Example: OutOfMemoryError, StackOverflowError
User-Defined Exception in Java
A user-defined exception (custom exception) is an exception created by the programmer
to handle specific errors.
✔ It helps make error messages more meaningful.
✔ It improves program security and debugging.
Steps to Create a User-Defined Exception:
1️ Create a class that extends the Exception class.
2️ Define a constructor to set the error message.
3️ Use throw to trigger the exception inside the program.
4️ Handle it using try-catch.
Example of User-Defined Exception:
// Step 1: Create a custom exception class
class MyException extends Exception {
public MyException(String message) {
super(message); // Call the parent class constructor
}
}
// Step 2: Use the custom exception
public class TestException {
public static void main(String[] args) {
try {
int age = 15;
if (age < 18) {
throw new MyException("Age must be 18 or above to
register.");
}
System.out.println("Registration successful!");
}
catch (MyException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Output:
Exception caught: Age must be 18 or above to register.
✔ Why Use a Custom Exception?
• It allows programmers to create meaningful error messages.
• It makes code easier to understand and debug.
----------
2 Explain try, catch, and finally blocks with example. -ch-3
Explain try, catch, and finally keywords. -ch-3
try-catch-finally in Java
Exception handling in Java uses try, catch, and finally to manage runtime errors
and prevent program crashes. These blocks help in making programs more robust and
error-free.
1. try Block
✔ The try block contains the code that might cause an error.
✔ If an exception occurs, Java immediately stops executing the try block and jumps to
the catch block.
✔ If no error occurs, the catch block is skipped.
Example:
try {
int num = 10 / 0; // This will cause an ArithmeticException
(division by zero)
}
What happens here? Since dividing by zero is not allowed, Java will throw an
ArithmeticException, and the program will stop executing the try block.
2. catch Block
✔ The catch block handles the exception that occurs in the try block.
✔ It prevents the program from crashing by providing an alternative solution.
✔ We can have multiple catch blocks for different types of exceptions.
Example:
catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
How does it work? The catch block catches the exception and prints an error
message instead of stopping the program.
✅ Multiple Catch Blocks Example:
try {
int arr[] = {1, 2, 3};
System.out.println(arr[5]); // Trying to access an index that
doesn’t exist
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurred!");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception
occurred!");}
Output:
Array Index Out of Bounds Exception occurred!
The program handles the error gracefully without crashing.
3. finally Block
✔ The finally block always runs, whether an exception occurs or not.
✔ It is mainly used to release resources (like closing files, database connections, or
network connections).
✔ It helps to prevent memory leaks.
Example:
finally {
System.out.println("Execution completed.");
}
When does finally execute?
• If there is an exception → finally will still run.
• If there is no exception → finally will still run.
Complete Example of try-catch-finally
public class TryCatchFinallyExample {
public static void main(String[] args) {
try {
int num = 10 / 0; // Error: Division by zero
}
catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
finally {
System.out.println("Execution completed.");
}
}
}
Output:
Error: Cannot divide by zero!
Execution completed.
The finally block runs even after catching the exception.