0% found this document useful (0 votes)
32 views42 pages

Advanced Java Lab Manual

The document is a lab manual for the Advanced Java Programming course (MCACPP 2.7) at CIT First Grade College for the academic year 2024-25. It includes a syllabus outlining programming exercises divided into two parts, covering topics such as inheritance, interfaces, exception handling, file handling, threading, AWT controls, and servlet programming. Each exercise provides a brief description and example code to demonstrate the concepts taught in the course.

Uploaded by

soundarya Cs
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)
32 views42 pages

Advanced Java Lab Manual

The document is a lab manual for the Advanced Java Programming course (MCACPP 2.7) at CIT First Grade College for the academic year 2024-25. It includes a syllabus outlining programming exercises divided into two parts, covering topics such as inheritance, interfaces, exception handling, file handling, threading, AWT controls, and servlet programming. Each exercise provides a brief description and example code to demonstrate the concepts taught in the course.

Uploaded by

soundarya Cs
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/ 42

CIT FIRST GRADE COLLEGE

(Affiliated to Tumkur University, Tumakuru)


CIT Campus, Gubbi, Tumakuru – 572 216. Karnataka

Department of Computer Applications

(Year 2024-25)

ADVANCED JAVA PROGRAMMING


(MCACPP 2.7)
LAB MANUAL

Prepared By:

Ms.VARSHA.N

Dept of ISE
SYLLABUS

Course Title: Advanced Programming Laboratory.


Course Code: MCACPP 2.7

Programming Exercises:
PART A:
1. Implement a java program to demonstrate Inheritance and Packages.
2. Implement a java program to demonstrate Interfaces.
3. Implement a java program to demonstrate Exception Handling Technique.
4. Implement a java program to demonstrate input/output streams.
5. Implement a java program to demonstrate File handling technique.
6. Implement a java program to demonstrate Threading.
7. Implement a java program to work with various AWT controls.
8. Write a Java program to illustrate different operations on collection classes like (i) Array List,
(ii)Iterator, (iii) Hash map.

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

PART B:
1. Implement a java program to illustrate the use of different types of String Buffer methods
2. Write a JAVA Servlet Program to implement a dynamic HTML using Servlet.
3. Write a JAVA Servlet Program to implement and demonstrate GET and POST methods
4. Write a JAVA Servlet Program using cookies to remember user preferences.
5. 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.
6. Write a JAVA Servlet program to track Http Session by accepting user name and password using
HTML and display the profile page on successful login.
7.A servlet program to display the name, USN, and total marks by accepting student detail.
8. Write a JAVA Program to implement CRUD application using Student DATA BASE.
9. A program to design the Login page and validating the USER ID and PASSWORD using JSP
TABLE OF CONTENTS

Sl.no. Programs Page no.


PART A
1. Implement a java program to demonstrate Inheritance and Packages. 01
2. Implement a java program to demonstrate Interfaces. 02
3. Implement a java program to demonstrate Exception Handling Technique. 03
4. Implement a java program to demonstrate input/output streams. 04
5. Implement a java program to demonstrate File handling technique. 05
6. Implement a java program to demonstrate Threading. 06-07
7. Implement a java program to work with various AWT controls. 07-08
8. Write a Java program to illustrate different operations on collection classes like 09
(i) Array List, (ii)Iterator, (iii) Hash map
9. Implement a java program to illustrate the use of different types of string class 10
constructors.
10. Implement a java program to illustrate the use of different types of character 11-12
extraction, string comparison, string search and string modification methods.

