0% found this document useful (0 votes)
6 views

Java Laboratory

The document contains multiple Java programming exercises, including creating classes for vehicles, handling exceptions, implementing client-server communication, and using JDBC for database operations. Each program is accompanied by code snippets and expected output, demonstrating various programming concepts such as inheritance, exception handling, and web application development. The exercises cover a range of topics from basic object-oriented programming to advanced database connectivity and web technologies.
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)
6 views

Java Laboratory

The document contains multiple Java programming exercises, including creating classes for vehicles, handling exceptions, implementing client-server communication, and using JDBC for database operations. Each program is accompanied by code snippets and expected output, demonstrating various programming concepts such as inheritance, exception handling, and web application development. The exercises cover a range of topics from basic object-oriented programming to advanced database connectivity and web technologies.
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/ 19

Program - 1

Create a class Vehicle. The class should have two fields – no_of_seats, no_of_wheels
and a method showVehicle. Create two objects – motorcycle and car for this class.
Display the output to show the descriptions for car and motorcycle.
Code:

public class vehicle


{
int no_of_seats;
int no_of_wheels;
public vehicle(int numseats, int numwheels)
{
this.no_of_seats = numseats;
this.no_of_wheels = numwheels;
}
public void showVehicle()
{
System.out.println("Total Number of seats: " + no_of_seats);
System.out.println("Total Number of wheels: " + no_of_wheels);
}
public static void main(String[] args)
{
vehicle motorcycle = new vehicle(1,2);
vehicle car = new vehicle(4,4);
System.out.println("Details of Car:");
car.showVehicle();
System.out.println("Details of Motorcycle:");
motorcycle.showVehicle();
}
}

