0% found this document useful (0 votes)
3 views18 pages

Advance Jab Lab Programs

The document outlines several Java programs demonstrating various concepts such as ArrayLists, custom comparators, user-defined classes, string manipulation, StringBuffer methods, and Swing event handling. Each program includes code snippets that illustrate the implementation of these concepts, along with expected outputs. The programs are designed for an advanced Java course (BIS402) taught by Prof. Arun K H at AIT.

Uploaded by

dilipbgp1941
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)
3 views18 pages

Advance Jab Lab Programs

The document outlines several Java programs demonstrating various concepts such as ArrayLists, custom comparators, user-defined classes, string manipulation, StringBuffer methods, and Swing event handling. Each program includes code snippets that illustrate the implementation of these concepts, along with expected outputs. The programs are designed for an advanced Java course (BIS402) taught by Prof. Arun K H at AIT.

Uploaded by

dilipbgp1941
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/ 18

Advanced Java (BIS402)

Program 1: Implement a java program to demonstrate creating an ArrayList, adding


elements, removing elements, sorting elements of ArrayList. Also illustrate the use of the
toArray() method.

import java.util.*;
public class ArrayListDemo {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> fruits = new ArrayList<>();

// Adding elements
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Banana");
fruits.add("Grapes");

System.out.println("Initial ArrayList: " + fruits);

// Removing an element
fruits.remove("Banana");
System.out.println("After removing Banana: " + fruits);

// Sorting the ArrayList


Collections.sort(fruits);
System.out.println("Sorted ArrayList: " + fruits);

// Using toArray() method


String[] fruitArray = fruits.toArray(new String[0]);
System.out.println("Array elements: " + Arrays.toString(fruitArray));
}
}

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 1


Advanced Java (BIS402)

Program 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 a comparator.

import java.util.*;
// Custom Comparator to sort based on the tens place
class TensPlaceComparator implements Comparator<Integer> {
public int compare(Integer num1, Integer num2) {
int tensPlace1 = (num1 / 10) % 10;
int tensPlace2 = (num2 / 10) % 10;
return Integer.compare(tensPlace1, tensPlace2);
}
}

public class RandomNumberSorter {


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

// Input range
System.out.print("Enter the lower bound of the range: ");
int lowerBound = scanner.nextInt();
System.out.print("Enter the upper bound of the range: ");
int upperBound = scanner.nextInt();

// Generate random numbers that are multiples of 2 and 5


List<Integer> numbers = new ArrayList<>();
Random random = new Random();

for (int i = 0; i < 20; i++) {


int num;
do {
num = random.nextInt(upperBound - lowerBound + 1) + lowerBound;

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 2


Advanced Java (BIS402)

} while (num % 2 != 0 || num % 5 != 0);


numbers.add(num);
}

System.out.println("Generated Numbers: " + numbers);

// Sort using custom comparator


Collections.sort(numbers, new TensPlaceComparator());
System.out.println("Sorted based on Tens Place: " + numbers);
}
}

Program 3: Implement a java program to illustrate storing user defined classes in


collection.

import java.util.*;
//User-defined class
class Student {
private int id;
private String name;
private double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
public String toString() {
return "Student{ID=" + id + ", Name='" + name + "', Grade=" + grade + "}";
}
}

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 3


Advanced Java (BIS402)

public class Main1 {


public static void main(String[] args) {
// Creating a collection to store user-defined objects
List<Student> s = new ArrayList<>();
// Adding Student objects to the collection
s.add(new Student(101, "Arun", 85.5));
s.add(new Student(102, "Madhu", 78.0));
s.add(new Student(103, "Aarohi", 92.3));

// Displaying the students


System.out.println("Student List:");
for (Student x : s) {
System.out.println(x);
}
}
}

