Advanced JAVALabManual
Advanced JAVALabManual
Advanced JAVALabManual
AdvancedJAVA – BIS402
IS&EDept,JNNCE,Shivamogga.
AdvancedJAVA[BIS402] 2
SubjectCode:BIS402 CIEMarks:50
NumberofContactHours/Week:3:0:2:0 SEEMarks:50
Total Number of Lecture Hours: 40 – 08 – 10 Lab Slots ExamHours:03
CREDITS – 04
2. Develop a program to read random numbers between a given range that are multiples of
2 and 5, sort the numbers according to tens place using comparator.
4. Implement a java program to illustrate the use of different types of string class constructors.
5. Implement a java program to illustrate the use of different types of character extraction,
stringcomparison, string search and string modification methods.
6. Implement a java program to illustrate the use of different types of StringBuffer methods.
7.Demonstrate a swing event handling application that creates 2 buttons Alpha and Beta and
displays thetext “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?”,
acceptusername from the client using servlet.
9. A servlet program to display the name, USN, and total marks by accepting student detail.
10. A Java program to create and read the cookie for the given cookie name as “EMPID” and its
value as“AN2356”.
11. Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on
queries(For example update, delete, search etc…).
12. A program to design the Login page and validating the USER_ID and PASSWORD using
JSP andDataBase.
IS&EDept,JNNCE,Shivamogga.
AdvancedJAVA[BIS402] 3
packageJava4thSem;
importjava.util.ArrayList;
importjava.util.Collections;
publicclassArrayListExample {
publicstaticvoidmain(String[] args) {
// Creating ArrayList
ArrayList<String>arrayList = newArrayList<>();
// Adding elements
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Orange");
arrayList.add("Mango");
// Removing element
arrayList.remove("Orange");
System.out.println("ArrayList after removing element: " +
arrayList);
// Sorting elements
Collections.sort(arrayList);
System.out.println("ArrayList after sorting: " + arrayList);
IS&EDept,JNNCE,Shivamogga.
AdvancedJAVA[BIS402] 4
Output:
IS&EDept,JNNCE,Shivamogga.
AdvancedJAVA[BIS402] 5
/*2.Develop a program to read random numbers between a given range that are
multiples of 2 and 5, sortthe numbers according to tens place using
comparator.*/
packageJava4thSem;
importjava.util.*;
classTensPlaceComparatorimplements Comparator<Integer> {
publicintcompare(Integer num1, Integer num2) {
inttensPlace1 = (num1 % 100) / 10;
inttensPlace2 = (num2 % 100) / 10;
returntensPlace1 - tensPlace2;
}
}
publicclassRandomNumbersSort {
publicstaticvoidmain(String[] args) {
try (Scanner scan = newScanner(System.in)) {
System.out.print("Enter the lower bound of the
range: ");
intlowerBound = scan.nextInt();
Output:
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 10
packageJava4thSem;
importjava.util.ArrayList;
importjava.util.List;
class Person {
private String name;
privateintage;
publicintgetAge() {
returnage;
}
@Override
public String toString() {
return"Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
publicclassPersonCollection {
publicstaticvoidmain(String[] args) {
// Create instances of Person class
Person person1 = newPerson("Alice", 30);
Person person2 = newPerson("Bob", 25);
Person person3 = newPerson("Charlie", 35);
Output:
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 1
9
This program demonstrates the use of various constructors available in the String class:
packageJava4thSem;
publicclassStringConstructorsExample {
publicstaticvoidmain(String[] args) {
// Constructor 1: Create a String using a string literal
String str1 = "Hello, World!";
System.out.println("String created using string literal:"+ str1);
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 1
10
// Constructor 6: Create a String using bytes from a //portion of
a byte array
String str6 = newString(byteArray, 0, 3); // Start from
//index 0, length 3
System.out.println("String created using portion of byte array: "
+ str6);
}
}
Output:
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 1
11
Package Java4thSem;
// Substring Method
String substring = str.substring(7); // Start from index
//7 to end
System.out.println("Substring from index 7: " + substring);
Output:
First character: H
Last character: !
Substring from index 7: World!
Case-sensitive Comparison: false
Case-insensitive comparison: true
Contains 'World': true
Starts with 'Hello': true
Ends with 'World!': true
Replaced 'World' with 'Java': Hello, Java!
Uppercase string: HELLO, WORLD!
Lowercase string: hello, world!
Trimmed string: 'Trimmed String'
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 1
13
This program demonstrates the usage of various methods available in the StringBuffer class:
• append(String str): Appends the specified string to the end of the buffer.
• insert(int offset, String str): Inserts the specified string into the buffer at the specified
offset.
• delete(int start, int end): Deletes characters from the buffer between the specified start
and end indices.
• deleteCharAt(int index): Deletes the character at the specified index.
• replace(int start, int end, String str): Replaces characters in the buffer between the
specified start and end indices with the specified string.
• reverse(): Reverses the characters in the buffer.
• capacity(): Returns the current capacity of the buffer.
• length(): Returns the length (character count) of the buffer.
• setLength(int newLength): Sets the length of the buffer to the specified value.
• ensureCapacity(int minimumCapacity): Ensures that the capacity of the buffer is at least
equal to the specified minimum capacity.
• trimToSize(): Reduces the capacity of the buffer to match its length.
• toString(): Converts the buffer to a string.
Package Java4thSem;
// Append method
stringBuffer.append(" World");
System.out.println("After append: " + stringBuffer);
System.out.println("hashcode of string buffer at first
stage:"+ stringBuffer.hashCode());
// Insert method
stringBuffer.insert(5, ", Java");
System.out.println("After insert: " + stringBuffer);
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 1
14
// Delete method
stringBuffer.delete(5, 11); // Deletes ", Java"
System.out.println("After delete: " + stringBuffer);
// DeleteCharAt method
stringBuffer.deleteCharAt(0); // Deletes 'H'
System.out.println("After deleteCharAt: " + stringBuffer);
// Replace method
stringBuffer.replace(0, 5, "Hi ");
System.out.println("After replace: " + stringBuffer);
// Reverse method
stringBuffer.reverse();
System.out.println("After reverse: " + stringBuffer);
// SetLength method
stringBuffer.setLength(5);
System.out.println("After setLength: " + stringBuffer);
// EnsureCapacity method
stringBuffer.ensureCapacity(18);
System.out.println("After ensureCapacity: " +
stringBuffer.capacity());
// TrimToSize method
stringBuffer.trimToSize();
System.out.println("After trimToSize: " +
stringBuffer.capacity());
System.out.println("hashcode of string buffer: "+
stringBuffer.hashCode() );
// toString method
String str = stringBuffer.toString();
System.out.println("String representation: " + str);
System.out.println("hashcode of string: "+ str.hashCode() );
}
}
Output:
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 1
15
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
1
packageJava4thSem;
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
publicclassButtonEventHandlingExample {
publicstaticvoidmain(String[] args) {
// Create a JFrame
JFrameframe = newJFrame("Button Event Handling Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JPanel
JPanelpanel = newJPanel();
frame.add(panel);
Output:
Initial Window:
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
3
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
4
packageJava3rdSem;
//Outerclass
classOuterClass{
//Displayfunctionintheouterclass
voiddisplay(){
System.out.println("OuterClassdisplaymethod");
}
//Innerclass
classInner{
//Displayfunctionintheinnerclass
voiddisplay(){
System.out.println("Innerdisplaymethod");
}
}//InnerClassEnds..
}//OuterClassEnds..
//Mainclass
publicclassMainClass{
publicstaticvoidmain(String[] args){
//Createaninstanceoftheouterclass
OuterClassouter = new OuterClass();
//Callthedisplaymethodoftheouterclass outer.display();
// Create an instance of the inner class
OuterClass.Innerinner=outer.newInner();
//Callthedisplaymethodoftheinnerclass inner.display();
}
}
Output:
OuterClassdisplaymethod
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
5
regardlessofwhetheranexceptionisthrownor not.
packageJava3rdSem;
//CustomexceptionforDivisionByZero
classDivisionByZeroExceptionextendsException{
publicDivisionByZeroException(Stringmessage){
super(message);
}
}
//Mainclass
publicclassDisionByZeroExample{
//Methodthatperformsdivisionandthrowsthecustom exception
if division by zero is attempted
staticdoubledivide(intnumerator,intdenominator)
throwsDivisionByZeroException{
if(denominator==0){
thrownewDivisionByZeroException("Divisionby zero
is not allowed");
}
return(double)numerator/denominator;
}
publicstaticvoidmain(String[] args){
intnumerator =10;
intdenominator=0;
try{
//Attemptthedivisionthatmaythrowthecustom
exception
doubleresult=divide(numerator,denominator);
System.out.println("Resultofdivision:"+
result);
}catch(DivisionByZeroExceptione){
// Catch the custom exception and handle it
System.err.println("Error:"+e.getMessage());
}finally {
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
6
//Codethatwillbeexecutedwhetheran
exception is thrown or not
System.out.println("Finallyblockexecuted");
}
}
}
Output:
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
7
/*10.DevelopaJAVAprogramtocreateapackagenamedmypackandimport& implement it
in a suitable class. */
packagemypack;
publicclassMyPackageClass{
public void displayMessage() {
System.out.println("HellofromMyPackageClass!");
}
}
2. Createaclassoutsidethepackage: CreateanotherJavafilenamed
outsidethe mypack package. This class will import and use MyPackageClass: MainClass.java
packageJava3rdSem;
importmypack.MyPackageClass;
publicclassMainClass_1{
publicstaticvoidmain(String[] args){
//CreateaninstanceofMyPackageClassMyPackageClassmyP
ackageObject= new
MyPackageClass();
//CallthedisplayMessagemethodfrom MyPackageClass
myPackageObject.displayMessage();
}
}
Output:
HellofromMyPackageClass!
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
8
Whenyourunthisprogram,you'lllikelyseeinterleavedoutputfromboththreads,asthey run
concurrentlyand independently. Keep in mind that the actual order of execution may vary
due to the nature of thread scheduling.
packageJava3rdSem;
classMyRunnableimplementsRunnable{
publicvoidrun(){
try{
System.out.println(Thread.currentThread().getName()+"is
running.");
//Sleepfor500milliseconds Thread.sleep(500);
System.out.println(Thread.currentThread().getName()+"is
done.");
}catch(InterruptedExceptione){
System.out.println(Thread.currentThread().getName()+"
was interrupted.");
}
}
}
publicclassRunnableThreadExample{
publicstaticvoidmain(String[] args){
//CreatetwoinstancesofMyRunnable
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
9
MyRunnablemyRunnable1=newMyRunnable();
MyRunnablemyRunnable2 =newMyRunnable();
//Createtwothreadsandassociatethemwiththe
MyRunnable instances
Threadthread1=newThread(myRunnable1,"Thread
1");
Threadthread2=newThread(myRunnable2,"Thread
2");
//Startthethreads
thread1.start();
thread2.start();
}
Output:
Thread 1 is running.
Thread2isrunning.
Thread 1 is done.
Thread2isdone.
//CanincreasetheTimeDelay,toslowexecutionofThread.
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
10
packageJava3rdSem;
classMyThreadextendsThread{
//ConstructorofMyThreadclass
publicMyThread(StringthreadName){
//Callthebaseclassconstructorusingsuper
super(threadName);
//Startthethread
start();
}
System.out.println(Thread.currentThread().getName()+"-
Count: " + i);
Thread.sleep(500);//Sleepfor500
milliseconds
}
}catch(InterruptedExceptione){
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
11
System.out.println(Thread.currentThread().getName()+"
was interrupted.");
}
}
}
publicclassThreadExample{
publicstaticvoidmain(String[] args){
//CreateaninstanceofMyThread
MyThreadmyThread=newMyThread("Child Thread");
//Themainthreadcontinuesitsexecution concurrently
with the child thread
try{
for(inti=0; i<5; i++){
System.out.println(Thread.currentThread().getName()+"-
Count: " + i);
Thread.sleep(1000);//Sleepfor1000
milliseconds
}
}catch(InterruptedExceptione){
System.out.println(Thread.currentThread().getName()+"
was interrupted.");
}
//Themainthreadcompletes,butthechildthread may
still be running
}
}
Output:
main-Count:0
Child Thread - Count: 0
Child Thread - Count: 1
main - Count: 1
Child Thread - Count: 2
Child Thread - Count: 3
main - Count: 2
Child Thread - Count: 4
main - Count: 3
main-Count:4
IS&EDept,JNNCE,Shivamogga.
ObjectOrientedProgrammingwithJAVA[BCSL305] 2
12
IS&EDept,JNNCE,Shivamogga.