Practical Java Code Examples: JDBC, Threads, Servlets, Sockets

Java Programming Examples Collection

This document presents a collection of practical Java programming examples, covering database interactions with MySQL using JDBC, multithreading concepts, Swing UI development, and basic web application development with Servlets, along with a simple network client.

JDBC Database Operations

These examples demonstrate how to connect to a MySQL database and perform common operations like counting records, creating tables, and retrieving data.

Count Records in MySQL Table

This Java program connects to a MySQL database and counts the total number of records in a specified table (e.g., Employee).

package practical;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class RecordCount {
    public static void main(String[] args) {
        // Database connection details
        String url = "jdbc:mysql://localhost:3306/Assignment"; // Replace with your database name
        String user = "root";  // Replace with your MySQL username
        String password = "Pass@word";  // Replace with your MySQL password

        // SQL query to count records in the table
        String query = "SELECT COUNT(*) FROM Employee"; // Replace 'Student' with your table name

        try {
            // Load JDBC Driver (optional for newer Java versions)
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish connection
            Connection conn = DriverManager.getConnection(url, user, password);
            System.out.println("Connected to database!");

            // Create a statement
            Statement stmt = conn.createStatement();

            // Execute the query
            ResultSet rs = stmt.executeQuery(query);

            // Get and print the count
            if (rs.next()) {
                int count = rs.getInt(1);
                System.out.println("Total records in table: " + count);
            }

            // Close resources
            rs.close();
            stmt.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            System.out.println("JDBC Driver not found!");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Database error!");
            e.printStackTrace();
        }
    }
}

Create Student Table in MySQL

This example illustrates how to create a new table named Student in a MySQL database using JDBC.

package practical;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Student {
    public static void main(String[] args) {
        // Database connection details
        String url = "jdbc:mysql://localhost:3306/Assignment"; // Replace 'MyDatabase' with your database name
        String user = "root";  // Replace with your MySQL username
        String password = "Pass@word";  // Replace with your MySQL password

        // SQL query to create Student table
        String createTableQuery = "CREATE TABLE  Student (" +
                "roll_no INT PRIMARY KEY, " +
                "sname VARCHAR(100) NOT NULL, " +
                "percentage DECIMAL(5,2) NOT NULL)";

        try {
            // 1. Load MySQL JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. Establish Connection
            Connection con = DriverManager.getConnection(url, user, password);

            // 3. Create Statement
            Statement stmt = con.createStatement();

            // 4. Execute Query to Create Table
            stmt.executeUpdate(createTableQuery);
            System.out.println("Student table created successfully!");

            // 5. Close Connection
            stmt.close();
            con.close();
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found!");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Error while creating table!");
            e.printStackTrace();
        }
    }
}

Display Employee Names from MySQL

This program retrieves and displays all employee names from an existing Employee table in a MySQL database.

//Write a Java program to display all the EName from the Employee table. Assume Employee (ENo,
//EName, Salary) table is already created.

package practical;
import java.sql.*;