Program 4
Problem statement
Implement a java program to illustrate the use of different types of string class
constructors.
Code
public class Main1 {
​ public static void main(String[] args) {
​ ​ // 1. Default constructor
String str1 = new String();
System.out.println("str1: '" + str1 + "'");

// 2. String from byte array


byte[] byteArray = {65, 66, 67, 68};

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 4


Advanced Java (BIS402)

String str2 = new String(byteArray);


System.out.println("str2: " + str2);

// 3. String from byte array with offset and length


String str3 = new String(byteArray, 1, 2);
System.out.println("str3: " + str3);

// 4. String from character array


char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str4 = new String(charArray);
System.out.println("str4: " + str4);

// 5. String from character array with offset and count


String str5 = new String(charArray, 1, 3);
System.out.println("str5: " + str5);

// 6. String from integer array (code points) with offset and count
int[] codePoints = {72, 101, 108, 108, 111};
String str6 = new String(codePoints, 0, 5);
System.out.println("str6: " + str6);

// 7. String from another String


String str7 = new String("Example");
System.out.println("str7: " + str7);

// 8. String from StringBuffer


StringBuffer sb = new StringBuffer("BufferedString");
String str8 = new String(sb);
System.out.println("str8: " + str8);

// 9. String from StringBuilder

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 5


Advanced Java (BIS402)

StringBuilder sb1 = new StringBuilder("BuilderString");


String str9 = new String(sb1);
System.out.println("str9: " + str9);
​ }
}

Output:
str1: ''
str2: ABCD
str3: BC
str4: Hello
str5: ell
str6: Hello
str7: Example
str8: BufferedString
str9: BuilderString

Program 5
Problem Statement
Implement a java program to illustrate the use of different types of character extraction,
string comparison, string search and string modification methods.