Output:
Details of Car:
Total Number of seats: 4
Total Number of wheels: 4
Details of Motorcycle:
Total Number of seats: 1
Total Number of wheels: 2
Program - 2
Write a program to make a package Balance which has Account class with display
method in it. Import Balance package in another program to access display method of
Account class to display account balance.
Code:
//Part-1 Package Creation
package balance;
import java.util.*;
public class Account
{
long acc,bal;
String name;
public void read()throws Exception
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name :");
name=in.nextLine();
System.out.println("Enter the account number :");
acc=Long.parseLong(in.nextLine());
System.out.println("Enter the account balance :");
bal=Long.parseLong(in.nextLine());
}
public void disp()
{
System.out.println("~~~~~~~~~~~~~~~~~");
System.out.println("--- Account Details ---");
System.out.println("~~~~~~~~~~~~~~~~~");
System.out.println("Name :"+name);
System.out.println("Account number :"+acc);
System.out.println("Balance :"+bal);
}
}
//Part – 2 Main Class
class BankBal
{
public static void main(String ar[])
{
try
{
balance.Account a=new balance.Account();
a.read(); //calling the method of Account class
a.disp();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

Output:
Enter the name:
Rithik K M
Enter the account number:
1235678429
Enter the account balance:
2987
~~~~~~~~~~~~~~~~~
----Account Details----
~~~~~~~~~~~~~~~~~
Name: Rithik K M
Account number 1235678429
Balance: 2987
Program - 3
Design a super class called Employee with details as EmployeeId, name, Phone,
Salary. Extend this class by writing three subclasses namely Teaching (domain,
publications), Technical (skills), and Contract (period). Write a JAVA program to read
and display at least 3 Employee objects of all three categories.
Code:
import java.util.*;
class Employee
{
String EmpID;
String Empname;
long EmpPhone;
float EmpSalary;
public void accept()
{
Scanner obj = new Scanner(System.in);
System.out.println("Enter Staff ID: ");
EmpID = obj.nextLine();
System.out.println("Enter Name: ");
Empname = obj.nextLine();
System.out.println("Enter Phone number: ");
EmpPhone = obj.nextLong();
System.out.println("Enter Salary: ");
EmpSalary = obj.nextFloat();
}
public void display()
{
System.out.println("Staff ID: " + EmpID);
System.out.println("Name: " + Empname);
System.out.println("Phone: " + EmpPhone);
System.out.println("Salary: " + EmpSalary);
}
}
class Teaching extends Employee
{
String domain;
int n;
public void accept()
{
super.accept();
Scanner obj = new Scanner(System.in);
System.out.println("Enter Domain:");
domain = obj.nextLine();
System.out.println("Enter number of Publications:");
n = obj.nextInt();
}
public void display()
{
super.display();
System.out.println("Doamin:" + domain);
System.out.println("Publications: " + n);
}
}
class Technical extends Employee
{
String skill;
public void accept()
{
super.accept();
Scanner obj = new Scanner(System.in);
System.out.println("Enter Technical Skills:");
skill = obj.nextLine();

}
public void display()
{
super.display();
System.out.println("Technical Skills: " + skill);
}
}
class Contract extends Employee
{
int period;
public void accept()
{
super.accept();
Scanner obj = new Scanner(System.in);
System.out.println("Enter Period:");
period = obj.nextInt();
}
public void display()
{
super.display();
System.out.println("Contract Period: " + period);
}
}
class EmployeeFour
{
public static void main(String[] args)
{
Teaching teach = new Teaching();
System.out.println("Enter the details of Teaching Staff:");
teach.accept();
Technical tech = new Technical();
System.out.println("Enter the details of Technical Staff:");
tech.accept();
Contract con = new Contract();
System.out.println("Enter the details of Contract Staff:");
con.accept();
System.out.println("The details of Teaching Staff:");
teach.display();
System.out.println("The details of Technical Staff:");
tech.display();
System.out.println("The details of Contract Staff:");
con.display();
}
}

Output:
Enter the details of Teaching Staff:
Enter Staff ID:
DS287
Enter Name:
Rahul M S
Enter Phone number:
7812356497
Enter Salary:
78567.89
Enter Domain:
Web Development
Enter number of Publications:
28

Enter the details of Technical Staff:


Enter Staff ID:
DS307
Enter Name:
Deepak Nayak
Enter Phone number:
8234156729
Enter Salary:
95532.56
Enter Technical Skills:
Machine Learning, Python and Java

Enter the details of Contract Staff:


Enter Staff ID:
Ds187
Enter Name:
Priya Hedge
Enter Phone number:
9234156987
Enter Salary:
89595
Enter Period:
5

The details of Teaching Staff:


Staff ID: DS287
Name: Rahul M S
Phone: 7812356497
Salary: 78567.89
Doamin: Web Development
Publications: 28

The details of Technical Staff:


Staff ID: DS307
Name: Deepak Nayak
Phone: 8234156729
Salary: 95532.56
Technical Skills: Machine Learning, Python and Java

The details of Contract Staff:


Staff ID: Ds187
Name: Priya Hedge
Phone: 9234156987
Salary: 89595.0
Contract Period: 5
Program – 4
Implement a JAVA program to read two integers a and b. Compute a/b and print, when
b is not zero. Raise an exception when b is equal to zero. Also demonstrate working of
ArrayIndexOutOfBoundException.

Code:
import java.util.Scanner;
class ExceptionDemo
{
public static void main(String[] args)
{
int a,b,result;
Scanner input =new Scanner(System.in);
System.out.println("Input two integers");
a=input.nextInt();
b=input.nextInt();
try
{
result=a/b;
System.out.println("Result = "+result);
}
catch(ArithmeticException e)
{
System.out.println("exception caught: Divide by zero
error"+e);
}
int array[]={2,3,4,5,6};
try
{
System.out.println("Input two integers"+array[5]);
}
catch(ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound"+e1);
}
Output:
}
Input two numbers:
}
30
Exception caught: Divide by zero error
Java.lang.ArithmeticException: / by zero
Array Index Out of Bound
Java.lang.ArrayIndexOutofBoundException:
5
Program – 5
Implement Java Program to Get the Components of any give URL such as
Protocol, file, port and host.

Code:
import java.net.URL;
public class URLMain
{
public static void main(String[] args)
{
try
{
URL url = new
URL("https://www.example.com/path/to/file.html?key=value#fra
gment");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("Path: " + url.getPath());
System.out.println("Query: " + url.getQuery());
System.out.println("Fragment: " + url.getRef());
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}

Output:
Protocol: https
Host: www.example.com
Port: -1
Path: /path/file.html
Query: key=value
Fragment: fragment
Program – 6
Implement client-server communication, where client can send the message and server
can receive the message without internet.

Code:
//Part-1 ServerSide.java
import java.io.*;
import java.net.*;
public class ServerSide
{
public static void main(String[]args)
{
try
{
ServerSocket ss=new ServerSocket(3306);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}

//Part-2 ClientSide.java
import java.io.*;
import java.net.*;
public class ClientSide
{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",3306);
DataOutputStreamdout=new
DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);}
}
}

Output:
Message = Hello Server
Program - 7
Implement JDBC program to insert and retrieve student (student_name, student_usn,
student_dept) record from student database.

Code:
//Part - 1 Insert Details
import java.sql.*;
import java.util.*;
public class InsertDetails
{
public static void main(String[] args)
{
String usn, name, dept;
Scanner obj = new Scanner(System.in);
System.out.println("Enter Student Name:");
name = obj.nextLine();
System.out.println("Enter Student USN:");
usn = obj.nextLine();
System.out.println("Enter Student Dept:");
dept = obj.nextLine();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/Student","root","root");
Statement stmt = con.createStatement();
String q1 = "insert into student values('"
+usn+"','"+name+"','"+dept+"')";
int x = stmt.executeUpdate(q1);
if(x>0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Enter Student Name:
Shreyas
Enter Student USN:
1DS22AI010
Enter Student Dept:
AIML
Successfully Inserted
Code:
//Part-2 Retrieve Details
import java.sql.*;
public class RetrieveDetails
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/Student","root","root");
Statement stmt = con.createStatement();
ResultSet rs= stmt.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getString(1)+"
"+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

1DS22IS073 Rithik ISE


1DS22EC044 Dhanya ECE
1DS22AI010 Shreyas AIML
Program – 8
Create web page authentication using JSP and JDBC connectivity (login
authentication) using session.

Code:
Login.html
<html>
<head>
<title>Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Login.jsp" method="post" id="styleform">
<h2>Login Authentication</h2><hr color="black"><br>
Username: <input type="text" name="user"/><br><br>
Password: <input type="password" name="pwd"/><br><br><br>
<input type="submit" value="Submit" id="stylesub"/>
</form>
</body>
</html>

Login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%String username = request.getParameter("user");
String pwd = request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/app","root","root");
Statement st= con.createStatement();
ResultSet rs= st.executeQuery("select * from login where
username='"+username+"'");
if(rs.next())
{if(rs.getString(2).equals(pwd)) {
session.setAttribute("user",rs.getString(1));
String name=(String)session.getAttribute("user");
out.println("Welcome "+ name);
}else
System.out.println("Invalid password try again");
}
%></body>
</html>

Output:
Program – 9
Structure the java servlet program to fetch the student details using JDBC.

Code:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

public class P9_DatabaseAccess extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL="jdbc:mysql://localhost/ise";
String USER = "root";
String PASS = "root";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT * from emp";
ResultSet rs = stmt.executeQuery(sql);
out.println("<table border=1>");
out.println("<tr><th>ID</th><th>Name</th><th>Age</th></tr>");
while(rs.next())
{
int id = rs.getInt(1);
String name = rs.getString(2);
String age = rs.getString(3);
out.println(
"<tr><td>"+id+"</td><td>"+name+"</td><td>"+age+
"</td></tr>");
out.println("<br>");
}
out.println("</body></html>");
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{
out.println(se);
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
out.println(e);
}
}
}

Output:
Program - 10
Develop a Servlet program to demonstrate hit counter.
Code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class P10_1HitCounter extends HttpServlet


{
private int hitcounter;
public void init()
{
hitcounter = 0;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type response.setContentType("text/html");
hitcounter++;
PrintWriter out = response.getWriter();
String title = "Total Number of Hits";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType + "<html>\n" +
"<head><title>" + title + "</title></head>\n"
+ "<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">" + hitcounter + "</h2>\n"
+ "</body> </html>"
);
}
public void destroy() {
// This is optional step but if you like you
// can write hitCount value in your database.
}
}
Output:

You might also like