MVJ22IS42-Advanced Java-LAB MANUAL
MVJ22IS42-Advanced Java-LAB MANUAL
and NAAC)
IV SEMESTER
ACADEMIC YEAR 2024–2025 [EVEN]
ADVANCED JAVA LABORATORY
MVJ22IS42
LABORATORY MANUAL
NAM E OF THE STUDENT :
BRANCH :
BATCH :
MVJ22IS42-Advanced Java Lab manual
Institute Vision
To become an institute of academic excellence with international standards.
Institute Mission
Impart quality education along with industry exposure.
Provide world class facilities to undertake research activities relevant to
industrial and professional needs.
Promote entrepreneurship and value added education that is socially
relevant with economic benefits
Department Vision
To be recognized as a department of repute in Information Science and Engineering by adopting
quality teaching learning process and impart knowledge to make students equipped with capabilities
required for professional, industrial and research areas to serve society.
Department Mission
Innovation and technically competent: To impart quality education in Information Science and
Engineering by adopting modern teaching learning processes using innovation techniques that
enable them to become technically competent.
Competitive Software Professionals: Providing training Programs that bridges gap between
industry and academia, to produce competitive software professionals.
Personal and Professional growth: To provide scholarly environment that enables value
addition to staff and students to achieve personal and profession growth.
10 A Java program to create and read the cookie for the given cookie name as
“EMPID” and its value as “AN2356”.
11 A program to design the Login page and validating the USER_ID and
PASSWORD using JSP and DataBase.
Lab Experiments
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.
Source Code:
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: "+al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: "+al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove("A2");
System.out.println("Size of al after deletions: "+al.size());
System.out.println("Contents of al: " + al);
Collections.sort(al);
System.out.println("Contents of al: " + al);
}
}
Output:
C:\Advanced Java4thSemLab\executedprograms>javac ArrayListDemo.java
C:\Advanced Java4thSemLab\executedprograms>java ArrayListDemo
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A, E, B, D]
Contents of al: [A, B, C, D, E]
import java.util.*;
class ArrayListToArray
{
public static void main(String args[])
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
al.add(3);
al.add(4);
System.out.println("Contents of al: " + al);
Integer ia[] = new Integer[al.size()];
ia = al.toArray(ia);
int sum = 0;
for(int i : ia)
sum += i;
System.out.println("Sum is: " + sum);
}
}
Output:
C:\Advanced Java4thSemLab\executedprograms>javac ArrayListToArray.java
C:\Advanced Java4thSemLab\executedprograms>java ArrayListToArray
Contents of al: [1, 2, 3, 4]
Sum is: 10
2. Implement a java program to illustrate the use of comparator
Source Code:
import java.util.*;
class MyComp implements Comparator<String>
{
public int compare(String a, String b)
{
String aStr, bStr;
aStr = a;
bStr = b;
return bStr.compareTo(aStr);
}
}
class CompDemo
{
public static void main(String args[])
{
TreeSet<String> ts = new TreeSet<String>(new MyComp());
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
for(String element : ts)
System.out.print(element + " ");
System.out.println();
}
}
Output:
C:\Advanced Java4thSemLab\executedprograms>javac CompDemo.java
C:\Advanced Java4thSemLab\executedprograms>java CompDemo
FEDCBA
import java.util.*;
class Address
{
private String name;
private String street;
private String city;
private String state;
private String code;
Address(String n, String s, String c,String st, String cd)
{
name = n;
street = s;
city = c;
state = st;
code = cd;
}
public String toString()
{
return name + "\n" + street + "\n" +city + " " + state + " " + code;
}
}
class MailList
{
public static void main(String args[])
{
LinkedList<Address> ml = new LinkedList<Address>();
ml.add(new Address("J.W. West", "11 Oak Ave","Urbana", "IL", "61801"));
ml.add(new Address("Ralph Baker", "1142 Maple Lane","Mahomet", "IL", "61853"));
ml.add(new Address("Tom Carlton", "867 Elm St","Champaign", "IL", "61820"));
Output:
C:\Advanced Java4thSemLab\executedprograms>javac StringConstructorDemo.java
C:\Advanced Java4thSemLab\executedprograms>java StringConstructorDemo
Hello Java
science
wind
abcd
CDEF
BC
5. Implement a java program to illustrate the use of different types of character extraction,
string comparison, string search and string modification methods.
Source Code:
/* String Methods
Character Extraction:
1.charAt( )
2.getChars( )
3.getBytes( )
4.toCharArray( )
String Comparison
1.equals( ) and equalsIgnoreCase( )
2.regionMatches( )
3.startsWith( ) and endsWith( )
4.equals( ) Versus ==
5.compareTo( )
Searching Strings
1.indexOf( ) and lastIndexOf( )
Modifying a String
1.substring( )
2.replace( )
3.trim( )
*/
/* 1.charAt( ) */
class CharStringDemo
{
public static void main(String args[])
{
char ch;
ch = "abc".charAt(1);
System.out.println(ch);
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java CharStringDemo
b
*/
/*2.getChars( )*/
class getCharsDemo
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java getCharsDemo
demo
*/
/*3.getBytes( )*/
class StringGetBytesExample
{
public static void main(String args[])
{
String s1="ABCDEFG";
byte[] barr=s1.getBytes();
for(int i=0;i<barr.length;i++)
{
System.out.println(barr[i]);
}
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java StringGetBytesExample
65
66
67
68
69
70
71
*/
/*4.toCharArray( )*/
class StringDemo
{
public static void main(String[] args)
{
String str = " Java was developed by James Gosling";
char retval[] = str.toCharArray();
System.out.println("Converted value to character array = ");
System.out.println(retval);
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java StringDemo
Converted value to character array =
Java was developed by James Gosling
*/
/*
String Comparison
1.equals( ) and equalsIgnoreCase( )
*/
class equalsDemo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +s1.equalsIgnoreCase(s4));
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java equalsDemo
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
*/
/*
2.regionMatches( )
*/
class Main {
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java Main
str1 and str2 region matches: true
str1 and str3 region matches: false
*/
/*
3.startsWith( ) and endsWith( )
*/
class Demo
{
/*
Searching Strings
1.indexOf( ) and lastIndexOf( )
*/
class indexOfDemo
{
public static void main(String args[])
{
String s = "Now is the time for all good men " +"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = "+s.indexOf('t'));
System.out.println("lastIndexOf(t) = "+s.lastIndexOf('t'));
System.out.println("indexOf(the) = "+s.indexOf("the"));
System.out.println("lastIndexOf(the) = "+s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = "+s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = "+s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = "+s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = "+s.lastIndexOf("the", 60));
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java indexOfDemo
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
*/
/*
Modifying a String
1.substring( )
*/
class TestSubstring
{
public static void main(String args[])
{
String s="SachinTendulkar";
System.out.println("Original String: "+ s);
System.out.println("Substring starting from index 6: "+s.substring(6));
System.out.println("Substring starting from index 0 to 6:"+s.substring(0,6));
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java TestSubstring
Original String: SachinTendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6:Sachin
*/
/*
2.replace( )
*/
class Main1 {
public static void main(String[] args) {
String str1 = "bat ball";
// replace b with c
System.out.println(str1.replace('b', 'c'));
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java Main1
cat call
*/
/*
3.trim( )
*/
class Main2
{
public static void main(String[] args) {
String myStr = " Hello World! ";
System.out.println(myStr);
System.out.println(myStr.trim());
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java Main2
Hello World!
Hello World!
*/
6. Implement a java program to illustrate the use of different types of StringBuffer methods
Source Code:
/*
StringBuffer
1.length( ) and capacity( )
2.ensureCapacity( ) and setLength( )
3.charAt( ) and setCharAt( )
4.append( )
5.insert( )
6.reverse( )
7.delete( ) and deleteCharAt( )
8.replace( )
9.substring( )
*/
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java StringBufferDemo
buffer = Hello
length = 5
capacity = 21
*/
/* 2.ensureCapacity( ) and setLength( ) */
class ensureCapacityDemo
{
public static void main(String[] args)
{
StringBuffer str= new StringBuffer("MVJCE ISE");
System.out.println("Before ensureCapacity "+"method capacity = "+ str.capacity());
str.ensureCapacity(42);
System.out.println("After ensureCapacity"+"method capacity = "+ str.capacity());
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java ensureCapacityDemo
Before ensureCapacity method capacity = 25
After ensureCapacitymethod capacity = 52
*/
class JavaExample
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("BeginnersBook");
System.out.println("Old Sequence: "+sb);
System.out.println("Old length: "+sb.length());
sb.setLength(21);
System.out.println("New Sequence: "+sb);
System.out.println("New length: "+sb.length());
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java JavaExample
Old Sequence: BeginnersBook
Old length: 13
New Sequence: BeginnersBook
New length: 21
*/
/*3.charAt( ) and setCharAt( )*/
class setCharAtDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java setCharAtDemo
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
*/
/*4.append( )*/
class appendDemo
{
public static void main(String args[])
{
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java appendDemo
a = 42!
*/
/*5.insert( )*/
class insertDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java insertDemo
I like Java!
*/
/*6.reverse( )*/
class ReverseDemo
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java ReverseDemo
abcdef
fedcba
*/
/*7.delete( ) and deleteCharAt( )*/
class deleteDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java deleteDemo
After delete: This a test.
After deleteCharAt: his a test.
*/
/*8.replace( )*/
class replaceDemo
{
public static void main(String args[])
{
jbtnAlpha.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jlab.setText("Alpha was pressed.");
}
});
jbtnBeta.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jlab.setText("Beta was pressed.");
}
});
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
jlab = new JLabel("Press a button.");
jfrm.add(jlab);
jfrm.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new EventDemo();
}
});
}
}
/*
OUTPUT:
*/
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("/HelloServlet1")
public class HelloServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloServlet1() {
doGet(request, response);
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="Form1" method="post" action="HelloServlet">
<input type="textbox" name="t1" size="25" value="">
<input type=submit value="Submit">
</form>
</body>
</html>
/*
OUTPUT:
*/
9. A servlet program to display the name, USN, and total marks by accepting
student detail
Source Code:
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("/StudentServlet")
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentServlet() {
String snm,sclass;
float per;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
sno=Integer.parseInt(req.getParameter("txtsno"));
snm=req.getParameter("txtnm");
sclass=req.getParameter("txtclass");
s1=Integer.parseInt(req.getParameter("txtsub1"));
s2=Integer.parseInt(req.getParameter("txtsub2"));
s3=Integer.parseInt(req.getParameter("txtsub3"));
total=s1+s2+s3;
per=(total/3);
out.println("<html><body>");
out.print("<h2>Result of student</h2><br>");
out.println("<b><i>Roll No :</b></i>"+sno+"<br>");
out.println("<b><i>Name :</b></i>"+snm+"<br>");
out.println("<b><i>Class :</b></i>"+sclass+"<br>");
out.println("<b><i>Subject1:</b></i>"+s1+"<br>");
out.println("<b><i>Subject2:</b></i>"+s2+"<br>");
out.println("<b><i>Subject3:</b></i>"+s3+"<br>");
out.println("<b><i>Total :</b></i>"+total+"<br>");
out.println("<b><i>Percentage :</b></i>"+per+"<br>");
if(per<50)
out.println("<h1><i>Pass Class</i></h1>");
else if(per<55 && per>50)
out.println("<h1><i>Second class</i></h1>");
else if(per<60 && per>=55)
out.println("<h1><i>Higher class</i></h1>");
out.close();
}
doGet(request, response);
}
NewFile.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="f1" method="Post" action="http://localhost:8089/StudentServlet/StudentServlet">
<legend><b><i>Enter Student Details :</i><b></legend>
Enter Roll No : <input type="text" name="txtsno"><br><br>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/StudentServlet</url-pattern>
</servlet-mapping>
</web-app>
/*
OUTPUT:
*/
10. A Java program to create and read the cookie for the given cookie name as
“EMPID” and its value as “AN2356”.
Source Code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/GetCookiesServlet")
public class GetCookiesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetCookiesServlet() {
doGet(request, response);
}
}
/*
OUTPUT:
*/
11. A program to design the Login page and validating the USER_ID and
PASSWORD using JSP and DataBase.
Source Code:
NewFile.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Login.jsp" method="post">
User name :<input type="text" name="userid" /><br><br> password :<input
type="password" name="password" /><br> <br><input type="submit" />
</form>
<p>
New user. <a href="register.html">Login Here</a>
</p>
</body>
</html>
Login.jsp
<%@ page language="java" contentType="text/html charset=ISO-8859-1" pageEncoding="ISO-8859-
1"%>
<%@ page import="java.sql.*,java.util.*,java.io.*"%>
<%
PrintWriter pw=response.getWriter();
String u= request.getParameter("userid");
String p= request.getParameter("password");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","admin");
PreparedStatement ps=con.prepareStatement("select userid from users where userid=? and password=?");
ps.setString(1,u);
ps.setString(2,p);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
pw.println("<font color=red size=16>Login Success</font>");
}
else
{
pw.println("<font color=red size=16>Login Failed</font>");
pw.println("<a href=Login.jsp>Try Again</a>");
}
}
catch(Exception e){
System.out.println(e);
}
%>
CREATE TABLE users (
userid varchar(45),
password varchar(45)
7 );
SQL> insert into users values('venky','venky');
SQL> select * from users;
/*
OUTPUT:
*/
MVJ COLLEGE OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING
Don'ts
1. Do not use mobile phone inside the lab.
2. Don't do anything that can make the LAB dirty (like, eating, throwing waste papers etc).
3. Do not carry any external devices without permission.
4. Don't move the chairs of the LAB.
5. Don't interchange any part of one computer with another.
6. Don't leave the computers of the LAB turned on while leaving the LAB.
7. Do not install or download any software or modify or delete any system files on any lab
computers.
8. Do not damage, remove, or disconnect any labels, parts, cables, or equipment.
9. Don't attempt to bypass the computer security system.
10. Do not read or modify other users' files.
11. If you leave the lab, do not leave your personal belongings unattended. We are not
responsible for any theft.