0% found this document useful (0 votes)
4 views23 pages

Java Exam Practice Questions

The document provides a comprehensive overview of key Java concepts including classes, objects, encapsulation, inheritance, polymorphism, abstraction, interfaces, and exception handling. It explains the Java Collections Framework, the differences between various data structures like List, Set, and Map, and the benefits of generics. Additionally, it covers Java's I/O system, access modifiers, and the signature of the main method, along with structured questions and code examples.

Uploaded by

presleycephas
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)
4 views23 pages

Java Exam Practice Questions

The document provides a comprehensive overview of key Java concepts including classes, objects, encapsulation, inheritance, polymorphism, abstraction, interfaces, and exception handling. It explains the Java Collections Framework, the differences between various data structures like List, Set, and Map, and the benefits of generics. Additionally, it covers Java's I/O system, access modifiers, and the signature of the main method, along with structured questions and code examples.

Uploaded by

presleycephas
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/ 23

Free Response Questions

1. What is a class and what is an object in Java?

A class in Java is a blueprint or template that defines the structure (fields/properties) and behavior
(methods) common to a group of objects. It is not a real-world entity, but a prototype from which
objects are created 1 . An object is an instance of a class – a concrete entity created at runtime that has
the attributes and behaviors defined by its class. For example, if Person is a class with fields name
and age , then new Person("Alice", 30) creates an object (instance) of Person with those
specific values. The class defines what data and methods each object has; the object is the actual data in
memory based on that class.

2. Explain encapsulation and its benefits in Java.

Answer: Encapsulation is an OOP principle that binds (encapsulates) data (fields) and methods that
operate on that data into a single unit (class), and restricts direct access to some of an object’s
components. In Java, this is achieved using access modifiers (like private ) to hide internal state and
provide public getter/setter methods. It is often described as a “protective shield” that prevents external
code from manipulating internal data directly 2 . Encapsulation hides the implementation details (how
something is done) and only exposes the functionality (what is done) to the user 3 . This improves
maintainability and security: internal changes to data structures do not affect external code, and data
can only be changed in controlled ways (e.g. with validation in setter methods).

3. Describe inheritance in Java and its advantages.

Inheritance is an OOP mechanism where one class (subclass/child) can inherit fields and methods from
another class (superclass/parent) 4 . In Java, inheritance is implemented using the extends
keyword. For example, class Dog extends Animal means Dog inherits all non-private members
of Animal . This promotes code reuse (common code in the parent can be reused by many subclasses)
and enables a hierarchical class structure. Inheritance also supports method overriding (a subclass can
redefine a parent’s method) and polymorphism (treating a subclass object as its parent type). Overall,
inheritance makes code more modular and easier to maintain 4 .

4. What is polymorphism in Java? Explain with examples.

Polymorphism means “many forms” – in Java it allows one interface (method name) to be used for
different underlying forms (actual object types). There are two main types: compile-time polymorphism
(method overloading) and runtime polymorphism (method overriding). At runtime, Java decides which
method implementation to invoke depending on the actual object type 5 . For example, if
Person p = new Father() , and Father overrides role() from Person , then p.role() will
call the Father version (even though the reference type is Person ). This is runtime polymorphism.
Method overloading (same method name, different parameters) is compile-time polymorphism.
Polymorphism allows code to be more flexible and extensible 5 . For instance, many different objects
can be treated through a common superclass or interface, and each can respond in its own way to the
same method call.

1
5. Explain abstraction in Java and how abstract classes and interfaces support it.

Abstraction is the concept of hiding complex implementation details and showing only the essential
features to the user. In Java, abstraction is achieved via abstract classes and interfaces. An abstract class
can have abstract methods (methods without a body) and concrete methods, providing a common base
with partial implementation. An interface declares methods (implicitly abstract) that implementing
classes must define. Interfaces in Java are a mechanism for total abstraction 6 : they specify a contract
or set of behaviors without detailing how they are implemented. Both abstract classes and interfaces
allow programmers to define what operations are available, without exposing the internal workings.
This ensures that users of a class or interface only need to know what it does, not how it does it 7
6 .

6. What is a Java interface and how is it used?

An interface in Java is an abstract type that defines a set of method signatures (and constants) without
implementations. It specifies a behavior that implementing classes must provide. Interfaces are defined
with the interface keyword and can include abstract methods, default methods, and static
constants. By default, fields in an interface are public static final and methods are public
abstract . Java interfaces enable a form of multiple inheritance: a class can implement multiple
interfaces. Interfaces are used to define a contract for classes: they describe what methods a class
must have, without specifying how to do it 8 . This promotes loose coupling (classes depend on
interfaces, not implementations) and allows different classes to be treated uniformly if they implement
the same interface.

