0% found this document useful (0 votes)
5 views44 pages

Java Labb

The document is a Java Lab Manual for the Artificial Intelligence and Machine Learning course at the Oriental Institute of Science & Technology, Bhopal. It outlines various programming experiments, including installation of J2SDK, basic arithmetic operations, function overloading, inheritance, exception handling, and multithreading. Each experiment includes aims, program code, and expected outputs for students to follow during their lab sessions from January to June 2025.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

Java Labb

The document is a Java Lab Manual for the Artificial Intelligence and Machine Learning course at the Oriental Institute of Science & Technology, Bhopal. It outlines various programming experiments, including installation of J2SDK, basic arithmetic operations, function overloading, inheritance, exception handling, and multithreading. Each experiment includes aims, program code, and expected outputs for students to follow during their lab sessions from January to June 2025.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 44

ORIENTAL INSTITUTE OF SCIENCE & TECHNOLOGY, BHOPAL

DEPARTMENT OF CSE - ARTIFICIAL INTELLIGENCE AND MACHINE


LEARNING

JAVA LAB MANUAL

Course Code: AL406

Semester: IV

Course: Java Lab

Session: Jan – June, 2025

Prepared By: Submitted to:


Name- GOUTAM PATIDAR PROF. SANDEEP PIPLOTIA
Roll No.- 0105AL231085 CSE – AIML, OIST
Lab Manual: Java Lab Department of CSE-
AIML

List of Programs

Experiment Date of Signature &


Aim
No. Submission Remarks
12/03/25
1. Installation of J2SDK
Write a program that accepts two numbers from the 19/03/25
2.
user and print their sum.
Write a program to calculate addition of two 26/03/25
3.
number using prototyping of methods.
Program to demonstrate function overloading for 02/04/25
4.
calculation of average.
Program to demonstrating overloaded constructor 09/04/25
5. for calculating box volume.
Program to show the detail of students using 16/04/25
6.
concept of inheritance.
23/04/25
7. Program to demonstrate package concept.
Program to demonstrate implementation of an 30/04/25
8.
interface which contains two methods declaration
square and
Program to cube.
demonstrate exception handling in case 07/05/25
9.
of division by zero error.
14/05/25
10. Program to demonstrate multithreading.
Program to demonstrate JDBC concept using 21/05/25
11.
create a GUI based application for student
information.
Program to display “Hello World” in web browser 28/05/25
12.
using applet.
04/06/25
13. Program to add user controls to applets.
Write a program to create an application using 11/06/25
14.
concept of swing.
Program to demonstrate student registration 18/06/25
15.
functionality using servlets with session
management.

1
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 1

AIM: Installation of J2SDK.

1. Algorithm:

Steps for Installation:


Download and install Java for Windows computer?
This article applies to:

 Platform(s): Windows 8, Windows 7, Vista, Windows XP, Windows 2000,


Windows 2003, Windows 2008 Server
 Java version(s): 6.0, 7.0

The procedure to install Java broadly consists of:


1. Download and Install
2. Test Installation
Windows System Requirements

Note: Installing Java requires that you can gain administrator access to Windows on your
computer.

Download and Install


It is recommended; before you proceed with online installation you may want to disable your
Internet firewall. In some cases the default firewall settings are set to reject all automatic or
online installations such as the Java online installation. If the firewall is not configured
appropriately it may stall the download/install operation of Java under certain conditions.
Refer to your specific Internet firewall manual for instructions on how to disable your Internet
Firewall.

 Go to the Manual download page


 Click on Windows Online
 The File Download dialog box appears prompting you to run or save the download file

 To run the installer, click Run.


 To save the file for later installation, click Save.
Choose the folder location and save the file to your local system.
Tip: Save the file to a known location on your computer, for example, to your desktop.
Double-click on the saved file to start the installation process.
 The installation process starts. Click the Install button to accept the license terms
and to continue with the installation.

2
Lab Manual: Java Lab Department of CSE-
AIML

 Oracle has partnered with companies that offer various products. The installer may
present you with option to install these programs when you install Java. After ensuring
that the desired programs are selected, click the Next button to continue the installation.

 A few brief dialogs confirm the last steps of the installation process; click Close on the
