chp 4 and 5 java assignment
chp 4 and 5 java assignment
•
2.What are user-defined exceptions? Illustrate them with an example.
User-defined exceptions are custom exceptions that the programmer
creates to handle specific errors in their application. These exceptions
are typically subclasses of Exception or RuntimeException.
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
int byteData;
while ((byteData = fis.read()) != -1) {
fos.write(byteData);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("Error during file copy: " + e.getMessage());
}
}
}
10.Write a java program to delete all the files from the current directory
having extension as .doc also display the count number of doc files
deleted separately.
import java.io.*;
if (files != null) {
for (File file : files) {
if (file.delete()) {
count++;
System.out.println("Deleted: " + file.getName());
}
}
}
System.out.println("Deleted " + count + " .doc files.");
}
}
11.Write a java program which stores the username and password in
two variables.If username and password are not same, then raise
"Invalid password" with appropriate message.
import java.util.Scanner;
if (!username.equals(inputUsername) ||
!password.equals(inputPassword)) {
System.out.println("Invalid password.");
} else {
System.out.println("Login successful.");
}
}
}
12.Write a Java program which displays the contents of file in reverse
order.
import java.io.*;
System.out.println(content);
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}
13.Write a Java program to appends the content of one file to another.
import java.io.*;
} catch (InvalidProductException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}
15.What is the use of finally keyword?
What is the use of the finally keyword?
The finally block is used to execute important code, such as closing
resources or cleaning up, regardless of whether an exception is thrown
or not. It is always executed after the try block, and even if an exception
is caught or thrown, the finally block will execute.
Key points about finally:
• It ensures that the code inside it is executed no matter what.
• It's typically used to release resources, close files, or handle
cleanup operations.
• If there is a return statement in the try or catch block, the finally
block will still be executed before the method returns.
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This will always execute, even if there is an
exception.");
}
}
}
16.List and describe any five methods of InputStream class along with
their syntax.
The InputStream class is the superclass for all byte input streams in
Java. It provides basic methods for reading byte data.
Here are five important methods of InputStream:
1. int read():
o Reads the next byte of data from the input stream.
o Returns the byte read as an integer (0 to 255), or -1 if the
end of the stream is reached.
int byteData = inputStream.read();
int read(byte[] b):
• Reads up to b.length bytes of data into an array b.
• Returns the number of bytes read, or -1 if the end of the stream is
reached.
int bytesRead = inputStream.read(byteArray);
int read(byte[] b, int off, int len):
• Reads up to len bytes of data into a portion of an array b starting
at the off position.
• Returns the number of bytes read, or -1 if the end of the stream is
reached.
int bytesRead = inputStream.read(byteArray, 0, 1024);
long skip(long n):
• Skips over n bytes of data from the input stream.
• Returns the number of bytes actually skipped (this could be less
than n if the end of the stream is reached).
long skippedBytes = inputStream.skip(100);
void close():
• Closes the input stream and releases any system resources
associated with it.
• It is a good practice to close the stream after using it to avoid
memory leaks.
inputStream.close();
import java.io.*;
} catch (IOException e) {
e.printStackTrace();
}
}
}
--------------Chp5-----------------------------------------------------
1.Define AWT and swing.
AWT (Abstract Window Toolkit):
• AWT is a set of application programming interfaces (APIs) used for
creating graphical user interfaces (GUIs) in Java.
• It provides a collection of classes for creating windows, buttons,
text fields, etc.
• AWT components are platform-dependent, meaning they rely on
the underlying operating system's GUI.
Swing:
• Swing is a part of Java's javax.swing package and is an extension
of AWT.
• Swing provides a rich set of GUI components like buttons,
checkboxes, labels, tables, trees, etc., but unlike AWT, Swing
components are lightweight and are platform-independent.
• Swing components do not rely on native OS components for
rendering, making them more consistent across different
platforms.
public MousePositionFrame() {
// Set up frame
setSize(400, 300);
setLayout(null);
10.Explain in brier the event handling mechanism in Java with the help
of suitable example.
Event handling in Java is the process of responding to user actions like
clicks, key presses, mouse movements, etc. It involves the following
steps:
1. Event Source: The object that generates an event (e.g., a button).
2. Event Listener: An object that listens to the event and responds to
it (e.g., ActionListener).
3. Event: The actual event object that holds information about the
action.
import java.awt.*;
import java.awt.event.*;
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " +
selectedFile.getAbsolutePath());
}
}
}
13.Why Swing objects are called as light weight components?
Swing objects are called lightweight components because they are
drawn entirely in Java using a single-threaded painting mechanism.
Unlike AWT components, which rely on native operating system
components (and thus have more overhead), Swing components do not
rely on the OS for rendering, making them lighter. This allows them to
be more flexible and consistent across different platforms
14.State any four methods of WindowListener.
WindowListener is an interface that receives events from a window
(such as opening, closing, minimizing, etc.).
1. windowOpened(WindowEvent we): Invoked when the window is
first opened.
2. windowClosing(WindowEvent we): Invoked when the user
attempts to close the window.
3. windowClosed(WindowEvent we): Invoked when the window has
been closed.
4. windowIconified(WindowEvent we): Invoked when the window is
minimized.
menuBar.add(fileMenu);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
16.What is the use of Checkboxes and RadioButtons? Explain with
suitable example.
Checkboxes allow the user to select multiple options from a set.
Radio buttons allow the user to select only one option from a group
of choices.
import javax.swing.*;
import java.awt.*;
// Checkbox
JCheckBox checkbox = new JCheckBox("I agree to the terms and
conditions");
// RadioButton
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
frame.setLayout(new FlowLayout());
frame.add(checkbox);
frame.add(radioButton1);
frame.add(radioButton2);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
17.Explain layout managers used in AWT.
Layout Managers in AWT help to arrange the components in a container
in a structured manner. Some of the common layout managers are:
1. FlowLayout: Components are placed one after another in a single
line, and they move to the next line if the current line is full.
2. BorderLayout: Divides the container into five regions: North,
South, East, West, and Center.
3. GridLayout: Arranges components in a grid with specified rows
and columns.
4. CardLayout: Allows components to be stacked on top of each
other, showing one at a time.
5. GridBagLayout: Provides a flexible grid system for positioning
components based on their grid position and weights.
18.What are the different types of dialogs in Java? Write any one in
detail.
Dialog boxes in Java can be used to interact with the user and collect
input or display information. Common types of dialogs include:
1. Message Dialog: A simple dialog that displays information.
2. Input Dialog: A dialog where the user can input data.
3. Confirm Dialog: A dialog that asks the user to confirm an action.
4. Custom Dialog: A dialog with customized components.
import javax.swing.*;
button.addActionListener(e -> {
// Use JColorChooser to get a color
Color color = JColorChooser.showDialog(frame, "Choose a Color",
Color.WHITE);
if (color != null) {
frame.getContentPane().setBackground(color); // Set
background color
}
});
frame.setLayout(new FlowLayout());
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
21.Write a program in Java to create a screen which contains three
checkboxes (net, php, java) and displays the selected items in a textbox.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
frame.setLayout(new FlowLayout());
frame.add(netCheckBox);
frame.add(phpCheckBox);
frame.add(javaCheckBox);
frame.add(textField);
frame.setSize(300, 200);
frame.setVisible(true);
}
frame.setLayout(new FlowLayout());
frame.add(netCheckBox);
frame.add(phpCheckBox);
frame.add(javaCheckBox);
frame.add(textField);
frame.setSize(300, 200);
frame.setVisible(true);
}
23.Write a java program which will create a frame if we try to close it.It
should change it's color Red and it display closing message on the
screen (Use swing)
import java.awt.*;
import java.awt.event.*;
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(button);
frame.setSize(400, 200);
frame.setVisible(true);
}
}