PART B
1. Implement a java program to illustrate the use of different types of String 13-14
Buffer methods
2. Write a JAVA Servlet Program to implement a dynamic HTML using Servlet. 14-15
3. Write a JAVA Servlet Program to implement and demonstrate GET and POST 16-17
methods
4. Write a JAVA Servlet Program using cookies to remember user preferences. 18-19
5. Demonstrate a swing event handling application that creates 2 buttons Alpha 20-21
and Beta and displays the text "Alpha pressed" when alpha button is clicked
and "Beta pressed" when beta button is clicked.
6. Write a JAVA Servlet program to track Http Session by accepting user name 22-24
and password using HTML and display the profile page on successful login.
7. A servlet program to display the name, USN, and total marks by accepting 25-26
student detail.
8. Write a JAVA Program to implement CRUD application using Student DATA 27-30
BASE
9. A program to design the Login page and validating the USER ID and 31-32
PASSWORD using JSP
Viva 33-38
Java programming Lab 2024-25

PART A

1. Implement a java program to demonstrate Inheritance and Packages.


package demo;

// Superclass (Parent)
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

// Subclass (Child)
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}

// Main class to run the program


public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in Dog
}
}

Output:

Animal is eating
Dog is barking

Master of Computer Applications (MCA) Page 1


Java programming Lab 2024-25

2.Implement a java program to demonstrate Interfaces.


package demo;

// Define an interface
interface AnimalSound {
void makeSound();
}

// Implement the interface in a class


class Dog implements AnimalSound {
public void makeSound() {
System.out.println("Dog says: Woof Woof");
}
}

// Main class to run the program


public class Main {
public static void main(String[] args) {
AnimalSound myDog = new Dog();
myDog.makeSound();
}
}

Output:

Dog says: Woof Woof

Master of Computer Applications (MCA) Page 2


Java programming Lab 2024-25

3.Implement a java program to demonstrate Exception Handling Technique.


package demo;

public class Main {


public static void main(String[] args) {
int numerator = 10;
int denominator = 0;

try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero");
}

System.out.println("Program continues after exception handling.");


}
}

Output:

Error: Cannot divide by zero


Program continues after exception handling.

Master of Computer Applications (MCA) Page 3


Java programming Lab 2024-25

4.Implement a java program to demonstrate input/output streams.


package demo;

import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.println("Hello, " + name + "! Welcome to Java I/O streams.");

scanner.close();
}
}

Output:

Enter your name: Varsha


Hello, Varsha! Welcome to Java I/O streams.

Master of Computer Applications (MCA) Page 4


Java programming Lab 2024-25

5.Implement a java program to demonstrate File handling technique.


package demo;

import java.io.*;

public class Main {


public static void main(String[] args) {
String fileName = "example.txt";
// Writing to a file
try (FileWriter writer = new FileWriter(fileName)) {
writer.write("Hello, this is a simple file handling demo in Java!");
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
// Reading from a file
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
System.out.println("Reading from the file:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading from the file.");
e.printStackTrace();
}}}

Output:

Successfully wrote to the file.


Reading from the file:
Hello, this is a simple file handling demo in Java!

Master of Computer Applications (MCA) Page 5


Java programming Lab 2024-25

6.Implement a java program to demonstrate Threading.


package demo;

public class Main {


public static void main(String[] args) {
// Create and start first thread
Thread thread1 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread 1 interrupted");
}
}
});
// Create and start second thread
Thread thread2 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread 2 interrupted");
}
}
});
thread1.start();
thread2.start();
}

Master of Computer Applications (MCA) Page 6


Java programming Lab 2024-25

Output (sample; actual order may vary):

Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5

7.Implement a java program to work with various AWT controls.


package demo;

import java.awt.*;

public class Main {


public static void main(String[] args) {
// Create a Frame
Frame frame = new Frame("Simple AWT Controls");

// Create controls
Label label = new Label("Enter your name:");
TextField textField = new TextField(20); // 20 columns wide
Button button = new Button("Click Me");

// Set a layout manager (FlowLayout arranges components left to right)


frame.setLayout(new FlowLayout());

// Add controls to the frame


frame.add(label);
frame.add(textField);

Master of Computer Applications (MCA) Page 7


Java programming Lab 2024-25

frame.add(button);

// Set frame size and make it visible


frame.setSize(300, 150);
frame.setVisible(true);
}
}

Output:

