0% found this document useful (0 votes)
25 views88 pages

Nafis Java - Manual

Java mca

Uploaded by

The RockyFF
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)
25 views88 pages

Nafis Java - Manual

Java mca

Uploaded by

The RockyFF
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/ 88

AMITY INSTITUTE OF

INFORMATION TECHNOLOGY
(AIIT)

Name: - Nafis Parwez


Enrolment No.: - A710145023050
Course: - MCA SEM I

JAVA LAB REPORT

1
AMITY UNIVERSITY MAHARASHTRA

Established vide Maharashtra Act No. 13 of 2014, of Government of


Maharashtra, and recognized under Section 2(t) of UGC Act 1956

CERTIFICATE

This is to certify that_MR. Nafis Parwez Enrolment No. A710145023050 of class MCA,
Semester 1 has satisfactorily completed the Java Lab Report Practical lab

Manual prescribed by Amity University Maharashtra during the academic year 2023-2024.

Sign of Faculty Sign of Dept. Coordinator

Name: Name:

_____________________ _____________________

Index
Sr. No Practical

2
1 1. WAP to print Hello World

2. WAP to perform Addition of numbers

3. WAP to calculate Simple Interest

4. WAP to calculate Perimeter of rectangle

1. WAP in java to print even and odd number between 100 to 150 using for loop.

2. WAP in java to print Fibonacci series upto 100 using while loop.

3. WAP in java to print prime number between 1 to 50.

4. WAP in java to check whether number is palindrome or not.

5. WAP in java to check whether number is armstrong or not.


3

1. Java Array Program to Find the Largest Element in an Array

2. Java Array Program to Copy All the Elements of One Array to Another Array

3. Java Array Program to Check Whether Two Matrices Are Equal or Not

4. Java Array Program to Find the Transpose

5. Java Array Program to Search an Element in an Array 6. Java Array Program for

Bubble Sort

3
1. Java Program to Count Number of Objects Created for Class Passing and
Returning Objects in Java

2. Java Program to Illustrate Use of Methods in a Class. Create different methods


to perform different arithmetic operations.

3. Java Program to Create a Method without Parameters and with Return Type.
Createmethod to calculate the volume of a cuboid which takes the dimensions length,
breadth and height as input and return the volume as output back to the main
method.

4. Java Program to Find Area of Square, Rectangle and Circle using Method
Overloading

5 1. Create a abstract class employee, having its properties & abstract function for
calculating net salary and displaying the information. Drive manager & clerk class
from this abstract class & implement the abstract method net salary and override
the display method.

2. Write a Java program to create a class known as "BankAccount" with methods


called deposit() and withdraw(). Create a subclass called SavingsAccount that
overrides the withdraw() method to prevent withdrawals if the account balance
falls below one hundred.

3. Write a Java program to create a vehicle class hierarchy. The base class should be
Vehicle, with subclasses Truck, Car and Motorcycle. Each subclass should have
properties such as make, model, year, and fuel type. Implement methods for
calculating fuel efficiency, distance traveled, and maximum speed.

4. Java Program to Use Super Keyword in Inheritance Class.

5. Java Program to Use This Keyword in Inheritance Class.

6. Write a Java Program to show the Implementation of Interface.

4
6

1. Write a Java program that throws an exception and catch it using a try-catch block.

2.Write a Java program to create a method that takes an integer as a parameter and
throws an exception if the number is odd.

3. Write a Java program to create a method that takes a string as input and throws an
exception if the string does not contain vowels.
7

1. Write a Java program to create a basic Java thread that prints "Hello, World!" when
executed.

2. Write a Java program that creates two threads to find and print even and odd number
s
from 1 to 20.

3. Write a Java program that creates a bank account with concurrent deposits and
withdrawals using threads.

4. Write a Java program to create and start multiple threads that increment a
shared counter variable concurrently.

5. Write a Java program to create a producer-consumer scenario using the wait()


and notify() methods for thread synchronization.
8
1. WAP to read text from text file.

2. WAP to write text in text file.


9
Write a java program for calculator operation using AWT controls

10

Write a java program for student registration using swing

5
Practical No. 1

6
7
8
Practical No. 2