public class Employee {
    public static void main(String[] args) {
        try {
            // Step 1: Load the MySQL JDBC driver (Optional for modern versions)
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Step 2: Connect to the database
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Assignment", "root", "Pass@word");

            // Step 3: Execute query
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT EName FROM Employee");

            // Step 4: Display results
            while (rs.next()) {
                System.out.println(rs.getString("EName"));
            }

            // Step 5: Close connections
            rs.close();
            stmt.close();
            con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Basic MySQL Database Connection Test

A simple Java program to establish and test a connection to a MySQL database.

package practical;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
    public static void main(String[] args) {
        // Database credentials
        String url = "jdbc:mysql://localhost:3306/Assignment"; 
        String user = "root";  
        String password = "Pass@word";  

        try {
            // Step 1: Load JDBC Driver (Optional for newer Java versions)
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Step 2: Establish connection
            Connection conn = DriverManager.getConnection(url, user, password);
            System.out.println("Database Connected Successfully!");

            // Step 3: Close connection
            conn.close();
        } catch (ClassNotFoundException e) {
            
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Database connection error!");
            e.printStackTrace();
        }
    }
}

Java Multithreading Examples

Explore various multithreading scenarios in Java, including concurrent execution, thread delays, and UI updates.

Display Vowels with Delay

This multithreaded program identifies and prints vowels from a given string, introducing a delay between each vowel displayed.

package practical;

class VowelThread extends Thread {
    private String str;
    
    public VowelThread(String str) {
        this.str = str;
    }
    
    @Override
    public void run() {
        for (char ch : str.toCharArray()) {
            if ("AEIOUaeiou".indexOf(ch) != -1) { // Check if the character is a vowel
                try {
                    Thread.sleep(3000); // 3-second delay
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(ch);
            }
        }
    }
}

public class Vowels {
    public static void main(String[] args) {
        String input = "Multithreading Example";
        VowelThread thread = new VowelThread(input);
        thread.start();
    }
}

Print Alphabet in Reverse Order

A Java multithreading example that prints the English alphabet in reverse order (Z to A) with a pause between characters.

package practical;

class ReverseAlphabetThread extends Thread {
    public void run() {
        try {
            Thread.sleep(5000); // Wait for 5 seconds before printing
            for (char ch = 'Z'; ch >= 'A'; ch--) {
                System.out.print(ch + " ");
                Thread.sleep(300); // Add a delay for better readability
            }
        } catch (InterruptedException e) {
            System.out.println("Thread interrupted!");
        }
    }
}

public class ReverseAlphabet {
    public static void main(String[] args) {
        ReverseAlphabetThread thread = new ReverseAlphabetThread();
        thread.start(); // Start the thread
    }
}

Concurrent Odd Numbers and Reverse Alphabet

This program demonstrates two threads running concurrently: one printing odd numbers up to a limit, and another printing the alphabet in reverse.

package practical;

class OddNumberThread extends Thread {
    private int n;

    public OddNumberThread(int n) {
        this.n = n;
    }

    @Override
    public void run() {
        for (int i = 1; i <= n; i += 2) {
            System.out.println("Odd: " + i);
            try {
                Thread.sleep(500); // 0.5-second delay
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class AlphabetThread extends Thread {
    @Override
    public void run() {
        for (char ch = 'Z'; ch >= 'A'; ch--) {
            System.out.println("Alphabet: " + ch);
            try {
                Thread.sleep(500); // 0.5-second delay
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class OddNumberAndAlphabet {
    public static void main(String[] args) {
        int n = 20; // Example limit for odd numbers
        
        OddNumberThread oddThread = new OddNumberThread(n);
        AlphabetThread alphabetThread = new AlphabetThread();
        
        oddThread.start();
        alphabetThread.start();
    }
}

Swing UI Counter with Multithreading

A Java Swing application that uses multithreading to continuously display numbers from 1 to 100 in a text field upon button click.

package practical;

import javax.swing.*;
import java.awt.*;

public class NumberCounterApp extends JFrame {
    private JTextField textField;
    private JButton startButton;

    public NumberCounterApp() {
        setTitle("Counter");
        setSize(250, 120);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        textField = new JTextField(10);
        textField.setEditable(false);
        add(textField);

        startButton = new JButton("Start");
        add(startButton);

        startButton.addActionListener(e -> new Thread(() -> {
            for (int i = 1; i <= 100; i++) {
                textField.setText(String.valueOf(i));
                try { Thread.sleep(100); } catch (InterruptedException ex) {}
            }
        }).start());
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new NumberCounterApp().setVisible(true));
    }
}

Console Bouncing Ball Animation

This example creates a simple console-based animation of a bouncing ball using Java threads. Note: Console clearing behavior may vary by terminal.

package practical;

class Ball extends Thread {
    private int position = 0;   // Ball starts at the top
    private int direction = 1; // 1 for down, -1 for up

    public void run() {
        while (true) {
            System.out.println("\n".repeat(position) + "   O"); // Print ball at position

            // Change position
            position += direction;

            // Reverse direction at boundaries
            if (position == 10 || position == 0) {
                direction *= -1;
            }

            try {
                Thread.sleep(300); // Delay for animation
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clearScreen(); // Clear console
        }
    }

    private void clearScreen() {

        System.out.flush();
    }
}

public class BouncingBall {
    public static void main(String[] args) {
        Ball ball = new Ball();
        ball.start(); // Start the bouncing ball thread
    }
}

Java Servlet Web Applications

Understand the fundamentals of Java Servlets for building web applications.

Servlet Lifecycle Demonstration

This servlet demonstrates the key lifecycle methods: init(), service(), and destroy().

package servlet;

import java.io.IOException;

import jakarta.servlet.Servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServlet;

public class ServletLifecycle implements Servlet{

 @Override
 public void destroy() {
  // TODO Auto-generated method stub
  System.out.println("destroy method is called");
  
 }

 @Override
 public void init(ServletConfig arg0) throws ServletException {
  // TODO Auto-generated method stub
  System.out.println("init method is called");
  
 }

 @Override
 public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
  // TODO Auto-generated method stub
  System.out.println("service method is called");
  
 }
 @Override
 public ServletConfig getServletConfig() {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public String getServletInfo() {
  // TODO Auto-generated method stub
  return null;
 }

}

Simple Hello World Servlet

A basic Java Servlet that outputs “Hello World” to the web browser.

package servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Servlet implementation class HelloMessage
 */
public class HelloMessage extends HttpServlet {
 private static final long serialVersionUID = 1L;
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloMessage() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  response.getWriter().append("Served at: ").append(request.getContextPath());
  response.setContentType("text/html"); // Set response type
        PrintWriter out = response.getWriter(); // Get response writer
        out.println("<h1>Hello World</h1>"); // Print message
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  doGet(request, response);
 }

}

Java Networking Example

A fundamental example of network programming in Java.

Basic Chat Client Implementation

This program provides a simple command-line chat client that connects to a server (assumed to be running on localhost:7777) and allows sending and receiving messages.

package practical;

import java.io.*;
import java.net.*;

public class ChatClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 7777);
        System.out.println("Connected to server!");

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            if (in.ready()) System.out.println("Server: " + in.readLine());
            if (console.ready()) out.println(console.readLine());
        }
    }
}