A window titled "Simple AWT Controls" will appear with a label, a text field, and a button.

Master of Computer Applications (MCA) Page 8


Java programming Lab 2024-25

8.Write a Java program to illustrate different operations on collection classes


like (i) Array List, (ii)Iterator, (iii) Hash map.
package demo;

import java.util.*;

public class Main {


public static void main(String[] args) {
// (i) ArrayList operations
ArrayList<String> arrList = new ArrayList<>();
arrList.add("Apple");
arrList.add("Banana");
arrList.add("Cherry");
System.out.println("ArrayList: " + arrList);
// (ii) Iterator usage
Iterator<String> itr = arrList.iterator();
System.out.print("Contents using Iterator: ");
while (itr.hasNext()) {
System.out.print(itr.next() + " "); }
System.out.println();
// (iii) HashMap operations
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("HashMap: " + hashMap);
// Accessing a value using key
System.out.println("Value for key 2: " + hashMap.get(2));
}}

Output:

ArrayList: [Apple, Banana, Cherry]


Contents using Iterator: Apple Banana Cherry
HashMap: {1=One, 2=Two, 3=Three}
Value for key 2: Two

Master of Computer Applications (MCA) Page 9


Java programming Lab 2024-25

9.Implement a java program to illustrate the use of different types of string


class constructors.
package demo;

public class Main {


public static void main(String[] args) {
// 1. Default constructor - creates an empty string
String emptyStr = new String();
System.out.println("Empty string: '" + emptyStr + "'");
// 2. Constructor with a string literal
String strLiteral = new String("Hello, Java!");
System.out.println("String from literal: " + strLiteral);
// 3. Constructor with a char array
char[] charArray = {'J', 'a', 'v', 'a'};
String strFromChars = new String(charArray);
System.out.println("String from char array: " + strFromChars);
// 4. Constructor with a char array, start index, and count
String strFromSubChars = new String(charArray, 1, 2);
System.out.println("String from subrange of char array: " + strFromSubChars);
// 5. Constructor with a byte array
byte[] byteArray = {65, 66, 67, 68};
String strFromBytes = new String(byteArray);
System.out.println("String from byte array: " + strFromBytes);
}

Output:

Empty string: ''


String from literal: Hello, Java!
String from char array: Java
String from subrange of char array: av
String from byte array: ABCD

Master of Computer Applications (MCA) Page 10


Java programming Lab 2024-25

10. Implement a java program to illustrate the use of different types of


character extraction, string comparison, string search and string modification
methods.
package demo;

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
String str = "Hello, Java World!";
String str2 = "Hello, Java World!";
String str3 = "hello, java world!";

// --- Character Extraction ---


// charAt()
char ch = str.charAt(7);
System.out.println("Character at index 7: " + ch); // Output: J

// getChars()
char[] dst = new char[11_5];
str.getChars(7, 12, dst, 0);
System.out.println("Extracted characters: " + new String(dst)); // Output: Java

// toCharArray()
char[] charArray = str.toCharArray();
System.out.println("Character array: " + Arrays.toString(charArray));
// --- String Comparison ---
// equals()
System.out.println("str equals str2: " + str.equals(str2)); // true
// equalsIgnoreCase()
System.out.println("str equalsIgnoreCase str3: " + str.equalsIgnoreCase(str3)); // true
// --- String Search ---
// indexOf()

Master of Computer Applications (MCA) Page 11


Java programming Lab 2024-25

System.out.println("Index of 'Java': " + str.indexOf("Java")); // Output: 7


// contains()
System.out.println("Contains 'World': " + str.contains("World")); // true
// --- String Modification ---
// replace()
String replaced = str.replace("Java", "Programming");
System.out.println("After replacement: " + replaced); // Hello, Programming World!
// toLowerCase()
System.out.println("Lowercase: " + str.toLowerCase());
// substring()
System.out.println("Substring: " + str.substring(7, 12)); // Output: Java
}}

Output:

