Java Question Paper-1
1 Marks Question
a) Define Exception:
Explanation:
An exception is an event that occurs during the execution of a program and
disrupts the normal flow of instructions. It is often caused by an error or
unexpected condition and may be handled by exception handling
mechanisms in the programming language.
b) Define Interface:
Explanation:
An interface in programming is a collection of abstract methods (methods
without a body) that a class can implement. It defines a contract for classes,
specifying the methods they must provide. Java uses the interface keyword
to declare an interface.
c) What is Javadoc?
Explanation:
Javadoc is a tool in Java for generating documentation from comments in the
source code. It reads special comments, denoted by /** ... */ , and
generates HTML documentation, making it easier for developers to create
and maintain documentation for their code.
d) What is AWT?
Explanation:
AWT stands for Abstract Window Toolkit. It is a set of classes and methods in
Java for creating graphical user interfaces (GUIs). AWT provides components
like buttons, text fields, and windows that can be used to build desktop
applications.
Java Question Paper-1 1
e) What is the Use of Static Keyword?
Explanation:
The static keyword in Java is used to create class-level variables and
methods. Class-level variables are shared among all instances of a class,
and class-level methods can be called without creating an instance of the
class.
f) What is Command Line Argument?
Explanation:
Command-line arguments are values passed to a program when it is
executed from the command line or terminal. They provide input to the
program, allowing users to customize its behavior without modifying the
source code.
g) List the Types of Constructor:
Explanation:
Types of constructors in Java include:
1. Default Constructor: Has no parameters and is provided by the
compiler if no other constructor is defined.
2. Parameterized Constructor: Accepts parameters during object creation.
3. Copy Constructor: Creates an object by copying the values of another
object.
h) What is Package?
Explanation:
In Java, a package is a way to organize related classes and interfaces. It
provides a namespace to avoid naming conflicts and helps in modularizing
code. Packages can be nested, and they reflect the directory structure in the
file system.
Java Question Paper-1 2
i) How to Open a File in Read Mode?
Explanation:
In Java, to open a file in read mode, you can use FileReader class or
BufferedReader with InputStreamReader. For example:
FileReader fr = new FileReader("filename.txt");
j) List Any Two Listeners:
Explanation:
In Java GUI programming, listeners are used to handle events. Two types of
listeners are:
1. ActionListener: Listens for action events, such as button clicks.
2. MouseListener: Listens for mouse-related events, like clicks and
movements.
2 Marks Question
a) List Any Two Methods of String Buffer Class:
append(String str) method:
Explanation:
Appends the specified string to the end of the current StringBuffer object.
insert(int offset, String str) method:
Explanation:
Inserts the specified string into the current StringBuffer object at the
specified offset.
b) What is the Use of 'throw' Keyword:
Explanation:
Java Question Paper-1 3
The throw keyword in Java is used to explicitly throw an exception. It is
followed by an instance of the Throwable class (or its subclasses), indicating
the exception to be thrown. This allows a programmer to signal that a specific
exceptional condition has occurred during the execution of a program.
c) Differentiate Between ‘final’ and ‘finally’ keyword:
Explanation:
‘final’ keyword:
Used to declare a variable, method, or class as unchangeable or not
overridable.
Example: ‘ final int x = 10; ’
‘finally’ keyword:
Used in a try-catch block to define a block of code that will be executed
whether an exception is thrown or not.
Example:
try
{
//Code that may throw an exception
}
catch (Exception e)
{
//Exception handling
}
finally
{
//Code that always executes, even if an exception occur
}
d) What is Method Overloading:
Explanation:
Method overloading in Java refers to the ability to define multiple methods in
the same class with the same name but different parameter lists. The
Java Question Paper-1 4
methods must have different types or a different number of parameters. This
allows for more flexibility and readability in method design.
e) What is Anonymous Inner Class:
Explanation:
An anonymous inner class in Java is a class without a name that is declared
and instantiated in a single statement. It is often used for one-time use and is
defined using the new keyword along with a class or interface. Anonymous
inner classes are commonly used in event handling.
4 Marks Question
a) Java Program using AWT to Change Background Color of Table to 'RED' by
Clicking on Button:
import java.awt.*;
import java.awt.event.*;
public class TableBackgroundColorChange extends Frame {
private TableBackgroundColorChange() {
Button changeColorButton = new Button("Change Color to
// Table creation (assumed)
// Replace this with your actual table creation logic
// Adding ActionListener to the button
changeColorButton.addActionListener(new ActionListene
@Override
public void actionPerformed(ActionEvent e) {
// Change background color of the table to RED
// Replace "table" with your actual table com
// Example: table.setBackground(Color.RED);
}
});
// Adding components to the frame
Java Question Paper-1 5
setLayout(new FlowLayout());
add(changeColorButton);
// Set frame properties
setSize(300, 200);
setTitle("Table Background Color Change");
setVisible(true);
// Close the frame on window close button
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new TableBackgroundColorChange();
}
}
b) Java Program to Copy Content from One File into Another File, Replacing Digits
with '*':
import java.io.*;
public class CopyFileWithDigitReplacement {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new Fi
BufferedWriter writer = new BufferedWriter(new Fi
int ch;
while ((ch = reader.read()) != -1) {
// Replace digits with '*'
if (Character.isDigit(ch)) {
ch = '*';
Java Question Paper-1 6
}
// Write the character to the output file
writer.write(ch);
}
System.out.println("File copied successfully with
} catch (IOException e) {
e.printStackTrace();
}
}
}
c) Java Program to Define an Interface Shape with Abstract Method area( ),
Calculate Area of Rectangle:
interface Shape {
double area(); // Abstract method to calculate area
}
class Rectangle implements Shape {
private double length;
private double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double area() {
return length * width;
}
}
public class CalculateRectangleArea {
public static void main(String[] args) {
// Creating a Rectangle object
Java Question Paper-1 7
Rectangle rectangle = new Rectangle(5.0, 3.0);
// Calculating and printing the area
System.out.println("Area of Rectangle: " + rectangle.a
}
}
4 Marks Question
a) Java Program to Accept a Number, Throw User-Defined Exception, and Calculate
Factorial:
import java.util.Scanner;
// User-defined exception for zero input
class ZeroInputException extends Exception {
public ZeroInputException(String message) {
super(message);
}
}
public class FactorialWithException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number == 0) {
throw new ZeroInputException("Number is zero"
} else {
long factorial = calculateFactorial(number);
System.out.println("Factorial of " + number +
}
} catch (ZeroInputException e) {
System.out.println("Exception: " + e.getMessage()
Java Question Paper-1 8
} finally {
scanner.close();
}
}
private static long calculateFactorial(int n) {
if (n == 1 || n == 0) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}
b) Explanation of the Uses of super Keyword with Suitable Example:
Uses of super Keyword:
The super keyword in Java is used to refer to the immediate parent class
object. It is often used to differentiate between the members of a subclass
and the members of the superclass.
Example:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void eat() {
super.eat(); // Calls the eat() method of the pare
System.out.println("Dog is eating");
}
}
public class SuperKeywordExample {
public static void main(String[] args) {
Java Question Paper-1 9
Dog dog = new Dog();
dog.eat();
}
}
In this example, the eat() method in the Dog class uses super.eat() to
explicitly call the eat() method of the parent class ( Animal ).
c) Differentiation Between AWT and Swing:
AWT (Abstract Window Toolkit):
AWT is the original Java GUI library.
AWT components are heavyweight, meaning they rely on the underlying
operating system's resources.
AWT lacks advanced components and has limited customization options.
AWT is part of the core Java API.
Swing:
Swing is an extension of AWT and provides a richer set of GUI components.
Swing components are lightweight, as they are implemented entirely in Java.
Swing offers a wide range of customizable components, including advanced
ones like tables and trees.
Swing is part of the Java Foundation Classes (JFC).
Example:
If you want to create a simple button:
In AWT: Button button = new Button("Click me");
In Swing: JButton button = new JButton("Click me");
These explanations cover the requested functionalities. If you have more questions
or need further clarification, feel free to ask!
3 Marks Question
a) Java Program to Count the Number of Vowels in a Given String:
Java Question Paper-1 10
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a string: ");
String inputString = scanner.nextLine().toLowerCa
int vowelCount = countVowels(inputString);
System.out.println("Number of vowels in the string
} finally {
scanner.close();
}
}
private static int countVowels(String str) {
int count = 0;
for (char ch : str.toCharArray()) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch ==
count++;
}
}
return count;
}
}
b) Explanation of the Features of Java:
Platform Independence:
Java programs can run on any device or platform with the help of the Java
Virtual Machine (JVM). The "Write Once, Run Anywhere" (WORA)
philosophy allows Java code to be executed on various platforms without
modification.
Object-Oriented:
Java Question Paper-1 11
Java is an object-oriented programming language, promoting the use of
objects and classes. It supports encapsulation, inheritance, and
polymorphism.
Simple and Easy to Learn:
Java has a clear syntax and eliminates the complexities of languages like
C++ (e.g., explicit pointers, operator overloading). This makes it easier for
programmers to learn and write clean code.
Robust:
Java enforces strong compile-time checking and runtime checking to ensure
that programs are free of errors. It also provides automatic garbage
collection to reclaim memory.
Secure:
Java has built-in security features, including a bytecode verifier to ensure the
integrity of the code. It also supports authentication and access control
mechanisms.
Distributed Computing:
Java supports the development of distributed applications through Remote
Method Invocation (RMI) and networking capabilities. This allows for the
creation of client-server applications.
Multithreading:
Java supports multithreading, allowing concurrent execution of multiple
threads. This is essential for creating responsive and efficient applications.
Dynamic:
Java supports dynamic memory allocation and dynamic class loading. It
allows the creation of dynamic web applications and supports reflection.
Java Question Paper-1 12