last dialog. This will complete Java installation process.

3
Lab Manual: Java Lab Department of CSE-
AIML

3. Required Software/ Software Tool:-

 Platform(s): Windows 8, Windows 7, Vista, Windows XP, Windows 2000,


Windows 2003, Windows 2008 Server
 Java version(s): 6.0, 7.0 (jdk1.6,jdk1.7)
 Editor :- Net Beans IDE 6.9.1
 Database:- Oracle9i / Mysql
 Web server:- Apache Tomcat 5.5

4
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 2

AIM:

Write a program that accepts two numbers from the user and print their sum.

PROGRAM:

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = s.nextInt();
System.out.print("Enter second number: ");
int num2 = s.nextInt();
int sum = num1 + num2;
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
s.close();
}
}

OUTPUT:

Enter first number: 10

Enter second number: 25

The sum of 10 and 25 is: 35

5
Lab Manual: Java Lab Department of CSE-
AIML

6
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 3

AIM:

Write a program to calculate addition of two number using prototyping of methods.

PROGRAM:

import java.util.Scanner;
public class Main
{
// Method prototype for addition
public static int add(int n1, int n2)
{
return n1 + n2;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = s.nextInt();
System.out.print("Enter second number: ");
int num2 = s.nextInt();
// Call the add method and store the result
int sum = add(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
s.close();
}
}

OUTPUT:

Enter first number: 15

Enter second number: 20

The sum of 15 and 20 is: 35

7
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 4

AIM:

Program to demonstrate function overloading for calculation of average.

PROGRAM:

public class AverageCalculator {

// Method to calculate average of two numbers


public double average(int a, int b) {
return (a + b) / 2.0;
}

// Overloaded method to calculate average of three numbers


public double average(int a, int b, int c) {
return (a + b + c) / 3.0;
}

// Overloaded method to calculate average of four numbers


public double average(int a, int b, int c, int d) {
return (a + b + c + d) / 4.0;
}

public static void main(String[] args) {


AverageCalculator calc = new AverageCalculator();

System.out.println("Average of 10 and 20: " + calc.average(10, 20));


System.out.println("Average of 5, 15, and 25: " + calc.average(5, 15, 25));
System.out.println("Average of 2, 4, 6, and 8: " + calc.average(2, 4, 6, 8));
}
}

OUTPUT:

Average of 10 and 20: 15.0


Average of 5, 15, and 25: 15.0
Average of 2, 4, 6, and 8: 5.0

8
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 5

AIM:

Program to demonstrating overloaded constructor for calculating box volume.

PROGRAM:

class Box {
double length, width, height;

// Default constructor
Box() {
length = width = height = 0;
}

// Constructor for cube


Box(double side) {
length = width = height = side;
}

// Constructor for rectangular box


Box(double l, double w, double h) {
length = l;
width = w;
height = h;
}

// Method to calculate volume


double volume() {
return length * width * height;
}
}

public class BoxVolumeDemo {


public static void main(String[] args) {
Box defaultBox = new Box(); // Default box
Box cube = new Box(5); // Cube with side = 5
Box rectangleBox = new Box(4, 5, 6); // Rectangular box

System.out.println("Volume of default box: " + defaultBox.volume());


System.out.println("Volume of cube: " + cube.volume());
System.out.println("Volume of rectangular box: " + rectangleBox.volume());
}
}

9
Lab Manual: Java Lab Department of CSE-
AIML

OUTPUT:

Volume of default box: 0.0


Volume of cube: 125.0
Volume of rectangular box: 120.0

10
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 6

AIM: Program to show the detail of students using concept of inheritance.

PROGRAM:

// Base class
class Person {
String name;
int age;

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

// Method to display person details


void displayPersonDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

// Derived class
class Student extends Person {
String studentId;
String course;

// Constructor
Student(String name, int age, String studentId, String course) {
super(name, age); // Call parent class constructor
this.studentId = studentId;
this.course = course;
}

// Method to display student details


void displayStudentDetails() {
displayPersonDetails(); // Display base class details
System.out.println("Student ID: " + studentId);
System.out.println("Course: " + course);
}
}

public class StudentDetailsDemo {


public static void main(String[] args) {
// Creating a Student object

11
Lab Manual: Java Lab Department of CSE-
AIML

Student student = new Student("Sandeep", 26, "0105AL23001", "Computer Science-


AIML");

// Displaying student details


student.displayStudentDetails();
}
}

OUTPUT:

Name: Sandeep
Age: 26
Student ID: 0105AL23001
Course: Computer Science-AIML

12
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 7

AIM:

Program to demonstrate package concept.

PROGRAM:

Key Concepts:

package keyword declares a package.

Import keyword is used to bring in classes from a package.

Packages help in organizing classes and avoiding naming conflicts.

Here's a simple Java program that demonstrates the package concept, including how to:

1. Create a package
2. Define a class inside the package
3. Import and use the class from the package in another file

Step-by-Step: Demonstrating Java Package


Directory Structure:
PackageDemo/
├── mypack/
│ └── Student.java
└── Main.java
1. mypack/Student.java – Class inside a package

package mypack; // declare package

public class Student {


private String name;
private int rollNo;

public Student(String name, int rollNo) {


this.name = name;
this.rollNo = rollNo;
}

public void displayDetails() {


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

13
Lab Manual: Java Lab Department of CSE-
AIML

}
}

2. Main.java – Using the package

import mypack.Student; // import class from package

public class Main {


public static void main(String[] args) {
Student s1 = new Student("James", 007);
s1.displayDetails();
}
}

How to Compile and Run:

Make sure you're in the Package Demo directory.

javac mypack/Student.java

javac Main.java

java Main

OUTPUT:

Student Name: James


Roll No: 007

14
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 8

AIM:

Program to demonstrate implementation of an interface which contains two methods


declaration square and cube.

PROGRAM:

// Define the interface


interface MathOperations {
void square(int num);
void cube(int num);
}

// Implement the interface


class Operation implements MathOperations {

// Implement square method


public void square(int num) {
System.out.println("Square of " + num + " is: " + (num * num));
}

// Implement cube method


public void cube(int num) {
System.out.println("Cube of " + num + " is: " + (num * num * num));
}
}

// Main class
public class InterfaceDemo {
public static void main(String[] args) {
Operation op = new Operation();

op.square(4); // Example input


op.cube(3); // Example input
}
}

OUTPUT:

Square of 4 is: 16
Cube of 3 is: 27

15
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 9

AIM:

Program to demonstrate exception handling in case of division by zero error.

PROGRAM:

Key Concepts:

try block: Code that may cause an exception.

catch (ArithmeticException): Catches division by zero.

finally: Executes code regardless of whether an exception occurred.

Scanner is used for user input.

import java.util.Scanner;

public class DivisionDemo {


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

try {
// Input from user
System.out.print("Enter numerator: ");
int numerator = scanner.nextInt();

System.out.print("Enter denominator: ");


int denominator = scanner.nextInt();

// Attempt division
int result = numerator / denominator;

System.out.println("Result: " + result);


} catch (ArithmeticException e) {
// Handle division by zero
System.out.println("Error: Division by zero is not allowed.");
} catch (Exception e) {
// Handle other potential exceptions
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Program execution completed.");
}
}
}

16
Lab Manual: Java Lab Department of CSE-
AIML

OUTPUT:

Output 1:

Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed.
Program execution completed.

Output 2:

Enter numerator: 20
Enter denominator: 5
Result: 4
Program execution completed.

17
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 10

AIM:

Program to demonstrate multithreading.

PROGRAM:

Key Concepts: MyThread class extends Thread and overrides run().

start() method is used to begin the execution of threads.

sleep() pauses thread execution for a while.

Threads run concurrently, demonstrating multithreading.

// Define a class by extending Thread

class MyThread extends Thread {

private String threadName;

// Constructor

MyThread(String name) {

threadName = name;

// Override run() method

public void run() {

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

System.out.println(threadName + " - Count: " + i);

18
Lab Manual: Java Lab Department of CSE-
AIML

try {

Thread.sleep(500); // Pause for 500 milliseconds

} catch (InterruptedException e) {

System.out.println(threadName + " interrupted.");

System.out.println(threadName + " finished.");

// Main class

public class MultithreadingDemo {

public static void main(String[] args) {

// Create thread objects

MyThread t1 = new MyThread("Thread-1");

MyThread t2 = new MyThread("Thread-2");

// Start threads

t1.start();

t2.start();

OUTPUT:

Thread-1 - Count: 1
Thread-2 - Count: 1
Thread-1 - Count: 2
Thread-2 - Count: 2
...
Thread-1 finished.
Thread-2 finished.

19
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 11

AIM:

Program to demonstrate JDBC concept using create a GUI based application for student
information.

PROGRAM: Here's a Java GUI-based application that demonstrates JDBC (Java Database
Connectivity) to manage student information. The program allows the user to input student
details (name, age, and course), save them to a database, and display all records.

Requirements:

1. Java Development Kit (JDK)


2. MySQL database (or any JDBC-compatible DB)

3. MySQL Connector/J (JDBC driver for MySQL)

4. Basic knowledge of Swing for GUI

Steps:

1. Create a MySQL database and a students table.

2. Set up JDBC in your Java project.

3. Create the GUI using Swing.

4. Use JDBC to connect and interact with the database.

1. MySQL Table Setup

CREATE DATABASE studentdb;

USE studentdb;

CREATE TABLE students (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

age INT,

20
Lab Manual: Java Lab Department of CSE-
AIML

course VARCHAR(100)

);

2. Java Code

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.sql.*;

public class StudentApp extends JFrame {

// DB credentials

static final String DB_URL = "jdbc:mysql://localhost:3306/studentdb";

static final String USER = "root"; // change if needed

static final String PASS = ""; // change if needed

// Components

JTextField nameField, ageField, courseField;

JTextArea outputArea;

public StudentApp() {

// GUI Setup

setTitle("Student Information");

setSize(500, 400);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new BorderLayout());

21
Lab Manual: Java Lab Department of CSE-
AIML

JPanel formPanel = new JPanel(new GridLayout(4, 2));

formPanel.add(new JLabel("Name:"));

nameField = new JTextField();

formPanel.add(nameField);

formPanel.add(new JLabel("Age:"));

ageField = new JTextField();

formPanel.add(ageField);

formPanel.add(new JLabel("Course:"));

courseField = new JTextField();

formPanel.add(courseField);

JButton addButton = new JButton("Add Student");

JButton displayButton = new JButton("Display Students");

formPanel.add(addButton);

formPanel.add(displayButton);

add(formPanel, BorderLayout.NORTH);

outputArea = new JTextArea();

add(new JScrollPane(outputArea), BorderLayout.CENTER);

22
Lab Manual: Java Lab Department of CSE-
AIML

// Button Actions

addButton.addActionListener(e -> addStudent());

displayButton.addActionListener(e -> displayStudents());

void addStudent() {

String name = nameField.getText();

String ageText = ageField.getText();

String course = courseField.getText();

if (name.isEmpty() || ageText.isEmpty() || course.isEmpty()) {

JOptionPane.showMessageDialog(this, "Please fill all fields.");

return;

try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS))


{

String sql = "INSERT INTO students (name, age, course) VALUES (?, ?, ?)";

PreparedStatement stmt = conn.prepareStatement(sql);

stmt.setString(1, name);

stmt.setInt(2, Integer.parseInt(ageText));

stmt.setString(3, course);

stmt.executeUpdate();

JOptionPane.showMessageDialog(this, "Student added successfully.");

} catch (Exception ex) {

ex.printStackTrace();

23
Lab Manual: Java Lab Department of CSE-
AIML

JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());

void displayStudents() {

outputArea.setText("");

try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS))


{

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM students");

while (rs.next()) {

outputArea.append("ID: " + rs.getInt("id") +

", Name: " + rs.getString("name") +

", Age: " + rs.getInt("age") +

", Course: " + rs.getString("course") + "\n");

} catch (Exception ex) {

ex.printStackTrace();

outputArea.setText("Error fetching data.");

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new StudentApp().setVisible(true));

24
Lab Manual: Java Lab Department of CSE-
AIML

3. Add MySQL JDBC Driver

If using an IDE like Eclipse or IntelliJ:

1. Add the mysql-connector-j-x.x.xx.jar to your project's classpath.


2. Or if using the command line:

javac -cp .:mysql-connector-j-8.0.xx.jar StudentApp.java

java -cp .:mysql-connector-j-8.0.xx.jar StudentApp

OUTPUT:

Features Demonstrated

JDBC Connection

Prepared Statements (to prevent SQL injection)

Swing-based GUI

Basic CRUD functionality (Create & Read)

25
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 12

AIM:

Program to display “Hello World” in web browser using applet.

PROGRAM:

1. Java Applet Code save this as HelloWorldApplet.java:

import java.applet.Applet;

import java.awt.Graphics;

/*

<applet code="HelloWorldApplet.class" width="300" height="100">

</applet>

*/

public class HelloWorldApplet extends Applet {

public void paint(Graphics g) {

g.drawString("Hello World", 100, 50);

2. Compile the Applet

javac HelloWorldApplet.java

3. HTML to Load Applet

Create an HTML file called HelloApplet.html:

<html>

<body>

26
Lab Manual: Java Lab Department of CSE-
AIML

<h3>My First Applet</h3>

<applet code="HelloWorldApplet.class" width="300" height="100">

</applet>

</body>

</html>

4. Run the Applet

Use the appletviewer tool (comes with JDK 8):

appletviewer HelloApplet.html

OUTPUT:

Hello World", 100, 50

27
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 13

AIM:

Program to add user controls to applets.

PROGRAM:

Here's a simple Java Applet program that adds user controls like TextField, Button, and Label
to demonstrate interactive input/output using an applet.

Objective

Create a Java Applet with the following:

1. A Text Field to enter a name


2. A Button to submit

3. A Label to display a greeting

1. Java Code: UserControlApplet.java java Copy Edit

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

/*

<applet code="UserControlApplet.class" width="400" height="200">

</applet>

*/

public class UserControlApplet extends Applet implements ActionListener {

TextField nameField;

Button greetButton;

Label outputLabel;

28
Lab Manual: Java Lab Department of CSE-
AIML

public void init() {

// Initialize components

nameField = new TextField(20);

greetButton = new Button("Greet");

outputLabel = new Label("Enter your name and click Greet");

// Add components to the applet

add(new Label("Name:"));

add(nameField);

add(greetButton);

add(outputLabel);

// Add event listener to button

greetButton.addActionListener(this);

public void actionPerformed(ActionEvent e) {

String name = nameField.getText();

outputLabel.setText("Hello, " + name + "!");

2. Compile the Applet

javac UserControlApplet.java

3. Create HTML File: UserControlApplet.html

29
Lab Manual: Java Lab Department of CSE-
AIML

<html>

<body>

<h3>User Control Applet Demo</h3>

<applet code="UserControlApplet.class" width="400" height="200">

</applet>

</body>

</html>

4. Run the Applet

appletviewer UserControlApplet.html

OUTPUT:

Features Demonstrated

Adding Swing/AWT components to applets

Handling button click events using Action Listener

Dynamic user interaction in applets.

30
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 14

AIM:

Write a program to create an application using concept of swing

PROGRAM:

Here is a simple Java Swing application that demonstrates the basic concepts of Swing
components, event handling, and a GUI-based interaction.

Objective

Build a Swing application that:

Accepts user's name via a JTextField

Has a JButton to trigger greeting

Displays a greeting in a JLabel.

Java Swing Application Code Save the following as SwingGreetingApp.java

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class SwingGreetingApp extends JFrame implements ActionListener {

// Declare Swing components

JTextField nameField;

JButton greetButton;

JLabel greetingLabel;

public SwingGreetingApp() {

// Set up the frame

setTitle("Swing Greeting App");

31
Lab Manual: Java Lab Department of CSE-
AIML

setSize(350, 200);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new FlowLayout());

// Initialize components

JLabel nameLabel = new JLabel("Enter your name:");

nameField = new JTextField(20);

greetButton = new JButton("Greet");

greetingLabel = new JLabel("");

// Add action listener

greetButton.addActionListener(this);

// Add components to frame

add(nameLabel);

add(nameField);

add(greetButton);

add(greetingLabel);

// Make it visible

setVisible(true);

// Action listener method

public void actionPerformed(ActionEvent e) {

32
Lab Manual: Java Lab Department of CSE-
AIML

String name = nameField.getText().trim();

if (!name.isEmpty()) {

greetingLabel.setText("Hello, " + name + "!");

} else {

greetingLabel.setText("Please enter your name.");

// Main method to run the app

public static void main(String[] args) {

new SwingGreetingApp();

How to Run

1. Compile the Java file:bash

javac SwingGreetingApp.java

2. Run the program:

java SwingGreetingApp

OUTPUT:

Features Demonstrated

Swing components: JFrame, JTextField, JButton, JLabel

Layout Manager: FlowLayout

Event Handling with ActionListener

Real-time GUI interaction

33
Lab Manual: Java Lab Department of CSE-
AIML

EXPERIMENT NO. - 15

AIM:

Program to demonstrate student registration functionality using servlets with session


management.

PROGRAM:

Here's a complete Java Servlet-based web application that demonstrates student registration
with session management.

Features

1. Student registration form (HTML)


2. Servlet to handle form submission

3. Session management to store user data temporarily

4. Display confirmation with student details

Technologies Used

1. Java Servlet API


2. HTML

3. Apache Tomcat (or any servlet container)

4. Java EE Web project structure (with web.xml)

Project Structure

StudentRegistrationApp/

├── WEB-INF/

│ ├── web.xml

│ └── classes/

│ └── StudentServlet.class

├── register.html

1. HTML Form (register.html)

<!DOCTYPE html>

<html>

34
Lab Manual: Java Lab Department of CSE-
AIML

<head>

<title>Student Registration</title>

</head>

<body>

<h2>Student Registration Form</h2>

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

Name: <input type="text" name="name"><br><br>

Email: <input type="email" name="email"><br><br>

Course: <input type="text" name="course"><br><br>

<input type="submit" value="Register">

</form>

</body>

</html>

2. Java Servlet (StudentServlet.java)

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class StudentServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Retrieve form data

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

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

35
Lab Manual: Java Lab Department of CSE-
AIML

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

// Store data in session

HttpSession session = request.getSession();

session.setAttribute("name", name);

session.setAttribute("email", email);

session.setAttribute("course", course);

// Set response type

response.setContentType("text/html");

PrintWriter out = response.getWriter();

// Display confirmation

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

out.println("<h2>Registration Successful</h2>");

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

out.println("<p>Email: " + session.getAttribute("email") + "</p>");

out.println("<p>Course: " + session.getAttribute("course") + "</p>");

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

3. web.xml Configuration (WEB-INF/web.xml)

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">

<servlet>

<servlet-name>StudentServlet</servlet-name>

36
Lab Manual: Java Lab Department of CSE-
AIML

<servlet-class>StudentServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>StudentServlet</servlet-name>

<url-pattern>/register</url-pattern>

</servlet-mapping>

</web-app>

How to Deploy

1. Compile the servlet:

javac -classpath /path/to/tomcat/lib/servlet-api.jar StudentServlet.java

2. Place StudentServlet.class in:

StudentRegistrationApp/WEB-INF/classes/

3. Deploy the whole StudentRegistrationApp directory to tomcat/webapps/.


4. Start Tomcat.

5. Access the form in browser:

http://localhost:8080/StudentRegistrationApp/register.html

OUTPUT:

- Basic Servlet handling of POST data


- Session management with HttpSession

- Form submission & dynamic response

37
Lab Manual: Java Lab Department of CSE-
AIML

LIST OF VIVA QUESTIONS

1) What is difference between JDK, JRE and JVM?

JVM

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the
runtime environment in which java byte code can be executed.

JVMs are available for many hardware and software platforms (so JVM is plate form
dependent).

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM and physically
exists.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools.

2) How many types of memory areas are allocated by JVM?

Many types:

3. Class(Method) Area
4. Heap
5. Stack
6. Program Counter Register
7. Native Method Stack

3) What is JIT compiler?

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the
byte code that have similar functionality at the same time, and hence reduces the amount of
time needed for compilation. Here the term “compiler” refers to a translator from the
instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

38
Lab Manual: Java Lab Department of CSE-
AIML

4) What is platform?

A platform is basically the hardware or software environment in which a program runs. There
are two types of platforms software-based and hardware-based. Java provides software-based
platform.

5) What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

6) What gives Java its 'write once and run anywhere' nature?

The bytecode. Java is compiled to be a byte code which is the intermediate language between
source code and machine code. This byte code is not platform specific and hence can be fed to
any platform.

7) What is classloader?

The classloader is a subsystem of JVM that is used to load classes and interfaces.There are
many types of classloaders e.g. Bootstrap classloader, Extension classloader, System
classloader, Plugin classloader etc.

8) Is Empty .java file name a valid source file name?

Yes, save your java file by .java only, compile it by javac .java and run by java
yourclassname Let's take a simple example:

//save by .java only


class A{
public static void main(String args[]){
System.out.println("Hello java");
}
}
//compile by javac .java
//run by java A

compile it by javac .java

run it by java A

9) Is delete,next,main,exit or null keyword in java?

No.

39
Lab Manual: Java Lab Department of CSE-
AIML

10) If I don't provide any arguments on the command line, then the String array of Main
method will be empty or null?

It is empty. But not null.

11) What if I write static public void instead of public static void?

Program compiles and runs properly.

12) What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object
references.

Core Java - OOPs Concepts: Initial OOPs Viva Questions

There is given more than 50 OOPs (Object-Oriented Programming and System) Viva
questions. But they have been categorized in many sections such as constructor Viva
questions, static Viva questions, Inheritance Viva questions, Abstraction Viva question,
Polymorphism Viva questions etc. for better understanding.

13) What is difference between object oriented programming language and object based
programming language?

Object based programming languages follow all the features of OOPs except Inheritance.
Examples of object based programming languages are JavaScript, VBScript etc.

14) What will be the initial value of an object reference which is defined as an instance
variable?

The object references are all initialized to null in Java.

Core Java - OOPs Concepts: Constructor Viva Questions

15) What is constructor?