Character at index 7: J
Extracted characters: Java
Character array: [H, e, l, l, o, ,, , J, a, v, a, , W, o, r, l, d, !]
str equals str2: true
str equalsIgnoreCase str3: true
Index of 'Java': 7
Contains 'World': true
After replacement: Hello, Programming World!
Lowercase: hello, java world!
Substring:
Java

Master of Computer Applications (MCA) Page 12


Java programming Lab 2024-25

PART B
1.Implement a java program to illustrate the use of different types of String
Buffer methods.
package demo;

public class Main {


public static void main(String[] args) {
// Create a StringBuffer
StringBuffer sb = new StringBuffer("Hello");
// append()
sb.append(" World");
System.out.println("After append: " + sb);
// insert()
sb.insert(5, ", Java");
System.out.println("After insert: " + sb);
// delete()
sb.delete(5, 11);
System.out.println("After delete: " + sb);
// reverse()
sb.reverse();
System.out.println("After reverse: " + sb);
sb.reverse(); // Reverse back to original order
// replace()
sb.replace(6, 11, "Everyone");
System.out.println("After replace: " + sb);
// capacity()
System.out.println("Capacity: " + sb.capacity());
// length()
System.out.println("Length: " + sb.length());
}
}

Master of Computer Applications (MCA) Page 13


Java programming Lab 2024-25

Output:

After append: Hello World


After insert: Hello, Java World
After delete: Hello World
After reverse: dlroW olleH
After replace: Hello Everyone
Capacity: 21
Length: 13

2. Write a JAVA Servlet Program to implement a dynamic HTML using


Servlet.
package demo;

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

public class SimpleServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<html>");
out.println("<head><title>Simple Servlet Example</title></head>");
out.println("<body>");
out.println("<h1 style='color:blue'>Welcome to Java Servlets!</h1>");
out.println("<p>This is a dynamic HTML page generated by a Servlet.</p>");
out.println("</body>");
out.println("</html>");
}
}

Master of Computer Applications (MCA) Page 14


Java programming Lab 2024-25

1. Configure web.xml:

o In WebContent/WEB-INF/web.xml, add the following inside <web-app>:

<servlet>
<servlet-name>SimpleServlet</servlet-name>
<servlet-class>demo.SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

2. Run on Server:

o Right-click the project and select Run As > Run on Server (Tomcat).

3. Access the Servlet:

o Open a browser and go to http://localhost:8080/YOUR_PROJECT_NAME/hello.

o Replace YOUR_PROJECT_NAME with your actual project title.

Output :

Welcome To Java servlets!


This is a dynamic HTML page generated by a Servlet

Master of Computer Applications (MCA) Page 15


Java programming Lab 2024-25

3.Write a JAVA Servlet Program to implement and demonstrate GET and


POST methods.
package demo;

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

public class GetPostServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Display a simple form for POST submission


out.println("<html><head><title>GET and POST Demo</title></head><body>");
out.println("<h2>GET and POST Example</h2>");
out.println("<form method='post'>");
out.println("Enter your name: <input type='text' name='name'>");
out.println("<input type='submit' value='Submit'>");
out.println("</form>");
out.println("<p>Try submitting the form (POST) or reloading (GET).</p>");
out.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Get the submitted name from the form
String name = request.getParameter("name");

Master of Computer Applications (MCA) Page 16


Java programming Lab 2024-25

out.println("<html><head><title>POST Response</title></head><body>");
out.println("<h2>Hello, " + name + "!</h2>");
out.println("<p>You submitted via POST.</p>");
out.println("<a href=''>Back to form</a>");
out.println("</body></html>");
}
}

1. Configure web.xml:

o In WebContent/WEB-INF/web.xml, add the following inside <web-app>:

<servlet>
<servlet-name>GetPostServlet</servlet-name>
<servlet-class>demo.GetPostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetPostServlet</servlet-name>
<url-pattern>/getpost</url-pattern>
</servlet-mapping>

Output :

Master of Computer Applications (MCA) Page 17


Java programming Lab 2024-25

