Java Programming Exam Questions 2023
Java Programming Exam Questions 2023
To use classes or interfaces from other packages, Java provides import statements.
}
(An Autonomous Institute under Kakatiya University, Warangal)
FACULTY OF ENGINEERING AND TECHNOLOGY } Import statements allow developers to reference classes and interfaces by their
B. Tech. (IT) IV Semester (Regular & Supplementary) Examination, May 2023 simple names instead of their fully qualified names.
Answer: This simplifies the code and enhances readability.
U18IT406: JAVA Programming KITS
WARANGAL 1 f Analyze and find out the output of the following program? [1] An CO2
1 a What role did the Java Virtual Machine (JVM) play in the early days of [1] R CO1 I2RE public class MultipleCatchBlock{
java. 1 d What is the difference between a superclass and a subclass in [1] U CO2 public static void main (String [] args)
Answer: Java, {
Platform Independence and how do you access inherited properties and methods? try{
Interpreted Execution Answer: int arr[]=new int[10];
Performance In Java, a superclass (also known as a parent class or base class) is a class that is extended by
arr[6]=25/0;
OptimizationMemory another class, known as a subclass (also known as a child class or derived class).
}
Management Security catch(ArithmeticException e)
Debugging and Monitoring Inheritance Relationship:
A subclass inherits properties and methods from its superclass. {
1 b How do arrays work in Java, and how can you use them to store [1] U CO1 The subclass can extend the functionality of the superclass by adding its own properties [Link]("Arithmetic Exception occurs");
and manipulate data? and methods or by overriding the inherited ones. }
Answer: catch(ArrayIndexOutOfBoundsException e)
Arrays in Java are data structures used to store collections of elements of the same type. Access Modifiers: {
They provide a convenient way to store and manipulate data in a contiguous block of Subclasses inherit accessible members (fields and methods) from the superclass. [Link]("ArrayIndexOutOfBounds
memory. Here's how arrays work in Java and how you can use them: Members with private access modifier in the superclass are not directly accessible in the Exception occurs");
Declaring an Array subclass. }
Creating an Array Members with default, protected, or public access modifiers are accessible in the subclass catch(Exception e)
Initializing Arrays depending on their access level and the relationship between the classes (same package, {
Accessing Array subclass, or any package). [Link]("Parent Exception occurs");
Elements Iterating Over
}
Arrays Array Length Methods:
}
Length of the numbers Inherited methods can be directly called in the subclass.
}
arrayArray Manipulation If the method is overridden in the subclass, the subclass version of the method will be
Answer:
[1] invoked when called from the subclass.
1 C Analyze and find out the output of the following code An CO1 In this program:
If the method is not overridden, the superclass version of the method will be invoked.
snippet? public class StringExample An array arr of size 10 is created.
1 e What is a package in Java, and how does it help in organizing classes [1] U CO2 Then, an attempt is made to assign a value to the 7th element (arr[6]) of the array, which
{
and
public static void main (String args []) will raise an ArithmeticException because of the division by zero (25 / 0).
interfaces?
{ Since the exception occurs within a try block, the program jumps to the appropriate
Answer:
String s1="KITS"; In Java, a package is a mechanism for organizing classes, interfaces, enumerations, and catch block based on the type of exception caught.
char ch[]={'W','A','R','A','N','G','A','L'}; annotations into namespaces. Packages help in structuring and managing the Java Given the type of exception raised (ArithmeticException), the first catch block that
String s2=new String(ch); codebase by grouping related types together. matches this type will execute.
String s3=new 1 g Explain the difference between process and thread in Java, and [1] R CO3
Packages also serve as a boundary for access control in Java.
string("I2RE"); how
Classes and interfaces within the same package have access to each other's theyare related to each other?
[Link](s1);
members (fields, methods) with default (package-private) access modifier without Answer:
[Link](s2);
explicitly specifying access modifiers. A process is an independent and self-contained unit of execution in an operating
[Link](s3);
Classes and interfaces in different packages need explicit access modifiers (public, system.
protected) to access each other's members.
A thread is the smallest unit of execution within a process.
Processes can contain multiple threads. When a Java program starts, it typically
begins
with a single process, which in turn can create multiple threads to perform running code from the local file system.
Local applets were more commonly used in the early days of Java applet 2 a Can a class have multiple constructors in Java? If so, how do you [6] U CO1
concurrenttasks. define
development but have become less prevalent with the advancement of web
Threads within the same process share the same memory space, allowing them them? What is the difference between a default constructor and a
technologies and increased emphasis on web security.
to communicate and synchronize their actions more efficiently compared to parameterized constructor in Java?
Remote Applet:
processes. Answer:
A remote applet is an applet that resides on a remote server and is delivered
1. Default Constructor:
Threads within the same process can access shared data and resources directly, to the client's machine over the network. A default constructor is a constructor with no parameters.
facilitating collaboration and coordination among concurrent tasks. It is typically embedded within an HTML document and loaded and If no constructors are explicitly defined in a class, Java provides a
Multiple threads within the same process can execute concurrently, enabling executed by a web browser or a Java applet viewer via a network default constructor automatically.
connection. The default constructor initializes the object with default values, if any,
parallelism and efficient utilization of multi-core processors.
Remote applets are launched using a URL that points to the location of the or performs any other initialization code specified within it.
1 h Differentiate multiprocessing and multithreading. [1] U CO3
applet on the remote server, typically using the "[Link] or "[Link] Example: public MyClass() { /* Constructor code */ }
Answer:
protocol.
Multiprocessing: Multiprocessing involves the simultaneous execution of
Remote applets are subject to the security restrictions imposed by the Java 2. Parameterized Constructor:
multiple
processes on a multi-core or multi-processor system. Each process runs Runtime Environment (JRE) and the web browser, such as the same-origin A parameterized constructor is a constructor with one or more parameters.
independentlyand has its own memory space. policy and the applet sandbox. It allows you to initialize the object with specific values provided as
Remote applets are commonly used for embedding interactive content, arguments when the object is created.
Multithreading: Multithreading involves the simultaneous execution of
multiple multimedia, or other dynamic functionality within web pages. Parameterized constructors are useful for initializing objects with
threads within a single process. Threads share the same memory space and 1 k What is the difference between Swing and AWT? [1] R CO4 different values based on the requirements.
resources of the process to which they belong. Answer: Example: public MyClass(int param1, String param2) { /* Constructor code */ }
1 i AWT: AWT is the original GUI toolkit for Java. It provides a platform-
A container class can be described as a special component that can [1] U CO3
independent while a default constructor is used to initialize objects with default values or perform basic
hold the gathering of the other components. List the different types of interface to native GUI elements provided by the underlying operating system. initialization, a parameterized constructor allows you to initialize objects with specific values
container classes available in Java. AWT components are lightweight, meaning they rely on the native platform's GUI provided as arguments during object creation.
libraries for rendering.
Answer: Swing: Swing is built on top of AWT and provides a richer set of GUI Having multiple constructors in a class provides flexibility in object initialization and
Different types of container classes components. enables the creation of objects in different ways.
Arrays Swing components are lightweight and are implemented entirely in Java. They Top of Form
ArrayList have a consistent look and feel across different platforms, as Swing renders its 2 b [6] Ap CO1
LinkedLis components instead of relying on the underlying native GUI libraries. Write a program to evaluate the following investment equation and
t HashSet 1 l What is the difference between BorderLayout and GridLayout? [1] R CO4 print the tables which would give the value of V for various combination
TreeSet Answer: of the following values of P, r and n. (where P is principal amount and V
HashMap BorderLayout: is the value of money at the end of n years. V=P(1+r)n
TreeMap BorderLayout divides the container into five regions: North, South, East, West,
and Center. V=P(1+r)n
LinkedHashMap
Components added to a container using BorderLayout are placed in one of Answer:
PriorityQueue
these regions, and each region can contain at most one component. public class InvestmentCalculator {
1 j Differentiate local applet and remote applet. [1] U CO4 GridLayout: public static void main(String[] args) {
Answer: GridLayout arranges components in a grid-like fashion with a specified number // Define arrays for different values of P, r, and n
Local Applet: of rows and columns. int[] principalValues = {1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
A local applet is an applet that resides on the client's machine, typically Components are added to the container sequentially, and they are laid out row by double[] interestRates = {0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20};
within the client's file system. row, filling each row before moving to the next.
It is loaded and executed by a web browser or a Java applet viewer All components in a GridLayout have the same size, which is determined by the size
directlyfrom the client's local file system. of
Local applets are launched using a URL that starts with the "[Link] the container divided by the number of rows and columns.
protocol, indicating that the applet is loaded from the local file system.
Due to security concerns, modern web browsers have restricted the ability
to
execute local applets due to potential security vulnerabilities associated
with
int[] years = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Method to read employee
Difference: details public void readEmployee() {
// Print table header String: Scanner scanner = new Scanner([Link]);
[Link]("%-10s %-10s %-10s %-15s\n", "P", "R", "n", "V"); Suitable for situations where the string value remains constant or does [Link]("Enter Employee Name: ");
notrequire frequent modifications. empName = [Link]();
// Iterate through each combination of P, r, Immutability ensures thread safety, making strings preferable in [Link]("Enter Employee ID: ");
and nfor (int i = 0; i < [Link]; multithreaded environments. empId = [Link]();
i++) { Less efficient for string manipulation operations, especially when dealing [Link]("Enter Basic Pay: ");
int P = principalValues[i]; witha large number of concatenations or modifications. basicPay = [Link]();
for (int j = 0; j < [Link]; j++) { StringBuilder: [Link]();
double r = interestRates[j]; Suitable for situations where string manipulation operations such as }
for (int k = 0; k < [Link]; k++) concatenation, deletion, or insertion are frequent.
{ int n = years[k]; Mutable nature allows efficient modification of strings without creating new // Method to calculate salary
// Calculate V using the investment objects, resulting in better performance. public void calculateSalary() {
equationdouble V = P * [Link](1 + r, n); Not thread-safe by default, so caution should be exercised when using if (basicPay >= 5000) {
// Print the values in tabular format StringBuilder in multithreaded environments. If thread safety is required, hra = 0.45 *
[Link]("%-10d %-10.2f %-10d %-15.2f\n", P, r, n, V); youcan use StringBuffer, which is similar to StringBuilder but thread-safe. basicPay; da = 0.33 *
} basicPay; pf = 0.22 *
} 2 d Write a java program to read and display employee salary details. [6] Ap CO1 basicPay; itr = 0.08 *
} basicPay;
Instance variables: EmpName, EmpId, BasicPay, DA, HRA, PF, ITR,
} } else {
and NetSalary, where NetSalary=BasicPay+DA+HRA-PF-ITR.
} hra = 0.32 *
OR Methods: readEmployee (), CalculateSalary(), DisplayEmployee()
basicPay; da = 0.28 *
2 c How do you create a string in Java? What is the difference between [6] U CO1 Conditions:
basicPay; pf = 0.15 *
a If BasicPay>=5000 then If BasicPay<5000 then
basicPay; itr = 0.05 *
string and a StringBuilder in Java explain with an example? HRA :45% on BasicPay HRA :32% on basicPay;
Answer:
BasicPay DA: 33% on BasicPay DA: 28% }
In Java, you can create a string using either a string literal or the String class
on BasicPay PF: 22% on BasicPay PF: 15% netSalary = basicPay + da + hra - pf - itr;
constructor.
}
on BasicPay IT: 8% on BasicPay IT: 5% on
1. Using String Literal: BasicPay // Method to display employee
String str1 = "Hello"; // Using string literal
details public void
Answer:
import [Link]; displayEmployee() {
2. Using String Constructor:
String str2 = new String("World"); // Using String constructor [Link]("Employee Name: " +
public class EmployeeSalary { empName); [Link]("Employee ID: " +
String: // Instance variables empId); [Link]("Basic Pay: " +
Strings in Java are immutable, meaning once a string object is created, its private String basicPay); [Link]("DA: " + da);
value cannot be changed. empName; private int [Link]("HRA: " + hra);
If you concatenate or modify a string, a new string object is created, which empId; private double [Link]("PF: " + pf);
canlead to performance overhead when dealing with a large number of basicPay; private [Link]("ITR: " + itr);
string operations. double da; private [Link]("Net Salary: " + netSalary);
StringBuilder: double hra; private }
StringBuilder is a mutable sequence of characters introduced in Java to double pf; private
efficiently manipulate strings. double itr; private public static void main(String[] args) {
Unlike strings, StringBuilder objects can be modified without creating new double netSalary; EmployeeSalary employee = new
objects, making them more efficient for string manipulation operations. EmployeeSalary(); [Link]();
[Link]();
[Link]();
}}
3 a Write a Java program that uses inheritance to model a school. Create a [6] Ap CO2 // Subclass Teacher [Link]("Teacher Information:");
base class called Person with properties such as name, age, and class Teacher extends Person [Link]();
gender, and subclasses such as Student, Teacher, and Administrator. { private String subject; [Link]();
Each subclass should have its own set of properties and methods,
and the program should be able to display information about // Constructor [Link]("Administrator Information:");
each public Teacher(String name, int age, String gender, String subject) { [Link]();
person in the school. super(name, age, gender); }
Answer: [Link] = subject; }
// Base class Person } 3 b Write a Java program that uses polymorphism to calculate the [6] Ap CO2
class Person { area of different shapes. Create a base class called Shape with
protected String name; // Method to display information about the methods such as getArea() and subclasses such as Rectangle, Circle,
protected int age; teacher public void displayInfo() { and Triangle. Each subclass should implement the getArea() method
protected String [Link](); to
gender; [Link]("Subject: " + subject); calculate the area of that shape.
} Answer:
// Constructor } // Base class Shape
public Person(String name, int age, String gender) abstract class Shape {
{ [Link] = name; // Subclass Administrator // Abstract method to calculate the
[Link] = age; class Administrator extends Person { area public abstract double getArea();
[Link] = private String department; }
gender;
// Constructor // Subclass Rectangle
}
public Administrator(String name, int age, String gender, String class Rectangle extends Shape
department) { super(name, age, gender); { private double length;
// Method to display information about the
[Link] = department; private double width;
personpublic void displayInfo() {
[Link]("Name: " + name); }
// Constructor
[Link]("Age: " + age);
// Method to display information about the public Rectangle(double length, double
[Link]("Gender: " +
administrator public void displayInfo() { width) { [Link] = length;
gender);
[Link](); [Link] = width;
}
[Link]("Department: " + department); }
}
}
} // Override getArea() method to calculate area of rectangle
// Subclass Student
@Override
class Student extends Person
// Main class to test the public double getArea()
{ private int studentId;
program public class { return length *
SchoolModel { width;
// Constructor
public static void main(String[] args) { }
public Student(String name, int age, String gender, int
// Create objects of each subclass and display their }
studentId) { super(name, age, gender);
[Link] = studentId; informationStudent student = new Student("Alice", 16,
"Female", 1001); // Subclass Circle
}
Teacher teacher = new Teacher("Mr. Smith", 35, "Male", "Mathematics"); class Circle extends Shape
Administrator administrator = new Administrator("Ms. Johnson", 40, { private double radius;
// Method to display information about the
student public void displayInfo() { "Female",
"Administration"); // Constructor
[Link]();
[Link]("Student Information:"); public Circle(double radius)
[Link]("Student ID: " +
[Link](); { [Link] = radius;
studentId);
[Link](); }
}}
// Override getArea() method to calculate area of Answer: [Link]("Salesperson:");
circle @Override // Interface [Link]();
public double getArea() { Employee interface }
return [Link] * radius * radius; Employee { }
} void work();
} } 3 d Write a Java program that handles exceptions when dividing two [6] Ap CO2
numbers. The program should prompt the user to enter two numbers
// Subclass Triangle // Subclass Manager and display the result of dividing the first number by the second
class Triangle extends Shape class Manager implements Employee number. If the second number is zero, the program should catch
{ private double base; { @Override the
private double height; public void work() { ArithmeticExceptionand display an error message.
[Link]("Manager is managing the team."); Answer:
// Constructor } import [Link];
public Triangle(double base, double }
height) { [Link] = base; public class DivisionProgram {
[Link] = height; // Subclass Developer public static void main(String[] args) {
} class Developer implements Employee Scanner scanner = new
{ @Override Scanner([Link]);
// Override getArea() method to calculate area of triangle public void work() {
@Override [Link]("Developer is coding and developing software."); // Prompt the user to enter two numbers
public double getArea() { } [Link]("Enter the first number: ");
return 0.5 * base * height; } double num1 = [Link]();
}
} // Subclass Salesperson [Link]("Enter the second number: ");
class Salesperson implements Employee double num2 = [Link]();
// Main class to test the { @Override
program public class public void work() { try {
ShapeCalculator { [Link]("Salesperson is selling products or services."); // Perform division
public static void main(String[] args) { } double result = num1 / num2;
// Create objects of each shape } [Link]("Result of division: " +
Rectangle rectangle = new Rectangle(5, 10); result);
Circle circle = new Circle(3); // Main class to test the } catch (ArithmeticException e) {
Triangle triangle = new Triangle(4, 6); program public class Company // Handle division by zero exception
{ [Link]("Error: Division by zero is not
// Calculate and display areas of each shape public static void main(String[] args) { allowed.");
[Link]("Area of Rectangle: " + [Link]()); // Create objects of each employee type }
[Link]("Area of Circle: " + [Link]()); Manager manager = new Manager();
[Link]("Area of Triangle: " + [Link]()); Developer developer = new Developer(); [Link]();
} Salesperson salesperson = new }
} Salesperson(); }
OR
3 c Write a Java program that uses interfaces to model different types [6] Ap CO2 // Display information about each 4 a Write a Java program that uses multithreading to simulate a race [6] Ap CO3
of employees at a company. Create an interface called Employee employee [Link]("Manager:"); between two cars. Create a class called Car that extends the Thread
with methods such as work() and subclasses such as Manager, [Link](); class and has methods such as accelerate() and brake(). The program
Developer, and Salesperson. Each subclass should [Link](); should create two instances of the Car class and start them in separate
implement the work() method differently, [Link]("Developer:"); threads. Each thread should simulate the movement of the car by
and the program should be able to display [Link](); calling the accelerate() and brake() methods, and the program
information about each employee. [Link](); should display the
progress of the race.
while ((bytesRead = [Link](buffer)) != -1) { This method is used to perform any cleanup tasks, such as releasing
[Link](buffer, 0, bytesRead); resources and closing connections. ii. JCheckBox and JRadioButton:
} Once the destroy() method completes, the applet's memory is reclaimed by the
[Link]("File copied successfully."); JVM, and the applet is removed from the browser window. JCheckBox:
} catch (IOException e) { A JCheckBox is a graphical component that represents a check box.
[Link]("An error occurred while copying the file: " + [Link]()); Syntax for creating a JCheckBox object:
} JCheckBox checkBox = new JCheckBox("Check
} Box");
}
JRadioButton:
A JRadioButton is a graphical component that allows the user to select one option
from a group of options.
5 a Discuss briefly about the execution flow of Applet life cycle [6] U CO4
Syntax for creating a JRadioButton object:
with
neatsketch.
JRadioButton radioButton = new JRadioButton("Radio Button");
Answer:
The execution flow of an applet's life cycle in Java can be illustrated with the following
stages: iii. JButton and JToggleButton:
1. Initialization:
The init() method is called when the applet is first loaded into memory.
JButton:
A JButton is a graphical component that represents a push button.
This method is used for initializing the applet and is called only once during
Syntax for creating a JButton
the applet's lifetime.
object: JButton button = new
Typically, initialization tasks such as setting up variables, loading
JButton("Button");
resources, and initializing GUI components are performed here.
2. Start:
After initialization, the applet enters the start state. JToggleButton:
The start() method is called after the init() method and each time the 5 b Compare the following components by giving syntax for creating [6] Ap CO4 A JToggleButton is a graphical component that represents a toggle button, which
applet needs to be restarted. object foreach component. can be in an "on" or "off" state.
This method is used to start the applet's execution, such as starting i. JList and JComboBox Syntax for creating a JToggleButton object:
animations or initiating background tasks. ii. JCheckBox and JRadioButton
The applet remains in this state until it is stopped or destroyed. JToggleButton toggleButton = new JToggleButton("Toggle Button");
iii. JButton and JToggleButton
3. Running: OR
During this phase, the applet is actively running and interacting with the Answer: 5 c The layout manager automatically positions all the components [6] U CO4
user. within
The applet may respond to user input events, such as mouse clicks or i. JList and JComboBox: the container. List and explain the three main types of layout
keyboard input. managers in Java?
JList: Answer:
The paint() or paintComponent() method is called to render the applet's
A JList displays a list of items from which the user can select one or more items.
Three main types of layout managers are:
graphical content.
The applet continues to run until it is stopped, paused, or destroyed. Syntax for creating a JList object:
4. Pause/Stop: 1. FlowLayout:
JList<String> list = new JList<>(new String[]{"Item 1", "Item 2", "Item 3"});
FlowLayout arranges components in a left-to-right flow, adding
The stop() method is called when the applet is paused or stopped, such as
when the user navigates away from the applet's page or switches to another components horizontally until no more components can be added in the
JComboBox:
application. A JComboBox is a drop-down list that allows the user to select a single item from a
current row, and then moving to the next row.
This method is used to suspend any ongoing activities or release resources Components are added one after the other, and if the container's
list of items.
thatare no longer needed. Syntax for creating a JComboBox object:
width is exceeded, components are wrapped to the next line.
The applet can be restarted later by calling the start() method. JComboBox<String> comboBox = new JComboBox<>(new String[]{"Option 1", "Option 2", FlowLayout is the default layout manager for JPanel.
5. Destroy: "Option 3"}); Syntax to set FlowLayout for a container:
The destroy() method is called when the applet is no longer needed JPanel panel = new JPanel(new
and is being unloaded from memory. FlowLayout());
// Create label
2. BorderLayout: label = new JLabel("Entered Text: ");
BorderLayout divides the container into five regions: North, South, East,
West, and Center. // Create panel and add components
Components can be added to these regions, and the layout manager JPanel panel = new JPanel(new BorderLayout());
automatically resizes and positions components within their specified [Link](textField, [Link]);
regions. [Link](label, [Link]);
Components added to the Center region take up all available space in the
container, while components in other regions are positioned around the add(panel);
Center region. }
Syntax to set BorderLayout for a container:
// Custom KeyListener implementation
JPanel panel = new JPanel(new BorderLayout()); class CustomKeyListener implements
KeyListener { @Override
3. GridLayout: public void keyTyped(KeyEvent e) {}
GridLayout arranges components in a grid of rows and columns.
All components in the grid have the same size, and the layout manager @Override
divides the container into equal-sized cells to accommodate components. public void keyPressed(KeyEvent e) {}
Syntax to set GridLayout for a container:
@Override
JPanel panel = new JPanel(new GridLayout(rows, columns)); public void keyReleased(KeyEvent e) {
The rows and columns parameters specify the number of rows and columns // Update label text when a key is released
in the grid, respectively. [Link]("Entered Text: " +
5 d Create a Java program that allows the user to enter text into a text [6] Ap CO4 [Link]());
field }
anddisplays the text in a label. The program should use the }
KeyListener interface to handle keyboard events.
Answer: public static void main(String[] args) {
import [Link](() {
[Link].*; TextFieldExample example = new
import [Link].*; TextFieldExample();
import [Link]; [Link](true);
import });
[Link]; }
}
public class TextFieldExample extends