7. Differentiate between composition and aggregation in Java.

Figure: UML diagram illustrating composition (solid diamond) vs aggregation (hollow diamond) relationships.
Composition and aggregation are both “has-a” relationships, but differ in strength of association.
Aggregation is a weak form: one object owns or uses another, but the owned object can exist
independently. For example, a Teacher has-a Department (aggregation), but a Department can exist
without that particular Teacher. Composition is a strong form: one object is composed of another and
owns it; the part cannot exist without the whole. For example, a Library is composed of Books: if the
Library is destroyed, its Books are too. In composition, the lifetime of the part (Book) is controlled by the
whole (Library), whereas in aggregation, the part (Department) can exist on its own 9 10 . UML often
denotes composition with a filled diamond and aggregation with an empty diamond.

8. What are constructors in Java? Explain constructor overloading.

A constructor is a special method in a class that is called when a new object is created. Its purpose is to
initialize the object’s fields. Constructors have the same name as the class and no return type. For
example, class Point { Point(int x, int y) { ... } } defines a constructor taking
coordinates. If no constructor is defined, Java provides a default no-argument constructor. Constructors
can be overloaded: a class can have multiple constructors with different parameter lists. This allows
objects to be initialized in different ways. For instance,
class Rectangle { Rectangle() { ... } Rectangle(int w, int h) { ... } } has two
overloaded constructors. The Java compiler determines which constructor to call based on the
arguments passed when using new . Constructor overloading improves flexibility by letting you create
objects with various initial states.

2
9. Describe the Java platform components (JDK, JRE, JVM) and explain the “Write
Once, Run Anywhere” principle.

The Java Virtual Machine (JVM) is the runtime engine that executes Java bytecode and provides platform
independence 11 . In the Java platform, the JDK (Java Development Kit) contains tools for developing
Java code, the JRE (Java Runtime Environment) includes the JVM and core libraries to run Java programs,
and the JVM is the part that loads and executes compiled .class files. Because Java is compiled to
bytecode (not machine code) and executed by the JVM, the same .class file can run on any device
with a compatible JVM — this is the “Write Once, Run Anywhere” (WORA) principle 11 . In other words,
developers can write Java code on one system and expect it to run on any other system that has the
Java platform. The diagram above shows the JVM’s key components (Class Loader, Bytecode Verifier,
Execution Engine, and Memory Areas) which collectively enable this cross-platform capability 11 .

10. Explain Java’s exception handling mechanism (try, catch, finally).

Java’s exception handling uses try , catch , and finally blocks to manage runtime errors without
crashing the program. Code that might throw an exception is placed in a try block. If an exception
occurs, control immediately jumps to a matching catch block, where the error can be handled (for
example, logging or recovery) 12 . The finally block (if present) executes after the try / catch
blocks regardless of whether an exception was thrown, and is typically used for cleanup (closing files,
releasing resources) 13 . If no matching catch is found, the JVM’s default handler is invoked. This
structured approach separates error-handling code from normal code flow and ensures that
exceptional conditions (like IOException or ArithmeticException ) are caught and dealt with
gracefully 12 13 .

11. What are checked and unchecked exceptions in Java? Give examples.

Java defines two exception categories: checked exceptions and unchecked exceptions. Checked
exceptions are those that the compiler forces you to handle or declare; they represent conditions
outside the program’s immediate control (like I/O errors). For example, IOException or
SQLException are checked exceptions and must be caught or declared with throws 14 .
Unchecked exceptions (subclasses of RuntimeException ) occur at runtime due to programming
bugs or unexpected conditions; examples include NullPointerException and
ArrayIndexOutOfBoundsException . Unchecked exceptions do not need to be declared or caught
explicitly 14 15 . In summary, checked exceptions are checked at compile time for mandatory handling,
whereas unchecked exceptions are checked only at runtime.

12. Describe the Java Collections Framework and its advantages.