4.Write a JAVA Servlet Program using cookies to remember user


preferences.

package demo;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookiePrefsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Get the favorite color from the cookie, if it exists
String favColor = "Not set";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("favColor")) {
favColor = cookie.getValue();
break;
}
}
}
out.println("<html><head><title>Cookie Preferences</title></head><body>");
out.println("<h2>Set Your Favorite Color</h2>");
out.println("<form method='post'>");
out.println("Favorite Color: <input type='text' name='favColor'>");
out.println("<input type='submit' value='Save'>");
out.println("</form>");
out.println("<p>Your current favorite color: <strong>" + favColor + "</strong></p>");
out.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)

Master of Computer Applications (MCA) Page 18


Java programming Lab 2024-25

throws ServletException, IOException {


String favColor = request.getParameter("favColor");
if (favColor != null && !favColor.trim().isEmpty()) {
// Create a cookie and send it to the browser
Cookie cookie = new Cookie("favColor", favColor);
cookie.setMaxAge(60 * 60 * 24 * 7); // Set cookie to expire in 7 days
response.addCookie(cookie);
}
// Redirect back to GET to show the updated preference
response.sendRedirect("cookieprefs");
}}

1. Configure web.xml:

o In WebContent/WEB-INF/web.xml, add the following inside <web-app>:

<servlet>
<servlet-name>CookiePrefsServlet</servlet-name>
<servlet-class>demo.CookiePrefsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookiePrefsServlet</servlet-name>
<url-pattern>/cookieprefs</url-pattern>
</servlet-mapping>

Output :

Master of Computer Applications (MCA) Page 19


Java programming Lab 2024-25

5.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.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonDemo extends JFrame {


private JLabel statusLabel;

public ButtonDemo() {
setTitle("Button Event Demo");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Create buttons
JButton alphaButton = new JButton("Alpha");
JButton betaButton = new JButton("Beta");

// Status label to display button presses


statusLabel = new JLabel("Press a button");
add(statusLabel);
add(alphaButton);
add(betaButton);

// Add action listeners


alphaButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Alpha pressed");
statusLabel.setText("Alpha pressed");
}
});

Master of Computer Applications (MCA) Page 20


Java programming Lab 2024-25

betaButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Beta pressed");
statusLabel.setText("Beta pressed");
}
});
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
ButtonDemo demo = new ButtonDemo();
demo.setVisible(true);
});
}
}

Output:

Master of Computer Applications (MCA) Page 21


Java programming Lab 2024-25

6.Write a JAVA Servlet program to track Http Session by accepting user name
and password using HTML and display the profile page on successful login
1. HTML Login Form (login.html)
Place this file in your WebContent folder:

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>User Login</h2>
<form action="login" method="post">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

2. Servlet (LoginServlet.java)
Place this class in your src/demo package (or similar):

package demo;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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");
// Simple authentication: username="admin", password="admin"
if ("admin".equals(username) && "admin".equals(password)) {

Master of Computer Applications (MCA) Page 22


Java programming Lab 2024-25

HttpSession session = request.getSession();


session.setAttribute("username", username);
// Display profile page
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Profile</title></head><body>");
out.println("<h2>Welcome, " + username + "!</h2>");
out.println("<p>This is your profile page.</p>");
out.println("<a href='logout'>Logout</a>");
out.println("</body></html>");
} else {
response.sendRedirect("login.html");
}
}
}

3.Logout Servlet (LogoutServlet.java)


Place this class in your src/demo package (or similar):

package demo;

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

public class LogoutServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
response.sendRedirect("login.html");
}}

Master of Computer Applications (MCA) Page 23


Java programming Lab 2024-25

4. web.xml Configuration
In WebContent/WEB-INF/web.xml, add:

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>demo.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>demo.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>

Output:

Master of Computer Applications (MCA) Page 24


Java programming Lab 2024-25

7. A servlet program to display the name, USN, and total marks by accepting
student detail .
1. HTML Form (student.html)
Place this file in your WebContent folder:

