Java IO Overview
Input/Output: exploring Java.io Explain
In Java, the `java.io` package is part of the standard library that provides input and output (I/O)
functionality, allowing programs to read data from sources (input) and write data to destinations
(output). These sources and destinations can be files, memory, keyboards, consoles, or network
connections.
🔹 Overview of `java.io`
The `java.io` package contains classes and interfaces for:
Reading and writing data (text or binary)
File manipulation
Serialization
Buffered streams for performance
🔹 Key Concepts
1. Streams
Streams represent sequences of data. Java uses streams to perform input and output:
InputStream / Reader – For reading data (input)
OutputStream / Writer – For writing data (output)
There are two types of streams:
Type Description Example Classes
Byte Streams For binary data (8-bit) `InputStream`, `OutputStream`
Character Streams For text data (16-bit Unicode) `Reader`, `Writer`
🔹 Important Classes in `java.io`
✅ File Class
Used to represent file and directory paths.
java
File file = new File("data.txt");
System.out.println(file.exists());
✅ FileInputStream / FileOutputStream
For reading and writing binary data from/to files.
java
FileInputStream fis = new FileInputStream("input.txt");
int i;
while ((i = fis.read()) != -1) {
System.out.print((char)i);
}
fis.close();
✅ FileReader / FileWriter
Simplifies reading and writing character files.
java
FileWriter fw = new FileWriter("output.txt");
fw.write("Hello Java I/O!");
fw.close();
✅ BufferedReader / BufferedWriter
Buffers input/output for efficiency (reads/writes large chunks at a time).
java
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
✅ PrintWriter
Easier way to write formatted data.
java
PrintWriter pw = new PrintWriter("output.txt");
pw.println("Hello, Java!");
pw.close();
✅ ObjectInputStream / ObjectOutputStream
Used for object serialization (reading/writing entire objects).
java
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.dat"));
oos.writeObject(new Student("Alex", 20));
oos.close();
🔹 Common I/O Operations
Task Class Used
Reading a file `FileReader`, `BufferedReader`
Writing to a file `FileWriter`, `BufferedWriter`, `PrintWriter`
Reading binary data `FileInputStream`
Writing binary data `FileOutputStream`
Working with files `File`
Object serialization `ObjectOutputStream` / `ObjectInputStream`
🔹 Exception Handling
Most I/O classes throw checked exceptions, especially `IOException`. You must handle them using
`try-catch` or declare them with `throws`.
java
try {
FileReader fr = new FileReader("input.txt");
} catch (IOException e) {
e.printStackTrace();
}
🔹 Summary Diagram
mathematica
Input Output
------------------- ---------------------
InputStream (bytes) OutputStream (bytes)
| |
FileInputStream FileOutputStream
BufferedInputStream BufferedOutputStream
Reader (characters) Writer (characters)
| |
FileReader FileWriter
BufferedReader BufferedWriter
If you want, I can also give you short practice questions or coding examples for any specific class like
`BufferedReader` or `FileWriter`.
Java Applet Explain
🌐 Java Applet – Explained Simply
A Java Applet is a special kind of Java program that runs in a web browser or applet viewer and is
embedded into a web page using HTML. It was widely used for creating interactive web content, but
it is now outdated and not supported by most modern browsers.
🔹 Key Characteristics of Java Applets
Runs inside a browser or applet viewer
Extends the class `java.applet.Applet` (or `javax.swing.JApplet` for Swing-based GUI)
No `main()` method (unlike regular Java programs)
Lifecycle methods control its behavior
Uses AWT (Abstract Window Toolkit) or Swing for GUI
🔹 Basic Applet Lifecycle
Java applets follow a specific lifecycle controlled by the browser or applet viewer. The main methods are:
Method Purpose
`init()` Called once when the applet is first loaded
`start()` Called every time the applet becomes active (e.g., user visits page)
`paint(Graphics g)` Called to draw the applet’s content on the screen
`stop()` Called when the applet is no longer active (e.g., user leaves page)
`destroy()` Called when the applet is being removed from memory
🔹 Sample Java Applet Code
➤ Java Code (AppletDemo.java)
java
import java.applet.Applet;
import java.awt.Graphics;
public class AppletDemo extends Applet {
public void paint(Graphics g) {
g.drawString("Hello from Java Applet!", 20, 20);
}
}
➤ HTML to Embed the Applet
html
<html>
<body>
<applet code="AppletDemo.class" width="300" height="100">
Your browser does not support applets.
</applet>
</body>
</html>
➤ How to Run:
1. Compile the Java file:
nginx
javac AppletDemo.java
2. Run using the applet viewer:
nginx
appletviewer filename.html
Note: Modern browsers have dropped support for Java Applets, so applet code will not run
directly in them anymore.
🔹 Key Classes and Packages
`java.applet.Applet` – Base class for applets (AWT-based)
`javax.swing.JApplet` – Swing-based applet class (for enhanced GUI)
`java.awt.Graphics` – Used for drawing in the applet window
`java.awt.*` – For GUI components like buttons, labels, etc.
🔹 Pros and Cons
Pros (Historical) Cons (Now)
Easy GUI in web pages Deprecated and unsupported in browsers
Lightweight and fast Requires Java Plugin (not supported today)
Interactive web applications Security and compatibility issues
🔹 Current Status
Java Applets are obsolete.
Use Java Web Start (also deprecated) or modern technologies like:
JavaFX (for desktop apps)
JavaScript + HTML5 (for web apps)
Spring Boot, JSP, or other frameworks for server-side Java
🔹 Summary
Feature Details
Runs in Browser / Applet viewer
Base class `Applet` or `JApplet`
GUI components AWT / Swing
Lifecycle methods `init()`, `start()`, `paint()`, `stop()`, `destroy()`
Status Deprecated
If you want, I can help you write a simple GUI-based applet with buttons or text fields for better
understanding.
Java Swing: Creating a Swing Applet and Application, Programming using Panes, Pluggable Look
and feel. Labels. Text fields, Buttons, Toggle buttons, Checkboxes, Radio Buttons, View ports, Scroll
Panes, Scroll Bars, Lists, Combo box, Progress Bar, Menus and Toolbars, Layered Panes, Tabbed
Panes, Split Panes, Layouts, Windows, Dialog Boxes. Explain with code
Here's a comprehensive explanation of Java Swing covering how to create Swing Applets and
Applications, use common GUI components, manage layouts, apply pluggable look and feel, and
more — with simple code examples for each.
🧩 1. What is Java Swing?
Swing is a part of `javax.swing` package used to build Graphical User Interfaces (GUIs) in Java. It is
built on top of AWT and provides rich, platform-independent components.
🖥️ 2. Creating a Swing Application
java
import javax.swing.*;
public class SwingApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Application");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello Swing!", SwingConstants.CENTER);
frame.add(label);
frame.setVisible(true);
}
}
🧪 3. Creating a Swing Applet
Note: Applets are deprecated. But for legacy learning:
java
import javax.swing.*;
import java.awt.*;
public class SwingApplet extends JApplet {
public void init() {
JLabel label = new JLabel("Swing Applet Example", SwingConstants.CENTER);
add(label);
}
}
🪟 4. GUI Components with Examples
✅ Labels, Text Fields, and Buttons
java
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField(15);
JButton submitButton = new JButton("Submit");
✅ Toggle Buttons, Checkboxes, and Radio Buttons
java
JToggleButton toggle = new JToggleButton("Toggle Me");
JCheckBox checkBox = new JCheckBox("I agree");
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(male);
genderGroup.add(female);
✅ List and Combo Box
java
String[] countries = {"India", "USA", "UK"};
JList<String> countryList = new JList<>(countries);
JComboBox<String> countryBox = new JComboBox<>(countries);
✅ Progress Bar
java
JProgressBar progressBar = new JProgressBar();
progressBar.setValue(50); // 50%
progressBar.setStringPainted(true);
✅ Scroll Panes and Scroll Bars
java
JTextArea area = new JTextArea(5, 20);
JScrollPane scrollPane = new JScrollPane(area);
🎨 5. Panes and Containers
✅ Viewports and Scroll Panes
java
JViewport viewport = new JViewport();
viewport.setView(new JLabel("Viewport Content"));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(viewport);
✅ Layered Pane
java
JLayeredPane layeredPane = new JLayeredPane();
JLabel background = new JLabel("Background");
JLabel foreground = new JLabel("Foreground");
layeredPane.add(background, JLayeredPane.DEFAULT_LAYER);
layeredPane.add(foreground, JLayeredPane.PALETTE_LAYER);
✅ Tabbed Pane
java
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new JLabel("Tab 1 Content"));
tabbedPane.addTab("Tab 2", new JLabel("Tab 2 Content"));
✅ Split Pane
java
JTextArea left = new JTextArea("Left");
JTextArea right = new JTextArea("Right");
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
🧰 6. Menus and Toolbars
✅ Menu Bar
java
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem open = new JMenuItem("Open");
file.add(open);
menuBar.add(file);
frame.setJMenuBar(menuBar);
✅ Toolbar
java
JToolBar toolBar = new JToolBar();
toolBar.add(new JButton("Tool 1"));
toolBar.add(new JButton("Tool 2"));
🧱 7. Layout Managers
Layout Purpose
`FlowLayout` Default for JPanel, adds left to right
`BorderLayout` Top, bottom, left, right, center
`GridLayout` Grid of rows and columns
`BoxLayout` Vertical or horizontal layout
java
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("Center"), BorderLayout.CENTER);
🪟 8. Windows and Dialog Boxes
✅ Dialog Box
java
JOptionPane.showMessageDialog(null, "This is a message dialog.");
✅ Input Dialog
java
String name = JOptionPane.showInputDialog("Enter your name:");
✅ Confirm Dialog
java
int result = JOptionPane.showConfirmDialog(null, "Do you agree?");
🎨 9. Pluggable Look and Feel
Swing allows you to change the appearance of your app:
java
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// or "javax.swing.plaf.metal.MetalLookAndFeel"
} catch (Exception e) {
e.printStackTrace();
}
🔚 Summary Table
Component Class Name
Label `JLabel`
Text Field `JTextField`
Button `JButton`
Toggle Button `JToggleButton`
Checkbox `JCheckBox`
Radio Button `JRadioButton`
List `JList`
Combo Box `JComboBox`
Progress Bar `JProgressBar`
Menu `JMenuBar`, `JMenu`, `JMenuItem`
Toolbar `JToolBar`
Tabbed Pane `JTabbedPane`
Split Pane `JSplitPane`
Dialog `JOptionPane`
Layouts `FlowLayout`, `GridLayout`, `BorderLayout`, `BoxLayout`
Let me know if you want a complete project example combining several components in one app.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/1