CLASS: II CS PROGRAMMING IN JAVA – QUESTION BANK CODE:225C31
STAFF: [Link] FATHIMA ANUJA
2 MARKS QUESTIONS AND ANSWERS
1. What is meant by Encapsulation?
Encapsulation is the process of compartmentalising the elements of an abstraction that defines the
structure and behavior. Encapsulation helps to separate the contractual interface of an abstraction and
implementation.
2. What are Packages in Java?
Packages in Java can be defined as the grouping of related types of classes, interfaces, etc providing
access to protection and namespace management. Packages are used in Java in order to prevent naming
conflicts, control access, and make searching/locating and usage of classes, interfaces, etc easier.
3. Explain different data types in Java.
There are 2 types of data types in Java as mentioned below:
1. Primitive Data Type
2. Non-Primitive Data Type or Object Data type
Primitive Data Type: Primitive data are single values with no special capabilities. There are 8 primitive
data types:
boolean: stores value true or false
byte: stores an 8-bit signed two's complement integer
char: stores a single 16-bit Unicode character
short: stores a 16-bit signed two’s complement integer
int: stores a 32-bit signed two’s complement integer
long: stores a 64-bit two’s complement integer
float: stores a single-precision 32-bit IEEE 754 floating-point
double: stores a double-precision 64-bit IEEE 754 floating-point
4. What is a static variable?
The static keyword is used to share the same variable or method of a given class. Static variables are
the variables that once declared then a single copy of the variable is created and shared among all
objects at the class level.
5. Define a user-defined class in Java.
A user-defined class is a class created by the programmer to represent objects or entities.
Example:
class Student {
int rollNo;
String name;
6. Identify the different types of inheritance in Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
7. What is the purpose of the finally block in exception handling?
The finally block contains code that always executes, whether or not an exception occurs. It is used
for resource cleanup, such as closing files or database connections.
8. Identify the difference between throw and throws in Java.
throw is used to manually throw an exception.
throws is used in method declarations to declare possible exceptions a method might throw.
9. Define a top-level container in Swing.
A top-level container is a component that provides the base window for Swing applications.
Examples:
JFrame, JDialog, and JApplet.
10. What is the function of the JLabel component in Swing?
JLabel is used to display text, images, or both on a GUI. It is non-editable and often used for
instructions or information display.
11. What is an adapter class in Java?
An adapter class provides default (empty) implementations of listener interfaces. It allows
programmers to override only required methods instead of all methods in the interface.
12. What is the role of the Comparator interface?
The Comparator interface is used to define custom sorting logic for objects. It provides the compare()
method to compare two objects based on specific attributes.
13. What is the purpose of the main method in a Java program?
The main() method serves as the entry point for any standalone Java application.
Syntax:
public static void main(String[] args)
14. Identify the primary difference between String and StringBuffer classes in Java.
String objects are immutable—once created, they cannot be changed.
StringBuffer objects are mutable, allowing modifications without creating new objects.
Hence, StringBuffer is preferred when frequent string modifications are required.
15. What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects,”
which contain data (fields) and methods (functions). It focuses on encapsulation, inheritance,
polymorphism, and abstraction to build modular, reusable, and maintainable code.
FIVE MARKS QUESTIONS AND ANSWERS:
1. Describe the architecture of the Java Virtual Machine (JVM) and its significance.
The Java Virtual Machine (JVM) is an abstract computing engine that enables Java programs
to be executed on any platform. It acts as a bridge between compiled Java bytecode and the
underlying operating system. The JVM architecture consists of several main components:
1. Class Loader Subsystem – loads .class files into memory and verifies their correctness.
2. Method Area – stores class-level data such as method code, field names, and constants.
3. Heap Area – used for dynamic memory allocation of objects and arrays at runtime.
4. Java Stack – holds local variables and partial results during method execution.
5. Program Counter (PC) Register – keeps track of the address of the current instruction being
executed.
6. Native Method Stack – manages native (non-Java) methods written in C or C++.
7. Execution Engine – converts bytecode into machine code using the interpreter or Just-In-
Time (JIT) compiler.
8. Garbage Collector – automatically frees memory by removing unused objects.
9. Native Method Interface (JNI) – enables interaction with native libraries.
10. Runtime Data Areas – together store all the data required for execution.
Significance:
The JVM ensures platform independence, security, and automatic memory management,
allowing Java programs to be “Write Once, Run Anywhere.”
2. Explain the concept of method overloading in Java with an example.
Method Overloading in Java is a feature that allows a class to have multiple methods with
the same name but different parameter lists (type, number, or order of parameters). It helps
improve code readability and reusability by performing similar operations with different
inputs.
The compiler differentiates between overloaded methods based on their method signatures
(parameters, not return type).
Method overloading is an example of compile-time polymorphism in Java.
Example:
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two double values
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](5, 10)); // Calls int version
[Link]([Link](5, 10, 15)); // Calls 3-int version
[Link]([Link](5.5, 2.5)); // Calls double version
}
}
3. Examine the concept of packages in Java.
Package in Java is a mechanism to group related classes, interfaces, and sub-packages together. It
helps in organizing code, avoiding name conflicts, and controlling access between different parts of a
program. Packages act like folders in a file system, keeping classes with similar functionality in one
place.
There are two types of packages in Java:
1. Built-in Packages:
These are predefined by Java and available for direct use.
Examples:
o [Link] → Contains core classes like String, Math, System.
o [Link] → Contains utility classes like ArrayList, HashMap.
o [Link] → For input and output operations.
o [Link] and [Link] → For GUI development.
2. User-defined Packages:
Created by programmers to organize their own classes.
Example:
package mypack; // Declares a user-defined package
public class Student {
public void display() {
[Link]("Welcome to Packages in Java");
import [Link];
class Test {
public static void main(String[] args) {
Student s = new Student();
[Link]();
4. What are inner classes in Java? Explain their different types.
1. Member Inner Class
Defined inside a class but outside any method.
Can access all members (even private) of the outer class.
Example:
class Outer {
private String msg = "Hello from Inner Class!";
class Inner {
void display() {
[Link](msg);
public static void main(String[] args) {
[Link] obj = new Outer().new Inner();
[Link]();
}
}
2. Static Nested Class
Declared using the static keyword.
Cannot access non-static members of the outer class directly.
Example:
class Outer {
static int data = 100;
static class Inner {
void show() {
[Link]("Data: " + data);
3. Local Inner Class
Defined inside a method or block of the outer class.
Accessible only within that method.
Example:
class Outer {
void outerMethod() {
class Inner {
void print() {
[Link]("Inside Local Inner Class");
Inner obj = new Inner();
[Link]();
4. Anonymous Inner Class
No name is given to the class.
Used to override methods of a class or interface instantly.
Example:
abstract class Animal {
abstract void sound();
class Test {
public static void main(String[] args) {
Animal a = new Animal() {
void sound() {
[Link]("Anonymous Inner Class Example");
};
[Link]();
5. Explain the process of creating your own exception classes in Java.
Steps to Create a User-Defined Exception
1. Extend the Exception Class
You create your exception by extending either:
Exception → for checked exceptions (must be declared using throws), or
RuntimeException → for unchecked exceptions (no need to declare).
2. Define a Constructor
The constructor is used to pass a custom error message to the parent Exception class.
3. Throw and Catch the Exception
Use the throw keyword to raise the exception and handle it using try-catch.
Example:
// Step 1: Create the user-defined exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message); // Passes message to parent Exception class
}
// Step 2: Use the exception in a program
public class TestCustomException {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above to vote.");
} else {
[Link]("Valid Age! You can vote.");
public static void main(String[] args) {
try {
validateAge(15); // This will cause the exception
} catch (InvalidAgeException e) {
[Link]("Caught Exception: " + [Link]());
TEN MARKS QUESTIONS AND ANSWERS
1. Evaluate the role of static data and static methods in Java.
Static Data: Shared by all objects of the class.
class Counter {
static int count = 0;
Counter() { count++; }
Static variables are declared using the keyword static inside a class.
Only one copy of a static variable exists, shared by all objects.
They are initialized only once at class loading time.
Used to represent common properties of all objects.
Accessed using the class name rather than the object.
class Student {
static String school = "ABC Public School";
String name;
Static Methods: Belong to the class, not to objects.
Declared using the keyword static before the method name.
They can be called without creating an object of the class.
They can access only static data and other static methods directly.
Commonly used for utility functions like mathematical or helper methods.
Example:
static void display() {}
class MathUtils {
static int square(int n) {
return n * n;
EXAMPLE:
class Counter {
static int count = 0; // static variable
Counter() {
count++; // shared among all objects
static void displayCount() { // static method
[Link]("Objects created: " + count);
}
public static void main(String[] args) {
new Counter();
new Counter();
[Link]();
2. Discuss the concept of deadlock in multithreaded programming.
In multithreaded programming, a deadlock is a situation where two or more threads are
permanently blocked, waiting for each other’s resources, and as a result, the program stops
progressing. It usually occurs when threads hold locks on shared resources and wait indefinitely for
other locks held by other threads.
Definition:
A deadlock is a condition where two or more threads are waiting for each other to release
resources, causing all of them to remain blocked forever.
Example Scenario:
Suppose we have two resources — Resource A and Resource B — and two threads, Thread 1 and
Thread 2.
Thread 1 locks Resource A and waits for Resource B.
Thread 2 locks Resource B and waits for Resource A.
Both threads keep waiting indefinitely, creating a deadlock.
class DeadlockExample {
public static void main(String[] args) {
final String resource1 = "Resource A";
final String resource2 = "Resource B";
Thread t1 = new Thread(() -> {
synchronized (resource1) {
[Link]("Thread 1: Locked Resource A");
try { [Link](100); } catch (Exception e) {}
synchronized (resource2) {
[Link]("Thread 1: Locked Resource B");
}
});
Thread t2 = new Thread(() -> {
synchronized (resource2) {
[Link]("Thread 2: Locked Resource B");
try { [Link](100); } catch (Exception e) {}
synchronized (resource1) {
[Link]("Thread 2: Locked Resource A");
});
[Link]();
[Link]();
3. Discuss in detail about Inheritance in Java.
Inheritance in Java is one of the key principles of Object-Oriented Programming (OOP). It allows one
class to acquire the properties and behaviors (fields and methods) of another class, promoting code
reusability and hierarchical classification.
Definition:
Inheritance is the process by which a new class (called the subclass or child class) inherits the
attributes and methods of an existing class (called the superclass or parent class).
Purpose of Inheritance:
To reuse existing code without rewriting it.
To achieve method overriding (runtime polymorphism).
To establish a hierarchical relationship between classes.
To make the code more organized and maintainable.
Syntax:
class Parent {
void display() {
[Link]("This is the parent class");
class Child extends Parent {
void show() {
[Link]("This is the child class");
public class Example {
public static void main(String[] args) {
Child obj = new Child();
[Link](); // Inherited from Parent
[Link](); // Defined in Child
Types of Inheritance in Java:
Type Description Example
Single Inheritance One class inherits another class. A→B
A class inherits from a derived
Multilevel Inheritance A→B→C
class.
Multiple classes inherit from one
Hierarchical Inheritance A → B, A → C
parent class.
Multiple Inheritance (via A class implements multiple interface A, interface B → class C
Interfaces) interfaces. implements A, B
Example:
class A {
void showA() { [Link]("Class A"); }
class B extends A {
void showB() { [Link]("Class B"); }
class C extends B {
void showC() { [Link]("Class C"); }
public class Demo {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
[Link]();