 Constructor is just like a method that is used to initialize the state of an object. It is
invoked at the time of object creation.

16) What is the purpose of default constructor?


 The default constructor provides the default values to the objects. The java compiler
creates a default constructor only if there is no constructor in the class.

17) Does constructor return any value?

Ans:yes, that is current instance (You cannot use return type yet it returns a value).

18)Is constructor inherited?

No, constructor is not inherited.

40
Lab Manual: Java Lab Department of CSE-
AIML

19) Can you make a constructor final?

No, constructor can't be final.

Core Java - OOPs Concepts: static keyword Viva Questions

20) What is static variable?


 static variable is used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.
 static variable gets memory only once in class area at the time of class loading.

21) What is static method?


 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 static method can access static data member and can change the value of it.

22) Why main method is static?

because object is not required to call static method if It were non-static method,jvm creates
object first then call main() method that will lead to the problem of extra memory allocation.

23) What is static block?


 Is used to initialize the static data member.
 It is executed before main method at the time of class loading.

24) Can we execute a program without main() method?

Ans) Yes, one of the way is static block.

25) What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

26) What is difference between static (class) method and instance method?
static or class method instance method
1)A method i.e. declared as static is known as static method. A method i.e. not
declared as static is
known as instance
method.

2)Object is not required to call static method. Object is required


to call instance
methods.

3)Non-static (instance) members cannot be accessed in static static and non-static


context (static method, static block and static nested class) variables both can

41
Lab Manual: Java Lab Department of CSE-
AIML

directly. be accessed in
instance methods.

4)For example: public static int cube(int n){ return n*n*n;} For example:
public void msg()
{...}.

Core Java - OOPs Concepts: Inheritance Viva Questions

27) What is this in java?

It is a keyword that that refers to the current object.

28) What is Inheritance?

Inheritance is a mechanism in which one object acquires all the properties and behavior of
another object of another class. It represents IS-A relationship. It is used for Code Reusability
and Method Overriding.

29) Which class is the superclass for every class.

Object class.

30) Why multiple inheritances is not supported in java?


 To reduce the complexity and simplify the language, multiple inheritances is not
supported in java in case of class.

42
Lab Manual: Java Lab Department of CSE-
AIML

Signature

Prof. Sandeep Piplotia

43

You might also like