<!DOCTYPE html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="student" method="post">
Name: <input type="text" name="name" required><br><br>
USN: <input type="text" name="usn" required><br><br>
Total Marks: <input type="number" name="marks" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

2. Servlet (StudentServlet.java)
Place this class in your src/demo package (or similar):

package demo;

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

public class StudentServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");

Master of Computer Applications (MCA) Page 25


Java programming Lab 2024-25

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


String marks = request.getParameter("marks");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Student Details</title></head><body>");
out.println("<h2>Student Details Submitted</h2>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>USN: " + usn + "</p>");
out.println("<p>Total Marks: " + marks + "</p>");
out.println("<a href='student.html'>Back to Form</a>");
out.println("</body></html>");
}
}

3. web.xml Configuration
In WebContent/WEB-INF/web.xml, add:

<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>demo.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/student</url-pattern>
</servlet-mapping>

Output:

Master of Computer Applications (MCA) Page 26


Java programming Lab 2024-25

8. Write a JAVA Program to implement CRUD application using Student


DATA BASE

package demo;
import java.util.ArrayList;
import java.util.Scanner;
class Student {
String name;
String usn;
int marks;
Student(String name, String usn, int marks) {
this.name = name;
this.usn = usn;
this.marks = marks;
}
@Override
public String toString() {
return "Name: " + name + ", USN: " + usn + ", Marks: " + marks;
}
}
public class StudentCRUD {
private static ArrayList<Student> students = new ArrayList<>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("\nStudent CRUD Application");
System.out.println("1. Add Student");
System.out.println("2. View All Students");
System.out.println("3. Update Student");
System.out.println("4. Delete Student");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
Master of Computer Applications (MCA) Page 27
Java programming Lab 2024-25

int choice = scanner.nextInt();


scanner.nextLine(); // consume newline
switch (choice) {
case 1:
addStudent();
break;
case 2:
viewStudents();
break;
case 3:
updateStudent();
break;
case 4:
deleteStudent();
break;
case 5:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice! Try again.");
}
}
}
private static void addStudent() {
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter USN: ");
String usn = scanner.nextLine();
System.out.print("Enter Marks: ");
int marks = scanner.nextInt();

Master of Computer Applications (MCA) Page 28


Java programming Lab 2024-25

students.add(new Student(name, usn, marks));


System.out.println("Student added successfully!");
}
private static void viewStudents() {
if (students.isEmpty()) {
System.out.println("No students found!");
return;
}
System.out.println("\nList of Students:");
for (int i = 0; i < students.size(); i++) {
System.out.println((i + 1) + ". " + students.get(i));
}
}
private static void updateStudent() {
viewStudents();
if (students.isEmpty()) return;
System.out.print("Enter student number to update: ");
int index = scanner.nextInt() - 1;
scanner.nextLine(); // consume newline
if (index < 0 || index >= students.size()) {
System.out.println("Invalid student number!");
return;
}
Student s = students.get(index);
System.out.print("Enter new Name (current: " + s.name + "): ");
String name = scanner.nextLine();
System.out.print("Enter new USN (current: " + s.usn + "): ");
String usn = scanner.nextLine();
System.out.print("Enter new Marks (current: " + s.marks + "): ");
int marks = scanner.nextInt();
students.set(index, new Student(name, usn, marks));

Master of Computer Applications (MCA) Page 29


Java programming Lab 2024-25

System.out.println("Student updated successfully!");


}
private static void deleteStudent() {
viewStudents();
if (students.isEmpty()) return;
System.out.print("Enter student number to delete: ");
int index = scanner.nextInt() - 1;
if (index < 0 || index >= students.size()) {
System.out.println("Invalid student number!");
return;
}
students.remove(index);
System.out.println("Student deleted successfully!");
}
}}

Output:

User Input 1
User Input 2

O\P
O\P

Master of Computer Applications (MCA) Page 30


Java programming Lab 2024-25

