Java Workbook
Java Workbook
Question 1: Design a class Car with attributes brand, model, and year. Include a method to
display car details. How would you instantiate and use this class?
class Car {
String brand;
String model;
int year;
Question 2: Explain how constructors work in Java. Create a Student class with a
parameterized constructor and show how to create an object.
class Student {
String name;
int age;
// Parameterized constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayStudentDetails() {
System.out.println("Student Name: " + name);
System.out.println("Student Age: " + age);
}
Question 3: What is the difference between instance and static variables? Demonstrate this
with a BankAccount class example.
class BankAccount {
static double interestRate = 5.0; // Static variable
double balance; // Instance variable
void displayDetails() {
System.out.println("Balance: " + balance);
System.out.println("Interest Rate: " + interestRate);
}
account1.displayDetails();
account2.displayDetails();
}
}
Question 4: Create a Book class with private attributes. Implement getter and setter
methods to access these attributes.
class Book {
private String title;
private String author;
Question 5: How would you implement method overloading in Java? Provide an example
using a Calculator class.
class Calculator {
// Overloaded methods for adding two numbers
int add(int a, int b) {
return a + b;
}
Inheritance:
Question 6: Explain single inheritance with an example. Create a Vehicle superclass and a
Car subclass that extends it.
class Vehicle {
String brand = "Generic Vehicle";
void displayDetails() {
System.out.println("Vehicle brand: " + brand);
}
}
void displayCarDetails() {
System.out.println("Car model: " + model);
}
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Multithreading:
Question 11: Write a Java program that creates two threads, one printing even numbers
and the other printing odd numbers.
evenThread.start();
oddThread.start();
}
}
Question 12: How can you implement multithreading using the Runnable interface?
Provide an example.
evenThread.start();
oddThread.start();
}
}
Question 13: What are daemon threads in Java? Demonstrate their use with an example.
Daemon threads are background threads that are used to perform repetitive tasks like garbage
collection. They terminate when the main program ends.
Thread synchronization is used to prevent race conditions when multiple threads access shared
resources.
class Counter {
private int count = 0;
int getCount() {
return count;
}
}
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Question 15: What is a deadlock in Java multithreading? Show an example and explain
how to prevent it.
A deadlock occurs when two or more threads are blocked forever, waiting for each other to
release resources.
class A {
synchronized void method1(B b) {
b.last();
}
class B {
synchronized void method1(A a) {
a.last();
}
t1.start();
t2.start();
}
}
Prevention:
To prevent deadlock, ensure that threads always acquire locks in a consistent order.
Arrays:
Question 16: Write a Java program to find the second largest number in an array.
class SecondLargest {
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
Question 17: How would you implement a two-dimensional array in Java? Provide an
example.
class TwoDimensionalArray {
public static void main(String[] args) {
int[][] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Question 18: Write a program to reverse an array without using an additional array.
class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int start = 0;
int end = arr.length - 1;
System.out.println("Reversed Array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Question 19: How can you sort an array in Java without using built-in functions? Provide a
solution.
class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 1, 2};
int n = arr.length;
System.out.println("Sorted Array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Question 20: Demonstrate how to search for an element in an array using linear search.
class LinearSearch {
public static int linearSearch(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
return i; // return the index where key is found
}
}
return -1; // key not found
}
Exception Handling
Question 21: Explain how try-catch blocks work in Java. Provide an example handling
ArrayIndexOutOfBoundsException.
class TryCatchExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
// This will throw ArrayIndexOutOfBoundsException
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Attempted to access index out of
bounds.");
e.printStackTrace();
}
System.out.println("Program continues...");
}
}
Question 22: What is the difference between throw and throws? Show an example.
class ThrowVsThrows {
// throws declaration: this method may throw ArithmeticException
static void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
// throw explicitly an exception
throw new ArithmeticException("Division by zero!");
}
System.out.println("Result: " + (a / b));
}
Question 23: Write a program that catches multiple exceptions using multiple catch blocks.
class MultipleCatch {
public static void main(String[] args) {
String s = null;
int[] arr = {1, 2, 3};
try {
// May throw NullPointerException
System.out.println(s.length());
// May throw ArrayIndexOutOfBoundsException
System.out.println(arr[5]);
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException");
} finally {
System.out.println("Finally block executed.");
}
}
}
Question 24: How would you create a custom exception in Java? Provide an example.
// Define custom exception by extending Exception
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
class CustomExceptionDemo {
// Method that throws our custom exception
static void validate(int age) throws MyCustomException {
if (age < 18) {
throw new MyCustomException("Age must be at least 18");
}
System.out.println("Age validated: " + age);
}
Question 25: Explain the finally block in exception handling with an example.
The finally block always executes regardless of whether an exception was thrown or caught.
Useful for cleanup activities (e.g., closing files).
class FinallyDemo {
public static void main(String[] args) {
try {
System.out.println("Inside try block");
int result = 10 / 0; // throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException");
} finally {
System.out.println("Finally block always executes");
}
System.out.println("Program continues...");
}
}
Collections in Java
Question 26: How would you use an ArrayList to store a list of student names? Provide an
example.
import java.util.ArrayList;
class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
students.add("Alice");
students.add("Bob");
students.add("Charlie");
System.out.println("Student List:");
for (String name : students) {
System.out.println(name);
}
}
}
Question 27: Write a program that uses a HashMap to store and retrieve student ID and
names.
import java.util.HashMap;
import java.util.Map;
class HashMapDemo {
public static void main(String[] args) {
HashMap<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Alice");
studentMap.put(102, "Bob");
studentMap.put(103, "Charlie");
System.out.println("Student Map:");
for (Map.Entry<Integer, String> entry : studentMap.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: " +
entry.getValue());
}
// Retrieve by key
System.out.println("Student with ID 102: " + studentMap.get(102));
}
}
Question 28: What is the difference between HashSet and TreeSet? Provide a Java example.
HashSet: No ordering; backed by a hash table; allows null; faster for add/remove operations.
TreeSet: Elements are sorted in natural order or via a comparator; no null; backed by a red–
black tree.
import java.util.HashSet;
import java.util.TreeSet;
class SetDemo {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Banana");
hashSet.add("Apple");
hashSet.add("Cherry");
System.out.println("HashSet (unordered): " + hashSet);
Question 29: How can you iterate over a LinkedList in Java? Show different methods.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("Red");
list.add("Green");
list.add("Blue");
System.out.println("Using for-each:");
for (String color : list) {
System.out.println(color);
}
System.out.println("Using Iterator:");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Question 30: Write a Java program to remove duplicate elements from an ArrayList.
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
class RemoveDuplicates {
public static void main(String[] args) {
List<String> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add("Apple");
listWithDuplicates.add("Banana");
listWithDuplicates.add("Apple");
listWithDuplicates.add("Orange");
listWithDuplicates.add("Banana");