Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

MVJ22IS42-Advanced Java-LAB MANUAL

The document is a laboratory manual for the Advanced Java Laboratory course for the Department of Information Science and Engineering at MVJ College of Engineering for the academic year 2024-2025. It outlines the institute's vision and mission, program outcomes, educational objectives, and specific outcomes, along with a series of experiments and their corresponding source codes for students to complete. The manual emphasizes the development of practical skills in Java programming, including the use of collections, string operations, and web applications.

Uploaded by

nareshm3225
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

MVJ22IS42-Advanced Java-LAB MANUAL

The document is a laboratory manual for the Advanced Java Laboratory course for the Department of Information Science and Engineering at MVJ College of Engineering for the academic year 2024-2025. It outlines the institute's vision and mission, program outcomes, educational objectives, and specific outcomes, along with a series of experiments and their corresponding source codes for students to complete. The manual emphasizes the development of practical skills in Java programming, including the use of collections, string operations, and web applications.

Uploaded by

nareshm3225
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

(Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA

and NAAC)

DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING


ACCREDITED BY NBA

IV SEMESTER
ACADEMIC YEAR 2024–2025 [EVEN]
ADVANCED JAVA LABORATORY

MVJ22IS42
LABORATORY MANUAL
NAM E OF THE STUDENT :

BRANCH :

UNIVERSITY SEAT NO. :

SEMESTER & SECTION :

BATCH :
MVJ22IS42-Advanced Java Lab manual

Department of Information Science and Engineering

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.

Program Outcomes (PO):


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.

Dept of ISE, MVJCE Page 2 2024-2025


MVJ22IS42-Advanced Java Lab manual

4. Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

Program Educational Objectives (PEOs):


 IT Proficiency: Graduates will excel as IT Experts with extensive knowledge to analyze and design
solutions to Information Engineering problems.
 Social &moral principles: Graduates will work in a team, showcase professionalism; ethical values
expose themselves to current trends and become responsible Engineers.
 Higher education: Graduates will pursue higher studies with the sound knowledge of fundamental
concepts and skills in basic sciences and IT disciplines.

Program Specific Outcomes (PSO):


PSO1. Software professional expertise: An ability to understand, analyze and develop
computer programs in the areas related to algorithms, system software, multimedia, web
design, DBMS, and networking for efficient design of computer-based systems of
varying complexity.
PSO2. Core competence: An ability to compete practically to provide solutions for real world
problems with a broad range of programming language and open source platforms in
various computing domains

Course outcomes (CO):


On the completion of this laboratory course, the students will be able to:
 Apply appropriate collection class/interface to solve the given problem
 Demonstrate the concepts of String operations in Java

Dept of ISE, MVJCE Page 3 2024-2025


MVJ22IS42-Advanced Java Lab manual

 Apply the concepts of Swings to build Java applications


 Develop web based applications using Java servlets and JSP
 Use JDBC to build database applications

ADVANCED JAVA LABORATORY


SEMESTER – IV
Laboratory Code: MVJ22IS42 IA Marks: 50
Exam Marks: 50 Exam Hours: 03

S.no Experiment Name


Implement a java program to demonstrate creating an ArrayList, adding elements,
1 removing elements,sorting elements of ArrayList. Also illustrate the use of
toArray() method.
2 Implement a java program to illustrate the use of comparator.
3 Implement a java program to illustrate storing user defined classes in collection.
Implement a java program to illustrate the use of different types of string class
4
constructors

5 Implement a java program to illustrate the use of different types of character


extraction, string comparison, string search and string modification methods.
Implement a java program to illustrate the use of different types of StringBuffer
6
methods.
Demonstrate a swing event handling application that creates 2 buttons Alpha and
7 Beta and displays the text “Alpha pressed” when alpha button is clicked and “Beta
pressed” when beta button is clicked.
8 A program to display greeting message on the browser “Hello UserName”, “How
Are You?”, accept username from the client using servlet.
A servlet program to display the name, USN, and total marks by accepting student
9
detail

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.

Dept of ISE, MVJCE Page 4 2024-2025


MVJ22IS42-Advanced Java Lab manual

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]

Dept of ISE, MVJCE Page 5 2024-2025


