2 marks all :--
Previous year question paper answers
1 a) state the difference between superclass and subclass .. 2 marks
>> A superclass is a class that is inherited from by another class. It's also known as a parent class or
base class. It contains generalized attributes and methods that can be shared with other classes.
A subclass is a class that inherits from another class, the superclass. It's also known as a child class or
derived class. The subclass inherits the superclass's fields and methods and can also add its own
unique fields and methods. This promotes code reuse and establishes a clear hierarchy.
• Superclass: The parent.
• Subclass: The child, which inherits from the parent.
2) Distinguish between void and return data type in method definition ? 2 marks
• >> Return Type (like int, String): The method promises to give a value back after it's done.
You must use the return keyword to send back a value of that type. Example: int get Age
() must return a number.
• void: The method does not give anything back. It just performs an action and
finishes. Example: void print Hello () just prints a message.
3) why is java known as platform neutral language ? 2 marks
>> Java is known as a platform-neutral language because of its "Write Once, Run Anywhere"
(WORA) capability.
When Java code is compiled, it creates a platform-independent file called bytecode (.class file). This
bytecode can be run on any device, regardless of its operating system (like Windows, macOS, or
Linux), as long as it has a Java Virtual Machine (JVM) installed. The JVM then translates the
universal bytecode into native machine code for that specific platform.
4) write the output of the code snippet below :-- 2 marks
Int m = 2 ;
Int n = 15 ;
for (int i=1 ; i<5; i++ ) ;
m++ ;-n ;
[Link](“m=”+m);
[Link](“n=”+n);
>> m=3
n=15
Module – 01
2 a) write a program to calculate the area of a triangle by creating objects and accessing member
class .. 4 marks
>>
b) How does java differ from python language ? 2 marks
>> Here are the key differences between Java and Python
1. **Typing and Compilation:**
* **Java** is a **statically typed** and **compiled** language. You must declare a variable's
type before use (e.g., `int x = 10;`), and the code is compiled into bytecode before it runs, which
generally results in faster execution.
* **Python** is a **dynamically typed** and **interpreted** language. The type is determined
at runtime (e.g., `x = 10`), and the code is executed line by line, making it more flexible but typically
slower than Java.
2. **Syntax:**
* **Java** has a more verbose and strict syntax. It requires semicolons at the end of statements
and uses curly braces `{}` to define blocks of code.
* **Python** uses a simpler, more readable syntax that relies on indentation to define code
blocks, making it quicker to write and easier to learn.
c) what do you understand by class and object ? also give an example ? 2 marks
>> A Class is a blueprint or template for creating objects. It defines a set of properties (variables) and
behaviors (methods) that all objects of that class will have. It is a logical entity and does not consume
any memory space itself.
An Object is a real, usable instance of a class. It is created from the class blueprint and has its own
specific values for the properties defined in the class. It is a physical entity that occupies memory.
Example
• Class (Blueprint): Car
o The Car class defines that any car will have properties like color and model, and can
perform actions like drive().
• Objects (Instances):
o A blue Tesla is an object.
o A red Ford is another object.
Both are created from the Car blueprint, but they are separate objects with their own
specific color and model.
d) write a program in java to generate the digits of a number in using ‘ while’loop … 4 marks …
>> import [Link];
public class DigitsWhileLoop {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
[Link]("Digits: ");
while (num > 0) {
int digit = num % 10;
[Link](digit + " ");
num = num / 10;
}
}
}
Or
3 a) explain the basic concepts of static variable and static function in java .. 4 marks
>> Static Variable :--
A static variable belongs to the class itself, not to any individual object of the class. This means there
is only one copy of the static variable, which is shared among all objects created from that class.
Key Concepts:
1. Shared Memory: If one object changes the value of a static variable, the change is reflected
for all other objects of that class.
2. Class-Level Scope: It is associated with the class, so you can access it directly using the class
name without creating an object (e.g., [Link]).
3. Memory Allocation: It gets memory only once when the class is loaded, not every time an
object is created.
Static Function (Method)
A static method also belongs to the class, not to an object. It can be called directly using the class
name without needing to create an instance of the class.
Key Concepts:
1. No Object Required: You can invoke it using [Link](). The main method
in Java is a common example of a static method.
2. Access Restrictions: A static method can only directly access other static members (variables
and methods) of the class. It cannot access non-static (instance) variables or methods because
it is not associated with any specific object instance and doesn't know which object's data to
use.
b) write a program in java to find the square root of a number ? 4 marks
>>
c) what is byte code ? define JVM , JRE and JDK .. (1 +3) Marks
>> Bytecode is the platform-independent, intermediate code generated by the Java compiler when it
compiles a .java source file. This code is not readable by humans and is stored in a .class file. It is
designed to be executed by the Java Virtual Machine (JVM) on any platform.
JVM, JRE, and JDK (3 Marks)
1. JVM (Java Virtual Machine): The JVM is an abstract machine that provides the runtime
environment in which Java bytecode can be executed. It interprets the compiled bytecode and
translates it into native machine code for the specific operating system, which is what makes
Java platform-independent.
2. JRE (Java Runtime Environment): The JRE is the software package required to run Java
applications. It contains the JVM, along with the Java Class Library (core classes and support
files). You need to have JRE installed on a machine to run any Java program, but it does not
contain tools for development like compilers or debuggers.
3. JDK (Java Development Kit): The JDK is the full software development kit for Java. It
includes everything the JRE has, plus essential development tools needed
to create and compile Java applications. Key tools in the JDK include the compiler (javac),
the debugger (jdb), and archiver (jar).
Module-02-4
1) Define a garbage collector , what are its special properties ? 2 marks
>> A Garbage Collector is a program that runs in the background as part of the Java Virtual
Machine (JVM) to perform automatic memory management. It automatically identifies and
frees up memory space that is being used by objects that are no longer needed or referenced
by the program.
Special Properties:
1. Automatic: It works automatically without the programmer having to write code to
deallocate memory manually. This helps prevent memory leaks.
2. Non-Deterministic: The programmer cannot predict or control exactly when the garbage
collector will run. The JVM decides the best time to execute it, usually when memory is
running low.
2) Write a program in java to find the largest among two numbers illustrating the nesting of
methods inside a class .. 4 marks
>> class LargestNumber {
int largest(int a, int b) {
return compare(a, b);
}
int compare(int x, int y) {
if (x > y)
return x;
else
return y;
}
public static void main(String[] args) {
LargestNumber obj = new LargestNumber();
int num1 = 15, num2 = 20;
int result = [Link](num1, num2);
[Link]("Largest number: " + result);
}
}
3) Compare and contrast method overloading methods .. 4 marks
>> Compare and Contrast Method Overloading Methods (4 marks)
Comparison:
• Definition: Method overloading is a feature in object-oriented programming where two or
more methods in the same class have the same name but different parameters (type, number,
or both).
• Purpose: It increases the readability of the program and allows the same method name to
handle different types or numbers of inputs.
Contrast:
• Parameters: Overloaded methods must differ in their parameter list (either by number, type,
or order of parameters). They cannot be distinguished by return type alone.
• Implementation: Each overloaded method can have a different implementation, even though
they share the same name.
• Usage: The method that gets called depends on the arguments passed during the call; the
compiler determines the appropriate method based on the signature.
• Inheritance: Overloading is resolved at compile time (static polymorphism), while
overriding (another OOP concept) is resolved at runtime.
4) Why is multiple inheritance not possible in java ? 2 marks
>> Java does not support multiple inheritance with classes to avoid ambiguity and complexity
caused by the “Diamond Problem.” If a class inherits from two classes that have a method
with the same signature, the compiler cannot decide which method to use, leading to
confusion. Instead, Java uses interfaces to achieve multiple inheritance of type, ensuring clear
and conflict-free design.
or
5 a) write a java program to demonstrate the use of constructor by determining the area and
volume of a sphere .. 4 marks
>> class Sphere {
double radius;
// Constructor
Sphere(double r) {
radius = r;
}
double area() {
return 4 * [Link] * radius * radius;
}
double volume() {
return (4.0 / 3.0) * [Link] * radius * radius * radius;
}
}
public class SphereDemo {
public static void main(String[] args) {
Sphere s = new Sphere(5); // Sphere with radius 5
[Link]("Area = " + [Link]());
[Link]("Volume = " + [Link]());
}
}
6) when do we declare a method or class abstract ? 2 marks
>> We declare a method as abstract when we want to define its signature but not its
implementation; subclasses must provide the actual implementation.
We declare a class as abstract when it contains one or more abstract methods, or when we
want to prevent direct instantiation and allow only inheritance for providing specific
implementations.
7) Discuss the different levels of access protection available in java .. 2 marks
>> Java provides four levels of access protection for class members:
1. **Public:** Members are accessible from any other class in any package.
2. **Protected:** Members are accessible within the same package and by subclasses in other
packages.
3. **Default (Package-private):** If no modifier is specified, members are accessible only
within the same package.
4. **Private:** Members are accessible only within the same class.
These levels help control the visibility and encapsulation of code.
8) write a java program by defining a marks class which contains the method PCM marks (
calculate the average of physics , chemistry and math marks ) and method PCB marks (
calculate the average of physics , chemistry and bio marks ) methods .. 4 marks …
>>
Module – 03
1) what is inheritance and how does it help us create new classes quickly ? 3 marks
>> **Inheritance** is an object-oriented programming concept where a new class (called the
subclass or derived class) acquires the properties and behaviors (fields and methods) of an
existing class (called the superclass or base class).
**How does inheritance help us create new classes quickly?**
- **Reusability:** Inheritance allows us to reuse code from existing classes, so we don’t have
to write the same functions and properties again for every new class.
- **Extensibility:** We can easily extend or modify the behavior of existing classes by
adding new features or overriding methods in the subclass.
- **Efficiency:** By inheriting from a base class, new classes can be created quickly with
minimal code, leading to faster development and easier maintenance.
**Example:**
If we have a base class `Vehicle` with properties like speed and methods like start(), we can
create a subclass `Car` that automatically has all those features, and then add or override
features specific to cars.
b) write a program in java demonstrating the role of super and implements keywords .. 4
marks
>>
c) Define user defined exception in java and the way to handle them with an example ?
5marks
>> **User Defined Exception in Java (5 marks):**
A user defined exception is a custom exception created by extending the `Exception` class (or
its subclasses) in Java. This allows programmers to signal and handle application-specific
error conditions.
**How to handle user defined exceptions:**
1. **Define a custom exception class** by extending `Exception`.
2. **Throw the exception** using the `throw` keyword.
3. **Handle the exception** using try-catch blocks.
**Example:**
```java name=[Link]
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class UserDefinedExceptionDemo {
// Method to check age
static void checkAge(int age) throws InvalidAgeException {
if(age < 18) {
throw new InvalidAgeException("Age must be 18 or above.");
} else {
[Link]("Access granted!");
}
}
public static void main(String[] args) {
try {
checkAge(15); // Will throw exception
} catch (InvalidAgeException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}
```
**Explanation:**
- `InvalidAgeException` is a user defined exception.
- `checkAge` method throws the exception if age is less than 18.
- The exception is handled using a try-catch block in the `main` method.
**Output:**
```
Caught Exception: Age must be 18 or above.
```
**Summary:**
User defined exceptions help signal application-specific errors, and are handled using
standard exception handling techniques in Java.
7. a) Define four unchecked exceptions with descriptions In java ? 4 marks
>> **Four Unchecked Exceptions in Java (with descriptions):**
1. **NullPointerException**
Thrown when an application attempts to use `null` where an object is required (e.g., calling
a method on a null object reference).
2. **ArrayIndexOutOfBoundsException**
Thrown to indicate that an array has been accessed with an illegal index (either negative or
greater than or equal to the array’s length).
3. **ArithmeticException**
Thrown when an exceptional arithmetic condition occurs, such as division by zero.
4. **IllegalArgumentException**
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
> These exceptions are unchecked because they inherit from `RuntimeException` and are not
required to be declared or caught explicitly.
b) what is polymorphism ? demonstrate with the help of an example ? 4 marks
>> **Polymorphism in Java (4 marks)**
**Definition:**
Polymorphism is an object-oriented programming concept that allows objects of different
classes to be treated as objects of a common superclass. It enables one interface to be used for
a general class of actions, with the specific action determined at runtime.
**Types:**
- **Compile-time polymorphism (Method Overloading)**
- **Runtime polymorphism (Method Overriding)**
**Example (Runtime Polymorphism):**
```java name=[Link]
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link](); // Output: Dog barks
a = new Cat();
[Link](); // Output: Cat meows
}
}
```
**Explanation:**
- The reference variable `a` of type `Animal` can point to objects of subclasses (`Dog`, `Cat`).
- The method `sound()` is called on `a`, and Java uses the actual object type to decide which
version of `sound()` to execute.
- This demonstrates runtime polymorphism.
c) write a java program to show the use of “ throws “ in exception . 4 marks
>> class ThrowsDemo {
// Method declares that it may throw an exception
static void check(int num) throws ArithmeticException {
if (num < 0) {
throw new ArithmeticException("Number is negative");
} else {
[Link]("Number is positive");
}
}
public static void main(String[] args) {
try {
check(-5); // This will throw an exception
} catch (ArithmeticException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}
Module – 04
8 a) write a java program to demonstrate the use of JTable () method in java swing .4 marks
>> import [Link];
import [Link];
import [Link];
public class JTableDemo {
public static void main(String[] args) {
// Sample data for the table
String[][] data = {
{"1", "Alice", "Math"},
{"2", "Bob", "Science"},
{"3", "Charlie", "English"}
};
// Column headers
String[] columnNames = {"ID", "Name", "Subject"};
// Create JTable
JTable table = new JTable(data, columnNames);
// Add table to scroll pane
JScrollPane scrollPane = new JScrollPane(table);
// Create JFrame
JFrame frame = new JFrame("JTable Example");
[Link](400, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](scrollPane);
[Link](true);
}
}
b) mention some java buit in exception and their uses ? 4 marks
>> **Java Built-in Exceptions and Their Uses (4 marks):**
1. **NullPointerException**
- **Use:** Thrown when an application tries to use `null` in a case where an object is
required, such as calling a method on a null reference.
2. **ArrayIndexOutOfBoundsException**
- **Use:** Occurs when an array has been accessed with an illegal index (less than zero or
greater than or equal to the array size).
3. **ArithmeticException**
- **Use:** Raised when an exceptional arithmetic condition occurs, such as division by
zero.
4. **NumberFormatException**
- **Use:** Thrown when an attempt is made to convert a string to a numeric type, but the
string does not have an appropriate format.
These built-in exceptions help identify common programming errors and make error handling
in Java programs more robust.
c) Define applet with examples . differentiate between a checkbox and a combobox .. 4 marks
>> **Applet Definition and Example:**
An **applet** is a small Java program that runs within a web browser or an applet viewer.
Applets are used for creating interactive features in web applications, and are subclasses of
`[Link]` or `[Link]`.
**Example:**
```java
import [Link];
import [Link];
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello, Applet!", 20, 20);
}
}
```
This applet displays "Hello, Applet!" on the screen when run in an applet viewer or supported
browser.
---
**Difference between Checkbox and Combobox:**
| Checkbox | Combobox |
|---------------------------------------|-------------------------------|
| Allows user to select one or more options independently. | Allows user to select one option
from a dropdown list. |
| Typically used for multiple selections. | Typically used for single selection. |
| In Java, represented by `Checkbox` class (AWT) or `JCheckBox` (Swing). | In Java,
represented by `Choice` class (AWT) or `JComboBox` (Swing). |
| Shows all options at once. | Shows all options only when clicked (dropdown). |
**Summary:**
Checkbox is for multiple independent choices, while Combobox presents a list for a single
selection.
Or
9) a) Differentiate between AWT and swing ? 4 marks
>> **Difference between AWT and Swing (4 marks):**
| Aspect | AWT (Abstract Window Toolkit) | Swing
|
|-----------------------|------------------------------------------------------|----------------------------------
-------------|
| **Component Type** | Heavyweight (uses native OS components) | Lightweight
(written in Java, not OS dependent) |
| **Look and Feel** | Platform-dependent (varies with OS) | Platform-
independent (consistent across OS) |
| **Features** | Limited GUI components and functionality | Rich set of
advanced GUI components (tables, trees, etc.) |
| **Event Handling** | Uses older event handling model | Uses improved and
more flexible event handling |
| **Package** | `[Link]` | `[Link]`
|
| **Customization** | Less customizable | Highly customizable with
pluggable look & feel |
**Summary:**
AWT relies on native OS for rendering and is limited in features, while Swing is fully Java-
based, more powerful, and provides a consistent, customizable GUI experience.
b) what is finally block ? when and how is it used ? Give a suitable example ? 4 marks
>> **Finally Block in Java (4 marks):**
**Definition:**
The `finally` block in Java is used in exception handling to execute code regardless of
whether an exception occurs or not. It ensures that crucial cleanup code (like closing files or
releasing resources) always runs after a try-catch block.
**When is it used?**
- When you need to guarantee that some code executes after try-catch, even if an exception is
thrown.
- Commonly used for releasing resources such as files, database connections, or network
sockets.
**How is it used?**
- The `finally` block follows the `try` and `catch` blocks.
- It executes after the try-catch, whether an exception is handled or not.
**Example:**
```java
public class FinallyExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // Will cause ArithmeticException
} catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
} finally {
[Link]("This is the finally block. It always executes.");
}
}
}
```
**Output:**
```
Exception caught: [Link]: / by zero
This is the finally block. It always executes.
```
**Summary:**
The `finally` block guarantees execution of important code (like cleanup) after exception
handling, making programs more robust.
c) write a java program to show the use of draw image() method in java swing ? 4 marks
>> import [Link].*;
import [Link].*;
public class DrawImageDemo extends JPanel {
private Image img;
public DrawImageDemo() {
img = [Link]().getImage("[Link]");
}
public void paintComponent(Graphics g) {
[Link](g);
// Draw the image at position (50, 50)
[Link](img, 50, 50, this);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Image Example");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new DrawImageDemo());
[Link](true);
}
}