MCA 208: Programming in Java MCA 2nd Semester
1. WAJP for Creation and Casting of Variables
class variable{
//(static variable is instance variable without using keyword static with varible declaration and
instance variable can not be accessed inside the class like static variable)
int x=5;
static String s= "Java Programming";
public static void main(String args[])
{
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
variable v=new variable();// (to access instance variable we need to create an instance
of the class in which the variable is declared/created)
System.out.println("Variable1 = "+v.x);
System.out.println("Variable2 = "+s);
}
}
Tanushree Nair Page 1 of 78
MCA 208: Programming in Java MCA 2nd Semester
2. WAJP to demonstrate the various Operators.
import java.io.*;
public class operator{
public static void main(String args[]){
System.out.println("Name : Tanushree Nair \nClass : MCA IInd
Semester\n__________________________________________________________");
int a=22;
int b=2;
System.out.println("Arithmetic operator--------------");
System.out.println("Sum : "+(a+b));
System.out.println("Difference : "+(a-b));
System.out.println("Multiplication : "+(a*b));
System.out.println("Division : "+(a/b));
System.out.println("Modulus : "+(a%b));
System.out.println("Unary operator------------------");
System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));
System.out.println("Postdecrement : " + (b--));
System.out.println("Predecrement : " + (--b));
System.out.println("Arithmetic operator---------------");
System.out.println("Arithmetic operator");
System.out.println("Arithmetic operator");
System.out.println("Arithmetic operator");
}
}
Tanushree Nair Page 2 of 78
MCA 208: Programming in Java MCA 2nd Semester
3. WAJP for printing the current date in different formats.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; public class DateTime {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
LocalDateTime myDateObj = LocalDateTime.now(); System.out.println("Before formatting: " +
myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate1 = myDateObj.format(myFormatObj); System.out.println("After
formatting: " + formattedDate1);
DateTimeFormatter myFormatObj2 = DateTimeFormatter.ofPattern("dd-MMM-yyyy
HH:mm:ss");
String formattedDate2 = myDateObj.format(myFormatObj2); System.out.println("After
formatting: " + formattedDate2);
DateTimeFormatter myFormatObj3 = DateTimeFormatter.ofPattern("yyyy-MM-dd
HH:mm:ss");
String formattedDate3 = myDateObj.format(myFormatObj3); System.out.println("After
formatting: " + formattedDate3);
}
}
Tanushree Nair Page 3 of 78
MCA 208: Programming in Java MCA 2nd Semester
4. WAJP for Inputting Data From Keyboard through Scanner Class.
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
// Create Scanner object to read input from keyboard
Scanner sc = new Scanner(System.in);
// Input string
System.out.print("Enter your name: ");
String name = sc.nextLine();
// Input integer
System.out.print("Enter your age: ");
int age = sc.nextInt();
// Input double
System.out.print("Enter your percentage: ");
double percentage = sc.nextDouble();
Tanushree Nair Page 4 of 78
MCA 208: Programming in Java MCA 2nd Semester
// Output the input data
System.out.println("\n--- User Information ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Percentage: " + percentage);
// Close the scanner
sc.close();
}
}
5. WAJP for Inputting Data From Keyboard through BufferedReader Class.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class BufferedReaderInput {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = br.readLine();
System.out.print("Enter your age: ");
int age = Integer.parseInt(br.readLine());
Tanushree Nair Page 5 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.print("Enter your percentage: ");
double percentage = Double.parseDouble(br.readLine());
System.out.println("\n--- User Information ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Percentage: " + percentage);
}
}
6. WAJP for Inputting Data From Keyboard through Console Class.
import java.io.Console;
public class ConsoleInput {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Console console = System.console();
if (console == null) {
System.out.println("Console is not available.");
return;
}
String name = console.readLine("Enter your name: ");
Tanushree Nair Page 6 of 78
MCA 208: Programming in Java MCA 2nd Semester
int age = Integer.parseInt(console.readLine("Enter your age: "));
double percentage = Double.parseDouble(console.readLine("Enter your percentage: "));
System.out.println("\n--- User Information ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Percentage: " + percentage);
}
}
7. WAJP to demonstrate the use of for–each loop.
public class foreach {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Elements of the array are:");
for (int num : numbers) {
System.out.println(num);
}
}
}
Tanushree Nair Page 7 of 78
MCA 208: Programming in Java MCA 2nd Semester
8. WAJP to demonstrate ragged arrays.
public class RaggedArray {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
int[][] raggedArray = new int[3][];
raggedArray[0] = new int[2]; // 2 elements in row 0
raggedArray[1] = new int[4]; // 4 elements in row 1
raggedArray[2] = new int[3]; // 3 elements in row 2
int value = 1;
Tanushree Nair Page 8 of 78
MCA 208: Programming in Java MCA 2nd Semester
for (int i = 0; i < raggedArray.length; i++) {
for (int j = 0; j < raggedArray[i].length; j++) {
raggedArray[i][j] = value++;
}
}
System.out.println("Ragged Array:");
for (int i = 0; i < raggedArray.length; i++) {
for (int j = 0; j < raggedArray[i].length; j++) {
System.out.print(raggedArray[i][j] + " ");
}
System.out.println();
}
}
}
9. WAJP to demonstrate anonymous arrays.
public class AnonymousArray {
public static void printArray(int[] arr) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
System.out.println("Elements of the array are:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
Tanushree Nair Page 9 of 78
MCA 208: Programming in Java MCA 2nd Semester
public static void main(String[] args) {
printArray(new int[] {10, 20, 30, 40, 50});
}
}
10.WAJP to demonstrate the methods of Arrays Class.
import java.util.Arrays;
public class arrays {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
int[] numbers = {5, 2, 9, 1, 7};
Tanushree Nair Page 10 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Original array: " + Arrays.toString(numbers));
Arrays.sort(numbers);
System.out.println("Sorted array: " + Arrays.toString(numbers));
Arrays.fill(numbers, 3);
System.out.println("Array after fill(): " + Arrays.toString(numbers));
int[] copiedArray = Arrays.copyOf(numbers, numbers.length);
System.out.println("Copied array: " + Arrays.toString(copiedArray));
boolean isEqual = Arrays.equals(numbers, copiedArray);
System.out.println("Are original and copied arrays equal? " + isEqual);
int[] searchArray = {1, 3, 5, 7, 9};
int index = Arrays.binarySearch(searchArray, 5);
System.out.println("Index of 5 in searchArray: " + index);
}
}
11.WAJP for Application Of Classes And Objects
class Student {
String name;
int rollNo;
double percentage;
Tanushree Nair Page 11 of 78
MCA 208: Programming in Java MCA 2nd Semester
void setDetails(String n, int r, double p) {
name = n;
rollNo = r;
percentage = p;
}
void displayDetails() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number : " + rollNo);
System.out.println("Percentage : " + percentage + "%");
System.out.println();
}
}
public class StudentApp {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Student s1 = new Student();
s1.setDetails("Aman", 101, 85.5);
s1.displayDetails();
Student s2 = new Student();
s2.setDetails("Priya", 102, 91.2);
s2.displayDetails();
}
}
12.WAJP to demonstrate method overloading
public class Methodoverloading {
void display(int a) {
System.out.println("Method with one int: " + a);
Tanushree Nair Page 12 of 78
MCA 208: Programming in Java MCA 2nd Semester
}
void display(int a, int b) {
System.out.println("Method with two ints: " + a + " and " + b);
}
void display(double a) {
System.out.println("Method with one double: " + a);
}
void display(String str) {
System.out.println("Method with one String: " + str);
}
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Methodoverloading obj = new Methodoverloading();
obj.display(10);
obj.display(10, 20);
obj.display(12.5);
obj.display("Hello Java");
}
}
13.WAJP to demonstrate constructor overloading.
public class Constructoroverloading {
Tanushree Nair Page 13 of 78
MCA 208: Programming in Java MCA 2nd Semester
String name;
int age;
Constructoroverloading() {
name = "Unknown";
age = 0;
}
Constructoroverloading(String n) {
name = n;
age = 0;
}
Constructoroverloading(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Constructoroverloading obj1 = new Constructoroverloading();
Constructoroverloading obj2 = new Constructoroverloading("Tanushree", 22);
Constructoroverloading obj3 = new Constructoroverloading("Priya", 22);
obj1.display();
obj2.display();
obj3.display();
}
}
Tanushree Nair Page 14 of 78
MCA 208: Programming in Java MCA 2nd Semester
14.WAJP Using Single Inheritance
class Person {
String name;
int age;
void setPersonDetails(String n, int a) {
name = n;
age = a;
}
void displayPersonDetails() {
System.out.println("Name: " + name);
System.out.println("Age : " + age);
}
}
class Student extends Person {
int rollNo;
void setStudentDetails(String n, int a, int r) {
setPersonDetails(n, a); // Call method from parent class
rollNo = r;
}
void displayStudentDetails() {
displayPersonDetails(); // Call method from parent class
System.out.println("Roll No: " + rollNo);
}
}
public class Singleinheritance {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Student s = new Student();
s.setStudentDetails("Ravi", 20, 101);
s.displayStudentDetails();
}
}
Tanushree Nair Page 15 of 78
MCA 208: Programming in Java MCA 2nd Semester
15.WAJP Using Super And This Keyword
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name; // refers to current class instance variable
this.age = age;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age : " + age);
}
}
class Student extends Person {
int rollNo;
Student(String name, int age, int rollNo) {
super(name, age);
this.rollNo = rollNo;
}
void display() {
super.display();
System.out.println("Roll No: " + rollNo);
}
}
public class SuperAndThis {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Student s = new Student("Tanushree", 22, 101);
Tanushree Nair Page 16 of 78
MCA 208: Programming in Java MCA 2nd Semester
s.display();
}
}
Tanushree Nair Page 17 of 78
MCA 208: Programming in Java MCA 2nd Semester
16.WAJP to demonstrate multilevel inheritance.
class Person {
String name;
int age;
void setPersonDetails(String n, int a) {
name = n;
age = a;
}
void displayPersonDetails() {
System.out.println("Name: " + name);
System.out.println("Age : " + age);
}
}
// Derived class
class Student extends Person {
int rollNo;
void setStudentDetails(String n, int a, int r) {
setPersonDetails(n, a);
rollNo = r;
}
void displayStudentDetails() {
displayPersonDetails();
System.out.println("Roll No: " + rollNo);
}
}
class GraduateStudent extends Student {
String degree;
void setGraduateDetails(String n, int a, int r, String d) {
setStudentDetails(n, a, r);
degree = d;
}
void displayGraduateDetails() {
displayStudentDetails();
Tanushree Nair Page 18 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Degree: " + degree);
}
}
// Main class
public class MultilevelInheritance {
public static void main(String[] args) {
GraduateStudent gs = new GraduateStudent();
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
gs.setGraduateDetails("Tanushree", 22, 105, "MCA");
gs.displayGraduateDetails();
}
}
Tanushree Nair Page 19 of 78
MCA 208: Programming in Java MCA 2nd Semester
17.WAJP to demonstrate method overriding.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class MethodOverriding {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Animal a = new Animal();
a.sound();
Dog d = new Dog();
d.sound();
Animal ref;
ref = new Dog();
ref.sound();
}
}
Tanushree Nair Page 20 of 78
MCA 208: Programming in Java MCA 2nd Semester
18. WAJP Using Multiple Inheritance Concept through interfaces.
interface Printable {
void print();
}
interface Showable {
void show();
}
class Document implements Printable, Showable {
public void print() {
System.out.println("Printing document...");
}
public void show() {
System.out.println("Showing document...");
}
}
public class MultipleInheritance {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Document doc = new Document();
doc.print();
doc.show();
}
Tanushree Nair Page 21 of 78
MCA 208: Programming in Java MCA 2nd Semester
}
19.WAJP to demonstrate the concept of inner class.
public class OuterClass {
String outerMessage = "This is Outer Class";
class InnerClass {
String innerMessage = "This is Inner Class";
void displayMessages() {
// Accessing both inner and outer class members
System.out.println(outerMessage);
System.out.println(innerMessage);
}
}
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.displayMessages();
}
}
Tanushree Nair Page 22 of 78
MCA 208: Programming in Java MCA 2nd Semester
20.WAJP to demonstrate the concept of local class.
public class LocalInnerClass {
void display() {
System.out.println("Inside outer method...");
class LocalClass {
void show() {
System.out.println("Hello from Local Inner Class!");
}
}
LocalClass lc = new LocalClass();
lc.show();
}
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
LocalInnerClass obj = new LocalInnerClass();
obj.display();
}
}
Tanushree Nair Page 23 of 78
MCA 208: Programming in Java MCA 2nd Semester
22. WAJP Using Try And Catch Statement
public class TryCatch {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
int[] numbers = {10, 20, 30};
try {
System.out.println("Accessing element at index 5:");
System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception Caught: " + e);
}
System.out.println("Program continues after the try-catch block.");
}
}
Tanushree Nair Page 24 of 78
MCA 208: Programming in Java MCA 2nd Semester
23. WAJP Using Multiple Catch Statements
public class MultipleCatch {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
try {
int a = 10, b = 0;
int result = a / b; // This will throw ArithmeticException
int[] arr = new int[3];
arr[5] = 50; // This will throw ArrayIndexOutOfBoundsException (if reached)
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage());
Tanushree Nair Page 25 of 78
MCA 208: Programming in Java MCA 2nd Semester
}
catch (Exception e) {
System.out.println("General Exception caught: " + e.getMessage());
}
System.out.println("Program continues after multiple catch blocks.");
}
}
24. WAJP to demonstrate the MultiCatch feature.
public class MultiCatchExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
try {
String str = null;
System.out.println(str.length()); // This will throw NullPointerException
Tanushree Nair Page 26 of 78
MCA 208: Programming in Java MCA 2nd Semester
int[] arr = new int[3];
System.out.println(arr[5]); // This would throw ArrayIndexOutOfBoundsException (if
reached)
}
catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught using multi-catch: " + e);
System.out.println("Program continues after multi-catch block.");
}
}
25. WAJP to demonstrate the use of finally block
public class FinallyBlock {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
try {
int num = 10, div = 0;
int result = num / div; // Will throw ArithmeticException
Tanushree Nair Page 27 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
finally {
System.out.println("Finally block is always executed.");
}
System.out.println("Program continues after try-catch-finally.");
}
}
26. WAJP Using Nested Try Statements
public class NestedTry {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
try {
Tanushree Nair Page 28 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Outer try block starts...");
try {
System.out.println("Inner try block starts...");
int num = 10, div = 0;
int result = num / div; // This will throw ArithmeticException
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Inner catch block: ArithmeticException caught: " + e.getMessage());
int[] arr = new int[3];
System.out.println(arr[5]); // This will throw ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch block: ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
}
System.out.println("Program continues after nested try-catch blocks.");
}
}
Tanushree Nair Page 29 of 78
MCA 208: Programming in Java MCA 2nd Semester
27. WAJP To Create Your Own Exception Class And Display Corresponding Error
Message
class AgeException extends Exception {
// Constructor to initialize the exception with a message
public AgeException(String message) {
super(message); // Calling the parent class constructor (Exception class)
}
Tanushree Nair Page 30 of 78
MCA 208: Programming in Java MCA 2nd Semester
}
public class CustomException {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
try {
int age = 15; // Example of an invalid age
// Throwing the custom exception if age is less than 18
if (age < 18) {
throw new AgeException("Age is less than 18. Cannot proceed with registration.");
} else {
System.out.println("Age is valid. Proceeding with registration.");
}
} catch (AgeException e) {
// Catching the custom exception and displaying the error message
System.out.println("Error: " + e.getMessage());
}
System.out.println("Program continues after handling custom exception.");
}
}
Tanushree Nair Page 31 of 78
MCA 208: Programming in Java MCA 2nd Semester
28. WAJP For Creating And Executing Threads by extending the Thread class.
// Custom class extending the Thread class
class MyThread extends Thread {
private String threadName;
// Constructor to assign a name to each thread
public MyThread(String name) {
Tanushree Nair Page 32 of 78
MCA 208: Programming in Java MCA 2nd Semester
threadName = name;
}
// Override the run() method - this is where the thread's task is defined
@Override
public void run() {
System.out.println(threadName + " is running.");
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " count: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(threadName + " was interrupted.");
}
}
System.out.println(threadName + " has finished.");
}
}
public class ThreadExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n___________________________________________");
MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");
// Starting the threads
t1.start();
t2.start();
}
}
Tanushree Nair Page 33 of 78
MCA 208: Programming in Java MCA 2nd Semester
29. WAJP To run Three Threads by implementing the Runnable Interface
// Custom class that implements Runnable
class MyRunnable implements Runnable {
Tanushree Nair Page 34 of 78
MCA 208: Programming in Java MCA 2nd Semester
private String threadName;
public MyRunnable(String name) {
this.threadName = name;
}
// run() method defines the task to be performed
public void run() {
System.out.println(threadName + " is starting.");
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " - Count: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(threadName + " was interrupted.");
}
}
System.out.println(threadName + " has finished.");
}
}
public class RunnableExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
// Creating Runnable objects
MyRunnable r1 = new MyRunnable("Thread 1");
MyRunnable r2 = new MyRunnable("Thread 2");
MyRunnable r3 = new MyRunnable("Thread 3");
Tanushree Nair Page 35 of 78
MCA 208: Programming in Java MCA 2nd Semester
// Wrapping Runnable in Thread objects
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);
// Starting the threads
t1.start();
t2.start();
t3.start();
}
30. WAJP to demonstrate the use of join() method.
Tanushree Nair Page 36 of 78
MCA 208: Programming in Java MCA 2nd Semester
// Custom thread class implementing Runnable
class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
public void run() {
System.out.println(name + " started.");
for (int i = 1; i <= 5; i++) {
System.out.println(name + " - Count: " + i);
try {
Thread.sleep(500); // Pause for 500 ms
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
}
System.out.println(name + " finished.");
}
public class JoinMethodExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
// Creating threads
Thread t1 = new Thread(new MyRunnable("Thread 1"));
Thread t2 = new Thread(new MyRunnable("Thread 2"));
Thread t3 = new Thread(new MyRunnable("Thread 3"));
Tanushree Nair Page 37 of 78
MCA 208: Programming in Java MCA 2nd Semester
// Start all threads
t1.start();
try {
t1.join(); // Wait until t1 finishes
} catch (InterruptedException e) {
System.out.println("t1 interrupted.");
}
t2.start();
try {
t2.join(); // Wait until t2 finishes
} catch (InterruptedException e) {
System.out.println("t2 interrupted.");
}
t3.start();
try {
t3.join(); // Wait until t3 finishes
} catch (InterruptedException e) {
System.out.println("t3 interrupted.");
}
System.out.println("All threads have completed.");
}
Tanushree Nair Page 38 of 78
MCA 208: Programming in Java MCA 2nd Semester
Tanushree Nair Page 39 of 78
MCA 208: Programming in Java MCA 2nd Semester
31. WAJP to demonstrate Multithreading using wait () & notify()
class SharedResource {
private boolean dataReady = false;
public synchronized void produce() {
System.out.println("Producer started producing data...");
try {
Thread.sleep(1000); // Simulate time to produce data
} catch (InterruptedException e) {
e.printStackTrace();
}
dataReady = true;
System.out.println("Producer finished producing data.");
notify(); // Notify the waiting consumer
}
public synchronized void consume() {
System.out.println("Consumer waiting for data...");
while (!dataReady) {
try {
wait(); // Wait until data is produced
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumer consumed the data!");
Tanushree Nair Page 40 of 78
MCA 208: Programming in Java MCA 2nd Semester
}
}
public class WaitNotify {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
SharedResource resource = new SharedResource();
// Consumer thread (waits for data)
Thread consumer = new Thread(() -> resource.consume());
// Producer thread (produces and notifies)
Thread producer = new Thread(() -> resource.produce());
consumer.start();
try {
Thread.sleep(500); // Ensure consumer starts first
} catch (InterruptedException e) {
e.printStackTrace();
}
producer.start();
}
}
Tanushree Nair Page 41 of 78
MCA 208: Programming in Java MCA 2nd Semester
32. WAJP to demonstrate The String Class & its methods.
public class StringMethods {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
String str1 = "Hello";
String str2 = "World";
String str3 = " Java Programming ";
// Concatenation
String combined = str1 + " " + str2;
System.out.println("Concatenation: " + combined);
// Length of a string
System.out.println("Length of str1: " + str1.length());
// charAt()
System.out.println("Character at index 1 of str1: " + str1.charAt(1));
// toUpperCase() and toLowerCase()
Tanushree Nair Page 42 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Uppercase: " + str1.toUpperCase());
System.out.println("Lowercase: " + str2.toLowerCase());
// trim()
System.out.println("Before trim: '" + str3 + "'");
System.out.println("After trim: '" + str3.trim() + "'");
// equals() and equalsIgnoreCase()
System.out.println("str1 equals str2? " + str1.equals(str2));
System.out.println("str1 equalsIgnoreCase(\"HELLO\")? " + str1.equalsIgnoreCase("HELLO"));
// substring()
System.out.println("Substring of str3 (start from 3): " + str3.substring(3));
// replace()
System.out.println("Replace 'a' with '@' in str3: " + str3.replace('a', '@'));
// contains()
System.out.println("Does str3 contain 'Java'? " + str3.contains("Java"));
// indexOf()
System.out.println("Index of 'o' in str2: " + str2.indexOf('o'));
// isEmpty()
String emptyStr = "";
System.out.println("Is emptyStr empty? " + emptyStr.isEmpty());
}
}
Tanushree Nair Page 43 of 78
MCA 208: Programming in Java MCA 2nd Semester
34. WAJP to demonstrate various Wrapper Classes.
public class WrapperClassExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
// Creating wrapper class objects from primitive values
// Integer Wrapper Class
int num = 10;
Integer intWrapper = Integer.valueOf(num); // Auto-boxing
System.out.println("Integer Wrapper: " + intWrapper);
// Double Wrapper Class
double dnum = 3.14;
Double doubleWrapper = Double.valueOf(dnum); // Auto-boxing
System.out.println("Double Wrapper: " + doubleWrapper);
Tanushree Nair Page 44 of 78
MCA 208: Programming in Java MCA 2nd Semester
// Character Wrapper Class
char character = 'A';
Character charWrapper = Character.valueOf(character); // Auto-boxing
System.out.println("Character Wrapper: " + charWrapper);
// Boolean Wrapper Class
boolean isTrue = true;
Boolean booleanWrapper = Boolean.valueOf(isTrue); // Auto-boxing
System.out.println("Boolean Wrapper: " + booleanWrapper);
// Convert wrapper objects back to primitive values (unboxing)
// Unboxing Integer to int
int unboxedInt = intWrapper.intValue();
System.out.println("Unboxed Integer: " + unboxedInt);
// Unboxing Double to double
double unboxedDouble = doubleWrapper.doubleValue();
System.out.println("Unboxed Double: " + unboxedDouble);
// Unboxing Character to char
char unboxedChar = charWrapper.charValue();
System.out.println("Unboxed Character: " + unboxedChar);
// Unboxing Boolean to boolean
boolean unboxedBoolean = booleanWrapper.booleanValue();
System.out.println("Unboxed Boolean: " + unboxedBoolean);
// String to Wrapper Class Conversion
String numStr = "100";
Integer strToInt = Integer.valueOf(numStr); // Parsing String to Integer
Tanushree Nair Page 45 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("String to Integer Wrapper: " + strToInt);
String boolStr = "false";
Boolean strToBool = Boolean.valueOf(boolStr); // Parsing String to Boolean
System.out.println("String to Boolean Wrapper: " + strToBool);
// Using parse methods
int parsedInt = Integer.parseInt(numStr); // Parsing String to primitive int
System.out.println("Parsed int from String: " + parsedInt);
boolean parsedBool = Boolean.parseBoolean(boolStr); // Parsing String to primitive boolean
System.out.println("Parsed boolean from String: " + parsedBool);
}
}
Tanushree Nair Page 46 of 78
MCA 208: Programming in Java MCA 2nd Semester
35. WAJP to demonstrate HashSet Class & its methods.
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
// Creating a HashSet
HashSet<String> set = new HashSet<>();
// Adding elements to the HashSet
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Mango");
set.add("Apple"); // Duplicate element, will not be added
System.out.println("HashSet after adding elements: " + set);
// Checking if an element exists in the HashSet
boolean isPresent = set.contains("Banana");
System.out.println("Does HashSet contain 'Banana'? " + isPresent);
Tanushree Nair Page 47 of 78
MCA 208: Programming in Java MCA 2nd Semester
// Removing an element from the HashSet
set.remove("Mango");
System.out.println("HashSet after removing 'Mango': " + set);
// Size of the HashSet
System.out.println("Size of HashSet: " + set.size());
// Checking if the HashSet is empty
boolean isEmpty = set.isEmpty();
System.out.println("Is the HashSet empty? " + isEmpty);
// Clearing all elements from the HashSet
set.clear();
System.out.println("HashSet after clearing all elements: " + set);
// Adding elements again to demonstrate the isEmpty method
set.add("Pineapple");
set.add("Grapes");
set.add("Watermelon");
System.out.println("HashSet after re-adding elements: " + set);
// Iterating through the HashSet
System.out.print("Elements in the HashSet: ");
for (String fruit : set) {
System.out.print(fruit + " ");
}
System.out.println();
// Checking if a specific element is present
if (set.contains("Grapes")) {
System.out.println("Grapes are present in the HashSet.");
}
}
}
Tanushree Nair Page 48 of 78
MCA 208: Programming in Java MCA 2nd Semester
36. WAJP to demonstrate ArrayList Class & its methods.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
// Creating an ArrayList
ArrayList<String> list = new ArrayList<>();
Tanushree Nair Page 49 of 78
MCA 208: Programming in Java MCA 2nd Semester
// Adding elements to the ArrayList
list.add("Apple");
list.add("Banana");
list.add("Orange");
list.add("Mango");
// Printing the ArrayList
System.out.println("ArrayList after adding elements: " + list);
// Adding an element at a specific position
list.add(2, "Grapes");
System.out.println("ArrayList after adding 'Grapes' at index 2: " + list);
// Retrieving an element from a specific index
String element = list.get(3);
System.out.println("Element at index 3: " + element);
// Removing an element from a specific index
list.remove(1);
System.out.println("ArrayList after removing element at index 1: " + list);
// Checking if an element exists in the ArrayList
boolean containsElement = list.contains("Mango");
System.out.println("Does ArrayList contain 'Mango'? " + containsElement);
// Getting the size of the ArrayList
System.out.println("Size of the ArrayList: " + list.size());
// Checking if the ArrayList is empty
boolean isEmpty = list.isEmpty();
System.out.println("Is the ArrayList empty? " + isEmpty);
// Setting a new value at a specific index
list.set(1, "Pineapple");
System.out.println("ArrayList after setting 'Pineapple' at index 1: " + list);
// Iterating through the ArrayList using a for-each loop
System.out.print("Elements in the ArrayList: ");
for (String fruit : list) {
System.out.print(fruit + " ");
}
System.out.println();
// Removing all elements from the ArrayList
list.clear();
Tanushree Nair Page 50 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("ArrayList after clearing all elements: " + list);
// Adding new elements to show isEmpty method again
list.add("Peach");
list.add("Plum");
System.out.println("ArrayList after re-adding elements: " + list);
}
}
37. WAJP to copy a File.
import java.io.*;
import java.nio.file.*;
Tanushree Nair Page 51 of 78
MCA 208: Programming in Java MCA 2nd Semester
public class FileCopyExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
// Source and destination file paths
Path sourcePath = Paths.get("source.txt");
Path destinationPath = Paths.get("destination.txt");
try {
// Copying the file using Files.copy() method
Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully!");
} catch (IOException e) {
System.out.println("An error occurred during file copy: " + e.getMessage());
}
}
38. WAJP to Count the numbers of Characters in a File.
import java.io.*;
Tanushree Nair Page 52 of 78
MCA 208: Programming in Java MCA 2nd Semester
public class CharacterCount {
public static void main(String[] args) {
String fileName = "sample.txt"; // Make sure this file exists in your working directory
int charCount = 0;
try (FileReader fr = new FileReader(fileName)) {
int ch;
while ((ch = fr.read()) != -1) {
charCount++;
}
System.out.println("NAME : TANUSHREE NAIR");
System.out.println("CLASS : MCA IInd Semester");
System.out.println("-------------------------------------------------");
System.out.println("Number of characters in the file: " + charCount);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + fileName);
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
}
}
}
39. WAJP to demonstrate Object Serialization.
import java.io.*;
Tanushree Nair Page 53 of 78
MCA 208: Programming in Java MCA 2nd Semester
// Serializable class
class Student implements Serializable {
String name;
int rollNo;
transient int age; // transient fields are not serialized
Student(String name, int rollNo, int age) {
this.name = name;
this.rollNo = rollNo;
this.age = age;
}
}
public class SerializationDemo {
public static void main(String[] args) {
Student s1 = new Student("Tanushree Nair", 101, 22);
// Serialize the object
try (FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(s1);
System.out.println("Object has been serialized to student.ser");
} catch (IOException e) {
System.out.println("Serialization error: " + e);
// Deserialize the object
try (FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
Student deserialized = (Student) in.readObject();
Tanushree Nair Page 54 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("NAME : TANUSHREE NAIR");
System.out.println("CLASS : MCA IInd Semester");
System.out.println("-------------------------------------------------");
System.out.println("Deserialized Student Info:");
System.out.println("Name: " + deserialized.name);
System.out.println("Roll No: " + deserialized.rollNo);
System.out.println("Age (transient): " + deserialized.age); // Will be 0 due to 'transient'
} catch (IOException | ClassNotFoundException e) {
System.out.println("Deserialization error: " + e);
}
}
}
Tanushree Nair Page 55 of 78
MCA 208: Programming in Java MCA 2nd Semester
40. WAJP to demonstrate Keyboard Event
import java.awt.*;
import java.awt.event.*;
public class KeyboardEventExample extends Frame implements KeyListener {
Label label;
KeyboardEventExample() {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
label = new Label();
label.setBounds(50, 100, 300, 30);
addKeyListener(this); // Register key listener
add(label);
setTitle("Keyboard Event Example");
setSize(400, 200);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose(); // close the window
}
});
}
// KeyListener methods
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {
label.setText("Key Released: " + e.getKeyChar());
Tanushree Nair Page 56 of 78
MCA 208: Programming in Java MCA 2nd Semester
}
public void keyTyped(KeyEvent e) {
label.setText("Key Typed: " + e.getKeyChar());
}
public static void main(String[] args) {
new KeyboardEventExample();
}
}
Tanushree Nair Page 57 of 78
MCA 208: Programming in Java MCA 2nd Semester
41. WAJP to demonstrate Mouse Event
import java.awt.*;
import java.awt.event.*;
public class MouseEventExample extends Frame implements MouseListener, MouseMotionListener {
Label label;
MouseEventExample() {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
label = new Label();
label.setBounds(50, 100, 300, 30);
add(label);
addMouseListener(this);
addMouseMotionListener(this);
setTitle("Mouse Event Example");
setSize(400, 300);
setLayout(null);
setVisible(true);
// Window closing event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
// MouseListener methods
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
Tanushree Nair Page 58 of 78
MCA 208: Programming in Java MCA 2nd Semester
label.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
label.setText("Mouse Released");
}
public void mouseDragged(MouseEvent e) {
label.setText("Mouse Dragged at (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Moved at (" + e.getX() + ", " + e.getY() + ")");
}
public static void main(String[] args) {
new MouseEventExample();
}
}
Tanushree Nair Page 59 of 78
MCA 208: Programming in Java MCA 2nd Semester
42. WAP to establish connection to the database.
import java.sql.*;
public class DatabaseConnectionDemo
{
public static void main(String[] args)
{
Connection con = null; try {
System.out.println(" ");
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
System.out.println("Loading driver..."); Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Connecting to database..."); con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "Tanushree ", " anjali123 ");
System.out.println("Database connected successfully!");
}
catch (ClassNotFoundException e)
{
System.out.println("Oracle JDBC Driver not found. Please add ojdbc.jar to classpath.");
e.printStackTrace();
}
catch (SQLException e)
{
System.out.println(" Error: Unable to connect to the database."); e.printStackTrace();
}
finally { try {
if (con != null)
{
con.close();
System.out.println("Database connection closed.");
}
} catch (SQLException e) {
System.out.println("Error while closing the connection.");
e.printStackTrace();
}
}
Tanushree Nair Page 60 of 78
MCA 208: Programming in Java MCA 2nd Semester
}
}
Tanushree Nair Page 61 of 78
MCA 208: Programming in Java MCA 2nd Semester
43. WAP to create a table named employee with feilds as emp_id, emp_name, age ,
dept.
import java.sql.*;
public class CreateEmployeeTable { public static void main(String[] args) {
try {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", " Tanushree ", " anjali123 "); Statement stmt = con.createStatement();
stmt.executeUpdate("create table employee1(emp_id number primary key,emp_name varchar(10),age
number,dept varchar(10))");
System.out.println(" Table 'employee1' created successfully!"); con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Tanushree Nair Page 62 of 78
MCA 208: Programming in Java MCA 2nd Semester
44. WAP to create a table and drop it.
import java.sql.*;
public class DropEmployeeTable { public static void main(String[] args) { try {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", " Tanushree", " anjali123 "); Statement stmt = con.createStatement();
stmt.executeUpdate("drop table employee1"); System.out.println(" Table 'employee1' droped successfully!");
con.close();
} catch (Exception e) {System.out.println(e);}
}
}
Tanushree Nair Page 63 of 78
MCA 208: Programming in Java MCA 2nd Semester
45. WAP to insert multiple rows in a table using prepared statement.
import java.sql.*;
public class CreateEmployeeTable { public static void main(String[] args) {
try {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", " Tanushree ", " anjali123 "); Statement stmt =
con.createStatement();
stmt.executeUpdate("create table employee1(emp_id number primary key,emp_name
varchar(10),age number,dept varchar(10))");
System.out.println(" Table 'employee1' created successfully!"); con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Tanushree Nair Page 64 of 78
MCA 208: Programming in Java MCA 2nd Semester
46. WAP to display contents of a table on the console.
import java.sql.*;
class Displayemployee {
public static void main(String args[]) { try {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
System.out.println("Loading driver..."); Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Connecting to database..."); Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", " Tanushree ", " anjali123 ");
System.out.println("Creating statement..."); Statement stmt = con.createStatement();
System.out.println("Executing query...");
ResultSet rs = stmt.executeQuery("SELECT * FROM employee1");
boolean found = false; while(rs.next()) { found = true;
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getInt(3) + " " + rs.getString(4));
}
if (!found) {
System.out.println("No records found in table.");
}
con.close();
} catch(Exception e) { System.out.println("Error: " + e);
}
}
}
Tanushree Nair Page 65 of 78
MCA 208: Programming in Java MCA 2nd Semester
49. WAP to demonstrate the ArrayList class.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
fruits.add("Orange");
System.out.println("Fruits List: " + fruits);
System.out.println("First fruit: " + fruits.get(0));
fruits.set(1, "Grapes"); // Replacing "Banana" with "Grapes"
System.out.println("Updated Fruits List: " + fruits);
System.out.println("After removing Mango: " + fruits);
System.out.println("List of fruits using loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}
Tanushree Nair Page 66 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Total fruits: " + fruits.size());
System.out.println("Contains Apple? " + fruits.contains("Apple"));
}
}
50. WAP to demonstrate the HashSet class.
public class HashSet {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
java.util.HashSet<String> countries = new java.util.HashSet<>();
countries.add("India");
countries.add("USA");
countries.add("UK");
countries.add("India"); // Duplicate
System.out.println("Countries: " + countries);
countries.remove("USA");
System.out.println("After removing USA: " + countries);
System.out.println("Contains UK? " + countries.contains("UK"));
System.out.println("Looping through HashSet:");
for (String country : countries) {
System.out.println(country);
}
Tanushree Nair Page 67 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Size: " + countries.size());
}
}
51. WAP to demonstrate the HashMap class.
public class hashmap {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
java.util.HashMap<String, Integer> marks = new java.util.HashMap<>();
marks.put("Alice", 85);
marks.put("Bob", 90);
marks.put("Charlie", 78);
marks.put("Alice", 95); // Overwrites previous value
System.out.println("Student Marks: " + marks);
System.out.println("Marks of Bob: " + marks.get("Bob"));
Tanushree Nair Page 68 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Is Alice in the map? " + marks.containsKey("Alice"));
marks.remove("Charlie");
System.out.println("After removing Charlie: " + marks);
System.out.println("All entries:");
for (String name : marks.keySet()) {
System.out.println(name + " -> " + marks.get(name));
}
System.out.println("Total entries: " + marks.size());
}
}
Tanushree Nair Page 69 of 78
MCA 208: Programming in Java MCA 2nd Semester
52. WAP to demonstrate the Vector class.
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Vector<String> animals = new Vector<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Elephant");
animals.add("Tiger");
System.out.println("Animals: " + animals);
System.out.println("First animal: " + animals.get(0));
animals.set(2, "Lion"); // Replacing "Elephant" with "Lion"
System.out.println("After update: " + animals);
animals.remove("Cat");
System.out.println("After removing Cat: " + animals);
System.out.println("Animals using loop:");
for (String animal : animals) {
System.out.println(animal);
}
System.out.println("Total animals: " + animals.size());
}
Tanushree Nair Page 70 of 78
MCA 208: Programming in Java MCA 2nd Semester
}
53. WAP to demonstrate the LinkedList class.
public class linkedlist {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
java.util.LinkedList<String> cities = new java.util.LinkedList<>();
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Chennai");
cities.add("Kolkata");
System.out.println("Cities: " + cities);
cities.addFirst("Bangalore");
cities.addLast("Hyderabad");
System.out.println("After adding at beginning and end: " + cities)
System.out.println("First city: " + cities.getFirst());
System.out.println("Last city: " + cities.getLast());
cities.remove("Chennai");
cities.removeFirst();
cities.removeLast();
System.out.println("After removals: " + cities);
System.out.println("Cities using loop:");
Tanushree Nair Page 71 of 78
MCA 208: Programming in Java MCA 2nd Semester
for (String city : cities) {
System.out.println(city);
}
// Size of the LinkedList
System.out.println("Total cities: " + cities.size());
}
}
54. WAP to demonstrate the JTextField class.
import javax.swing.*;
import java.awt.*;
public class jtextfield {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
JFrame frame = new JFrame("JTextField Example");
frame.setLayout(new FlowLayout());
JTextField textField = new JTextField(20); // 20 columns wide
textField.setText("Enter your name here");
JLabel label = new JLabel("Name:");
JButton button = new JButton("Show Name");
button.addActionListener(e -> {
Tanushree Nair Page 72 of 78
MCA 208: Programming in Java MCA 2nd Semester
String name = textField.getText(); // Get text from JTextField
JOptionPane.showMessageDialog(frame, "Hello, " + name + "!");
});
frame.add(label);
frame.add(textField);
frame.add(button);
frame.setSize(300, 150); // Width, Height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
56. WAP to demonstrate the JToggleButton class.
import javax.swing.*;
import java.awt.*;
public class JToggleButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JToggleButton Example");
frame.setLayout(new FlowLayout());
JToggleButton toggleButton = new JToggleButton("Off");
toggleButton.addActionListener(e -> {
if (toggleButton.isSelected()) {
toggleButton.setText("On");
} else {
toggleButton.setText("Off");
}
});
Tanushree Nair Page 73 of 78
MCA 208: Programming in Java MCA 2nd Semester
frame.add(toggleButton);
frame.setSize(300, 150); // Width, Height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Make the frame visible
}
}
57. WAP to demonstrate the JCheckbox class.
import javax.swing.*;
import java.awt.*;
public class JCheckBoxExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
JFrame frame = new JFrame("JCheckBox Example");
frame.setLayout(new FlowLayout());
JCheckBox checkBox = new JCheckBox("Accept Terms and Conditions");
checkBox.addActionListener(e -> {
if (checkBox.isSelected()) {
JOptionPane.showMessageDialog(frame, "You accepted the terms.");
} else {
JOptionPane.showMessageDialog(frame, "You did not accept the terms.");
}
});
Tanushree Nair Page 74 of 78
MCA 208: Programming in Java MCA 2nd Semester
frame.add(checkBox);
frame.setSize(300, 150); // Width, Height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Make the frame visible
}
}
58. WAP to demonstrate the JRadioButton class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JRadioButtonExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
JFrame frame = new JFrame("JRadioButton Example");
frame.setLayout(new FlowLayout());
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
Tanushree Nair Page 75 of 78
MCA 208: Programming in Java MCA 2nd Semester
JRadioButton radioButton3 = new JRadioButton("Option 3");
ButtonGroup group = new ButtonGroup();
group.add(radioButton1);
group.add(radioButton2);
group.add(radioButton3);
JButton button = new JButton("Show Selected Option");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedOption = "";
if (radioButton1.isSelected()) {
selectedOption = "Option 1";
} else if (radioButton2.isSelected()) {
selectedOption = "Option 2";
} else if (radioButton3.isSelected()) {
selectedOption = "Option 3";
}
JOptionPane.showMessageDialog(frame, "Selected Option: " + selectedOption);
}
});
frame.add(radioButton1);
frame.add(radioButton2);
frame.add(radioButton3);
frame.add(button);
frame.setSize(300, 200); // Width, Height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Make the frame visible
}
}
59. WAP to demonstrate the JComboBox class.
import javax.swing.*;
import java.awt.*;
public class JComboBoxExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
JFrame frame = new JFrame("JComboBox Example");
frame.setLayout(new FlowLayout());
String[] options = { "Option 1", "Option 2", "Option 3", "Option 4" };
JComboBox<String> comboBox = new JComboBox<>(options);
Tanushree Nair Page 76 of 78
MCA 208: Programming in Java MCA 2nd Semester
comboBox.addActionListener(e -> {
String selectedOption = (String) comboBox.getSelectedItem();
JOptionPane.showMessageDialog(frame, "You selected: " + selectedOption);
});
frame.add(comboBox);
frame.setSize(300, 150); // Width, Height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Make the frame visible
}
}
60. WAP to demonstrate the JList class
import javax.swing.*;
import java.awt.*;
public class JListExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
JFrame frame = new JFrame("JList Example");
frame.setLayout(new FlowLayout());
String[] fruits = { "Apple", "Banana", "Cherry", "Mango", "Orange", "Pineapple" };
JList<String> list = new JList<>(fruits);
list.addListSelectionListener(e -> {
Tanushree Nair Page 77 of 78
MCA 208: Programming in Java MCA 2nd Semester
if (!e.getValueIsAdjusting()) {
String selectedFruit = list.getSelectedValue();
JOptionPane.showMessageDialog(frame, "You selected: " + selectedFruit);
}
});
JScrollPane scrollPane = new JScrollPane(list);
frame.add(scrollPane);
frame.setSize(300, 200); // Width, Height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Make the frame visible
}
}
Tanushree Nair Page 78 of 78