0% found this document useful (0 votes)
9 views14 pages

Java Workbook

The document contains a comprehensive set of Java programming questions and answers covering various topics including class design, inheritance, multithreading, arrays, exception handling, and collections. Each question is followed by a code example that illustrates the concept being discussed, such as constructors, method overloading, synchronization, and using data structures like ArrayList and HashMap. The document serves as a practical guide for understanding and implementing Java programming principles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views14 pages

Java Workbook

The document contains a comprehensive set of Java programming questions and answers covering various topics including class design, inheritance, multithreading, arrays, exception handling, and collections. Each question is followed by a code example that illustrates the concept being discussed, such as constructors, method overloading, synchronization, and using data structures like ArrayList and HashMap. The document serves as a practical guide for understanding and implementing Java programming principles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

JAVA WORKBOOK

Theory & Programming Questions:

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;

// Method to display car details


void displayDetails() {
System.out.println("Car brand: " + brand);
System.out.println("Car model: " + model);
System.out.println("Car year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Toyota";
car1.model = "Corolla";
car1.year = 2020;

car1.displayDetails(); // Call the method to display car details


}
}

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);
}

public static void main(String[] args) {


Student student1 = new Student("John", 21);
student1.displayStudentDetails();
}
}

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

// Constructor to initialize balance


BankAccount(double balance) {
this.balance = balance;
}

void displayDetails() {
System.out.println("Balance: " + balance);
System.out.println("Interest Rate: " + interestRate);
}

public static void main(String[] args) {


BankAccount account1 = new BankAccount(1000);
BankAccount account2 = new BankAccount(2000);

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;

// Getter and Setter methods


public String getTitle() {
return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}

public static void main(String[] args) {


Book book1 = new Book();
book1.setTitle("The Java Programming");
book1.setAuthor("John Doe");

System.out.println("Book Title: " + book1.getTitle());


System.out.println("Book Author: " + book1.getAuthor());
}
}

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;
}

double add(double a, double b) {


return a + b;
}

public static void main(String[] args) {


Calculator calc = new Calculator();
System.out.println("Sum of integers: " + calc.add(5, 10));
System.out.println("Sum of doubles: " + calc.add(5.5, 10.5));
}
}

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);
}
}

class Car extends Vehicle {


String model = "Sedan";

void displayCarDetails() {
System.out.println("Car model: " + model);
}

public static void main(String[] args) {


Car car1 = new Car();
car1.displayDetails();
car1.displayCarDetails();
}
}
Question 7: What is method overriding? Demonstrate this using an Animal superclass and
a Dog subclass.

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}

public static void main(String[] args) {


Dog dog = new Dog();
dog.sound(); // Method overriding
}
}

Multithreading:

Question 11: Write a Java program that creates two threads, one printing even numbers
and the other printing odd numbers.

class EvenThread extends Thread {


public void run() {
for (int i = 0; i <= 10; i += 2) {
System.out.println("Even: " + i);
}
}
}

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i += 2) {
System.out.println("Odd: " + i);
}
}
}

public class Main {


public static void main(String[] args) {
EvenThread evenThread = new EvenThread();
OddThread oddThread = new OddThread();

evenThread.start();
oddThread.start();
}
}
Question 12: How can you implement multithreading using the Runnable interface?
Provide an example.

class EvenRunnable implements Runnable {


public void run() {
for (int i = 0; i <= 10; i += 2) {
System.out.println("Even: " + i);
}
}
}

class OddRunnable implements Runnable {


public void run() {
for (int i = 1; i <= 10; i += 2) {
System.out.println("Odd: " + i);
}
}
}

public class Main {


public static void main(String[] args) {
Thread evenThread = new Thread(new EvenRunnable());
Thread oddThread = new Thread(new OddRunnable());

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.

class DaemonThread extends Thread {


public void run() {
while (true) {
System.out.println("Daemon Thread is running");
}
}
}

public class Main {


public static void main(String[] args) {
DaemonThread thread = new DaemonThread();
thread.setDaemon(true); // Set the thread as daemon
thread.start();

// Main thread ends, daemon thread also terminates


System.out.println("Main thread ends");
}
}
Question 14: Explain thread synchronization in Java. Provide an example using the
synchronized keyword.

Thread synchronization is used to prevent race conditions when multiple threads access shared
resources.

class Counter {
private int count = 0;

synchronized void increment() {


count++;
}

int getCount() {
return count;
}
}

public class Main {


public static void main(String[] args) {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final count: " + counter.getCount());


}
}

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();
}

synchronized void last() {


System.out.println("In A's last method");
}
}

class B {
synchronized void method1(A a) {
a.last();
}

synchronized void last() {


System.out.println("In B's last method");
}
}

public class DeadlockExample {


public static void main(String[] args) {
final A a = new A();
final B b = new B();

Thread t1 = new Thread(() -> {


a.method1(b);
});

Thread t2 = new Thread(() -> {


b.method1(a);
});

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;

for (int num : arr) {


if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}

System.out.println("Second Largest Number: " + secondLargest);


}
}

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}
};

for (int i = 0; i < arr.length; i++) {


for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}

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;

while (start < end) {


int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}

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;

for (int i = 0; i < n-1; i++) {


for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

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
}

public static void main(String[] args) {


int[] arr = {10, 20, 30, 40, 50};
int key = 30;
int result = linearSearch(arr, key);
if (result == -1) {
System.out.println(key + " not found in the array.");
} else {
System.out.println(key + " found at index: " + result);
}
}
}

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...");
}
}

 The code inside try is executed.


 If an ArrayIndexOutOfBoundsException occurs, control passes to the matching catch
block.
 After handling, execution continues after the try-catch.

Question 22: What is the difference between throw and throws? Show an example.

 throw is used within a method to explicitly throw an exception instance.


 throws is used in a method signature to declare that this method may throw certain exceptions.

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));
}

public static void main(String[] args) {


try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

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);
}

public static void main(String[] args) {


try {
validate(16);
} catch (MyCustomException e) {
System.out.println("Validation failed: " + e.getMessage());
}
}
}

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);

TreeSet<String> treeSet = new TreeSet<>();


treeSet.add("Banana");
treeSet.add("Apple");
treeSet.add("Cherry");
System.out.println("TreeSet (sorted): " + treeSet);
}
}

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());
}

System.out.println("Using ListIterator (reverse):");


ListIterator<String> listIt = list.listIterator(list.size());
while (listIt.hasPrevious()) {
System.out.println(listIt.previous());
}
}
}

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");

// Use LinkedHashSet to preserve insertion order and remove


duplicates
LinkedHashSet<String> set = new LinkedHashSet<>(listWithDuplicates);
ArrayList<String> listWithoutDuplicates = new ArrayList<>(set);

System.out.println("Original List: " + listWithDuplicates);


System.out.println("Without Duplicates: " + listWithoutDuplicates);
}
}

You might also like