JavaHR22 mid.pdf

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

HYDERABAD INSTITUTE OF TECHNOLOGY & MANAGEMENT (AUTONOMOUS)

Gowdavelli, -Medchal Dist. – 501 401

CONTINUOUS INTERNAL EVALUATION MID-I Exam Odd Semester : 2024-25


CSM
Faculty In-Charge : Dr.M.Rajeshwar II Yr. I Sem / Branch
(A&B)
Subject Name :Object oriented programming using Java Time : 1½
Date : -12-2024
Subject Code : Hour

Q. PART-A (2 Mark Question) Bloom’


Marks COs POs
No s Level

Module - I

1 Explain any two methods of File class. 2 2 2 1


1. exists()
 Purpose: Checks whether the file or directory exists.
 Syntax: public boolean exists()
 Returns: true if the file exists, false otherwise.
Example:
File file = new File("example.txt");
System.out.println(file.exists()); // true if file exists

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

RandomAccessFile allows reading and writing to a file at any


position, enabling random (non-sequential) access.

 Constructor: RandomAccessFile(String fileName, String


mode)
o mode: "r" for read, "rw" for read/write.
 Key Methods:
o read(): Reads a byte.
o write(): Writes a byte.
o seek(long pos): Moves the file pointer to the specified
position.

Example:

RandomAccessFile file = new RandomAccessFile("data.txt", "rw");

file.seek(10);

file.write(65); // Writes 'A' at byte 10

3 Give differences between byte stram and character stream 2 2 2 1


4

Module – II

1 Draw the hierarchy of AWT. 2 1 4 1

2 Why is applet technology considered outdated in modern web 2 2 4 1


development?

Applet technology is outdated due to;


1. Security Vulnerabilities
2. Lack of Browser Support
3. Poor Performance
4. Modern Alternatives
5. Deprecation by Oracle
3 Explain any two layouts in java 2 2 4 1

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

The Applet life cycle consists of four main methods:


1. init(): Called when the applet is initialized. Used for one-time
setup like initializing variables or UI components.
2. start(): Invoked when the applet starts or is resumed. Used to
start animations or threads.
3. stop(): Called when the applet is stopped or minimized. Used
to pause threads or animations.
4. destroy(): Invoked when the applet is permanently removed.
Used for cleanup tasks.

5 Create a Frame with “CSMSECOND” as title 2 2 4 1


import java.awt.*;
public class MyFrame {
public static void main(String[] args) {
Frame frame = new Frame("CSMSECOND");
frame.setSize(400, 300);
frame.setVisible(true);
}
}

Module - III

1 Give two differences between ArrayList and Vector 2 2 3 1

2 Draw the hierarchy of Collections 2 1 3 1

3 Compare AWT and Swings 2 2 4 1


4 Using Iterator traverse through a ArrayList 2 2 2 1
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
5 Compare Hashtable vs Hashset 2 2 2 1

Q. PART-B ( 5 Mark Question) Bloom’


Marks COs POs
No s Level

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.*;

class Person implements Serializable {

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

@Override

public String toString() {

return "Person{name='" + name + "', age=" + age + "}";

public class SimpleSerialization {

public static void main(String[] args) {

String file = "person.ser";

Person person = new Person("Alice", 30);

// Serialize

try (ObjectOutputStream out = new ObjectOutputStream(new


FileOutputStream(file))) {

out.writeObject(person);

System.out.println("Serialized: " + person);

} catch (IOException e) {

e.printStackTrace();
}

// Deserialize

try (ObjectInputStream in = new ObjectInputStream(new


FileInputStream(file))) {

Person deserialized = (Person) in.readObject();

System.out.println("Deserialized: " + deserialized);

} catch (IOException | ClassNotFoundException e) {

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.

Purpose of Adapter Classes in Event Handling:


In Java's event-handling model, adapter classes are used to simplify event
handling by providing default (empty) implementations for all the methods
in a listener interface. This is particularly helpful when you only need to
handle a subset of the events defined in a listener interface. Without adapter
classes, you would need to implement all the methods in the interface, even
if some are not used.
Adapter classes are abstract, so you can extend them and override only the
methods relevant to your requirements.

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.

Role of Layout Managers in AWT


In AWT (Abstract Window Toolkit), layout managers are responsible for
determining the size and position of components (such as buttons, labels,
text fields, etc.) inside a container (like a Frame, Panel, etc.). Without layout
managers, you would need to manually position and resize every
component, which can be tedious and error-prone. Layout managers
provide a way to automate the arrangement of components in a container,
making the layout more adaptable to different screen sizes and resolutions.
The layout manager automatically adjusts the placement of components
when the window is resized or when components are added or removed.
This allows for more flexible and responsive UI designs.

5 Develop a Java program that simulates a traffic light. The 5 3 4 1


program lets the user select one of three lights: red, yellow, or
green with radio buttons. On selecting a button, an appropriate
message with “Stop” or “Ready” or “Go” should appear above the
buttons in selected color. Initially, there is no message shown.

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

1 Explain the purpose of ArrayList and LinkedList. Compare their 5 2 3 1


performance for insertion and retrieval operations

Purpose of ArrayList and LinkedList:


ArrayList:
 Purpose:
o An ArrayList is a dynamic array that grows
automatically when elements are added. It provides
fast access to elements using an index.
o It is generally used when you need quick access to
elements by index or when you need a resizable array.
LinkedList:
 Purpose:
o A LinkedList is a doubly-linked list that allows for
more efficient insertion and removal of elements from
anywhere in the list, as it doesn't require shifting
elements like an ArrayList.
o It is ideal when you need frequent insertions and
deletions in the middle of the list.
Performance Comparison:
1. Insertion Operations:
 ArrayList:
o End: O(1) (amortized), resizing takes O(n)
occasionally.
o Middle: O(n), elements after the insertion point must
be shifted.
 LinkedList:
o End: O(1), just update pointers.
o Middle: O(n) to find the position, but insertion itself is
O(1) once the position is found.
2. Retrieval (Access) Operations:
 ArrayList: O(1), direct indexing is fast.
 LinkedList: O(n), needs to traverse the list to access an
element.
Summary:
 ArrayList: Best for fast retrieval and fewer
insertions/deletions.
 LinkedList: Best for frequent insertions and deletions but
slower retrieval.
2 Write a Java program to iterate through a HashSet and display its keys and 5 2 3 1
values using an Iterator.

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);
}
}

You might also like