Java Programming: Exceptions, Threads, and Networking
Java Exceptions: Checked vs Unchecked
Differentiating Exception Types in Java
Exceptions in Java are runtime errors that disrupt the normal flow of a program. They are classified into checked and unchecked exceptions.
Checked Exceptions are verified at compile time. The programmer must either handle them using try-catch blocks or declare them using the throws keyword. These exceptions usually occur due to external factors such as file handling, database access, or network issues. Examples include IOException, SQLException, and FileNotFoundException.
Unchecked Exceptions are checked at runtime and are subclasses of RuntimeException. They generally occur due to programming errors like incorrect logic or improper use of objects. The compiler does not force the programmer to handle them. Examples include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
Key Differences
- Checked exceptions are mandatory to handle; unchecked are optional.
- Checked exceptions are external to the program logic, while unchecked are logical errors.
- Checked exceptions improve reliability; unchecked exceptions improve debugging.
Code Examples
// Checked Exception
FileReader fr = new FileReader("abc.txt"); // Throws FileNotFoundException
// Unchecked Exception
int a = 10 / 0; // Throws ArithmeticExceptionJava File I/O Program Example
Below is a Java program that reads input from the user, writes it to Myfile.txt, and then reads and displays the file content:
import java.io.*;
import java.util.Scanner;
public class FileIOExample {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = sc.nextLine();
FileWriter fw = new FileWriter("Myfile.txt");
fw.write(text);
fw.close();
FileReader fr = new FileReader("Myfile.txt");
BufferedReader br = new BufferedReader(fr);
String line;
System.out.println("File Content:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}This program demonstrates Java’s file handling using FileWriter, FileReader, and proper exception handling.
Life Cycle of a Thread in Java
A thread in Java is a lightweight process that allows concurrent execution of tasks. The thread life cycle defines the various states a thread goes through from creation to termination.
Thread Life Cycle States
- New: A thread is in the new state when it is created using the
Threadclass but not yet started. - Runnable: After calling
start(), the thread enters the runnable state. It is ready to run and waiting for CPU time. - Running: The thread is executing its task. The JVM scheduler decides which thread runs.
- Blocked / Waiting: A thread enters this state when it waits for resources or another thread’s action. Methods like
sleep(),wait(), orjoin()cause this state. - Terminated (Dead): Once the
run()method finishes execution, the thread enters the terminated state.
Common Thread Methods
start()– Starts the thread.run()– Contains thread logic.sleep()– Pauses execution.join()– Waits for another thread.yield()– Pauses execution temporarily.stop()– Stops thread (deprecated).
Understanding Thread Priority
Thread priority determines the importance of a thread to the scheduler. Java provides priority values from 1 to 10:
MIN_PRIORITY(1)NORM_PRIORITY(5)MAX_PRIORITY(10)
Higher priority threads get more CPU time, but priority does not guarantee execution order because it depends on the JVM and OS. Threads improve performance and resource utilization in Java applications.
Java Swing GUI Components Example
Below is a simple Java Swing program that creates a GUI with buttons, a text field, and labels:
import javax.swing.*;
public class SimpleForm {
public static void main(String[] args) {
JFrame frame = new JFrame("Form");
frame.setSize(300, 200);
frame.setLayout(null);
JLabel label = new JLabel("Name:");
label.setBounds(20, 20, 50, 25);
frame.add(label);
JTextField textField = new JTextField();
textField.setBounds(80, 20, 150, 25);
frame.add(textField);
JButton yesBtn = new JButton("Yes");
yesBtn.setBounds(30, 60, 80, 25);
frame.add(yesBtn);
JButton noBtn = new JButton("No");
noBtn.setBounds(130, 60, 80, 25);
frame.add(noBtn);
JButton submitBtn = new JButton("Submit");
submitBtn.setBounds(90, 100, 100, 30);
frame.add(submitBtn);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}This program uses Swing components like JFrame, JButton, JLabel, and JTextField.
TCP/IP Networking in Java
TCP/IP programming enables communication between two computers over a network. Java supports TCP/IP through the java.net package. TCP (Transmission Control Protocol) is connection-oriented and reliable. Java uses sockets to establish communication between a client and a server.
Important Classes in java.net
Socket– Used by the client to connect to the server.ServerSocket– Waits for client requests.InetAddress– Represents an IP address.URL– Represents a web address.URLConnection– Connects to a URL.
Basic Working Mechanism
- Server creates a
ServerSocket. - Client creates a
Socket. - Connection is established.
- Data is exchanged using input/output streams.
- Connection is closed.
TCP/IP programming is widely used in chat applications, file transfer systems, and client-server applications. Java makes networking simple, secure, and platform-independent.
