CAT2 QB Java
CAT2 QB Java
Q.No Question
1. What are the various states of a thread and write the importances of using Threads?
New: The thread is in this state when it has been created but has not yet started.
The necessary resources are allocated, but the thread has not been scheduled for
execution.
Runnable/Ready: The thread is ready to run, but the operating system has not
selected it to be the running thread yet. It's waiting for the CPU time.
Blocked/Waiting: The thread is waiting for some event to occur, such as user input
or the availability of a resource. While in this state, the thread does not consume
CPU time.
Timed Waiting: Similar to the blocked state, but with a specified waiting time.
The thread will automatically transition to the Runnable state after the specified
time.
Terminated/Dead: The thread has completed its execution or has been explicitly
terminated. Once in this state, a thread cannot be restarted.
The smallest unit of execution within a Involves concurrent execution of multiple threads
Definition process. within a single process.
3. What are the constructors used for creating a string with byte array?
String(byte[] bytes):
4. What value is assigned to string type when it is automatically initialized and specify some
operations that are performed using string?
5 Is it possible to change an object after it has been deserialized? If yes, then how?
In Java, after an object has been deserialized, it is indeed possible to modify its state.
Deserialization is the process of reconstructing an object from its serialized form, and once
the object is reconstructed in memory, you can interact with it just like any other object.
Serialization is the process of converting an object into a format that can be easily stored,
transmitted, or reconstructed. It's useful in various scenarios, and here are some common
situations where serialization is employed:
n Java, the AdjustmentEvent class is associated with constants that represent different
types of adjustment events. The constants are typically used to identify the type of
adjustment that occurred. The constants are part of the Adjustable interface, and they are
as follows:
UNIT_INCREMENT (int):
UNIT_DECREMENT (int):
BLOCK_INCREMENT (int):
BLOCK_DECREMENT (int):
8. Which package contains the methods to receive and process events and the method that support
the events?
In Java, the java.awt package contains classes and interfaces related to Abstract
Window Toolkit (AWT), which is a part of the Java Foundation Classes (JFC). This
package includes methods to receive and process events, as well as methods that
support events.
Key classes and interfaces related to events in the java.awt package include:
1. Component Class:
The Component class is a fundamental part of AWT and Swing.
Components can generate various events, and it provides methods for
event registration and handling.
2. Container Class:
The Container class extends Component and represents a container
of components. It also plays a role in the event-handling mechanism.
3. Event Class:
The Event class is part of the AWT event model, and it represents an
event that can occur within a graphical user interface. However, note that as
of Java 1.1, the event-delegation model is recommended, and the Event
class is considered obsolete.
4. EventListener Interface:
The EventListener interface is the base interface for all event
listener interfaces. It doesn't declare any methods but serves as a tag
interface for event listener objects.
9. How to place controls in a window and remove controls from a window?
In Java, checkbox operations generate ItemEvent events. The ItemEvent class is part of the Java
AWT (Abstract Window Toolkit) and Swing event model. It is used to handle events related to
items, such as checkboxes, radio buttons, and choice components.
When a user interacts with a checkbox, for example by clicking on it to toggle its state, an
ItemEvent is generated. This event is then sent to registered listeners, allowing your application
to respond to the checkbox state change.
11. List the various methods available for drawing polygons, ellipses, arcs.
In Java, drawing polygons, ellipses, and arcs can be accomplished using the Graphics class, which
provides various methods for rendering shapes on a graphical component (e.g., JPanel, Canvas).
Below are some of the commonly used methods for drawing polygons, ellipses, and arcs:
Drawing Polygons:
drawPolygon(int[] xPoints, int[] yPoints, int n) and fillPolygon(int[] xPoints, int[] yPoints, int n):
In Java applets, the init() and start() methods are part of the applet lifecycle,
and they serve different purposes:
1. init() Method:
The init() method is called when an applet is first created. It is
responsible for initializing the applet and is typically used to perform one-
time setup tasks. This method is called after the applet is instantiated but
before it is displayed on the screen.
Q.No Question
public MultithreadedClock() {
setTitle("Multithreaded Clock");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
setSize(300, 150);
setLayout(new FlowLayout());
add(hoursLabel);
add(minutesLabel);
add(secondsLabel);
hoursThread.start();
minutesThread.start();
secondsThread.start();
}
@Override
public void run() {
try {
while (true) {
Calendar calendar =
Calendar.getInstance();
int timeValue =
calendar.get(calendarField);
String timeString = new
SimpleDateFormat(format).format(calendar.getTime())
;
if (calendarField ==
Calendar.HOUR_OF_DAY) {
hoursLabel.setText("Hours: " +
timeString);
} else if (calendarField ==
Calendar.MINUTE) {
minutesLabel.setText("Minutes: " +
timeString);
} else if (calendarField ==
Calendar.SECOND) {
secondsLabel.setText("Seconds: " +
timeString);
}
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
System.out.println("Odd Thread:");
for (int i = 0; i < array.length; i += 2) {
System.out.print(array[i] + " ");
try {
Thread.sleep(100); // Sleep for a short
duration for better readability of output
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
System.out.println("\nEven Thread:");
for (int i = 1; i < array.length; i += 2) {
System.out.print(array[i] + " ");
try {
Thread.sleep(100); // Sleep for a short
duration for better readability of output
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} The OddEvenThreadExample class
initializes an array of size 100 with numbers
from 1 to 100.
The OddThread class extends Thread
and is responsible for printing odd-
numbered elements from the array.
The EvenThread class extends Thread
and is responsible for printing even-
numbered elements from the array.
Both threads start simultaneously, and
the output may vary on each run due to
thread scheduling.
try {
// Read the file
FileReader fileReader = new
FileReader(filePath);
BufferedReader bufferedReader = new
BufferedReader(fileReader);
int wordCount = 0;
int lineCount = 0;
// Read each line from the file
String line;
while ((line = bufferedReader.readLine()) !=
null) {
// Count lines
lineCount++;
} catch (IOException e) {
System.err.println("Error reading the file: " +
e.getMessage());
}
} The user is prompted to enter the path of a .txt file.
The program then uses FileReader and BufferedReader
to read the file line by line.
For each line, it increments the line count.
It uses StringTokenizer to count the number of words
in each line and increments the total word count.
Finally, it displays the number of words and lines in the
file.
}
Abstraction:
Efficiency:
Flexibility:
Standardization:
Uniformity:
boolean markSupported():
Writes a string.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public CounterApp() {
setLayout(new FlowLayout());
add(countButton);
add(counterLabel);
countButton.addActionListener(new
ActionListener() {
@Override
counter++;
}
});
setTitle("Counter Application");
setSize(300, 150);
setVisible(true);
addWindowListener(new
java.awt.event.WindowAdapter() {
public void
windowClosing(java.awt.event.WindowEvent
windowEvent) {
System.exit(0);
});
new CounterApp();
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@Override
super.paintComponent(g);
g2d.setColor(Color.BLUE);
};
frame.add(colorFrame);
@Override
super.paintComponent(g);
g2d.setPaint(texturePaint);
}
private TexturePaint createTexturePaint() {
g2d.setColor(Color.YELLOW);
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, 9, 9);
g2d.dispose();
};
frame.add(textureFrame);
@Override
super.paintComponent(g);
g2d.setPaint(gradientPaint);
};
frame.add(gradientFrame);
frame.setSize(300, 120);
frame.setVisible(true);
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
public ThreeFrameExample() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);
@Override
g2d.setColor(Color.BLUE);
};
frame.add(colorFrame);
@Override
super.paintComponent(g);
TexturePaint texturePaint =
createTexturePaint();
g2d.setPaint(texturePaint);
Graphics2D g2d =
textureImage.createGraphics();
g2d.setColor(Color.YELLOW);
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, 9, 9);
g2d.dispose();
};
frame.add(textureFrame);
@Override
super.paintComponent(g);
g2d.setPaint(gradientPaint);
};
frame.add(gradientFrame);
frame.setSize(300, 120);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public ActionListenerExample() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);
clickButton.addActionListener(this);
frame.setSize(300, 200);
frame.setVisible(true);
@Override
JOptionPane.showMessageDialog(frame, "Button
Clicked!");
SwingUtilities.invokeLater(ActionListenerExample::ne
w);
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public CheckBoxExample() {
// Create the frame
frame = new JFrame("CheckBox Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
frame.setLayout(new FlowLayout());
statusLabel.setText(status);
}
}
SwingUtilities.invokeLater(CheckBoxExample::new);
}
} Four checkboxes (checkBox1, checkBox2,
checkBox3, checkBox4) are created using
JCheckBox.
An ActionListener (CheckBoxListener) is
implemented to handle checkbox state changes.
The status label (statusLabel) is updated
based on the state of each checkbox.
The program uses a simple FlowLayout for
arranging components.