Advanced Java Programs: Collections, Strings, Swing, Servlets and Cookies

Computer science11.85 KB

Advanced Java Programs

This collection of Java programs demonstrates core and advanced concepts, including collections, string handling, GUI development with Swing, servlets, and cookie management.

1. ArrayList Operations

The following program shows how to add, remove, sort, and convert an ArrayList to an array.

package Advanced_java;
import java.util.ArrayList;
import java.util.Collections;

public class Program1 {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(5);
        arrayList.add(3);
        arrayList.add(8);
        arrayList.add(1);
        System.out.println("ArrayList after adding elements: " + arrayList);
        arrayList.remove(2);
        System.out.println("ArrayList after removing element at index 2: " + arrayList);
        Collections.sort(arrayList);
        System.out.println("ArrayList after sorting: " + arrayList);
        Integer[] array = arrayList.toArray(new Integer[0]);
        System.out.print("Array obtained from ArrayList using toArray(): ");
        for (int i : array) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}

2. Sorting Random Numbers by Tens Place

This program generates random numbers and sorts them using a custom Comparator based on the tens place digit.

package Advanced_java;
import java.util.*;

class TensPlaceComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer num1, Integer num2) {
        int tensPlace1 = (num1 % 100) / 10;
        int tensPlace2 = (num2 % 100) / 10;
        return Integer.compare(tensPlace1, tensPlace2);
    }
}

public class Program2 {
    public static void main(String[] args) {
        int lowerBound = 100;
        int upperBound = 1000;
        ArrayList<Integer> numbers = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int randomNumber;
            do {
                randomNumber = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
            } while (randomNumber % 2 != 0 || randomNumber % 5 != 0);
            numbers.add(randomNumber);
        }
        System.out.println("Random numbers: " + numbers);
        Collections.sort(numbers, new TensPlaceComparator());
        System.out.println("Sorted numbers according to tens place: " + numbers);
    }
}

3. Storing Objects in an ArrayList

This example stores Person objects in an ArrayList and prints their contents.

package Advanced_java;
import java.util.ArrayList;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
    }
}

public class Program3 {
    public static void main(String[] args) {
        ArrayList<Person> personList = new ArrayList<>();
        personList.add(new Person("Alice", 30));
        personList.add(new Person("Bob", 25));
        personList.add(new Person("Charlie", 40));
        System.out.println("Contents of the ArrayList:");
        for (Person person : personList) {
            System.out.println(person);
        }
    }
}

4. String Constructors

This program demonstrates the different ways to construct a String object in Java.

package Advanced_java;

public class Program4 {
    public static void main(String[] args) {
        String str1 = "Hello, World!";
        System.out.println("Constructor 1: Using a string literal: " + str1);
        char[] charArray = {'H', 'e', 'l', 'l', 'o'};
        String str2 = new String(charArray);
        System.out.println("Constructor 2: Using a character array: " + str2);
        String str3 = new String(charArray, 2, 3);
        System.out.println("Constructor 3: Using a portion of a character array: " + str3);
        byte[] byteArray = {72, 101, 108, 108, 111};
        String str4 = new String(byteArray);
        System.out.println("Constructor 4: Using bytes and specifying character encoding: " + str4);
        String str5 = new String(byteArray, 2, 3);
        System.out.println("Constructor 5: Using bytes, specifying character encoding, and specifying range: " + str5);
        String str6 = new String(str1);
        System.out.println("Constructor 6: Using another String object: " + str6);
    }
}

5. Common String Methods

This program uses frequently used String methods such as charAt(), substring(), equals(), replace(), and toUpperCase().

package Advanced_java;