9. A program to design the Login page and validating the USER ID and
PASSWORD using JSP

1. login.jsp (Login Form)


Place this file in your WebContent folder.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-


8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="checkLogin.jsp" method="post">
User ID: <input type="text" name="userid" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

2. checkLogin.jsp (Validation Logic)


Place this file in your WebContent folder.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-


8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Login Check</title>
</head>
<body>

Master of Computer Applications (MCA) Page 31


Java programming Lab 2024-25

<%
String userid = request.getParameter("userid");
String password = request.getParameter("password");

// Hardcoded valid credentials (for demo only)


if (userid.equals("admin") && password.equals("admin123")) {
%>
<h2>Welcome, <%= userid %>!</h2>
<p>Login successful.</p>
<%
} else {
%>
<h2>Invalid User ID or Password!</h2>
<a href="login.jsp">Try again</a>
<%
}
%>
</body>
</html>

Output:

Master of Computer Applications (MCA) Page 32


Java programming Lab 2024-25

VIVA QUESTIONS
1.Which keyword is used to implement an interface in Java?

A) extends

B) implements

C) interface

D) class

2.Which Java construct is used to handle runtime errors?

A) if-else

B) try-catch

C) switch-case

D) for-loop

3.What is the output of the following code snippet?

try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero");
}

A) Compilation error

B) No output

C) Error: Cannot divide by zero

D) 0

Master of Computer Applications (MCA) Page 33


Java programming Lab 2024-25

4.Which class is used to read user input from the keyboard in Java?

A) FileReader

B) Scanner

C) BufferedReader

D) InputStream

5.Which method is used to write data to a file in Java?

A) read()

B) write()

C) append()

D) open()

6.What is the purpose of the Thread class in Java?

A) To handle exceptions

B) To create and manage threads

C) To read files

D) To create interfaces

7.Which AWT control is used to display text in a GUI?

A) Button

B) Label

C) TextField

D) Frame

Master of Computer Applications (MCA) Page 34


Java programming Lab 2024-25

8.Which method is used to add elements to an ArrayList?

A) put()

B) add()

C) insert()

D) append()

9.Which interface is used to iterate over a collection?

A) List

B) Iterator

C) Set

D) Map

10.Which method is used to get the value associated with a key in a HashMap?

A) find()

B) get()

C) value()

D) key()

11.Which constructor creates a String from a char array in Java?

A) String(char[] value)

B) String(String str)

C) String(int length)

D) String(byte[] bytes)

Master of Computer Applications (MCA) Page 35


Java programming Lab 2024-25

12.Which StringBuffer method is used to add text at the end?

A) insert()

B) append()

C) replace()

D) delete()

13.Which method is used to create a new session in a Servlet?

A) request.getParameter()

B) request.getSession()

C) response.sendRedirect()

D) response.setContentType()

14.Which HTML form method is used to send data to a Servlet for processing?

A) post

B) get

C) put

D) delete

15.Which Servlet method is used to handle HTTP GET requests?

A) doGet()

B) doPost()

C) doPut()

D) doDelete()

Master of Computer Applications (MCA) Page 36


Java programming Lab 2024-25

16.Which JSP directive is used to include another file?

A) <%@ include file="..." %>

B) <jsp:forward page="..."/>

C) <jsp:include page="..."/>

D) <jsp:useBean .../>

17.Which method in JSP is used to retrieve form data?

A) request.getParameter()

B) response.getWriter()

C) session.setAttribute()

D) application.getInitParameter()

18.Which of the following is NOT a CRUD operation?

A) Read

B) Create

C) Update

D) Delete

19.Which Swing method is used to add an event listener to a button?

A) addListener()

B) addActionListener()

C) setListener()

D) onClick()

Master of Computer Applications (MCA) Page 37


Java programming Lab 2024-25

20.Which Java class is used to store cookies in a web application?

A) Session

B) Cookie

C) Request

D) Response

Master of Computer Applications (MCA) Page 38

You might also like