MVJ22IS42-Advanced Java Lab manual

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");

Dept of ISE, MVJCE Page 6 2024-2025


MVJ22IS42-Advanced Java Lab manual

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

3. Implement a java program to illustrate storing user defined classes in collection.


Source Code:

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"));

Dept of ISE, MVJCE Page 7 2024-2025


MVJ22IS42-Advanced Java Lab manual

for(Address element : ml)


System.out.println(element + "\n");
System.out.println();
}
}
Output:

C:\Advanced Java4thSemLab\executedprograms>javac MailList.java


C:\Advanced Java4thSemLab\executedprograms>java MailList
J.W. West
11 Oak Ave
Urbana IL 61801
Ralph Baker
1142 Maple Lane
Mahomet IL 61853
Tom Carlton
867 Elm St
Champaign IL 61820
4. Implement a java program to illustrate the use of different types of string class
constructors.
Source Code:
/*
The most commonly used constructors of the String class are as follows:
String()
String(String str)
String(char chars[ ])
String(char chars[ ], int startIndex, int count)
String(byte byteArr[ ])
String(byte byteArr[ ], int startIndex, int count)
*/
public class StringConstructorDemo
{
public static void main(String[ ] args)
{
String s1 = new String();
System.out.println(s1);

String s2 = new String("Hello Java");


System.out.println(s2);

char chars1[] = {'s', 'c', 'i', 'e', 'n', 'c', 'e'};


String s3 = new String(chars1);
System.out.println(s3);

char chars2[] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' };

Dept of ISE, MVJCE Page 8 2024-2025


MVJ22IS42-Advanced Java Lab manual

String s4 = new String(chars2, 0,4);


System.out.println(s4);

byte b1[] = { 97, 98, 99, 100 };


String s5 = new String(b1);
System.out.println(s5);

byte b2[] = { 65, 66, 67, 68, 69, 70 };


String s6 = new String(b2, 2, 4);
System.out.println(s6);

int[] bytes = new int[] { 65, 66, 67, 68 };


System.out.println(new String(bytes, 1, 2));
}
}

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( )

Dept of ISE, MVJCE Page 9 2024-2025


MVJ22IS42-Advanced Java Lab manual

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();

Dept of ISE, MVJCE Page 10 2024-2025