public class Main1 {


​ public static void main(String[] args) {
​ ​ // Creating a String
String str = " Java Programming is fun! ";

// 1. length()
System.out.println("Length of the string: " + str.length());

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 6


Advanced Java (BIS402)

// 2. trim()
System.out.println("Trimmed string: '" + str.trim() + "'");

// 3. toUpperCase()
System.out.println("Uppercase string: " + str.toUpperCase());

// 4. toLowerCase()
System.out.println("Lowercase string: " + str.toLowerCase());

// 5. charAt()
System.out.println("Character at index 5: " + str.charAt(5));

// 6. contains()
System.out.println("Contains 'Java': " + str.contains("Java"));

// 7. startsWith()
System.out.println("Starts with ' Java': " + str.startsWith(" Java"));

// 8. endsWith()
System.out.println("Ends with 'fun!': " + str.endsWith("fun!"));

// 9. indexOf()
System.out.println("Index of 'Programming': " + str.indexOf("Programming"));

// 10. lastIndexOf()
System.out.println("Last index of 'a': " + str.lastIndexOf('a'));

// 11. equals()
String str2 = "Java Programming is fun!";
System.out.println("Strings are equal: " + str.equals(str2));

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 7


Advanced Java (BIS402)

// 12. equalsIgnoreCase()
System.out.println("Strings are equal (ignoring case): " + str.equalsIgnoreCase("java
programming is fun!"));

// 13. replace()
System.out.println("Replace 'Java' with 'C++': " + str.replace("Java", "C++"));

// 14. substring()
System.out.println("Substring from index 5: " + str.substring(5));

// 15. substring(start, end)


System.out.println("Substring from index 5 to 15: " + str.substring(5, 15));

// 16. split()
String[] words = str.split(" ");
System.out.println("Split string by spaces: ");
for (String word : words) {
System.out.println(word);
}

// 17. valueOf()
int num = 123;
System.out.println("String representation of number: " + String.valueOf(num));

// 18. concat()
System.out.println("Concatenated string: " + str.concat(" Let's code more!"));

// 19. isEmpty()
System.out.println("Is the string empty? " + str.isEmpty());

// 20. replaceAll()

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 8


Advanced Java (BIS402)

System.out.println("Replace all 'a' with 'o': " + str.replaceAll("a", "o"));

// 21. compareTo()
System.out.println("Compare to another string: " + str.compareTo(str2));

// 22. compareToIgnoreCase()
System.out.println("Compare to another string (ignore case): " +
str.compareToIgnoreCase("java programming is fun!"));

​ }
}

Output
Length of the string: 28
Trimmed string: 'Java Programming is fun!'
Uppercase string: JAVA PROGRAMMING IS FUN!
Lowercase string: java programming is fun!
Character at index 5: a
Contains 'Java': true
Starts with ' Java': true
Ends with 'fun!': false
Index of 'Programming': 7
Last index of 'a': 12
Strings are equal: false
Strings are equal (ignoring case): false
Replace 'Java' with 'C++': C++ Programming is fun!
Substring from index 5: a Programming is fun!
Substring from index 5 to 15: a Programm
Split string by spaces:
Java
Programming

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 9


Advanced Java (BIS402)

is
fun!
String representation of number: 123
Concatenated string: Java Programming is fun! Let's code more!
Is the string empty? False
Replace all 'a' with 'o': Jovo Progromming is fun!
Compare to another string: -42
Compare to another string (ignore case): -74

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 10


Advanced Java (BIS402)

Program 6
Problem Statement
Implement a java program to illustrate the use of different types of StringBuffer methods
public class Main {
public static void main(String[] args) {
// Creating a StringBuffer
StringBuffer sb = new StringBuffer(" Java Programming is fun! ");

System.out.println("Length of the StringBuffer: " + sb.length()); // 1. length()


System.out.println("Capacity of the StringBuffer: " + sb.capacity()); // 2. capacity()

sb.append(" Let's code more!"); // 3. append()


System.out.println("After append: " + sb);

sb.insert(5, "Awesome "); // 4. insert()


System.out.println("After insert: " + sb);

sb.delete(5, 13); // 5. delete()


System.out.println("After delete: " + sb);

sb.deleteCharAt(5); // 6. deleteCharAt()
System.out.println("After deleteCharAt: " + sb);

sb.replace(5, 15, "Programming"); // 7. replace()


System.out.println("After replace: " + sb);

sb.reverse(); // 8. reverse()
System.out.println("After reverse: " + sb);

sb.setLength(10); // 9. setLength()
System.out.println("After setLength: " + sb);

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 11


Advanced Java (BIS402)

System.out.println("Character at index 5: " + sb.charAt(5)); // 10. charAt()

System.out.println("Index of 'Java': " + sb.indexOf("Java")); // 11. indexOf()


System.out.println("Last index of 'a': " + sb.lastIndexOf("a")); // 12. lastIndexOf()

System.out.println("Substring from index 5: " + sb.substring(5)); // 13. substring()

System.out.println("StringBuffer to String: " + sb.toString()); // 14. toString()

// 15. ensureCapacity()
sb.ensureCapacity(50);
System.out.println("After ensureCapacity(50), capacity: " + sb.capacity());
}
}
Output
Length of the StringBuffer: 28
Capacity of the StringBuffer: 44
After append: Java Programming is fun! Let's code more!
After insert: JavAwesome a Programming is fun! Let's code more!
After delete: Java Programming is fun! Let's code more!
After deleteCharAt: Jav Programming is fun! Let's code more!
After replace: JavProgrammingng is fun! Let's code more!
After reverse: !erom edoc s'teL !nuf si gngnimmargorPvaJ
After setLength: !erom edoc
Character at index 5:
Index of 'Java': -1
Last index of 'a': -1
Substring from index 5: edoc
StringBuffer to String: !erom edoc
After ensureCapacity(50), capacity: 90

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 12


Advanced Java (BIS402)

Program 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.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class AlphaBetaButtons extends JFrame implements ActionListener {

private JButton alphaButton;


private JButton betaButton;
private JLabel messageLabel;

public AlphaBetaButtons() {
// Set the title of the frame
setTitle("Alpha Beta Button Demo");

// Set layout manager


setLayout(new FlowLayout());

// Create buttons and label


alphaButton = new JButton("Alpha");
betaButton = new JButton("Beta");
messageLabel = new JLabel("Press a button");

// Add action listeners


alphaButton.addActionListener(this);
betaButton.addActionListener(this);

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 13


Advanced Java (BIS402)

// Add components to frame


add(alphaButton);
add(betaButton);
add(messageLabel);

// Frame settings
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window
setVisible(true);
}

// Event handling logic


@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == alphaButton) {
messageLabel.setText("Alpha pressed");
} else if (e.getSource() == betaButton) {
messageLabel.setText("Beta pressed");
}
}

public static void main(String[] args) {


new AlphaBetaButtons();
}
}

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 14


