Java External Imp Answers
Java External Imp Answers
Important Questions
Q1. Describe the JVM architecture with a neat diagram. Explain the role of Class Loader,
Memory Areas, and Execution Engine.
The Java Virtual Machine (JVM) is the runtime environment that executes Java bytecode. It provides
platform independence by abstracting the underlying hardware and OS. The JVM architecture consists
of three main subsystems:
3. Execution Engine
The Execution Engine reads and executes bytecode:
• Interpreter: Executes bytecode line by line. Fast startup but slow due to repeated interpretation.
• JIT Compiler (Just-In-Time): Compiles frequently used bytecode into native machine code for
faster execution.
• Garbage Collector: Automatically deallocates memory for objects no longer referenced.
Q2. Discuss the features of Java (Java Buzzwords) in detail. How do these features
make Java robust and secure?
Java was designed with a set of features that distinguish it from other languages. These features are
often called 'Java Buzzwords':
1. Simple
Java has a clean, easy-to-learn syntax based on C/C++, but removes complex features like pointers,
operator overloading, and multiple inheritance, making it simpler to use.
2. Object-Oriented
Java follows OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction. Everything in
Java is an object (except primitives).
4. Robust
Java is robust due to: Strong type checking at compile time, exception handling mechanism, automatic
garbage collection (no memory leaks), and no pointer arithmetic.
5. Secure
Java provides security via: Bytecode verifier, Security manager, No explicit pointers, Classloader
(prevents unauthorized class loading), and sandbox execution for applets.
6. Architecture Neutral
Bytecode can run on any architecture. Data types have fixed sizes (e.g., int is always 32-bit), unlike
C/C++.
7. Portable
Java programs can run on any platform without modification. The JVM handles OS-specific details.
8. High Performance
Java uses JIT (Just-In-Time) compilation to convert bytecode to native machine code at runtime,
improving execution speed.
9. Multithreaded
Java has built-in support for multithreading. Multiple threads can run concurrently, enabling efficient use
of CPU resources.
10. Distributed
Java supports distributed computing through RMI (Remote Method Invocation), CORBA, and networking
APIs ([Link]), making it ideal for internet-based applications.
11. Dynamic
Java loads classes dynamically at runtime. Programs can adapt to new environments by loading new
classes without recompiling.
Q3. Explain Java source file structure and compilation process with an example.
Example:
// Package Declaration
package [Link];
// Import Statement
import [Link];
// Class Declaration
public class HelloWorld {
// Field
String message = "Hello";
// Main Method
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Compilation Process
• Step 1 - Write source code: Save as [Link]
• Step 2 - Compile: Use javac [Link] → produces [Link] (bytecode)
• Step 3 - Execute: Use java HelloWorld → JVM loads .class and executes it
The Java compiler (javac) checks syntax and semantics. Bytecode is platform-neutral and
interpreted/compiled by the JVM on the target machine.
Q4. Discuss various operators in Java. Explain in detail about Bitwise operators with
suitable examples.
Q5. Explain type conversion and type casting in Java. Differentiate between implicit and
explicit conversion.
Java allows values to be converted from one data type to another. This is called type conversion or type
casting.
Comparison Table
Implicit: Automatic, no data loss, smaller to larger type.
Explicit: Manual, possible data loss, larger to smaller type, requires cast operator.
Q6. Discuss the selection (decision-making) statements in Java with suitable examples.
Java provides several decision-making statements that allow conditional execution of code blocks:
1. if Statement
Executes a block if condition is true.
int x = 10;
if (x > 5) { [Link]("Greater"); }
2. if-else Statement
if (x % 2 == 0) { [Link]("Even"); }
else { [Link]("Odd"); }
3. if-else-if Ladder
int marks = 75;
if (marks >= 90) [Link]("A Grade");
else if (marks >= 75) [Link]("B Grade");
else if (marks >= 60) [Link]("C Grade");
else [Link]("Fail");
4. Nested if
if (x > 0) {
if (x < 100) [Link]("Between 0 and 100");
}
5. switch Statement
Evaluates an expression and executes the matching case. Supports int, char, String, and enum.
int day = 3;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Other day");
}
The break statement prevents fall-through to the next case. The default clause handles unmatched
values.
Loops allow repeated execution of a block of code. Java provides four types of loops:
1. for Loop
Used when the number of iterations is known. Syntax: for(init; condition; update)
for (int i = 1; i <= 5; i++) {
[Link](i + " "); // 1 2 3 4 5
}
2. while Loop
Condition is checked before execution. Used when number of iterations is unknown.
int i = 1;
while (i <= 5) {
[Link](i + " ");
i++;
}
3. do-while Loop
Executes at least once. Condition checked after execution.
int i = 1;
do {
[Link](i + " ");
i++;
} while (i <= 5);
Jump Statements
• break: Terminates the loop or switch immediately.
• continue: Skips the rest of the current iteration and moves to next.
• return: Exits from the current method.
Q8. Write a Java program to remove duplicate elements from an integer array.
import [Link];
import [Link];
Java is a strongly-typed language. Every variable must have a declared type. Java data types are divided
into two categories:
An array is a fixed-size, ordered collection of elements of the same data type. Arrays are objects in Java,
stored in heap memory.
1. One-Dimensional Array
Syntax: dataType[] arrayName = new dataType[size];
int[] marks = new int[5]; // Declaration + creation
marks[0] = 90; marks[1] = 85; // Initialization
// Accessing elements
for (int i = 0; i < [Link]; i++) {
[Link]("Score " + i + ": " + scores[i]);
}
// Initializing a 2D array
int[][] mat = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
// Displaying using nested loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](mat[i][j] + " ");
}
[Link]();
}
Q1. Discuss the use of this, static and final keywords with suitable examples.
1. 'this' Keyword
The 'this' keyword refers to the current instance of the class. Uses:
• Distinguish instance variables from local variables with same name.
• Call another constructor of the same class (constructor chaining).
• Pass current object as argument to a method.
class Student {
int id; String name;
Student(int id, String name) {
[Link] = id; // '[Link]' is instance variable
[Link] = name;
}
void display() { [Link](id + " " + name); }
}
2. 'static' Keyword
'static' members belong to the class, not any instance. Uses:
• Static variable: Shared across all objects.
• Static method: Called without creating an object.
• Static block: Executed once when class is loaded.
class Counter {
static int count = 0; // shared among all objects
Counter() { count++; }
static void display() { [Link]("Count: " + count); }
}
// main: [Link](); // called without object
3. 'final' Keyword
• Final variable: Value cannot be changed once assigned (constant).
• Final method: Cannot be overridden in subclass.
• Final class: Cannot be extended (inherited).
final double PI = 3.14159; // cannot reassign
final class Math { } // cannot extend
Q2. What are the special characteristics of constructors in Java? Explain different types
of constructors with example.
Characteristics of Constructors
• Same name as the class.
• No return type (not even void).
• Called automatically when an object is created.
• Cannot be static, abstract, or final.
• Can be overloaded (multiple constructors with different parameters).
• If no constructor is defined, Java provides a default constructor.
Types of Constructors
1. Default Constructor (No-argument)
class Car {
String brand;
Car() { // default constructor
brand = "Unknown";
[Link]("Default Constructor called");
}
}
2. Parameterized Constructor
class Car {
String brand; int year;
Car(String brand, int year) { // parameterized
[Link] = brand;
[Link] = year;
}
}
3. Copy Constructor
class Car {
String brand;
Car(Car c) { // copy constructor
[Link] = [Link];
}
}
// Usage: Car c1 = new Car("Toyota", 2020);
// Car c2 = new Car(c1); // copy of c1
Q3. Discuss the significance of StringTokenizer class and write a Java program to
extract numbers from a comma-separated string using StringTokenizer and find their
sum.
StringTokenizer Class
StringTokenizer (in [Link]) is used to break a string into tokens based on a delimiter. It is simpler than
split() for basic tokenization and doesn't use regular expressions.
• StringTokenizer(String str): Default delimiter is whitespace.
• StringTokenizer(String str, String delim): Custom delimiter.
• hasMoreTokens(): Returns true if more tokens exist.
• nextToken(): Returns the next token.
• countTokens(): Returns number of remaining tokens.
Method overloading allows a class to have multiple methods with the same name but different parameter
lists. The Java compiler determines which method to call based on the number, type, and order of
arguments. This is an example of compile-time polymorphism (static binding).
Example:
public class Calculator {
// Add two integers
int add(int a, int b) { return a + b; }
// Add three integers (different number of params)
int add(int a, int b, int c) { return a + b + c; }
Q5. Explain about String class and discuss various methods in String class with an
example.
The String class in [Link] represents a sequence of characters. Strings in Java are immutable — once
created, their value cannot be changed.
String s = "Hello, Java!"; // String literal
String s2 = new String("Hello"); // String object
Example Program:
public class StringDemo {
public static void main(String[] args) {
String s = " Hello Java ";
[Link]([Link]()); // Hello Java
[Link]([Link]().length()); // 10
[Link]([Link]()); // HELLO JAVA
[Link]([Link]("Java","World")); // Hello World
String[] words = [Link]().split(" ");
for(String w : words) [Link](w);
}
}
Constructor overloading means having multiple constructors in a class with different parameter lists. Java
distinguishes them based on the number and types of arguments. It provides flexibility to create objects
in different ways.
public class Employee {
int id;
String name;
double salary;
// Constructor 1: No parameters
Employee() {
id = 0; name = "Unknown"; salary = 0.0;
}
void display() {
[Link](id + " " + name + " " + salary);
}
Q7. Compare String, StringBuffer and StringBuilder in Java with suitable examples.
1. String
• Immutable: Content cannot be changed once created.
• Thread-safe (since it's immutable).
• New object created on every modification (uses more memory).
String s = "Hello";
s = s + " World"; // Creates a new String object
2. StringBuffer
• Mutable: Can be modified without creating new objects.
• Thread-safe: All methods are synchronized.
• Slower than StringBuilder due to synchronization overhead.
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Modifies same object
[Link](5, ","); // Insert at index 5
[Link](); // Reverses content
[Link](sb); // dlroW ,olleH
3. StringBuilder
• Mutable: Like StringBuffer, modifiable in-place.
• Not thread-safe: Methods not synchronized.
• Faster than StringBuffer. Preferred in single-threaded scenarios.
StringBuilder sb = new StringBuilder("Hello");
[Link](" Java");
[Link](0, 5); // Removes "Hello"
[Link](sb); // Java
Comparison Summary
• String: Immutable, thread-safe, slow for frequent modifications.
• StringBuffer: Mutable, thread-safe (synchronized), moderate speed.
• StringBuilder: Mutable, not thread-safe, fastest for single-threaded use.
A Pangram is a sentence that contains every letter of the English alphabet at least once. Example: 'The
quick brown fox jumps over the lazy dog'
public class PangramCheck {
static boolean isPangram(String s) {
boolean[] letters = new boolean[26];
s = [Link]();
for (char c : [Link]()) {
if (c >= 'a' && c <= 'z') {
letters[c - 'a'] = true;
}
}
for (boolean b : letters) {
if (!b) return false; // some letter missing
}
return true;
}
Two strings are anagrams if one is formed by rearranging the letters of the other. Example: 'listen' and
'silent' are anagrams.
import [Link];
Q10. Write a Java program to display details of a person (personal details in one
method, qualification in another).
public class PersonDetails {
String name, dob, address, phone;
String degree, college, year;
double percentage;
PersonDetails(String n, String d, String a, String p,
String deg, String col, String yr, double pct) {
name=n; dob=d; address=a; phone=p;
degree=deg; college=col; year=yr; percentage=pct;
}
void displayPersonal() {
[Link]("--- Personal Details ---");
[Link]("Name : " + name);
[Link]("DOB : " + dob);
[Link]("Address : " + address);
[Link]("Phone : " + phone);
}
void displayQualification() {
[Link]("--- Qualification Details ---");
[Link]("Degree : " + degree);
[Link]("College : " + college);
[Link]("Year : " + year);
[Link]("Percentage : " + percentage + "%");
}
Q11. Write a Java program to count number of vowels and consonants in the given text.
public class VowelConsonantCount {
public static void main(String[] args) {
String text = "Java Programming is Fun and Exciting";
int vowels = 0, consonants = 0;
String vowelStr = "aeiouAEIOU";
for (char c : [Link]()) {
if ([Link](c)) {
if ([Link](c) != -1)
vowels++;
else
consonants++;
}
}
[Link]("Text: " + text);
[Link]("Vowels: " + vowels);
[Link]("Consonants: " + consonants);
}
}
Output: Vowels: 11, Consonants: 19 (for the given string)
Q1. Explain inheritance in Java. Discuss different types of inheritance with examples.
Inheritance is a fundamental OOP concept where a class (subclass/child) acquires the properties and
behaviors of another class (superclass/parent). It promotes code reusability and establishes an IS-A
relationship.
Syntax: class ChildClass extends ParentClass { }
2. Multilevel Inheritance
A class inherits from a derived class (chain of inheritance).
class A { void m1() { [Link]("A"); } }
class B extends A { void m2() { [Link]("B"); } }
class C extends B { void m3() { [Link]("C"); } }
3. Hierarchical Inheritance
Multiple classes inherit from a single parent class.
class Shape { void draw() { [Link]("Drawing"); } }
class Circle extends Shape { void area() { [Link]("Circle area"); } }
class Rectangle extends Shape { void area() { [Link]("Rect area"); } }
5. Hybrid Inheritance
Combination of two or more types of inheritance. Achieved in Java using interfaces. Not supported
directly through classes.
Q2. Write a Java program using an abstract class to calculate the area of different
geometric shapes.
abstract class Shape {
String color;
Shape(String color) { [Link] = color; }
abstract double area(); // abstract method
void displayColor() { [Link]("Color: " + color); }
}
Q3. What is method overriding? Explain dynamic method dispatch with an example.
Method overriding occurs when a subclass provides its own implementation of a method already defined
in its superclass, with the same name, return type, and parameters. This is runtime polymorphism.
Q4. Discuss the advantage of the super keyword with a Java program.
The super keyword in Java refers to the immediate parent class of the current class. It is used to access
parent class members that are hidden by the child class.
Uses of super
• 1. Access parent class variables (when child class has same-named field).
• 2. Call parent class method (when overridden in child class).
• 3. Call parent class constructor (using super() in child constructor).
class Vehicle {
String brand = "Generic Vehicle";
int speed;
Vehicle(int speed) {
[Link] = speed;
[Link]("Vehicle constructor: speed = " + speed);
}
void display() { [Link]("Brand: " + brand); }
}
Java does NOT support multiple inheritance through classes. This is a deliberate design decision to avoid
the Diamond Problem.
An interface is a reference type in Java that contains abstract methods, constants, default methods (Java
8+), and static methods. It defines a contract that implementing classes must fulfill.
Declaring an Interface
interface InterfaceName {
// Constants (public static final by default)
int MAX = 100;
// Abstract methods (public abstract by default)
void methodName();
}
Implementing an Interface
interface Drawable {
double PI = 3.14; // constant
void draw(); // abstract method
default void info() { // default method (Java 8+)
[Link]("Drawing shape...");
}
}
Q7. Explain about abstract methods and abstract classes in Java with suitable
examples.
Abstract Method
An abstract method is a method declared without an implementation (no body). It must be overridden by
any concrete subclass.
abstract void methodName(); // no body, ends with semicolon
Abstract Class
• Declared with abstract keyword.
• Cannot be instantiated directly.
• May contain both abstract and concrete (regular) methods.
• May have constructors and instance variables.
• A subclass must implement all abstract methods (or itself be abstract).
abstract class Animal {
String name;
Animal(String name) { [Link] = name; }
abstract void sound(); // abstract method
void breathe() { // concrete method
[Link](name + " breathes air");
}
}
Q8. Differentiate between interfaces and abstract classes with suitable examples.
• Abstract class can have concrete methods; Interface (pre-Java 8) can only have abstract
methods. Java 8+ allows default/static methods in interfaces.
• Abstract class can have constructors; Interface cannot have constructors.
• Abstract class supports single inheritance (extend one); Interface supports multiple
implementation (implement many).
• Abstract class can have any access modifiers; Interface members are public by default.
• Abstract class can have instance variables; Interface can only have public static final constants.
• Use abstract class when classes share common behavior; use interface to define a
capability/contract.
// Abstract class example
abstract class Vehicle {
int speed; // instance variable
Vehicle(int s) { speed = s; } // constructor
abstract void fuelType();
void move() { [Link]("Moving at " + speed); }
}
// Interface example
interface Electric { void charge(); }
interface GPS { void navigate(); }
Q9. Illustrate various uses of 'final' keyword with suitable code segments.
1. final Variable
Value cannot be changed once assigned. Acts as a constant.
final double PI = 3.14159;
// PI = 3.0; // ERROR: cannot assign a value to final variable
2. final Method
Cannot be overridden in a subclass.
class Parent {
final void display() { [Link]("Parent display"); }
}
class Child extends Parent {
// void display() {} // ERROR: cannot override final method
}
3. final Class
Cannot be subclassed (inherited).
final class MathUtils {
static int square(int n) { return n * n; }
}
// class AdvancedMath extends MathUtils { } // ERROR
4. final Parameter
A method parameter declared final cannot be modified inside the method.
void greet(final String name) {
// name = "New"; // ERROR
[Link]("Hello " + name);
}
Q1. Explain the steps involved in creating and working with user-defined packages with
an example.
A package in Java is a namespace that groups related classes and interfaces. User-defined packages
help organize code and prevent naming conflicts.
Example:
File: mypackage/[Link]
package mypackage;
Q2. Discuss access control for class members across different packages. Illustrate with
examples.
Java provides four access modifiers to control the visibility of class members:
• private: Accessible only within the same class.
• default (no modifier): Accessible within the same package only.
• protected: Accessible within same package AND subclasses in other packages.
• public: Accessible from anywhere.
// package pack2
package pack2;
import [Link];
public class Child extends Parent {
void test() {
// [Link](priv); // ERROR: private
// [Link](def); // ERROR: default
[Link](prot); // OK: protected + subclass
[Link](pub); // OK: public
}
}
Q3. Write a Java program to copy Even numbers into [Link] file and Odd Numbers
into [Link] file.
import [Link].*;
BufferedWriter evenWriter =
new BufferedWriter(new FileWriter("[Link]"));
BufferedWriter oddWriter =
new BufferedWriter(new FileWriter("[Link]"));
1. FileReader
FileReader is a character-based input stream used to read character data from a file. Reads one
character at a time.
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) [Link]((char) ch);
[Link]();
2. FileWriter
FileWriter is a character-based output stream used to write character data to a file. Creates or overwrites
the file.
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello, Java!");
[Link]();
3. BufferedReader
BufferedReader wraps a Reader to provide buffered character input. The readLine() method reads a full
line at a time, making I/O faster.
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) [Link](line);
[Link]();
4. BufferedWriter
BufferedWriter wraps a Writer for buffered output. Provides write() and newLine() methods for efficient
file writing.
BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"));
[Link]("First Line");
[Link]();
[Link]("Second Line");
[Link]();
Buffered streams improve performance by reducing the number of actual disk I/O operations.
Q5. Discuss in detail about various Wrapper classes available in Java with suitable
examples.
Wrapper classes convert Java primitive types into objects. They are in the [Link] package. Each
primitive type has a corresponding wrapper class:
• byte → Byte
• short → Short
• int → Integer
• long → Long
• float → Float
• double → Double
• char → Character
• boolean → Boolean
Example Program
import [Link];
public class WrapperDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](10); [Link](20); [Link](30); // autoboxing
for (int x : list) [Link](x + " "); // unboxing
[Link]();
Double d = [Link]("3.14");
[Link]("Parsed double: " + d);
[Link]("Max int: " + Integer.MAX_VALUE);
}
}
Q6. Write a Java program to illustrate the usage of protected members in a package.
// File: pack1/[Link]
package pack1;
public class ParentClass {
protected String name = "Java";
protected void display() {
[Link]("Protected method: " + name);
}
}
// File: pack2/[Link]
package pack2;
import [Link];
public class ChildClass extends ParentClass {
public void access() {
name = "Java Programming"; // can access protected variable
display(); // can call protected method
[Link]("Name from child: " + name);
}
}
// File: pack2/[Link]
package pack2;
public class TestProtected {
public static void main(String[] args) {
ChildClass c = new ChildClass();
[Link]();
}
}
Q7. Write a Java program to read and display student details stored in a Collection
using the Iterator interface.
import [Link].*;
class Student {
int rollNo; String name; double marks;
Student(int r, String n, double m) { rollNo=r; name=n; marks=m; }
public String toString() {
return "Roll: " + rollNo + " | Name: " + name + " | Marks: " + marks;
}
}
[Link]("Student Details:");
[Link]("-----------------------------------");
Iterator<Student> it = [Link]();
while ([Link]()) {
Student s = [Link]();
[Link](s);
}
}
}
Q8. Explain ArrayList and LinkedList. Compare their features, performance, and
applications.
ArrayList
ArrayList is a resizable array implementation of the List interface. Internally uses a dynamic array.
• Fast random access: O(1) using index.
• Slow insertion/deletion in middle: O(n) due to shifting.
• Better for read-heavy operations.
ArrayList<String> list = new ArrayList<>();
[Link]("Apple"); [Link]("Banana"); [Link]("Cherry");
[Link]([Link](1)); // Banana
[Link]("Banana");
LinkedList
LinkedList is a doubly linked list implementation of List and Deque interfaces.
• Slow random access: O(n) - must traverse from head.
• Fast insertion/deletion: O(1) at beginning and end.
• Better for frequent insert/delete operations.
• Can also be used as Queue, Deque, Stack.
LinkedList<String> ll = new LinkedList<>();
[Link]("A"); [Link]("Z"); [Link]("M");
[Link]([Link]()); // Z
[Link]();
Comparison
• Underlying structure: ArrayList uses dynamic array; LinkedList uses doubly-linked nodes.
• get(index): ArrayList O(1) vs LinkedList O(n).
• add/remove (middle): ArrayList O(n) vs LinkedList O(1).
• Memory: ArrayList less overhead; LinkedList more (each node has prev/next pointers).
• Use ArrayList when: frequent reads, random access needed.
• Use LinkedList when: frequent insertions/deletions, used as queue/stack.
Comparable Interface
Comparable ([Link]) is used to define natural ordering of objects. The class must implement the
compareTo() method.
class Student implements Comparable<Student> {
String name; int marks;
Student(String n, int m) { name = n; marks = m; }
public int compareTo(Student other) {
return [Link] - [Link]; // ascending by marks
}
public String toString() { return name + "(" + marks + ")"; }
}
// [Link](list); // uses compareTo
Comparator Interface
Comparator ([Link]) is used to define custom/multiple orderings without modifying the class. Implement
the compare() method.
import [Link].*;
class NameComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return [Link]([Link]); // alphabetical by name
}
}
// [Link](list, new NameComparator());
// Or using lambda: [Link]((a,b) -> [Link]([Link]));
Key Differences
• Comparable: in [Link], single natural ordering, modifies class, uses compareTo.
• Comparator: in [Link], multiple custom orderings, external class, uses compare.
Q10. Explain about HashSet and TreeSet. How do they store elements and maintain
uniqueness?
HashSet
HashSet implements Set interface using a hash table. Stores elements in no particular order and does
not allow duplicates.
• Allows one null element.
• O(1) for add, remove, contains (average).
• No guaranteed insertion or sorted order.
HashSet<String> hs = new HashSet<>();
[Link]("Banana"); [Link]("Apple"); [Link]("Cherry"); [Link]("Apple");
[Link](hs); // [Apple, Cherry, Banana] (unordered)
// 'Apple' added only once - duplicate ignored
TreeSet
TreeSet implements SortedSet interface using a Red-Black Tree. Stores elements in sorted (ascending)
order.
• Does NOT allow null elements.
• O(log n) for add, remove, contains.
• Elements are always in sorted order.
• Supports range operations: headSet(), tailSet(), subSet().
TreeSet<Integer> ts = new TreeSet<>();
[Link](50); [Link](10); [Link](30); [Link](10); [Link](40);
[Link](ts); // [10, 30, 40, 50] (sorted, no duplicate)
[Link]([Link]()); // 10
[Link]([Link]()); // 50
Comparison
• HashSet: Unordered, O(1) ops, allows 1 null, uses hashCode/equals.
• TreeSet: Sorted order, O(log n) ops, no null, uses Comparable/Comparator.
Q1. What are the five keywords used in Java exception handling? Explain their usage
with code snippets.
Java exception handling uses five keywords: try, catch, finally, throw, and throws.
1. try
Encloses the code that might throw an exception.
try {
int result = 10 / 0; // might throw ArithmeticException
}
2. catch
Handles the specific exception thrown in the try block.
catch (ArithmeticException e) {
[Link]("Error: " + [Link]()); // / by zero
}
3. finally
Always executes after try-catch, regardless of whether an exception occurred. Used for cleanup (closing
files, connections, etc.).
finally {
[Link]("Finally block always runs");
}
4. throw
Used to explicitly throw an exception (user-defined or predefined).
void checkAge(int age) {
if (age < 18) throw new IllegalArgumentException("Under age");
}
5. throws
Declares that a method may throw certain checked exceptions. The caller must handle them.
void readFile(String path) throws IOException {
FileReader fr = new FileReader(path); // may throw IOException
}
Complete Example:
public class ExceptionDemo {
static void divide(int a, int b) throws ArithmeticException {
if (b == 0) throw new ArithmeticException("Cannot divide by 0");
[Link]("Result: " + (a / b));
}
public static void main(String[] args) {
try {
divide(10, 2);
divide(10, 0);
} catch (ArithmeticException e) {
[Link]("Caught: " + [Link]());
} finally {
[Link]("Done");
}
}
}
Q2. Explain multiple catch clauses in Java and write a program to illustrate handling
different exceptions using multiple catch blocks.
Java allows multiple catch blocks for a single try block, each handling a different type of exception. The
JVM matches the exception to the first compatible catch block from top to bottom.
Rules
• More specific (child) exceptions must be caught before more general (parent) ones.
• Java 7+ allows multi-catch: catch (IOException | SQLException e)
• At most one catch block executes per exception.
import [Link];
import [Link];
User-defined (custom) exceptions extend the Exception class (for checked) or RuntimeException class
(for unchecked). They allow meaningful, domain-specific error messages.
// Custom checked exception
class InsufficientBalanceException extends Exception {
double amount;
InsufficientBalanceException(double amount) {
super("Insufficient balance! Needed: " + amount);
[Link] = amount;
}
}
class BankAccount {
String owner; double balance;
BankAccount(String owner, double balance) {
[Link] = owner; [Link] = balance;
}
void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException(amount);
}
balance -= amount;
[Link]("Withdrew %.2f. New balance: %.2f%n", amount, balance);
}
}
Q4. What are unchecked exceptions in Java? Explain the commonly used built-in
unchecked exceptions with examples.
Unchecked exceptions (also called runtime exceptions) are subclasses of RuntimeException. They are
not checked at compile time — the compiler does not force you to handle or declare them. They typically
represent programming errors.
1. ArithmeticException
int x = 10 / 0; // ArithmeticException: / by zero
2. NullPointerException
String s = null;
[Link]([Link]()); // NullPointerException
3. ArrayIndexOutOfBoundsException
int[] arr = {1, 2, 3};
[Link](arr[5]); // ArrayIndexOutOfBoundsException
4. NumberFormatException
int n = [Link]("abc"); // NumberFormatException
5. ClassCastException
Object obj = "Hello";
Integer i = (Integer) obj; // ClassCastException
6. StackOverflowError
void recurse() { recurse(); } // StackOverflowError
7. IllegalArgumentException
void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("Invalid age");
}
8. StringIndexOutOfBoundsException
String s = "Java";
char c = [Link](10); // StringIndexOutOfBoundsException
Best practice: Fix the logic to avoid unchecked exceptions rather than just catching them.
JDBC (Java Database Connectivity) is an API that enables Java applications to interact with relational
databases. It provides a standard interface for database operations regardless of the database vendor.
2. JDBC API
Provides classes and interfaces (in [Link] and [Link]): DriverManager, Connection, Statement,
PreparedStatement, ResultSet, CallableStatement.
4. JDBC Driver
A driver translates JDBC calls into database-specific protocol. Types: Type 1 (JDBC-ODBC Bridge), Type
2 (Native API), Type 3 (Network Protocol), Type 4 (Thin/Pure Java — most common).
5. Database
The actual database server (MySQL, Oracle, PostgreSQL, etc.) that executes the SQL queries.
Q7. Write a Java program to create threads by extending Thread class — three threads
displaying Good Morning, Hello, and Welcome at different intervals. (Also using
Runnable Interface)
Q8. Write the steps involved in setting up the JDBC environment for developing Java
database applications.
Complete Example:
import [Link].*;
public class JDBCSetup {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/school";
Connection conn = [Link](url, "root", "pass");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM students");
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
[Link](); [Link](); [Link]();
}
}
Q9. Discuss in detail about various types of JDBC drivers available in Java with suitable
examples.
JDBC drivers translate JDBC calls into database-specific network protocols or native library calls. There
are four types:
Importance
• Prevents race conditions and data corruption.
• Ensures thread safety for shared resources.
• Maintains consistency of shared data.
• Enables inter-thread communication via wait(), notify(), notifyAll().
1. Synchronized Method
Declaring a method with the synchronized keyword ensures only one thread can execute it at a time.
class Counter {
private int count = 0;
synchronized void increment() { // only 1 thread at a time
count++;
}
int getCount() { return count; }
}
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Thread t1 = new Thread(() -> { for(int i=0;i<1000;i++) [Link](); });
Thread t2 = new Thread(() -> { for(int i=0;i<1000;i++) [Link](); });
[Link](); [Link]();
[Link](); [Link]();
[Link]("Count: " + [Link]()); // Always 2000
}
}
2. Synchronized Block
Synchronizes only a specific block of code rather than the entire method. This is more efficient when only
a portion of the method needs synchronization.
class Printer {
void printDoc(String doc) {
[Link]("Preparing document...");
synchronized(this) { // only this block is synchronized
[Link]("Printing: " + doc);
try { [Link](500); } catch (InterruptedException e) {}
}
[Link]("Done.");
}
}
Key Points
• Every Java object has an intrinsic lock (monitor). synchronized acquires this lock.
• wait(), notify(), notifyAll() must be called from synchronized context.
• Over-synchronization reduces performance — use only when necessary.