9
1. WAP in java to print even and odd number between 100 to 150 using for
loop.
Evenodd.java public class EvenOdd { public

static void main(String[] args) {

System.out.println("Even numbers between 100 and 150:"); for (int i

= 100; i <= 150; i++) { if (i % 2 == 0) {

System.out.print(i + ", ");

System.out.println("\n\nOdd numbers between 100 and 150:"); for (int i =

100; i <= 150; i++) { if (i % 2 != 0) {

System.out.print(i + ", ");

Output:

10
11
12
}

13
}

Output:

. WAP in java to check whether number is palindrome or not.


Palindrome.java import
java.util.Scanner;

public class Palindrome { public static void

main(String[] args) {

Scanner input = new Scanner(System.in);


System.out.print("Enter a number: "); int num = input.nextInt();
int reversedNum = 0, originalNum = num, remainder; while
originalNum != 0) {

14
(

15
public class Armstrong { public static void main(String[]

args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a number: ");

16
int num = input.nextInt(); int originalNum,

remainder, result = 0; originalNum = num; while

(originalNum != 0) { remainder = originalNum %

10; result +=

Math.pow(remainder, 3); originalNum /= 10;

} if (result == num)

System.out.println(num + " is an Armstrong number."); else

System.out.println(num + " is not an Armstrong number."); input.close();

}
}

Practical No. 3

Q.1) Java Array Program to Find the Largest Element in an Array.


Solution –

Code  public class LargestElement_array { public

static void main(String[] args) { int [] arr = new int

[] {25, 11, 7,

75, 56}; int max = arr[0]; for (int i = 0; i <

17
arr.length; i++) { if(arr[i] > max) max =

arr[i];

System.out.println("Largest element present in given array: " + max);

Output 

Q.2) Java Array Program to Copy All the Elements of One Array to
Another Array.
Solution – Code

public class CopyArrayElements { public static

void main(String[] args) {

int [] arr1 = new int [] {1, 2, 3, 4, 5}; int arr2[] =

new int[arr1.length]; for (int i = 0; i < arr1.length; i++)

{ arr2[i] = arr1[i];

System.out.println("Elements of original array: "); for (int i =

0; i < arr1.length; i++) {

System.out.print(arr1[i] + " ");

18
}

System.out.println();

System.out.println("Elements of new array: "); for (int i =

0; i < arr2.length; i++) {

System.out.print(arr2[i] + " ");

Output 

Q.3) Java Array Program to Check Whether Two Matrices Are Equal or
Not.
Solution –

Code 

public class EqualMatrix

{ public static void main(String[] args) {

int row1, col1, row2, col2; boolean flag =

true; int a[][] = {

{1, 2, 5},

19
{4, 3, 7},

{8, 4, 6}

};

int b[][]

={

{1, 2, 5},

{4, 3, 7},

{8, 4, 6}

}; row1

a.length; col1 =

a[0].length;

row2 = b.length;

col2 = b[0].length;

if(row1 != row2 || col1 != col2){

System.out.println("Matrices are not equal");

} else { for(int i = 0; i <

row1; i++){ for(int j = 0; j < col1; j++){

if(a[i][j] != b[i][j]){ flag = false;

break;

} if(flag)

System.out.println("Matrices are equal"); else

System.out.println("Matrices are not equal");

20
}

Output 

Q.4) Java Array Program to Find the Transpose.


Solution –

Code 

public class Transpose { public static void main(String[] args) { int

row = 3, column = 3; int[][] matrix = { {2, 3, 4}, {5, 6, 4},

{8, 9, 7} };

display(matrix);

int[][] transpose = new int[column][row];

for(int i = 0; i < row; i++) { for (int j

= 0; j < column; j++) { transpose[j][i] =

matrix[i][j];

} display(transpose);

} public static void display(int[][] matrix) {

21
System.out.println("The matrix is: "); for(int[] row

: matrix) { for (int column : row) {

System.out.print(column + " ");

System.out.println();

Output 

Q.5) Java Array Program to Search an Element in an Array.


Solution –
Code 

public class LinearSearch{ public static int

linearSearch(int[] arr, int key){ for(int

i=0;i<arr.length;i++){ if(arr[i] == key){

return i;

22
return -1;

public static void main(String a[]){ int[]

a = {10,20,30,40,50,100}; int key

= 30;

System.out.println(key+" is found at index:

"+ linearSearch(a, key));

Output 

Q.6) Java Array Program for Bubble Sort.

Solution –

Code 

public class LinearSearch{ public static int

linearSearch(int[] arr, int key){ for(int

i=0;i<arr.length;i++){ if(arr[i] == key){

return i;

return -1;

23
public static void main(String a[]){ int[]

a = {10,20,30,40,50,100}; int key

= 30;

System.out.println(key+" is found at index: "+ linearSearch(a, key));

Output 

Practical No. 4
1. Java Program to Count Number of Objects Created for Class Passing and

Returning Objects in Java Prac41.java class ObjectCounter { static int objectCount =

0;

ObjectCounter() {

objectCount++;

ObjectCounter createNewObject() {

return new ObjectCounter(); }

public static void main(String[] args)

24
ObjectCounter obj1 = new ObjectCounter();

ObjectCounter obj2 = obj1.createNewObject();

System.out.println("Number of objects created: " + objectCount);

Output :

2. Java Program to Illustrate Use of Methods in a Class. Create different


methods to perform different arithmetic operations.

Prac42.java import java.util.Scanner; class

ArithmeticOperations { public static void

main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter first number: "); int num1

= input.nextInt();

System.out.print("Enter second number: "); int num2

= input.nextInt();

ArithmeticOperations obj = new ArithmeticOperations();

int result1 = obj.add(num1, num2);

25
System.out.println("Addition: " + result1); int result2 = obj.subtract(num1, num2);

System.out.println("Subtraction: " + result2);

int result3 = obj.multiply(num1, num2);

System.out.println("Multiplication: " + result3); int result4

= obj.divide(num1, num2);

System.out.println("Division: " + result4);

} int add(int a, int b) {

return a + b; } int

subtract(int a, int b) {

return a - b; } int

multiply(int a, int b) {

return a * b; } int

divide(int a, int b) { return

a / b;

}
}
Output:

3. Java Program to Create a Method without Parameters and with Return


Type. Create method to calculate the volume of a cuboid which takes the

26
dimensions length, breadth and height as input and return the volume as
output back to the main method.

Prac43.java import java.util.Scanner;

public class CuboidVolume { public static

void main(String[] args) { Scanner

input = new Scanner(System.in);

System.out.print("Enter length of the

cuboid: "); double length

= input.nextDouble();

System.out.print("Enter breadth of the cuboid: "); double breadth

= input.nextDouble();

System.out.print("Enter height of the cuboid: "); double height =

input.nextDouble(); double volume = calculateVolume(length,

breadth, height);

System.out.println("Volume of the cuboid: " + volume);

public static double calculateVolume(double length, double breadth, double height) {

return length * breadth * height;

27
}
Output:

4. Java Program to Find Area of Square, Rectangle and Circle using Method
Overloading
Prac44.java public class

AreaCalculator {

// Method to calculate the area of a square public

static double calculateArea(double side) { return side

* side;

// Method to calculate the area of a rectangle public static double

calculateArea(double length, double width) { return length * width;

// Method to calculate the area of a circle public static double calculateArea(double

radius, String shape) { if

(shape.equalsIgnoreCase("circle")) { return Math.PI * radius

* radius;

} else {

28
System.out.println("Invalid shape specified for circle area calculation."); return

-1;

} public static void main(String[] args) {

//

Calculate area of a square double squareSide =

5.0; double squareArea = calculateArea(squareSide);

System.out.println("Area of the square: " + squareArea);

// Calculate area of a rectangle double rectangleLength = 4.0; double

rectangleWidth = 6.0; double rectangleArea = calculateArea(rectangleLength,

rectangleWidth);

System.out.println("Area of the rectangle: " + rectangleArea);

// Calculate area of a circle double circleRadius =

3.0; double circleArea = calculateArea(circleRadius,

"circle");

System.out.println("Area of the circle: " + circleArea);

}
}
Output:

29
Practical No. 5

1. Create a abstract class employee, having its properties & abstract function
for calculating net salary and displaying the information. Drive manager &
clerk class from this abstract class & implement the abstract method net
salary and override the display method.
abstract class Employee {

String name; int employeeId;

double basicSalary;

Employee(String name, int

employeeId, double

basicSalary) { this.name =

name; this.employeeId =

employeeId;

this.basicSalary = basicSalary;

// Abstract method for calculating net salary

public abstract double calculateNetSalary();

// Display information public void

display() {

System.out.println("Employee ID: " + employeeId);

System.out.println("Name: " + name);

30
System.out.println("Basic Salary: " + basicSalary);

System.out.println("Net Salary: " + calculateNetSalary());

class Manager extends Employee { double

bonus;

Manager(String name, int employeeId, double basicSalary, double bonus) {

super(name, employeeId, basicSalary); this.bonus = bonus;

@Override public double calculateNetSalary()

{ return basicSalary

+ bonus;

@Override public void

display() {

super.display();

System.out.println("Bonus: " + bonus);

31
class Clerk extends Employee { double

overtime;

Clerk(String name, int employeeId, double basicSalary, double overtime) {

super(name, employeeId, basicSalary); this.overtime = overtime;

@Override public double

calculateNetSalary() { return basicSalary

+ overtime;

@Override public void

display() {

super.display();

System.out.println("Overtime: " + overtime);

class EmployeeTest { public static

void main(String[] args) {

Manager manager = new Manager("John", 101, 50000, 10000); manager.display();

System.out.println();

32
Clerk clerk = new Clerk("Alice", 102, 40000, 5000); clerk.display();

}
}
Output :

2. Write a Java program to create a class known as "BankAccount" with


methods called deposit() and withdraw(). Create a subclass called
SavingsAccount that overrides the withdraw() method to prevent
withdrawals if the account balance falls below one hundred.

class BankAccount { protected

double balance;

public void deposit(double amount) { balance

+= amount;

System.out.println("Deposited: " + amount);

33
public void withdraw(double amount) { if

(balance >= amount) { balance -

= amount;

System.out.println("Withdrawn: " + amount);

} else {

System.out.println("Insufficient funds. Withdrawal not allowed.");

class SavingsAccount extends BankAccount {

@Override public void withdraw(double

amount) { if (balance - amount >= 100)

{ balance -= amount;

System.out.println("Withdrawn: " + amount);

} else {

System.out.println("Withdrawal not allowed. Minimum balance should be 100.");

public class BankAccountTest {

public static void main(String[] args) {

34
SavingsAccount savingsAccount = new SavingsAccount();

savingsAccount.deposit(200); savingsAccount.withdraw(50);

savingsAccount.withdraw(150);

}
}
Output :

3. Write a Java program to create a vehicle class hierarchy. The base class
should be Vehicle, with subclasses Truck, Car and Motorcycle. Each subclass
should have properties such as make, model, year, and fuel type. Implement
methods for calculating fuel efficiency, distance traveled, and maximum
speed.
class Vehicle { protected

String make; protected

String model; protected int

year; protected String

fuelType;

// Constructor public Vehicle(String make, String model, int year,

String fuelType) { this.make = make; this.model = model;

this.year = year; this.fuelType

= fuelType;

35
// Method to calculate fuel efficiency (dummy implementation)

public double calculateFuelEfficiency() { // Dummy

implementation, replace with actual logic return 20.0; //

Assuming 20 miles per gallon for simplicity

// Method to calculate distance traveled (dummy implementation) public

double calculateDistance(double fuelAmount) { // Dummy

implementation, replace with actual logic return fuelAmount *

calculateFuelEfficiency();

// Method to get the maximum speed (dummy implementation) public int

getMaxSpeed() {

// Dummy implementation, replace with actual logic return

120; // Assuming 120 mph for simplicity

// Example usage in the same file public

static void main(String[] args) {

// Creating instances of Truck, Car, and Motorcycle

Truck truck = new Truck("Ford", "F-150", 2022, "Gasoline", 1500.0);

Car car = new Car("Toyota", "Camry", 2022, "Gasoline", 5);

Motorcycle motorcycle = new Motorcycle("Harley-Davidson", "Sportster",

2022, "Gasoline", false);

36
// Displaying information and using methods

System.out.println("Truck Fuel Efficiency: " +

truck.calculateFuelEfficiency() + " mpg");

System.out.println("Car Max Speed: " + car.getMaxSpeed() + " mph");

System.out.println("Motorcycle Distance Traveled: " +

motorcycle.calculateDistance(2.5) + " miles");

class Truck extends Vehicle { private double payloadCapacity;

// Additional property for trucks

// Constructor public Truck(String make, String model, int year, String

fuelType, double payloadCapacity) { super(make, model, year,

fuelType); this.payloadCapacity = payloadCapacity;

// Additional methods for trucks (if needed)

class Car extends Vehicle { private int seatingCapacity;

// Additional property for cars

// Constructor public Car(String make, String model, int year,

String fuelType, int seatingCapacity) { super(make, model, year,

fuelType); this.seatingCapacity = seatingCapacity;

// Additional methods for cars (if needed)

37
}

class Motorcycle extends Vehicle { private boolean hasSidecar;

// Additional property for motorcycles

// Constructor public Motorcycle(String make, String model, int year,

String fuelType, boolean hasSidecar) { super(make, model, year,

fuelType); this.hasSidecar = hasSidecar;

// Additional methods for motorcycles (if needed)


}
Output :

4. Java Program to Use Super Keyword in Inheritance Class.


class Animal {

String type;

// Constructor for Animal class public

Animal(String type) { this.type = type;

} void eat()

38
{

System.out.println("Animal is eating.");

} } class Dog extends

Animal {

String breed;

// Constructor for Dog class public

Dog(String type, String breed) {

// Using super to call the constructor of the immediate parent class Animal)

super(type); this.breed = breed;

// Overriding the eat method of the Animal class

@Override

void eat() {

// Using super to call the eat method of the immediate parent class Animal)

super.eat();

System.out.println("Dog is eating.");

} void bark()

System.out. println("Dog

is barking.");

} } class InheritanceExample { public static void

main(String[] args) {

// Creating an instance of the Dog class

39
Dog myDog = new Dog("Mammal", "Labrador");

// Calling methods from the Dog class

myDog.eat();

// Calls overridden eat method in Dog class, which alsocalls the eat method in Animal class

using super myDog.bark(); // Calls bark method in Dog class

// Accessing fields from the Animal class through the Dog class

System.out.println("Type of the dog: " + myDog.type);

System.out.println("Breed of the dog: " + myDog.breed);

}
}
Output :

5. Java Program to Use This Keyword in Inheritance Class.

class ParentClass {

int x;

void setX(int x) { this.x = x; // Using this keyword to distinguish between instance

variable and parameter

40
}

class ChildClass extends ParentClass { void

display() {

System.out.println("Value of x: " + x);

class ThisKeywordExample { public static void

main(String[] args) { ChildClass child = new

ChildClass(); child.setX(10); child.display();

Output :

6. Write a Java Program to show the Implementation of Interface.

// Example interface interface Shape { double calculateArea();

// Abstract method to calculate the area

41
double calculatePerimeter(); // Abstract method to calculate the perimeter }

// Example class implementing the Shape interface class

Circle implements Shape { private double radius;

// Constructor for Circle class public

Circle(double radius) { this.radius = radius;

// Implementation of the calculateArea method for Circle

@Override public double calculateArea()

{ return

Math.PI * radius * radius;

// Implementation of the calculatePerimeter method for Circle

@Override public double calculatePerimeter()

{ return 2 *

Math.PI * radius;

// Example class implementing the Shape interface

class Rectangle implements Shape { private double

length; private double width; // Constructor for

42
Rectangle class public Rectangle(double length,

double width) { this.length = length; this.width

= width;

// Implementation of the calculateArea method for Rectangle

@Override public double calculateArea()

{ return length

* width;

// Implementation of the calculatePerimeter method for Rectangle

@Override public double

calculatePerimeter() { return 2 *

(length + width); } } class

InterfaceExample { public static void

main(String[] args) {

// Creating instances of Circle and Rectangle

Circle circle = new Circle(5.0);

Rectangle rectangle = new Rectangle(4.0, 6.0);

// Using the implemented methods from the Shape interface

System.out.println("Circle Area: " + circle.calculateArea());

System.out.println("Circle Perimeter: " + circle.calculatePerimeter());

System.out.println("Rectangle Area: " + rectangle.calculateArea());

System.out.println("Rectangle Perimeter: " + rectangle.calculatePerimeter());

43
}

Output :

Practical No. 6

44
1. Write a Java program that throws an exception and catch it using a try-catch block.

import java.util.Scanner;

public class ExceptionExample { public static

void main(String[] args) {

try {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: "); int

userInput = scanner.nextInt();

// Throw an exception if (userInput < 0) { throw new

RuntimeException("Negative number entered!");

System.out.println("Entered number: " + userInput);

} catch (Exception e) {

// Catch the exception

System.out.println("Caught exception: " + e.getMessage());

45
}

Output:

46
2.Write a Java program to create a method that takes an integer as a parameter and
throws an exception if the number is odd.

import java.util.Scanner; public class

OddException { public static void main(String[] args)

try {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: "); int userInput =

scanner.nextInt(); // Call the method with user input

checkIfEven(userInput);

} catch (Exception e) {

System.out.println("Caught exception: " + e.getMessage());

47
// Method to check if a number is even public static void checkIfEven(int

number) throws Exception { if (number % 2 != 0) { throw new

Exception("Number is odd!");

} else {

System.out.println("Number is even.");

Output :

48
3. Write a Java program to create a method that takes a string as input and throws an

exception if the string does not contain vowels. Vowel.java import java.util.Scanner;

public class vowel { public static void main(String[]

args) {

try {

Scanner scanner = new Scanner(System.in);

49
50
1. Write a Java program to create a basic Java thread that prints "Hello, World!" when

executed. Prac71.java class HelloWorldThread extends Thread { public void run() {

System.out.println("Hello, World!");

public static void main(String[] args) {

HelloWorldThread thread = new HelloWorldThread();

thread.start();

Output:

51
2. Write a Java program that creates two threads to find and print even and odd

numbers from 1 to 20. Prac72.java class EvenOddThreadExample { public static void

main(String[] args) {

Thread evenThread = new Thread(() -> printNumbers(true));

52
Thread oddThread = new Thread(() -> printNumbers(false));

evenThread.start(); oddThread.start();

private static void printNumbers(boolean isEven) { for (int i =

(isEven ? 2 : 1); i <= 20; i += 2) {

System.out.println((isEven ? "Even: " : "Odd: ") + i);

Output:

53
54
55
3. Write a Java program that creates a bank account with concurrent deposits and

withdrawals using threads. Prac73.java class BankAccount { private int balance = 0;

public synchronized void deposit(int amount) { balance +=

amount;

System.out.println("Deposit: " + amount + ", Balance: " + balance);

public synchronized void withdraw(int amount) { if

(balance >= amount) { balance -= amount;

System.out.println("Withdrawal: " + amount + ", Balance: " + balance);

} else {

System.out.println("Insufficient funds for withdrawal");

class BankTransaction { public static void main(String[]


args) {

56
BankAccount account = new BankAccount();

Thread depositThread = new Thread(() -> {

for (int i = 0; i < 5; i++) { account.deposit(100);

});

Thread withdrawThread = new Thread(() -> {

for (int i = 0; i < 3; i++) { account.withdraw(50);

});

depositThread.start(); withdrawThread.start();

Output:

57
4. Write a Java program to create and start multiple threads that increment a shared counter

variable concurrently. Prac74.java class SharedCounter { private int count =

0;

public synchronized void increment() { count++;

System.out.println("Count: " + count);

public class SharedCounterExample { public static

void main(String[] args) {

SharedCounter counter = new SharedCounter();

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

58
Thread thread = new Thread(() -> { for

(int j = 0; j < 5; j++) { counter.increment();

} });

thread.start();

Output:

5. Write a Java program to create a producer-consumer scenario using the wait() and
notify() methods for thread synchronization. Prac75.java import java.util.LinkedList; import
java.util.Queue;

59
60
61
class SharedResource { private Queue<Integer> buffer = new

LinkedList<>(); private int capacity = 5;

public synchronized void produce() throws InterruptedException { while

(buffer.size() == capacity) { wait();

int item = (int) (Math.random() * 100); buffer.add(item);

System.out.println("Produced: " + item);

notify();

public synchronized void consume() throws InterruptedException { while

(buffer.isEmpty()) { wait();

int item = buffer.poll();

System.out.println("Consumed: " + item);

62
63
64
65
notify();

class ProducerConsumerExample { public static

void main(String[] args) {

SharedResource sharedResource = new SharedResource();

Thread producerThread = new Thread(() -> {

for (int i = 0; i < 5; i++) { try {

sharedResource.produce();

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

});

Thread consumerThread = new Thread(() -> {

for (int i = 0; i < 5; i++) { try {


sharedResource.consume();

66
Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

});

producerThread.start(); consumerThread.start();

}
}

Output:

67
Practical No. 8

1. WAP to read text from text file. Prac81.java


import java.io.BufferedReader; import

java.io.FileReader; import java.io.IOException;

class ReadTextFromFile { public static


void main(String[] args) {
String fileName = "sample.txt"; // Replace with the actual file path and name

try (BufferedReader reader = new BufferedReader(new


FileReader(fileName))) {
String line;
System.out.println("Contents of " + fileName + ":"); while ((line =
reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:

68
2. WAP to write text in text file.
Prac82.java import

java.io.BufferedWriter; import

java.io.FileWriter; import

java.io.IOException;

public class WriteTextFileExample { public static

void main(String[] args) {

String fileName = "output.txt";

try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {

String content = "Hello, this is a sample text.\nWritten to a file using Java.";

// Writing content to the file writer.write(content);

System.out.println("Text written to " + fileName);

} catch (IOException e) {

e.printStackTrace();

69
}

Output:

Practical 9
1. Write a java program for calculator operation using AWT controls.
Code 

70
import java.awt.*;
import java.awt.event.*;

public class TextFieldExample2 extends Frame implements ActionListener {


TextField tf1, tf2, tf3;
Button b1, b2;

TextFieldExample2() {
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false); b1
= new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);

b1.addActionListener(this);
b2.addActionListener(this);

add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);

setSize(300,300);
setLayout(null); setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0; if
(e.getSource() == b1){
c = a + b;

71
} else if
(e.getSource() == b2){ c
= a - b;
}
String result = String.valueOf(c); tf3.setText(result);
} public static void main(String[] args)
{ new
TextFieldExample2();
}
}

Output 

72
Practical 10
1. Write a java program for student registration using swing.
Code 

73
import javax.swing.*; import
java.awt.*; import java.awt.event.*;
class MyFrame extends JFrame
implements ActionListener {
private Container c; private
JLabel title; private JLabel name;
private JTextField tname; private
JLabel mno; private
JTextField tmno; private
JLabel gender; private
JRadioButton male; private
JRadioButton female;
private ButtonGroup gengp;
private JLabel dob; private
JComboBox date; private
JComboBox month; private
JComboBox year; private
JLabel add; private
JTextArea tadd; private
JCheckBox term; private
JButton sub; private
JButton reset; private
JTextArea tout; private
JLabel res; private
JTextArea resadd;
private String dates[]
= { "1", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"11", "12", "13", "14", "15",
"16", "17", "18", "19", "20",
"21", "22", "23", "24", "25",
"26", "27", "28", "29", "30",
"31" };
private String months[]
= { "Jan", "feb", "Mar", "Apr",
"May", "Jun", "July", "Aug",
"Sup", "Oct", "Nov", "Dec" }; private
String years[]
= { "1995", "1996", "1997", "1998",

74
Adarsh Harpude
A710145023067

75
Adarsh Harpude
A710145023067

"2003", "2004", "2005", "2006",


"2007", "2008", "2009", "2010",
"2011", "2012", "2013", "2014",
"2015", "2016", "2017", "2018",
"2019" };
public
MyFrame()
{ setTitle("Registration
Form"); setBounds(300, 90, 900,
600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false); c =
getContentPane();
c.setLayout(null); title = new
JLabel("Registration Form"); title.setFont(new
Font("Arial", Font.PLAIN, 30));
title.setSize(300, 30); title.setLocation(300,
30);
c.add(title); name = new
JLabel("Name"); name.setFont(new Font("Arial",
Font.PLAIN, 20)); name.setSize(100, 20);
name.setLocation(100, 100);
c.add(name); tname = new JTextField();
tname.setFont(new Font("Arial", Font.PLAIN, 15));
tname.setSize(190, 20); tname.setLocation(200,
100);
c.add(tname); mno = new
JLabel("Mobile"); mno.setFont(new
Font("Arial", Font.PLAIN, 20));
mno.setSize(100, 20); mno.setLocation(100,
150);
c.add(mno);
tmno = new JTextField();
tmno.setFont(new Font("Arial", Font.PLAIN, 15));
tmno.setSize(150, 20); tmno.setLocation(200,
150);
c.add(tmno);

gender = new JLabel("Gender");

76
Adarsh Harpude
A710145023067

77
Adarsh Harpude
A710145023067

78
Adarsh Harpude
A710145023067

gender.setSize(100, 20);
gender.setLocation(100, 200);
c.add(gender); male = new
JRadioButton("Male"); male.setFont(new
Font("Arial", Font.PLAIN, 15));
male.setSelected(true); male.setSize(75, 20);
male.setLocation(200, 200);
c.add(male); female = new
JRadioButton("Female"); female.setFont(new
Font("Arial", Font.PLAIN, 15));
female.setSelected(false);
female.setSize(80, 20);
female.setLocation(275, 200); c.add(female);
gengp = new ButtonGroup(); gengp.add(male);
gengp.add(female); dob = new
JLabel("DOB"); dob.setFont(new Font("Arial",
Font.PLAIN, 20)); dob.setSize(100, 20);
dob.setLocation(100,
250);
c.add(dob); date = new
JComboBox(dates); date.setFont(new
Font("Arial", Font.PLAIN, 15));
date.setSize(50, 20); date.setLocation(200,
250);
c.add(date); month = new
JComboBox(months); month.setFont(new
Font("Arial", Font.PLAIN, 15));
month.setSize(60, 20); month.setLocation(250,
250);
c.add(month); year = new
JComboBox(years); year.setFont(new
Font("Arial", Font.PLAIN, 15));
year.setSize(60, 20);
year.setLocation(320,
250);
c.add(year);

add = new JLabel("Address");

79
Adarsh Harpude
A710145023067

80
Adarsh Harpude
A710145023067

81
Adarsh Harpude
A710145023067

add.setFont(new Font("Arial", Font.PLAIN, 20));


add.setSize(100, 20); add.setLocation(100,
300);
c.add(add); tadd = new JTextArea();
tadd.setFont(new Font("Arial", Font.PLAIN, 15));
tadd.setSize(200, 75); tadd.setLocation(200,
300); tadd.setLineWrap(true);
c.add(tadd); term = new JCheckBox("Accept
Terms And Conditions."); term.setFont(new
Font("Arial", Font.PLAIN, 15));
term.setSize(250, 20); term.setLocation(150,
400); c.add(term); sub = new
JButton("Submit"); sub.setFont(new Font("Arial",
Font.PLAIN, 15)); sub.setSize(100, 20);
sub.setLocation(150, 450);
sub.addActionListener(this); c.add(sub);
reset = new
JButton("Reset"); reset.setFont(new
Font("Arial", Font.PLAIN, 15));
reset.setSize(100, 20);
reset.setLocation(270, 450);
reset.addActionListener(this); c.add(reset);
tout = new JTextArea(); tout.setFont(new
Font("Arial", Font.PLAIN, 15));
tout.setSize(300, 400); tout.setLocation(500,
100); tout.setLineWrap(true);
tout.setEditable(false); c.add(tout);
res = new JLabel(""); res.setFont(new
Font("Arial", Font.PLAIN, 20));
res.setSize(500, 25); res.setLocation(100,
500);
c.add(res);
resadd = new JTextArea();
resadd.setFont(new Font("Arial", Font.PLAIN, 15));

82
Adarsh Harpude
A710145023067

83
Adarsh Harpude
A710145023067

84
Adarsh Harpude
A710145023067

resadd.setSize(200, 75); \ resadd.setLocation(580, 175);


resadd.setLineWrap(true);
c.add(resadd);
setVisible(true); }
public void
actionPerformed(ActionEvent e)
{ if (e.getSource() ==
sub) { if
(term.isSelected()) {
String data1;
String data
= "Name : "
+ tname.getText() + "\n"
+ "Mobile : "
+ tmno.getText() +
"\n"; if (male.isSelected())
data1 = "Gender : Male"
+ "\n";
else data1 = "Gender :
Female"
+ "\n";
String data2
= "DOB : "
+ (String)date.getSelectedItem()
+ "/" + (String)month.getSelectedItem()
+ "/" + (String)year.getSelectedItem()
+ "\n";

String data3 = "Address : " + tadd.getText();


tout.setText(data + data1 + data2 + data3);
tout.setEditable(false);
res.setText("Registration Successfully..");
} else {
tout.setText("");
resadd.setText("");
res.setText("Please accept the"
+ " terms & conditions..");
}
}
else if (e.getSource() ==
reset) {

85
Adarsh Harpude
A710145023067

String def = ""; tname.setText(def);


tadd.setText(def);

86
Adarsh Harpude
A710145023067

tmno.setText(def);
res.setText(def);
tout.setText(def);
term.setSelected(false);
date.setSelectedIndex(0);
month.setSelectedIndex(0);
year.setSelectedIndex(0);
resadd.setText(def);
}
}
} class
Registration {
public static void main(String[] args) throws
Exception
{
MyFrame f = new MyFrame();
}
}

Output 

87
Adarsh Harpude
A710145023067

88

You might also like