The Java Collections Framework (in java.util ) provides a unified architecture to store and
manipulate groups of objects. At the top level are interfaces like Collection and Map which define
common operations. All collection types (e.g., List , Set , Queue ) implement or extend these
interfaces. For example, the Collection interface extends Iterable , providing basic methods like
add() , remove() , and iteration 16 . The diagram above illustrates the hierarchy: Collection is
extended by List (implemented by ArrayList , LinkedList , etc.) and Set ( HashSet ,
TreeSet ), and Map (with HashMap , TreeMap , etc.) 16 . Advantages include code reuse (common
methods for different data structures), flexibility (easy to swap implementations), and a rich set of utility
algorithms. The Collections Framework saves developers from implementing common data structures
from scratch and provides well-tested, high-performance classes.

3
13. What are the differences between List, Set, and Map in Java?

A List (e.g. ArrayList , LinkedList ) is an ordered collection that allows duplicate elements. It
preserves insertion order and elements can be accessed by index. The List interface extends
Collection 17 . A Set (e.g. HashSet , TreeSet ) is an unordered collection that does not allow
duplicate elements. It’s used when uniqueness is required 18 . For example, adding the same element
twice to a HashSet will only keep one instance. A Map (e.g. HashMap , TreeMap ) is a key-value data
structure. Each key maps to exactly one value and duplicate keys are not allowed (but different keys can
map to the same value) 19 . Unlike List and Set , Map does not extend Collection but
provides methods like put(key,value) and get(key) . In summary: Lists allow ordered duplicates,
Sets allow unique, unordered items, and Maps store unique keys with associated values.

14. Explain Java generics and their benefits.

Generics allow classes, interfaces, and methods to operate on type parameters specified at instantiation
time. In other words, generics parameterize types, enabling stronger compile-time type checks and
code reuse. For example, ArrayList<String> is a list specifically of String , and the compiler
ensures only strings are added. Java generics are similar to C++ templates: they let you write a class
once and reuse it with different data types 20 . This prevents type errors (e.g. you can’t insert an
Integer into ArrayList<String> ) and eliminates the need for explicit casts. For example, a
generic class Box<T> can hold any type T , and using generics ensures type safety without extra
overhead 20 . Overall, generics increase code flexibility and safety by catching type-related errors at
compile time.

15. Compare Java with C. Why might Java be more suitable for certain applications?

Java is a high-level, object-oriented, platform-independent language, whereas C is a procedural,


platform-dependent language. In Java, memory management is automatic (garbage collection) and
developers don’t use pointers, which reduces certain classes of errors like segmentation faults. Java’s
bytecode runs on the JVM, making programs portable (“write once, run anywhere”) 11 , whereas C
programs must be recompiled for each platform. Java also has a rich standard library (collections, I/O,
networking) that simplifies many tasks. Unlike C, Java inherently supports OOP concepts (classes,
inheritance, polymorphism) and exception handling. These features make Java more robust and
productive for building large, cross-platform, enterprise-level applications, while C might be chosen for
low-level system programming or performance-critical tasks.

16. Describe Java’s I/O system. What are byte streams and character streams?

Java’s I/O APIs in the java.io package provide streams to handle input and output of data. A stream
is a sequence of data (bytes or characters). Java distinguishes between byte streams (subclasses of
InputStream / OutputStream ) for raw binary data, and character streams (subclasses of Reader /
Writer ) for text data. Byte streams read/write 8-bit bytes; character streams use a character encoding
(16-bit char in Java). For example, FileInputStream / FileOutputStream read and write raw
bytes, while FileReader / FileWriter read and write characters with encoding. The I/O system
supports buffered streams, data streams, and object streams to handle various data types. In general,
one wraps lower-level streams with higher-level classes (like BufferedReader or PrintWriter ) for
efficiency and convenience. Overall, Java’s I/O package provides many classes to perform file and
network I/O in a flexible way 21 .

4
17. What is the difference between an abstract class and an interface in Java?

While both abstract classes and interfaces provide abstraction, there are key differences. An abstract
class can have instance variables, constructors, and concrete methods in addition to abstract methods;
interfaces cannot be instantiated and can only have constants (implicitly public static final ) and
abstract methods (prior to Java 8). In Java 8+, interfaces can also have default and static methods. A
class can extend only one abstract class (single inheritance) but can implement multiple interfaces
(providing a form of multiple inheritance) 22 23 . Abstract classes are used when classes share some
common implementation or state; interfaces are used to define a contract that multiple classes can
implement. In summary, use an abstract class for shared code and state, and an interface to define
roles or capabilities that can apply across unrelated classes.

18. Explain the static keyword in Java.

