0% found this document useful (0 votes)
11 views27 pages

Advanced Java Manual

The document contains multiple Java programs demonstrating various concepts such as ArrayList manipulation, sorting, user-defined classes, string methods, Swing event handling, servlet usage, cookie handling, JDBC operations, and JSP for login validation. Each program includes code snippets and expected outputs, showcasing practical applications of Java in different scenarios. The document serves as a comprehensive guide for implementing fundamental Java programming techniques and web application development.

Uploaded by

sssecsis25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views27 pages

Advanced Java Manual

The document contains multiple Java programs demonstrating various concepts such as ArrayList manipulation, sorting, user-defined classes, string methods, Swing event handling, servlet usage, cookie handling, JDBC operations, and JSP for login validation. Each program includes code snippets and expected outputs, showcasing practical applications of Java in different scenarios. The document serves as a comprehensive guide for implementing fundamental Java programming techniques and web application development.

Uploaded by

sssecsis25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1.

Implement a java program to demonstrate creating an ArrayList, adding elements,


removing elements, sorting elements of ArrayList. Also illustrate the use of toArray()
method.

import java.util.ArrayList;

import java.util.Collections;

public class ArrayListDemo {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();

// Adding elements to ArrayList

list.add(5);

list.add(3);

list.add(8);

list.add(1);

System.out.println("ArrayList before sorting: " + list);

// Removing element from ArrayList

list.remove(2);

// Sorting elements of ArrayList

Collections.sort(list);

System.out.println("ArrayList after removing and sorting: " + list);

// Using toArray() method

Integer[] arr = new Integer[list.size()];

arr = list.toArray(arr);

System.out.print("Array: ");

for(Integer num : arr) {

System.out.print(num + " ");


}

OUTPUT:

ArrayList before sorting: [5, 3, 8, 1]

ArrayList after removing and sorting: [1, 3, 5]

Array: 1 3 5
2. Develop a program to read random numbers between a given range that are multiples of
2 and 5, sort the numbers according to tens place using comparator.

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

public class SortMultiples {

public static void main(String[] args) {

ArrayList<Integer> numbers = new ArrayList<>();

// Adding random multiples of 2 and 5 to ArrayList

// Assuming range from 1 to 100

for(int i = 1; i <= 100; i++) {

if(i % 2 == 0 && i % 5 == 0) {

numbers.add(i);

// Sorting by tens place

Collections.sort(numbers, new Comparator<Integer>() {

@Override

public int compare(Integer num1, Integer num2) {

return Integer.compare(num1 % 10, num2 % 10);

});
System.out.println("Sorted numbers: " + numbers);

OUTPUT:

Sorted numbers: [10, 20, 50, 40, 30, 60, 70, 80, 90, 100]
3. Implement a java program to illustrate storing user defined classes in collection.

import java.util.ArrayList;

class Student {

String name;

int rollNo;

Student(String name, int rollNo) {

this.name = name;

this.rollNo = rollNo;

public class UserDefinedCollection {

public static void main(String[] args) {

ArrayList<Student> students = new ArrayList<>();

// Storing user-defined objects in collection

students.add(new Student("Alice", 101));

students.add(new Student("Bob", 102));

// Retrieving objects from collection

for(Student student : students) {

System.out.println("Name: " + student.name + ", Roll No: " + student.rollNo);

}
}

OUTPUT:

Student [name=Alice, rollNo=101]

Student [name=Bob, rollNo=102]


4 Implement a java program to illustrate the use of different types of string class
constructors.

public class StringConstructors {

public static void main(String[] args) {

// Different types of String constructors

String str1 = new String(); // Empty String

String str2 = new String("Hello"); // String with specified content

char[] charArray = {'H', 'e', 'l', 'l', 'o'};

String str3 = new String(charArray); // String from character array

String str4 = new String(charArray, 0, 2); // String from part of character array

System.out.println(str1);

System.out.println(str2);

System.out.println(str3);

System.out.println(str4);

5 Implement a java program to illustrate the use of different types of character extraction,
string comparison, string search and string modification methods.

public class StringMethods {

public static void main(String[] args) {

String str = "Hello, world!";

// Character extraction

char ch = str.charAt(0); // Extracts character at index 0

System.out.println("First character: " + ch);


// String comparison

String anotherStr = "Hello";

boolean isEqual = str.equals(anotherStr); // Compare strings for equality

System.out.println("Strings are equal: " + isEqual);

// String search

int index = str.indexOf('o'); // Search for 'o'

System.out.println("Index of 'o': " + index);

// String modification

String modifiedStr = str.replace('l', 'z'); // Replace 'l' with 'z'

System.out.println("Modified string: " + modifiedStr);

OUTPUT:

str1:

str2: Hello

str3: Hello

str4: He
6 Implement a java program to illustrate the use of different types of StringBuffer methods

public class StringBufferMethods {

public static void main(String[] args) {

StringBuffer buffer = new StringBuffer("Hello");

// Append method

buffer.append(" world");

// Insert method

buffer.insert(5, ",");

// Delete method

buffer.delete(5, 6); // Deletes character at index 5

// Reverse method

buffer.reverse();

System.out.println(buffer);

OUTPUT:

dlrow ,olleH
7 Demonstrate a swing event handling application that creates 2 buttons Alpha and Beta
and displays the text “Alpha pressed” when alpha button is clicked and “Beta pressed”
when beta button is clicked.

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SwingEventDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("Event 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(null, "Alpha pressed");

});

betaButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


JOptionPane.showMessageDialog(null, "Beta pressed");

});

frame.getContentPane().add(alphaButton);

frame.getContentPane().add(betaButton);

frame.pack();

frame.setVisible(true);

Here's a Java Swing program that demonstrates event handling for button clicks:

```java

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SwingEventDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("Event 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(null, "Alpha pressed");

});

betaButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(null, "Beta pressed");

});

frame.getContentPane().add(alphaButton);

frame.getContentPane().add(betaButton);

frame.pack();

frame.setVisible(true);

```Output:

Upon clicking the "Alpha" button, a dialog box with the message "Alpha pressed" will be
displayed. Similarly, clicking the "Beta" button will display a dialog box with the message "Beta
pressed".
8 A program to display greeting message on the browser “Hello UserName”, “How Are
You?”, accept username from the client using servlet.

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class GreetingServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String username = request.getParameter("username");

out.println("<html><body>");

out.println("<h2>Hello " + username + "</h2>");

out.println("<p>How Are You?</p>");

out.println("</body></html>");

9 A servlet program to display the name, USN, and total marks by accepting student detail

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class StudentDetailsServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String name = request.getParameter("name");

String usn = request.getParameter("usn");

int totalMarks = Integer.parseInt(request.getParameter("totalMarks"));

out.println("<html><body>");

out.println("<h2>Student Details:</h2>");

out.println("<p>Name: " + name + "</p>");

out.println("<p>USN: " + usn + "</p>");

out.println("<p>Total Marks: " + totalMarks + "</p>");

out.println("</body></html>");

OUTPUT: Here's a simple servlet program that displays a greeting message on the browser,
accepting the username from the client:

```java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/GreetingServlet")

public class GreetingServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

// Get username from the request

String username = request.getParameter("username");

out.println("<html><body>");

out.println("<h2>Hello " + username + "</h2>");

out.println("<p>How Are You?</p>");

out.println("</body></html>");

Output:

When you access this servlet through a web browser, it will display a form prompting for a
username. After submitting the form, it will display a greeting message like "Hello [username],
How Are You?".
If you want to test this servlet, you need to deploy it on a servlet container like Apache Tomcat
and access it through a web browser.

10 A Java program to create and read the cookie for the given cookie name as “EMPID”
and its value as “AN2356”.

import javax.servlet.http.*;

import java.io.*;

public class CookieExample extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


IOException {

Cookie cookie = new Cookie("EMPID", "AN2356");

response.addCookie(cookie);

PrintWriter out = response.getWriter();

out.println("Cookie created and read successfully!");

11 Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on
particular queries(For example update, delete, search etc...).

// Assuming a MySQL database

import java.sql.*;

public class JDBCExample {

public static void main(String[] args) {

try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username",
"password");

Statement stmt = conn.createStatement();

// Insert data

String insertQuery = "INSERT INTO Student VALUES ('Alice', 101)";

stmt.executeUpdate(insertQuery);

// Retrieve data

String selectQuery = "SELECT * FROM Student WHERE name = 'Alice'";

ResultSet rs = stmt.executeQuery(selectQuery);

while(rs.next()) {

System.out.println("Name: " + rs.getString("name") + ", Roll No: " +


rs.getInt("rollNo"));

conn.close();

} catch (Exception e) {

System.out.println(e);

OUTPUT:

Cookie Name: EMPID

Cookie Value: AN2356


12 A program to design the Login page and validating the USER_ID and PASSWORD using JSP
and DataBase. give the programs for all 12 questions mentioned above

To create a login page validation using JSP and database, you'll need to follow these steps:

●​ Setup Database: First, you need to set up a database to store user credentials. You can use
MySQL, PostgreSQL, or any other database of your choice.

●​ Create Table: Create a table in your database to store user information like username and
password.

●​ Configure Database Connection: Create a Java class to handle the database connection.
This class will have methods to connect to the database, insert user data, and retrieve user
data.

●​ Create JSP Files: Create JSP files for the login page and for handling login validation.

●​ Servlet for Validation: Create a servlet to handle form submission from the login page.
This servlet will validate the username and password against the database.

●​ Deployment: Deploy your application on a server. You can use Apache Tomcat or any
other servlet container.
1. Database Configuration Class (DBConnection.java):

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class DBConnection {

private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";

private static final String USER = "username";

private static final String PASSWORD = "password";

public static Connection getConnection() throws SQLException {

return DriverManager.getConnection(URL, USER, PASSWORD);

2. Servlet for Login Validation (LoginServlet.java):

import java.io.IOException;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

String username = request.getParameter("username");

String password = request.getParameter("password");

try (Connection conn = DBConnection.getConnection()) {

String sql = "SELECT * FROM users WHERE username = ? AND password = ?";

PreparedStatement statement = conn.prepareStatement(sql);

statement.setString(1, username);

statement.setString(2, password);

ResultSet result = statement.executeQuery();

if (result.next()) {

// Successful login

response.sendRedirect("welcome.jsp");

} else {

// Invalid credentials

response.sendRedirect("login.jsp?error=1");

} catch (SQLException ex) {

ex.printStackTrace();

response.sendRedirect("login.jsp?error=2");
}

3. Login Page (login.jsp):

<!DOCTYPE html>

<html>

<head>

<title>Login Page</title>

</head>

<body>

<h2>Login</h2>

<% if (request.getParameter("error") != null) { %>

<% if (request.getParameter("error").equals("1")) { %>

<p>Invalid username or password!</p>

<% } else if (request.getParameter("error").equals("2")) { %>

<p>Error connecting to database!</p>

<% } %>

<% } %>

<form action="login" method="post">

<label for="username">Username:</label>

<input type="text" id="username" name="username" required><br>

<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br>

<button type="submit">Login</button>

</form>
</body>

</html>

4. Welcome Page (welcome.jsp):

<!DOCTYPE html>

<html>

<head>

<title>Welcome</title>

</head>

<body>

<h2>Welcome</h2>

<p>You have successfully logged in!</p>

</body>

</html>

OUTPUT:

Designing a login page with JSP and validating the user_id and password against a database
involves multiple files and configurations. I'll provide you with a basic example to get you
started.

1. **Database Configuration (DBConnection.java)**:

```java

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class DBConnection {

private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";


private static final String USER = "username";

private static final String PASSWORD = "password";

public static Connection getConnection() throws SQLException {

return DriverManager.getConnection(URL, USER, PASSWORD);

```

2. **Login Servlet (LoginServlet.java)**:

```java

import java.io.IOException;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/login")

public class LoginServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

String username = request.getParameter("username");

String password = request.getParameter("password");

try (Connection conn = DBConnection.getConnection()) {

String sql = "SELECT * FROM users WHERE username = ? AND password = ?";

PreparedStatement statement = conn.prepareStatement(sql);

statement.setString(1, username);

statement.setString(2, password);

ResultSet result = statement.executeQuery();

if (result.next()) {

// Successful login

response.sendRedirect("welcome.jsp");

} else {

// Invalid credentials

response.sendRedirect("login.jsp?error=1");

} catch (SQLException ex) {

ex.printStackTrace();

response.sendRedirect("login.jsp?error=2");

}
```

3. **Login Page (login.jsp)**:

```jsp

<!DOCTYPE html>

<html>

<head>

<title>Login Page</title>

</head>

<body>

<h2>Login</h2>

<% if (request.getParameter("error") != null) { %>

<% if (request.getParameter("error").equals("1")) { %>

<p>Invalid username or password!</p>

<% } else if (request.getParameter("error").equals("2")) { %>

<p>Error connecting to database!</p>

<% } %>

<% } %>

<form action="login" method="post">

<label for="username">Username:</label>

<input type="text" id="username" name="username" required><br>

<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br>

<button type="submit">Login</button>

</form>
</body>

</html>

```

4. **Welcome Page (welcome.jsp)**:

```jsp

<!DOCTYPE html>

<html>

<head>

<title>Welcome</title>

</head>

<body>

<h2>Welcome</h2>

<p>You have successfully logged in!</p>

</body>

</html>

```

OUTPUT:

To run this application:

- Make sure you have a MySQL database set up with a table named `users` containing
`username` and `password` columns.

- Deploy these files in a servlet container like Apache Tomcat.

- Access the login page through a web browser.

- Enter valid or invalid credentials and observe the behavior.


This is a basic example. In a real-world scenario, you would also need to consider security
measures like password hashing and SQL injection prevention.

You might also like