MVJ22IS42-Advanced Java Lab manual

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[])
{

Dept of ISE, MVJCE Page 11 2024-2025


MVJ22IS42-Advanced Java Lab manual

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 {

public static void main(String args[]) {


String str1 = new String("This is regionMatches() example");
String str2 = new String("region");
String str3 = new String("world");

System.out.println("str1 and str2 region matches: " + str1.regionMatches(8, str2, 0, 6));

System.out.println("str1 and str3 region matches: " + str1.regionMatches(8, str3, 0, 6));

}
}
/*
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
{

Dept of ISE, MVJCE Page 12 2024-2025


MVJ22IS42-Advanced Java Lab manual

public static void main(String args[])


{
String myStr =" Foobar ";
System.out.println(myStr.endsWith("bar"));
System.out.println(myStr.startsWith("Foo"));
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java Demo
false
false
*/
/*
4.equals( ) Versus ==
*/
class EqualsNotEqualTo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java EqualsNotEqualTo
Hello equals Hello -> true
Hello == Hello -> false
*/
/*
5.compareTo( )
*/
class CompareToExample
{
public static void main(String args[])
{
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
Dept of ISE, MVJCE Page 13 2024-2025
MVJ22IS42-Advanced Java Lab manual

System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"


System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}
}
/*
OUTPUT:
C:\Users\User\Desktop\Venkatesh MVJCE\Advanced Java4thSemLab\executedprograms>java
CompareToExample
0
-5
-1
2
*/

/*
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

Dept of ISE, MVJCE Page 14 2024-2025


MVJ22IS42-Advanced Java Lab manual

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
*/

Dept of ISE, MVJCE Page 15 2024-2025


MVJ22IS42-Advanced Java Lab manual

/*
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

Dept of ISE, MVJCE Page 16 2024-2025


MVJ22IS42-Advanced Java Lab manual

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[])

Dept of ISE, MVJCE Page 17 2024-2025


MVJ22IS42-Advanced Java Lab manual

{
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);
}
}

Dept of ISE, MVJCE Page 18 2024-2025


MVJ22IS42-Advanced Java Lab manual

/*
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[])
{

Dept of ISE, MVJCE Page 19 2024-2025


MVJ22IS42-Advanced Java Lab manual

StringBuffer sb = new StringBuffer("This is a test.");


sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
/*
OUTPUT:
C:\Advanced Java4thSemLab\executedprograms>java replaceDemo
After replace: This was a test.
*/
/*9.substring( )*/
class Substr2
{
public static void main(String args[])
{
StringBuffer Str = new StringBuffer("Welcome to MVJCE ISE");

System.out.print("The extracted substring is : ");


System.out.println(Str.substring(10, 16));
}
}
/*
OUTPUT:
C:\Users\User\Desktop\Venkatesh MVJCE\Advanced Java4thSemLab\executedprograms>java
Substr2
The extracted substring is : MVJCE
*/
7. Demonstrate a swing event handling application that creates 2 buttons Alpha and Beta and
displays the text “Alpha pressed” when alpha button is clicked and “Beta pressed” when
beta button is clicked.
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo
{
JLabel jlab;
EventDemo()
{
JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");

Dept of ISE, MVJCE Page 20 2024-2025


MVJ22IS42-Advanced Java Lab manual

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:

Dept of ISE, MVJCE Page 21 2024-2025


MVJ22IS42-Advanced Java Lab manual

*/

8. A program to display greeting message on the browser “Hello UserName”,


“How Are You?”,accept username from the client using servlet.
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("/HelloServlet1")
public class HelloServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;

public HelloServlet1() {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.getWriter().append("Served at: ").append(request.getContextPath());


response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String msg=request.getParameter("t1");
pw.println("hello"+msg+"How are you");
pw.close();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

doGet(request, response);
}

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

Dept of ISE, MVJCE Page 22 2024-2025


MVJ22IS42-Advanced Java Lab manual

</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() {

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,


IOException {
int sno,s1,s2,s3,total;

Dept of ISE, MVJCE Page 23 2024-2025


MVJ22IS42-Advanced Java Lab manual

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();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

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>

Dept of ISE, MVJCE Page 24 2024-2025


MVJ22IS42-Advanced Java Lab manual

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


Enter class :<input type="text" name="txtclass"><br><br>
Enter Student Marks Details :
Subject 1 : <input type="text" name="txtsub1"><br><br>
Subject 2 :<input type="text" name="txtsub2"><br><br>
Subject 3 : <input type="text" name="txtsub3"><br><br>
<input type="submit" value="Result">
</div>
</form>
</body>
</html>

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:

Dept of ISE, MVJCE Page 25 2024-2025


MVJ22IS42-Advanced Java Lab manual

*/

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() {

Dept of ISE, MVJCE Page 26 2024-2025


MVJ22IS42-Advanced Java Lab manual

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();

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


response.addCookie(cookie);

Cookie[] cookies = request.getCookies();


for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name);
pw.println("value = " + value);
}
pw.close();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

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>

Dept of ISE, MVJCE Page 27 2024-2025


MVJ22IS42-Advanced Java Lab manual

<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 (

Dept of ISE, MVJCE Page 28 2024-2025


MVJ22IS42-Advanced Java Lab manual

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

DO'S AND DON'TS


Do's
1. Do wear ID card and follow dress code.
2. Do log off the computers when you finish.
Dept of ISE, MVJCE Page 29 2024-2025
MVJ22IS42-Advanced Java Lab manual

3. Do ask the staff for assistance if you need help.


4. Do keep your voice low when speaking to others in the LAB.
5. Do ask for assistance in downloading any software.
6. Do make suggestions as to how we can improve the LAB.
7. In case of any hardware related problem, ask LAB in charge for solution.
8. if you are the last one leaving the LAB, make sure that the staff in charge of the LAB is
informed to close the LAB.
9. Be on time to LAB sessions.
10. Do Keep the LAB as clean as possible

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.

Dept of ISE, MVJCE Page 30 2024-2025

You might also like