The static keyword in Java marks members of a class (variables or methods) as belonging to the
class itself rather than to any instance. A static field is shared by all objects of the class – for
example, a static int count can track how many objects have been created. A static method
can be called on the class without needing an object instance (e.g. Math.max() ). Static members exist
even if no objects have been instantiated. Because main is static , the JVM can invoke it without
creating an instance. In essence, static creates class-level members rather than per-object
members. Static methods cannot directly access instance ( non-static ) fields or methods, since they
might not have an object context.

19. What are Java access modifiers and how do they work?

Java access modifiers control the visibility of classes, methods, and fields. The four levels are: public
(visible everywhere), protected (visible within its package and subclasses), default (no modifier,
visible only in its own package), and private (visible only within its own class). For example, a
private field can only be accessed by methods of the same class (supporting encapsulation),
whereas a public method can be called from any other class. protected is often used to allow
subclasses (even in different packages) to access a member. Packages and imports also affect visibility:
default (package-private) means classes in the same package can see the member. Proper use of access
modifiers helps enforce encapsulation by exposing only the necessary parts of a class’s interface.

20. Explain the signature of the main method in Java and its purpose.

The standard Java entry point is public static void main(String[] args) . Each part has a
purpose: public so the JVM can call it from outside the class; static so it can be invoked without
creating an object; void because it does not return a value; main is the fixed name the JVM looks
for; and String[] args is an array of command-line arguments passed as strings. When you run a
Java program, the JVM calls this main method of the specified class. The args array can be used to
accept user inputs from the command line. Without this exact signature, the JVM will not recognize the
method as the starting point.

Structured Questions
21. Complete the code to print "Hello, World!" to the console.

5
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Answer: The completed code above defines the main method and uses System.out.println() to
print the string. In Java, System.out.println() outputs text followed by a newline. Ensuring the
class and method signatures are correct allows the program to compile and run, displaying Hello, World!
on the console.

22. Fill in the blanks to declare a method printAge in class Person that takes an
int parameter and prints it. Then show how to call it from main .

class Person {
public void printAge(int age) {
System.out.println("Age = " + age);
}
}

public class Test {


public static void main(String[] args) {
Person p = new Person();
p.printAge(25);
}
}

Answer: The printAge method is declared with a return type ( void ), name, and parameter list
(int age) , and it prints the age. In main , we create a Person object p and call
p.printAge(25) , passing the integer 25. The output will be Age = 25 .

23. Given the following code, identify and correct the error:

public class Example {


public void main(String[] args) {
System.out.println("Test");
}
}

Answer: The error is that the main method has no static keyword. It should be declared public
static void main(String[] args) . Without static , the JVM cannot call it as the entry point.
The corrected method signature is:

public static void main(String[] args) { ... }

With this change, running the program prints Test.

6
24. What is the output of the following code?

for(int i = 1; i <= 3; i++) {


System.out.println(i + " ");
}

Answer: The loop runs with i = 1, 2, 3. Each iteration prints i followed by a space. So the output will
be:

1
2
3

Each number appears on its own line (because println moves to a new line after printing).

25. Correct the error in variable declaration:

int number = "5";

Answer: This assignment tries to put a string "5" into an int . The types mismatch. It should be:

int number = 5;

Without quotes, 5 is an integer literal. Alternatively, if you want to convert a string, use
Integer.parseInt("5") .

26. Write a code snippet to create an ArrayList of integers and add the numbers
1 through 5. Then loop to print them.

List<Integer> list = new ArrayList<>();


for(int i = 1; i <= 5; i++) {
list.add(i);
}
for(int num : list) {
System.out.println(num);
}

Answer: This code uses List<Integer> and new ArrayList<>() (Java’s Collections) to store
integers. The first loop adds 1,2,...,5 to the list. The second loop ( for-each ) iterates through the list
and prints each number. The output will be 1, 2, 3, 4, 5 each on a new line.

27. Complete the for-loop to sum the elements of an array arr .

