JAVA PROGRAMMING - EXAM ANSWERS (17MCS24C1)
[Link]. Computer Science 4th Semester (CBCS) Examination - July, 2021
------------------------------------------------------------
[Link]. 1(a)
Question:
Why is Java platform independent language?
Answer:
Java is platform-independent because its compiler converts source code into an intermediate
format called bytecode (.class file), rather than machine-specific executable code. This bytecode
can be executed on any operating system that has a Java Virtual Machine (JVM). This approach
implements the "Write Once, Run Anywhere" (WORA) principle.
------------------------------------------------------------
[Link]. 1(b)
Question:
What are short-circuit logical operators in Java? Give example.
Answer:
Short-circuit logical operators (&& for logical AND, || for logical OR) optimize condition
evaluation by skipping the evaluation of the second operand if the final outcome is already
determined by the first operand.
Example / Program:
if (obj != null && [Link]()) {
// isValid() is skipped if obj is null, preventing
NullPointerException
}
------------------------------------------------------------
[Link]. 1(c)
Question:
Write the syntax of adding a package into a Java program and give one example.
Answer:
To add or use a package in a Java program, the 'import' keyword is used at the top of the file
before the class declaration.
Example / Program:
Syntax:
import package_name.ClassName;
import package_name.*;
Example:
import [Link];
------------------------------------------------------------
[Link]. 1(d)
Question:
Do exception objects exist? If yes, what purpose they serve?
Answer:
Yes, exception objects exist in Java. They are instantiated from subclasses of [Link]
when an error occurs.
Purpose: They encapsulate detailed information about the error (such as the type of exception,
program state, and call stack trace). This object is thrown and can be caught by a catch block,
allowing the program to handle errors gracefully without crashing.
------------------------------------------------------------
[Link]. 1(e)
Question:
Define Thread.
Answer:
A Thread is the smallest unit of execution or a lightweight sub-process in Java. Threads allow a
program to perform multiple tasks concurrently (multithreading), sharing the same memory
space to maximize CPU utilization.
------------------------------------------------------------
[Link]. 1(f)
Question:
What is the role of status window?
Answer:
In Java Applets and AWT applications, the status window (or status bar) is a dedicated area
typically at the bottom of the applet viewer or web browser. Its role is to display informational
messages, background processing status, or state updates to the user using the
showStatus("message") method.
------------------------------------------------------------
[Link]. 1(g)
Question:
What are AWT controls? Label
Answer:
AWT Controls are the graphical user interface (GUI) components provided by the [Link]
package (e.g., Button, TextField, Checkbox) that allow users to interact with a Java application.
Label: A Label is a simple, passive AWT control used to display a single line of read-only text
string on the GUI. It does not generate any user events.
------------------------------------------------------------
[Link]. 1(h)
Question:
What is the purpose of using a layout manager?
Answer:
A layout manager automatically controls the positioning and sizing of GUI components within a
container. Its primary purpose is to ensure that the interface adapts dynamically and correctly
to different screen resolutions, resizing of windows, and cross-platform font differences without
relying on hard-coded absolute coordinates.
------------------------------------------------------------
[Link]. 2(a)
Question:
What is Object Oriented programming? Give the reason of accessing data of a class through its
functions only.
Answer:
Object-Oriented Programming (OOP) is a programming paradigm built around the concept of
"objects" that contain data (attributes/fields) and behavior (methods). It relies on four main
principles: Encapsulation, Inheritance, Polymorphism, and Abstraction. It models real-world
entities to make software easier to develop and maintain.
Reasons for accessing data through functions only (Encapsulation):
1. Data Security & Hiding: Prevents unauthorized or accidental modification of data from
external classes.
2. Data Validation: Setter functions can enforce business rules (e.g., ensuring an age variable is
never negative) before committing changes to the data.
3. Maintainability: The internal implementation of the class can be modified without breaking
the external code that relies on the class's public methods.
------------------------------------------------------------
[Link]. 2(b)
Question:
Write a Java code for finding the transpose of a given matrix.
Answer:
The transpose of a matrix is found by swapping its rows with its columns.
Example / Program:
public class MatrixTranspose {
public static void main(String[] args) {
int[][] original = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int rows = 3, cols = 3;
int[][] transpose = new int[cols][rows];
// Finding Transpose
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = original[i][j];
}
}
// Printing Transpose
[Link]("Transposed Matrix:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
[Link](transpose[i][j] + " ");
}
[Link]();
}
}
}
Output:
Transposed Matrix:
1 4 7
2 5 8
3 6 9
------------------------------------------------------------
[Link]. 3(a)
Question:
Write a Java Program to find the sum of series of n-terms of 1 + 1/2 + 1/3 + 1/4 ........ 1/n
Answer:
The given series is a Harmonic Series. We can compute its sum by running a loop from 1 to n and
adding the reciprocal of each term.
Example / Program:
import [Link];
public class HarmonicSeries {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of terms (n): ");
int n = [Link]();
double sum = 0.0;
for (int i = 1; i <= n; i++) {
sum += 1.0 / i; // Force floating point division
}
[Link]("Sum of the series upto %d terms is: %.4f\n",
n, sum);
[Link]();
}
}
Output:
Enter number of terms (n): 4
Sum of the series upto 4 terms is: 2.0833
------------------------------------------------------------
[Link]. 3(b)
Question:
How is decision making done in Java? Explain various control structures used in decision-making
and branching with their syntax.
Answer:
Decision making in Java allows a program to conditionally execute specific blocks of code based
on whether a boolean condition evaluates to true or false.
Various Control Structures for Decision Making:
1. Simple 'if' statement: Executes a block of code only if the condition is true.
Syntax:
if (condition) {
// statements
}
2. 'if-else' statement: Executes the if-block if true, otherwise executes the else-block.
Syntax:
if (condition) {
// true statements
} else {
// false statements
}
3. 'nested if-else' / 'else-if' ladder: Used to test multiple independent conditions sequentially.
Syntax:
if (condition1) {
// statements 1
} else if (condition2) {
// statements 2
} else {
// default statements
}
4. 'switch' statement: Tests a single variable against multiple exact values (cases). It is more
readable than long else-if ladders.
Syntax:
switch(variable) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statements
}
------------------------------------------------------------
[Link]. 4(a)
Question:
What do you understand by Polymorphism? How many different kinds of polymorphism
possible in Java?
Answer:
Polymorphism (derived from Greek meaning "many forms") is an OOP principle that allows a
single entity (such as a method, operator, or object) to behave differently depending on the
context in which it is used.
Kinds of Polymorphism in Java:
1. Compile-Time Polymorphism (Static Binding): Achieved through Method Overloading. The
compiler determines which method to call based on the number, types, and order of
parameters at compile time.
2. Run-Time Polymorphism (Dynamic Binding): Achieved through Method Overriding. When a
subclass provides a specific implementation for a method already defined in its superclass, the
JVM determines which method to invoke at runtime based on the actual object type being
referenced, not the reference variable's type.
------------------------------------------------------------
[Link]. 4(b)
Question:
What are packages? Explain the need of importing a package. How do we import packages in
Java? Discuss.
Answer:
Packages in Java are directory-like namespaces used to group related classes, interfaces, and
sub-packages together.
Need for Importing a Package:
1. Name-Space Management: Packages prevent naming conflicts. (e.g., [Link] and
[Link] can coexist because they are in different packages).
2. Access Protection: Packages provide a boundary for access modifiers (default/package-private
level access).
3. Reusability: They make it easy to locate and reuse existing code components.
How to Import Packages in Java:
Packages are imported using the 'import' keyword placed at the top of the Java source file.
Approaches to importing:
1. Importing a specific class:
import [Link];
(Recommended, as it explicitly states what is being used).
2. Importing all classes in a package (Wildcard):
import [Link].*;
(Imports all classes within [Link], though it does not import sub-packages).
------------------------------------------------------------
[Link]. 5(a)
Question:
What is Exception? How is it different from error? What does the method getMessage() and
printStackTrace() do in exception handling?
Answer:
Exception: An exception is an unwanted or unexpected event occurring during program
execution (runtime) that disrupts the normal flow of instructions. Exceptions can be caught and
handled programmatically using try-catch blocks.
Difference from Error:
- Exceptions (e.g., IOException, ArithmeticException) are caused by program logic or controllable
external factors and are recoverable.
- Errors (e.g., OutOfMemoryError, StackOverflowError) represent severe, unrecoverable system
failures that the application should generally not attempt to catch.
Methods in Exception Handling:
- getMessage(): Returns a brief, descriptive string message detailing the cause of the exception.
- printStackTrace(): Prints a detailed trace of the exception to the standard error stream. It
shows the exception name, description, and the exact sequence of method calls (with file names
and line numbers) that led to the error, making it invaluable for debugging.
------------------------------------------------------------
[Link]. 5(b)
Question:
What is an interface? Write a program to show how a class implements two interfaces.
Answer:
An interface in Java is a reference type containing abstract methods (methods without a body)
and constant variables. It acts as a contract that implementing classes must follow. Since Java
does not support multiple inheritance of classes, interfaces are primarily used to achieve
multiple inheritance and 100% abstraction.
Example / Program:
interface Drawable {
void draw();
}
interface Printable {
void print();
}
// Class implementing two interfaces
class Shape implements Drawable, Printable {
public void draw() {
[Link]("Drawing a shape...");
}
public void print() {
[Link]("Printing the shape...");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Shape myShape = new Shape();
[Link]();
[Link]();
}
}
Output:
Drawing a shape...
Printing the shape...
------------------------------------------------------------
[Link]. 6(a)
Question:
What are threads? How do they differ from processes? Explain the two ways to create child
threads? Which approach is better? Why?
Answer:
Threads: A thread is a lightweight sub-process. It is the smallest path of execution within a
program.
Difference from Process:
- Processes are heavyweight, independent execution units with separate memory spaces.
- Threads exist within a process, are lightweight, and share the same memory and resources,
making inter-thread communication faster and context switching cheaper.
Two ways to create threads in Java:
1. By extending the 'Thread' class: The class inherits from Thread and overrides the run()
method.
2. By implementing the 'Runnable' interface: The class implements the run() method and an
instance of it is passed to a Thread object.
Better Approach:
Implementing the Runnable interface is considered the better approach.
Why?
Because Java does not support multiple class inheritance. If a class extends Thread, it cannot
extend any other superclass. Implementing Runnable leaves the class free to extend another
superclass if needed. Also, Runnable promotes better object-oriented design by separating the
task (the Runnable) from the runner (the Thread).
------------------------------------------------------------
[Link]. 6(b)
Question:
What is stream? Differentiate between stream source and stream destination.
Answer:
Stream: In Java I/O, a stream is a continuous, ordered sequence of data (either bytes or
characters). It provides a uniform way to handle input and output operations regardless of the
underlying device (like a file, network connection, or memory buffer).
Difference:
1. Stream Source (Input Stream):
- It represents the origin of data.
- It is used to read data from a source (e.g., reading a file on disk, taking input from the
keyboard).
- Primary classes: InputStream, Reader.
2. Stream Destination (Output Stream):
- It represents the endpoint where data is being sent.
- It is used to write data to a destination (e.g., writing to a file, displaying output on a console
monitor).
- Primary classes: OutputStream, Writer.
------------------------------------------------------------
[Link]. 7(a)
Question:
Differentiate between Processes and Threads? How can we synchronize threads?
Answer:
Processes vs Threads:
- Process: Heavyweight, isolated memory space, slower context switching, higher overhead for
inter-process communication.
- Thread: Lightweight, shared memory space within the parent process, faster context switching,
easier communication between threads.
Thread Synchronization:
Since threads share resources, concurrent access can lead to data inconsistency (race
conditions). Synchronization restricts access to shared resources to only one thread at a time.
How to synchronize:
Java uses the 'synchronized' keyword to achieve synchronization via intrinsic locks (monitors).
1. Synchronized Method: Locks the entire method for the object instance.
public synchronized void updateData() { ... }
2. Synchronized Block: Locks only a specific block of code, providing finer control and better
performance than synchronizing the whole method.
synchronized(this) { ... }
------------------------------------------------------------
[Link]. 7(b)
Question:
Write a program using FileReader and PrintWriter classes for copying a file named [Link] to
[Link].
Answer:
The FileReader class is used to read character data from a file, while PrintWriter is used to write
formatted character data to a file.
Example / Program:
import [Link];
import [Link];
import [Link];
public class FileCopyProgram {
public static void main(String[] args) {
try (FileReader fr = new FileReader("[Link]");
PrintWriter pw = new PrintWriter("[Link]")) {
int ch;
// Read character by character until End of File (-1)
while ((ch = [Link]()) != -1) {
[Link](ch);
}
[Link]("File copied successfully from [Link]
to [Link]");
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
[Link]();
}
}
}
Output:
File copied successfully from [Link] to [Link]
------------------------------------------------------------
[Link]. 8(a)
Question:
What are Applets? How HTML tags are used in applets? Explain taking suitable example.
Answer:
Applets are small Java programs specifically designed to be embedded within web pages and
executed securely by a Java-enabled web browser or an appletviewer utility.
HTML Tags in Applets:
Applets require an HTML file to execute. The <applet> tag (historically used) instructs the
browser to load the compiled Java bytecode (.class file) and allocate a specific area (width and
height) on the web page for the applet's GUI.
Suitable Example:
Java Code ([Link]):
import [Link];
import [Link];
public class MyApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello Applet", 50, 50);
}
}
HTML Code ([Link]):
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
------------------------------------------------------------
[Link]. 8(b)
Question:
Differentiate between: (i) FlowLayout and BorderLayout (ii) Panel and Frame
Answer:
(i) FlowLayout vs BorderLayout
- FlowLayout: Arranges GUI components in a line, one after another (left to right). If the space
runs out, it wraps to the next line. It is the default layout manager for Applets and Panels.
- BorderLayout: Arranges components into five specific geographical regions: North, South, East,
West, and Center. It is the default layout manager for Frames and Dialogs.
(ii) Panel vs Frame
- Panel: It is an inner container class. It does not have a title bar, borders, or minimize/maximize
buttons. It cannot exist independently and must be added to a top-level container (like a Frame
or Applet) to be visible.
- Frame: It is a top-level standalone window container. It comes with a title bar, borders, and
window control buttons (close, minimize, maximize) and can exist independently on the desktop
screen.
------------------------------------------------------------
[Link]. 9(a)
Question:
What are the various ways to execute an Applet?
Answer:
There are primarily two ways to execute a compiled Java Applet (.class file):
1. Using a Web Browser:
The applet is embedded into an HTML file using the <applet> or <object> tags. The HTML file is
opened in a Java-enabled web browser. The browser's built-in Java plugin (JVM) executes the
applet.
2. Using the Appletviewer Utility:
The 'appletviewer' is a command-line tool provided by the Java Development Kit (JDK). It acts as
a minimal browser environment specifically designed to test applets. It parses the HTML file,
ignores standard HTML tags, and only executes the <applet> tag.
Command syntax: appletviewer [Link]
------------------------------------------------------------
[Link]. 9(b)
Question:
Write a program which shows the coordinates of point of click of mouse on the frame.
Answer:
This program utilizes the MouseListener interface to capture mouse events on a Frame.
Example / Program:
import [Link];
import [Link];
import [Link];
import [Link];
public class MouseCoordinates extends Frame implements MouseListener {
int mouseX = 0, mouseY = 0;
String msg = "Click anywhere on the frame";
public MouseCoordinates() {
addMouseListener(this);
setTitle("Mouse Coordinates App");
setSize(400, 300);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
mouseX = [Link]();
mouseY = [Link]();
msg = "Clicked at (" + mouseX + ", " + mouseY + ")";
repaint(); // Calls update() which calls paint()
}
// Empty implementations for other MouseListener methods
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void paint(Graphics g) {
[Link](msg, mouseX, mouseY);
}
public static void main(String[] args) {
new MouseCoordinates();
}
}
Output:
A GUI frame opens. When the user clicks on it, the string "Clicked at
(X, Y)" gets drawn exactly at the clicked location.