Advanced Java (BIS402)

Program 11:
Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on
particular queries(For example update, delete, search etc…).

CREATE DATABASE studentdb;

USE studentdb;

CREATE TABLE students (


id INT PRIMARY KEY,
name VARCHAR(100),
branch VARCHAR(50),
marks FLOAT
);

import java.sql.*;
import java.util.Scanner;
public class StudentDBOperations {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
String url = "jdbc:mysql://localhost:3306/studentDB"; // DB URL
String user = "root"; // Replace with your MySQL username
String password = "Admin123"; // Replace with your MySQL password
Scanner sc = new Scanner(System.in);

// Load JDBC driver (optional for newer JDBC)


Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
Connection con = DriverManager.getConnection(url, user, password);
int choice;

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 15


Advanced Java (BIS402)

do {
System.out.println("\n--- Student Database Menu ---");
System.out.println("1. Insert");
System.out.println("2. Update");
System.out.println("3. Delete");
System.out.println("4. Search");
System.out.println("5. Exit");
System.out.print("Enter choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter ID: ");
int id = sc.nextInt();
sc.nextLine(); // consume newline
System.out.print("Enter Name: ");
String name = sc.nextLine();
System.out.print("Enter Branch: ");
String branch = sc.nextLine();
System.out.print("Enter Marks: ");
float marks = sc.nextFloat();
String insertQuery = "INSERT INTO Students VALUES (?, ?, ?, ?)";
PreparedStatement insertStmt = con.prepareStatement(insertQuery);
insertStmt.setInt(1, id);
insertStmt.setString(2, name);
insertStmt.setString(3, branch);
insertStmt.setFloat(4, marks);
insertStmt.executeUpdate();
System.out.println("Record Inserted Successfully.");
break;
case 2:
System.out.print("Enter ID to update: ");

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 16


Advanced Java (BIS402)

int uid = sc.nextInt();


sc.nextLine();
System.out.print("Enter new Marks: ");
float newMarks = sc.nextFloat();
String updateQuery = "UPDATE Students SET marks = ? WHERE id = ?";
PreparedStatement updateStmt = con.prepareStatement(updateQuery);
updateStmt.setFloat(1, newMarks);
updateStmt.setInt(2, uid);
int updated = updateStmt.executeUpdate();
if (updated > 0)
System.out.println("Record Updated Successfully.");
else
System.out.println("Record Not Found.");
break;
case 3:
System.out.print("Enter ID to delete: ");
int did = sc.nextInt();
String deleteQuery = "DELETE FROM Students WHERE id = ?";
PreparedStatement deleteStmt = con.prepareStatement(deleteQuery);
deleteStmt.setInt(1, did);
int deleted = deleteStmt.executeUpdate();
if (deleted > 0)
System.out.println("Record Deleted Successfully.");
else
System.out.println("Record Not Found.");
break;
case 4:
System.out.print("Enter ID to search: ");
int sid = sc.nextInt();
String searchQuery = "SELECT * FROM Students WHERE id = ?";
PreparedStatement searchStmt = con.prepareStatement(searchQuery);

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 17


Advanced Java (BIS402)

searchStmt.setInt(1, sid);
ResultSet rs = searchStmt.executeQuery();
if (rs.next()) {
System.out.println("ID: " + rs.getInt("id"));
System.out.println("Name: " + rs.getString("name"));
System.out.println("Branch: " + rs.getString("branch"));
System.out.println("Marks: " + rs.getFloat("marks"));
} else {
System.out.println("Record Not Found.");
}
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
}
} while (choice != 5);
con.close();
sc.close();
}
}

Prof. Arun K H, Dept. of ISE, AIT ​ ​ ​ ​ ​ ​ ​ 18

You might also like