public class Program5 {
    public static void main(String[] args) {
        String str = "Hello, World!";
        char firstChar = str.charAt(0);
        char lastChar = str.charAt(str.length() - 1);
        String substring = str.substring(7);
        String anotherStr = "hello, world!";
        boolean isEqual = str.equals(anotherStr);
        boolean isEqualIgnoreCase = str.equalsIgnoreCase(anotherStr);
        boolean containsHello = str.contains("Hello");
        int indexOfComma = str.indexOf(',');
        String replacedStr = str.replace("World", "Universe");
        String upperCaseStr = str.toUpperCase();
        String lowerCaseStr = str.toLowerCase();
        System.out.println("First Character: " + firstChar);
        System.out.println("Last Character: " + lastChar);
        System.out.println("Substring: " + substring);
        System.out.println("Is equal?: " + isEqual);
        System.out.println("Is equal (ignore case)?: " + isEqualIgnoreCase);
        System.out.println("Contains 'Hello'?: " + containsHello);
        System.out.println("Index of comma: " + indexOfComma);
        System.out.println("Replaced String: " + replacedStr);
        System.out.println("Upper Case: " + upperCaseStr);
        System.out.println("Lower Case: " + lowerCaseStr);
    }
}

6. Working with StringBuffer

This example shows how to append, insert, delete, reverse, and replace content in a StringBuffer.

package Advanced_java;

public class Program6 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.append(" World");
        System.out.println("After appending: " + sb);
        sb.insert(5, " Java");
        System.out.println("After inserting: " + sb);
        sb.delete(5, 10);
        System.out.println("After deleting: " + sb);
        sb.reverse();
        System.out.println("After reversing: " + sb);
        sb.replace(6, 11, "Program");
        System.out.println("After replacing: " + sb);
        System.out.println("Capacity of StringBuffer: " + sb.capacity());
        System.out.println("Length of StringBuffer: " + sb.length());
        sb.ensureCapacity(50);
        System.out.println("Capacity after ensureCapacity(50): " + sb.capacity());
    }
}

7. Swing Button Demo

This Swing application displays two buttons, each showing a message dialog when clicked.

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

public class ButtonDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Button Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton alphaButton = new JButton("Alpha");
        JButton betaButton = new JButton("Beta");
        alphaButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Alpha pressed");
            }
        });
        betaButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Beta pressed");
            }
        });
        JPanel contentPane = new JPanel();
        contentPane.add(alphaButton);
        contentPane.add(betaButton);
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setVisible(true);
    }
}

8. Greeting Servlet

This servlet reads a username parameter and returns a greeting page.

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/GreetingServlet")
public class GreetingServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        String username = request.getParameter("username");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>Greeting Servlet</title></head><body>");
        out.println("<h1>Hello " + username + "</h1>");
        out.println("<p>How are you?</p>");
        out.println("</body></html>");
        out.close();
    }
}

9. Student Details Servlet

This servlet receives student information from a form and displays it in the browser.

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/StudentDetailsServlet")
public class StudentDetailsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        String name = request.getParameter("name");
        String usn = request.getParameter("usn");
        String totalMarksStr = request.getParameter("totalMarks");
        int totalMarks = 0;
        try {
            totalMarks = Integer.parseInt(totalMarksStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>Student Details</title></head><body>");
        out.println("<h1>Student Details</h1>");
        out.println("<p>Name: " + name + "</p>");
        out.println("<p>USN: " + usn + "</p>");
        out.println("<p>Total Marks: " + totalMarks + "</p>");
        out.println("</body></html>");
        out.close();
    }
}

10. Cookie Management Example

This program creates an HttpCookie, stores it in a CookieStore, and retrieves its value.

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;

public class CookieExample {
    public static void main(String[] args) {
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
        HttpCookie cookie = new HttpCookie("EMPID", "AN2356");
        CookieStore cookieStore = cookieManager.getCookieStore();
        cookieStore.add(null, cookie);
        String empId = null;
        for (HttpCookie storedCookie : cookieStore.getCookies()) {
            if (storedCookie.getName().equals("EMPID")) {
                empId = storedCookie.getValue();
                break;
            }
        }
        if (empId != null) {
            System.out.println("Value of EMPID cookie: " + empId);
        } else {
            System.out.println("EMPID cookie not found");
        }
    }
}

Download

PDF Word HTML