7
int[] arr = {2, 4, 6, 8};
int sum = 0;
for(int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum = " + sum);

Answer: This loop runs from i = 0 to i < arr.length , adding each arr[i] to sum . After the
loop, sum equals 2+4+6+8 = 20. So the program prints Sum = 20 .

28. Show how to handle a checked exception when reading a file named
"data.txt" .

try {
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}

Answer: Because FileReader and readLine() can throw IOException (a checked exception),
the code is placed in a try block. The catch block catches IOException . If the file is not found or
a read error occurs, e.printStackTrace() will print an error. Otherwise, each line of the file is
printed.

29. Given String s = "hello"; , write code to remove duplicate characters using
a Set .

String s = "hello";
Set<Character> seen = new LinkedHashSet<>();
for(char c : s.toCharArray()) {
seen.add(c);
}
for(char c : seen) {
System.out.print(c);
}

Answer: We use a Set<Character> to keep track of seen characters. A LinkedHashSet maintains


insertion order. The code converts s to a char array and adds each character to the set. Duplicates (“l”
appears twice in “hello”) are stored only once. The final loop prints helo (each unique character in
order).

8
30. What is the output of the following inheritance example?

class A { void show() { System.out.println("A"); } }


class B extends A { void show() { System.out.println("B"); } }
public class Test {
public static void main(String[] args) {
A obj = new B();
obj.show();
}
}

Answer: Here, B overrides show() . In main , obj is declared as type A but refers to a new B()
object. Due to polymorphism, obj.show() calls the B version of show() . So it will print:

Even though the reference type is A , the actual object is B , so the overridden method in B runs.

31. Identify the error and correct it:

List<String> list = new ArrayList<>();


list.add("One");
list.add("Two");
System.out.println(list.get(2));

Answer: The error is an IndexOutOfBoundsException . We are trying to get(2) (the third element)
but only two elements (indices 0 and 1) exist in the list. To fix it, either use a valid index (0 or 1) or add
another element first. For example:

System.out.println(list.get(1)); // prints "Two"

32. Fill in the code so that interface Action is correctly implemented by class
Run .

interface Action {
void perform();
}

class Run implements Action {


@Override
public void perform() {
System.out.println("Running");
}
}

9
public class Test {
public static void main(String[] args) {
Action a = new Run();
a.perform();
}
}

Answer: The class Run must declare implements Action and provide a
public void perform() method. The @Override annotation is optional but good practice. The
main method then uses Run to implement Action . The program will print Running .

33. Predict the output of overloading example:

class Calc {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
public class Test {
public static void main(String[] args) {
Calc c = new Calc();
System.out.println(c.add(2, 3));
System.out.println(c.add(2.5, 3.5));
}
}

Answer: This class has two overloaded add methods. The first call c.add(2, 3) invokes
add(int,int) and returns 5 . The second c.add(2.5, 3.5) invokes add(double,double)
and returns 6.0 . So the output is:

5
6.0

34. Complete the code to catch multiple exceptions:

try {
int x = 10 / 0;
String s = null;
System.out.println(s.length());
} catch (ArithmeticException | NullPointerException e) {
System.out.println("Exception: " + e);
}

Answer: The try block may throw either an ArithmeticException or NullPointerException .


We can catch both in one multi-catch block using | . The code above will catch either exception and
print its message. In this example, division by zero happens first, so it prints something like
Exception: java.lang.ArithmeticException: / by zero .

10
35. What will be printed by the following code?

public class Test {


public static void main(String[] args) {
int a = 5;
int b = a++;
System.out.println(a + " " + b);
}
}

Answer: This uses post-increment. b = a++ assigns the original value of a to b (which is 5) and
then increments a . After this statement, a becomes 6. The println prints the current values:
6 5 .

36. Fill in the code to copy a HashMap to another:

Map<String, Integer> map1 = new HashMap<>();


map1.put("Alice", 30);
map1.put("Bob", 25);

Map<String, Integer> map2 = new HashMap<>(map1);


System.out.println(map2.get("Alice")); // outputs 30

Answer: The HashMap constructor that takes another map allows copying. We use new
HashMap<>(map1) to create map2 with the same entries. Then map2.get("Alice") returns 30 as
expected.

37. Identify the cause of NullPointerException and fix the code:

String str = null;


System.out.println(str.length());

Answer: The NullPointerException occurs because str is null and we called str.length() .
To fix this, ensure str is initialized before using it:

String str = "";


System.out.println(str.length()); // Now prints 0

Alternatively, check for null before calling:

if (str != null) {
System.out.println(str.length());
}

11
38. How would you use a Scanner to read an integer from user input?

Scanner scanner = new Scanner(System.in);


System.out.print("Enter a number: ");
int n = scanner.nextInt();
System.out.println("You entered: " + n);

Answer: We create a Scanner on System.in . The nextInt() method reads the next integer typed
by the user. We store it in n and then print it. If the user enters, say, 42 , the program prints You
entered: 42 . (Be sure to handle exceptions in real programs, but nextInt() suffices for basic use.)

39. What is the output of the following method call?

public static void greet() {


System.out.println("Hello");
}
public static void main(String[] args) {
greet();
System.out.println("World");
}

Answer: The main method first calls greet() , which prints Hello (with a newline). Then it prints
World . So the output will be:

Hello
World

(Each on its own line because of println .)

40. Fix the syntax error in the interface and its implementation:

interface Shape {
double area();
}
class Circle implements Shape {
double radius;
Circle(double r) { radius = r; }
public double area() { return Math.PI * radius * radius; }
}

Answer: The Circle class must declare implements Shape (done) and provide a public method
double area() . The code above is correct. Ensure the area method is public , as interface
methods are implicitly public . The code compiles, and you can create a Circle c = new
Circle(2.0); System.out.println(c.area()); to get the area.

12
Coding Problems
41. Define a class Person with fields name and age . Include a constructor and a
method displayInfo that prints the person’s details.

public class Person {


private String name;
private int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

public void displayInfo() {


System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Test {


public static void main(String[] args) {
Person p = new Person("Alice", 30);
p.displayInfo(); // Output: Name: Alice, Age: 30
}
}

Model Answer: The Person class has private fields for encapsulation and a constructor to initialize
them. The displayInfo() method prints the values. In main , we create a Person and call
displayInfo() , resulting in Name: Alice, Age: 30 .

42. Create a class hierarchy with a base class Animal having a method speak() ,
and a subclass Dog that overrides speak() . Demonstrate polymorphism.

class Animal {
public void speak() {
System.out.println("Animal speaks");
}
}

class Dog extends Animal {


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

13
public class Test {
public static void main(String[] args) {
Animal a1 = new Animal();
Animal a2 = new Dog();
a1.speak(); // Outputs: Animal speaks
a2.speak(); // Outputs: Dog barks
}
}

Model Answer: Dog extends Animal and overrides speak() . In main , a1 is an Animal object,
so a1.speak() prints "Animal speaks". a2 is declared as Animal but refers to a Dog() , so
a2.speak() calls the overridden method and prints "Dog barks". This demonstrates runtime
polymorphism.

43. Define an interface Drivable with method drive() . Implement it in class


Car .

interface Drivable {
void drive();
}

class Car implements Drivable {


@Override
public void drive() {
System.out.println("Car is driving");
}
}

public class Test {


public static void main(String[] args) {
Drivable d = new Car();
d.drive(); // Output: Car is driving
}
}

Model Answer: The Drivable interface declares void drive() . Car implements Drivable and
provides the drive() method. In main , a Car object is referenced by the Drivable interface
type, and calling d.drive() invokes Car ’s implementation, printing "Car is driving".

44. Write a method that divides two numbers and handles any possible
ArithmeticException .

public class Test {


public static void divide(int a, int b) {
try {
int result = a / b;
System.out.println("Result = " + result);
} catch (ArithmeticException e) {

14
System.out.println("Error: Division by zero!");
}
}
public static void main(String[] args) {
divide(10, 2); // Output: Result = 5
divide(10, 0); // Output: Error: Division by zero!
}
}

Model Answer: The divide method wraps the division in a try block. If b is 0, an
ArithmeticException is thrown and caught, printing an error message. Otherwise it prints the
quotient. The example shows both a successful division and a divide-by-zero case.

45. Use an ArrayList to store the numbers 1 to 5 and compute their sum.

import java.util.ArrayList;
import java.util.List;

public class Test {


public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();
for(int i = 1; i <= 5; i++) {
nums.add(i);
}
int sum = 0;
for(int n : nums) {
sum += n;
}
System.out.println("Sum = " + sum); // Sum = 15
}
}

Model Answer: We create an ArrayList<Integer> , add numbers 1 through 5, then iterate to sum
them. The resulting sum is 15, which the code prints as Sum = 15 .

46. Use a HashSet to remove duplicates from an integer array.

import java.util.*;

public class Test {


public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 5};
Set<Integer> set = new LinkedHashSet<>();
for(int x : arr) {
set.add(x);
}
System.out.println(set); // Output: [1, 2, 3, 4, 5]

15
}
}

Model Answer: We iterate through the array and add each element to a LinkedHashSet . A Set
automatically ignores duplicates. Using LinkedHashSet preserves insertion order. Printing the set
shows only unique elements [1, 2, 3, 4, 5] .

47. Count the frequency of each character in a string using a HashMap .

import java.util.*;

public class Test {


public static void main(String[] args) {
String s = "hello";
Map<Character, Integer> freq = new HashMap<>();
for(char c : s.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
System.out.println(freq); // Output: {h=1, e=1, l=2, o=1}
}
}

Model Answer: The code converts the string to a char array and iterates. For each character, it updates its
count in the HashMap ( getOrDefault handles the case where the key is not yet in the map). The
final map {h=1, e=1, l=2, o=1} shows the frequency of each character.

48. Create a generic class Box<T> that holds an object of type T and a method to
get it. Demonstrate its use.

class Box<T> {
private T object;
public Box(T object) { this.object = object; }
public T getObject() { return object; }
}

public class Test {


public static void main(String[] args) {
Box<Integer> intBox = new Box<>(123);
Box<String> strBox = new Box<>("Hello");
System.out.println(intBox.getObject()); // 123
System.out.println(strBox.getObject()); // Hello
}
}

Model Answer: Box<T> is a generic class with type parameter T . It stores an object of type T . We
create a Box<Integer> to hold 123 and a Box<String> to hold "Hello" . Calling

16
getObject() returns the contained object, demonstrating type-safe reuse of the same class for
different data types.

49. Write code to read all lines from a file "input.txt" and print them.

import java.io.*;

public class Test {


public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new
FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Model Answer: This uses a try-with-resources to open input.txt . The BufferedReader reads each
line until null . Each line is printed. Using try-with-resources ensures the file is closed automatically.
Any IOException is caught and printed.

50. Write code to save an array of strings to a file "output.txt", one per line.

import java.io.*;

public class Test {


public static void main(String[] args) {
String[] data = {"Line1", "Line2", "Line3"};
try (PrintWriter pw = new PrintWriter(new FileWriter("output.txt")))
{
for (String s : data) {
pw.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Model Answer: We use a PrintWriter wrapped around FileWriter in a try-with-resources.


Looping over the data array, println writes each string followed by a newline. This creates (or
overwrites) output.txt with:

17
Line1
Line2
Line3

Any I/O errors are caught and printed.

51. Define a custom exception NegativeNumberException and throw it if a


method sqrt(int x) receives a negative number.

class NegativeNumberException extends Exception {


public NegativeNumberException(String message) {
super(message);
}
}

public class Test {


public static double sqrt(int x) throws NegativeNumberException {
if (x < 0) {
throw new NegativeNumberException("Negative not allowed: " + x);
}
return Math.sqrt(x);
}
public static void main(String[] args) {
try {
System.out.println(sqrt(25)); // 5.0
System.out.println(sqrt(-9));
} catch (NegativeNumberException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

Model Answer: We define NegativeNumberException extending Exception . The sqrt method


checks if x is negative; if so, it throws the custom exception. In main , calling sqrt(25) prints 5.0.
Then sqrt(-9) throws our exception, which is caught and prints Caught: Negative not
allowed: -9 .

52. Demonstrate exception handling with multiple catch blocks (e.g., catching both
ArithmeticException and NullPointerException ).

public class Test {


public static void main(String[] args) {
try {
int a = 10 / 0;
String s = null;
System.out.println(s.length());
} catch (ArithmeticException e) {

18
System.out.println("Arithmetic error: " + e);
} catch (NullPointerException e) {
System.out.println("Null pointer error: " + e);
}
}
}

Model Answer: We have two catch blocks. First divides by zero, throwing ArithmeticException , so
the first catch runs and prints an arithmetic error message. If we swapped the operations, the
NullPointerException would be caught by the second block. The key is that each type of exception
can be handled separately.

53. Create a class Car that contains an inner class Engine . Demonstrate creating
a Car with an Engine .

public class Car {


private String model;

public class Engine {


private int horsepower;
public Engine(int hp) {
this.horsepower = hp;
}
public void start() {
System.out.println("Engine started with " + horsepower + " HP");
}
}

public Car(String model) {


this.model = model;
}

public static void main(String[] args) {


Car car = new Car("Sedan");
Car.Engine eng = car.new Engine(150);
eng.start(); // Output: Engine started with 150 HP
}
}

Model Answer: Engine is an inner class of Car . We instantiate it using car.new Engine(150) . The
start method prints the horsepower. The example prints Engine started with 150 HP.

54. Sort a list of strings using Collections.sort .

import java.util.*;

public class Test {


public static void main(String[] args) {

19
List<String> list = Arrays.asList("banana", "apple", "cherry");
Collections.sort(list);
System.out.println(list); // [apple, banana, cherry]
}
}

Model Answer: We create a mutable list of fruits. Collections.sort(list) sorts it in natural


(alphabetical) order. The output list is ["apple", "banana", "cherry"] .

55. Create a class Point with overloaded constructors: one with no arguments
(default to origin) and one with coordinates.

public class Point {


private int x, y;

public Point() {
this(0, 0); // call the other constructor
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void display() {
System.out.println("(" + x + ", " + y + ")");
}

public static void main(String[] args) {


Point p1 = new Point();
Point p2 = new Point(5, 7);
p1.display(); // (0, 0)
p2.display(); // (5, 7)
}
}

Model Answer: We have two constructors: Point() which calls Point(int,int) with (0,0) , and
Point(int x,int y) . The display method shows the coordinates. The output demonstrates
constructor overloading.

56. Use a static field to count how many instances of a class Counter have been
created.

public class Counter {


private static int count = 0;
public Counter() {
count++;
}
public static int getCount() {
return count;

20
}

public static void main(String[] args) {


new Counter();
new Counter();
System.out.println(Counter.getCount()); // 2
}
}

Model Answer: The count field is static , shared by all Counter objects. Each time the constructor
runs, it increments count . After creating two instances, count is 2, which getCount() returns
and prints.

57. Define an abstract class Shape with an abstract method area() . Create a
subclass Circle that implements area() .

abstract class Shape {


abstract double area();
}

class Circle extends Shape {


private double r;
public Circle(double r) { this.r = r; }
@Override
double area() {
return Math.PI * r * r;
}
}

public class Test {


public static void main(String[] args) {
Shape s = new Circle(2.0);
System.out.println(s.area()); // 12.566370...
}
}

Model Answer: Shape is abstract with area() method. Circle extends Shape and provides the
implementation. In main , we use a Shape reference to hold a Circle . Calling s.area()
computes and prints the circle’s area (approximately 12.566).

58. Demonstrate method overloading with a class Printer that has two print
methods (one taking int and one taking String ).

public class Printer {


public void print(int x) {
System.out.println("Printing int: " + x);
}
public void print(String s) {

21
System.out.println("Printing String: " + s);
}

public static void main(String[] args) {


Printer p = new Printer();
p.print(100); // Printing int: 100
p.print("Hello"); // Printing String: Hello
}
}

Model Answer: The Printer class has two overloaded methods print . Depending on the argument
type, the correct method is called. The example prints “Printing int: 100” and “Printing String: Hello”
respectively.

59. Use a Scanner to read a list of integers from the user until a negative number
is entered, then print the sum.

import java.util.Scanner;

public class Test {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0, num;
System.out.println("Enter numbers (negative to stop):");
while ((num = sc.nextInt()) >= 0) {
sum += num;
}
System.out.println("Sum = " + sum);
}
}

Model Answer: The code reads integers in a loop. When a negative number is entered, the loop ends. It
then prints the sum of all non-negative numbers entered. This demonstrates user input with
Scanner .

60. Write a program to write the numbers 1 to 10 to a file using FileWriter .

import java.io.*;

public class Test {


public static void main(String[] args) {
try (FileWriter fw = new FileWriter("numbers.txt")) {
for(int i = 1; i <= 10; i++) {
fw.write(i + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}

22
}
}

Model Answer: This uses a FileWriter to open (and create) numbers.txt . It writes each number 1
through 10 followed by a newline. After running, the file contains the numbers 1–10, each on its own
line.

1 4 7 Inheritance in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/inheritance-in-java/

2 3 Encapsulation in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/encapsulation-in-java/

5 Polymorphism in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/polymorphism-in-java/

6 8 22 23 Java Interface - GeeksforGeeks


https://www.geeksforgeeks.org/interfaces-in-java/

9 10 Difference Between Aggregation and Composition in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/difference-between-aggregation-and-composition-in-java/

11 How JVM Works - JVM Architecture - GeeksforGeeks


https://www.geeksforgeeks.org/java/how-jvm-works-jvm-architecture/

12 13 Java Try Catch Block - GeeksforGeeks


https://www.geeksforgeeks.org/java/java-try-catch-block/

14 15 Java Checked vs Unchecked Exceptions - GeeksforGeeks


https://www.geeksforgeeks.org/java/java-checked-vs-unchecked-exceptions/

16 17 18 19 Collections in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/collections-in-java-2/

20 Generics in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/generics-in-java/

21 Java IO - Input/Output in Java with Examples - GeeksforGeeks


https://www.geeksforgeeks.org/java/java-io-input-output-in-java-with-examples/

23

You might also like