JavaHR22 mid.pdf
JavaHR22 mid.pdf
JavaHR22 mid.pdf
Module - I
2. delete()
Purpose: Deletes the file or directory.
Syntax: public boolean delete()
Returns: true if the file is deleted successfully, false if not.
Example:
File file = new File("example.txt");
System.out.println(file.delete()); // true if file is deleted
2 Explain RandomAccessFile. 2 2 2 1
Example:
file.seek(10);
Module – II
FlowLayout
Arranges components in a row, wrapping to the next line
when needed.
Default layout for JPanel.
BorderLayout
Divides the container into five regions: NORTH, SOUTH,
EAST, WEST, and CENTER.
Default layout for JFrame.
4 Explain Applet life cycle 2 2 4 1
Module - III
Module – I
1 Write a Java program to copy the contents of one file to another using 5 3 2 1
FileInputStream and FileOutputStream.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
String sourceFile = "source.txt";
String destFile = "destination.txt";
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, bytesRead, bytesRead);
}
System.out.println("File copied successfully!");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
2 Write a Java program to serialize and deserialize an object containing 5 3 2 1
attributes name and age..
import java.io.*;
this.name = name;
this.age = age;
@Override
// Serialize
out.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
// Deserialize
e.printStackTrace();
}
3 Design a program to merge the contents of two text files into a third file 5 3 2 1
import java.io.*;
public class FileMerge {
public static void main(String[] args) {
String file1 = "file1.txt";
String file2 = "file2.txt";
String outputFile = "mergedFile.txt";
try (BufferedReader br1 = new BufferedReader(new
FileReader(file1));
BufferedReader br2 = new BufferedReader(new
FileReader(file2));
BufferedWriter bw = new BufferedWriter(new
FileWriter(outputFile)))
{
// Write contents of the first file
String line;
while ((line = br1.readLine()) != null)
{
bw.write(line);
bw.newLine();
}
// Write contents of the second file
while ((line = br2.readLine()) != null)
{
bw.write(line);
bw.newLine();
}
System.out.println("Files merged successfully into " +
outputFile);
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
4
Module – II
1 Write the HTML code and the corresponding Java code for an applet 5 3 4 1
that accepts two numbers as parameters and displays their sum.
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>Applet Sum</title>
</head>
<body>
<applet code="SumApplet.class" width="300" height="150">
<param name="number1" value="10">
<param name="number2" value="20">
</applet>
</body>
</html>
JAVA CODE:
import java.applet.Applet;
import java.awt.Graphics;
public class SumApplet extends Applet {
private int number1;
private int number2;
private int sum;
@Override
public void init() {
// Get the parameters from the HTML
String num1 = getParameter("number1");
String num2 = getParameter("number2");
// Convert to integers
try {
number1 = Integer.parseInt(num1);
number2 = Integer.parseInt(num2);
sum = number1 + number2;
} catch (NumberFormatException e) {
sum = 0; // Default to 0 if parsing fails
}
}
@Override
public void paint(Graphics g) {
g.drawString("Number 1: " + number1, 20, 40);
g.drawString("Number 2: " + number2, 20, 60);
g.drawString("Sum: " + sum, 20, 80);
}
}
2 Analyze the purpose of adapter classes in event handling. Provide an 5 3 4 1
example where they simplify event handling.
EXAMPLE:
import java.awt.*;
import java.awt.event.*;
public class WithAdapterExample extends Frame {
public WithAdapterExample() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked");
}
});
setSize(400, 300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new WithAdapterExample();
}
}
Key Benefits of Adapter Classes
1. Simplifies Code: Reduces boilerplate by allowing you to override
only the required methods.
2. Improves Readability: The code focuses on relevant event-handling
logic, making it easier to understand.
3. Flexible Usage: Adapters can be used as anonymous classes or
extended for reuse.
3 Develop a Java program to demonstrate Mouse Listener, Mouse Motion 5 2 4 1
Listener
import java.awt.*;
import java.awt.event.*;
public class MouseListenerAndMotionListenerExample extends
Frame implements MouseListener, MouseMotionListener {
// Constructor to set up the frame
public MouseListenerAndMotionListenerExample() {
// Add mouse listeners to the frame
addMouseListener(this);
addMouseMotionListener(this);
setSize(400, 300);
setLayout(null);
setTitle("Mouse Listener and Motion Listener Demo");
setVisible(true);
}
// MouseListener methods
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked at: (" + e.getX() + ", " + e.getY()
+ ")");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Mouse Pressed at: (" + e.getX() + ", " + e.getY()
+ ")");
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse Released at: (" + e.getX() + ", " +
e.getY() + ")");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse Entered the frame.");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("Mouse Exited the frame.");
}
// MouseMotionListener methods
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged at: (" + e.getX() + ", " +
e.getY() + ")");
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved to: (" + e.getX() + ", " + e.getY()
+ ")");
}
// Main method to run the application
public static void main(String[] args) {
new MouseListenerAndMotionListenerExample();
}
}
4 Describe the role of layout managers in AWT and explain the differences 5 2 4 1
between FlowLayout, BorderLayout, and GridLayout.
import java.awt.*;
import java.awt.event.*;
public class TrafficLights extends Frame {
Label label;
CheckboxGroup group;
Checkbox green, orange, red;
public TrafficLights() {
setTitle("Traffic Lights");
setSize(500, 500);
setLayout(null);
setVisible(true);
// Create and position the label
label = new Label();
label.setBounds(10, 50, 150, 30);
add(label);
// Create Checkbox group and checkboxes
group = new CheckboxGroup();
green = new Checkbox("Green", group, false);
green.setBounds(10, 100, 100, 30);
orange = new Checkbox("Orange", group, false);
orange.setBounds(10, 140, 100, 30);
red = new Checkbox("Red", group, false);
red.setBounds(10, 180, 100, 30);
// Add checkboxes to the frame
add(green);
add(orange);
add(red);
// Set item listeners for each checkbox
green.addItemListener(e -> {
label.setText("Go");
label.setForeground(Color.GREEN);
});
orange.addItemListener(e -> {
label.setText("Ready");
label.setForeground(Color.ORANGE);
});
red.addItemListener(e -> {
label.setText("Stop");
label.setForeground(Color.RED);
});
// Window closing listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new TrafficLights();
}
}
Module - III
import java.util.*;
public class HashMapIteratorExample {
public static void main(String[] args) {
// Create a HashMap with some key-value pairs
HashMap<String, String> map = new HashMap<>();
map.put("Key1", "Value1");
map.put("Key2", "Value2");
map.put("Key3", "Value3");
// Get an iterator for the entry set of the HashMap
Iterator<Map.Entry<String, String>> iterator =
map.entrySet().iterator();
// Iterate through the HashMap and display keys and values
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " +
entry.getValue());
}
}
}
3 Develop a Java program that reads a list of integers, stores them in a 5 2 4 1
PriorityQueue, and displays them in ascending order.
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Create a PriorityQueue (min-heap by default)
PriorityQueue<Integer> pq = new PriorityQueue<>();
// Read integers from the user
System.out.println("Enter integers (type 'done' to finish):");
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
pq.add(num); // Add the integer to the PriorityQueue
}
// Display integers in ascending order
System.out.println("\nIntegers in ascending order:");
while (!pq.isEmpty()) {
System.out.println(pq.poll()); // Retrieve and remove the
smallest element
}
scanner.close();
}
}
4 Write a Swing program to create a login form with a JTextField for 5 3 4 1
username and a JPasswordField for password, and a JButton for login
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginForm extends JFrame {
public LoginForm() {
setTitle("Login Form");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Components
JTextField usernameField = new JTextField(20);
JPasswordField passwordField = new JPasswordField(20);
JButton loginButton = new JButton("Login");
// Add components
add(new JLabel("Username:"));
add(usernameField);
add(new JLabel("Password:"));
add(passwordField);
add(loginButton);
// Login button action
loginButton.addActionListener(e -> {
String username = usernameField.getText();
char[] password = passwordField.getPassword();
if ("admin".equals(username) && "1234".equals(new
String(password))) {
JOptionPane.showMessageDialog(null, "Login Successful!");
} else {
JOptionPane.showMessageDialog(null, "Invalid username or
password.");
}
});
setVisible(true);
}
public static void main(String[] args) {
new LoginForm();
}
}
5 Write a program to tokenize a string using StringTokenizer and store 5 3 3 1
each token in a HashSet
import java.util.*;
public class TokenizeString {
public static void main(String[] args) {
// Input string to be tokenized
String input = "Java is a programming language and Java is popular";
// Create a StringTokenizer to split the string by space
StringTokenizer tokenizer = new StringTokenizer(input);
// Create a HashSet to store unique tokens
HashSet<String> tokenSet = new HashSet<>();
// Tokenize the string and add each token to the HashSet
while (tokenizer.hasMoreTokens()) {
tokenSet.add(tokenizer.nextToken());
}
// Display the unique tokens
System.out.println("Unique tokens: " + tokenSet);
}
}