0% found this document useful (0 votes)
5 views123 pages

DhruvShah JavaExperiments

The document outlines a series of Java programming laboratory experiments for the academic year 2023-24, focusing on control statements, loops, arrays, and strings. Each experiment includes problem statements, code implementations, and expected outputs. The conclusion emphasizes the successful implementation of the respective Java concepts.

Uploaded by

arnavdalal1234
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)
5 views123 pages

DhruvShah JavaExperiments

The document outlines a series of Java programming laboratory experiments for the academic year 2023-24, focusing on control statements, loops, arrays, and strings. Each experiment includes problem statements, code implementations, and expected outputs. The conclusion emphasizes the successful implementation of the respective Java concepts.

Uploaded by

arnavdalal1234
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/ 123

Object Oriented Programming using Java Laboratory (DJS23FLES201)

Academic Year 2023-24

EXPERIMENT NO. 1

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement Java control statements, loops, and command line argument

PROGRAM/CODE:

Problem Statement 1:

Given an integer, n, perform the following conditional actions:


· If n is odd, print Weird
· If n is even and in the inclusive range of 2 to 5, print Not Weird
· If n is even and in the inclusive range of 6 to 20, print Weird
· If n is even and greater than 20, print Not Weird

Code:

import java.util.Scanner;

class Main {
public static void main(String args[]){
Scanner scanner= new Scanner(System.in);
System.out.println("Enter a number:");
int n = scanner.nextInt();
if(n%2!=0)

System.out.println("Weird");
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
else if(n>=2 && n<=5)
System.out.println("Not Weird");
else if(n>=20 && n<= 6)
System.out.println("Weird");
else if(n>20)
System.out.println("Not Weird");
}
}

OUTPUT:

Problem Statement 2:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
WAP to find largest of 3 numbers using nested if else and nested ternary
operator.

Code:

(a)

import java.util.Scanner;

class Main {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter three numbers:");
int a = s.nextInt();
int b = s.nextInt();
int c = s.nextInt();

if (a > b) {
if (a > c)
System.out.println("The greatest is " + a);
else
System.out.println("The greatest is " + c);
} else {
if (b > c)
System.out.println("The greatest is " + b);
else
System.out.println("The greatest is " + c);
}
}
}

(b)

import java.util.Scanner;

class Main{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
System.out.println("Enter three numbers:");
int a = s.nextInt();
int b = s.nextInt();
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
int c = s.nextInt();

int largest = (a>b)?(a>c)?a:c:(b>c)?b:c;


System.out.println("The greatest is " + largest);
}
}

Output:

(a)

(b)

Problem Statement 3:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Write a Java program that reads a positive integer from command line and count
the number of digits the number (less than ten billion) has.

Code:

class Main{
public static void main(String args[]){
long n = Long.parseLong(args[0]);
int count = 0;
while(n!=0){
count++;
n/=10;
}

System.out.println("The number of digits is " + count);


}

Output:

Problem Statement 4:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Write a menu driven program using switch case to perform mathematical
operations.

Code:

import java.util.Scanner;
class Main{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
System.out.println("Enter two numbers:");
int a = s.nextInt();
int b = s.nextInt();
System.out.println("Enter the operation:");
System.out.println("1 for Addition");
System.out.println("2 for Subtraction");
System.out.println("3 for Multiplication");
System.out.println("4 for Division");
char choice = s.next().charAt(0);
String result = "The result of the operation is ";
switch(choice){
case '1':
result+= (a+b);
break;
case '2':
result += (a-b);
break;
case '3':
result += (a*b);
break;
case '4':
result += ((float)a/b);
break;
default:
result = "Invalid Input";
}
System.out.println(result);
}

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Problem Statement 5:

WAP to find grade of student from input marks using if else ladder and switch
case.

Code:

(a)

import java.util.Scanner;

class Main {
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter marks:");
int marks = scanner.nextInt();
String output = "Your grade is ";
if(marks>100)
output = "Invalid marks";
else if(marks>=90)
output+= "A";
else if(marks>=80)
output += "B";
else if(marks>=70)
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
output += "C";
else if(marks>=60)
output+= "D";
else if(marks>=50)
output+= "E";
else
output+= "F";
System.out.println(output);
}
}

(b)

import java.util.Scanner;

class Main{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter marks:");
int marks = scanner.nextInt();
String output = "Your grade is ";
switch(marks/10){
case 10:
case 9:
output += "A";
break;
case 8:
output += "B";
break;
case 7:
output += "C";
break;
case 6:
output += "D";
break;
case 5:
output += "E";
break;
case 4:
case 3:
case 2:
case 1:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
case 0:
output += "F";
break;
default:
output = "Invalid marks";
}
System.out.println(output);
}
}

Output :

(a)

(b)
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Problem Statement 6:

WAP to print the sum of following series 1+1/2^2+1/3^2+1/4^2……+1/n^2

Code:

import java.util.Scanner;

class Main{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter n:");
int n = scanner.nextInt();
double sum = 0;
for(int i = 1;i<=n;i++){
sum += 1.0/(i*i);
}
System.out.println("The value of the series is " + sum);
}
}

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Problem Statement 7:

WAP to display the following patterns:


1
21
123
4321
12345
654321
1234567
A
CB
FED
JIHG

Code:

(a)

class Main{
public static void main(String args[]){
int n = Integer.parseInt(args[0]);
int i,j;
for(i = 1;i<=n;i++){
if(i%2==0)
for(j = i;j>=1;j--)
System.out.print(j + " ");
else
for(j = 1;j<=i;j++)
System.out.print(j + " ");
System.out.println();
}
}
}
(b)
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
class Main{

public static void main(String args[]){


int n = Integer.parseInt(args[0]);
int i,j;
char c = 'A';
for(i = 1;i<=n;i++){
for(j = 1;j<=n-i;j++)
System.out.print(" ");
for(j = 1;j<=i;j++)
System.out.print((char)(c-j+1));

c=(char)((i+1)*(i+2)/2+64);
System.out.println();
}
}
}

Output:

(a)

(b)
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

CONCLUSION:

We have successfully studied and implemented java control statement, loops and command
line arguments

Website References:​ (Give references to the cited material)


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 2

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

Aim/ Objective :

To implement Arrays

Program/ Code:

Problem Statement 1:

You have been given an array of positive integers A1, A2,...,An with length N and
you have to print an array of same length (N) where the values in the new array are
the sum of every number in the array, except the number at that index.
i/p 1 2 3 4
For the 0th index, the result will be 2+3+4= 9, similarly for the second, third and
fourth index the corresponding results will be 8, 7 and 6 respectively.
i/p 4 5 6
o/p 11 10 9
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

Scanner s = new Scanner(System.in);

System.out.print("Enter the length of array:");

int nums[] = new int[s.nextInt()];

System.out.println("Enter the elements:");

int sum = 0;

for(int i = 0;i<nums.length;i++){

nums[i] = s.nextInt();

sum += nums[i];

int sumarray[] = new int[nums.length];

for(int i = 0;i<nums.length;i++)

sumarray[i] = sum-nums[i];

System.out.println("The output Array:");

for(int n : sumarray)

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

System.out.println();

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Output:

Problem Statement 2:

The annual examination results of 5 students are tabulated as follows:

WAP to read the data and determine the following


Total marks obtained by each student
The student who obtained the highest total marks

Code:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
import java.util.Scanner;

class Main{

public static void main(String args[]){

Scanner s = new Scanner(System.in);

int size = 5;

int highest = 0;

int rollno[] = new int[size];

int sub1[] = new int[size];

int sub2[] = new int[size];

int sub3[] = new int[size];

int total[] = new int[size];

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

System.out.println("Enter Rollno and marks of Subject1, Subject2,


Subject3:");

rollno[i]=s.nextInt();

sub1[i]=s.nextInt();

sub2[i]=s.nextInt();

sub3[i]=s.nextInt();

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

total[i] = sub1[i]+sub2[i]+sub3[i];

if(total[i]>total[highest])
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
highest = i;

System.out.println("\nData entered");

System.out.println("Rollno\tSub1\tSub2\tSub3\tTotal");

for(int i = 0;i<size;i++)

System.out.println(rollno[i] + "\t" + sub1[i] + "\t" + sub2[i] + "\t" +


sub3[i] + "\t" + total[i]);

System.out.println("Rollno of student with highest total marks is " +


rollno[highest]);

System.out.println("Highest total marks " + total[highest]);

}}

Output:

Problem Statement 3:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
WAP to display following pattern using irregular arrays (jagged arrays).
1
12
123…

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number if rows:");

int row = scanner.nextInt();

int arr[][] = new int[row][];

for(int i = 1;i<=row;i++){

arr[i-1] = new int[i];

for(int j = 1;j<=i;j++){

arr[i-1][j-1] = j;

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

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

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

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println();

}}

Output:

CONCLUSION:

We have successfully studied and implemented concept of java arrays and jagged arrays.

Website References:​ (Give references to the cited material)


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 3

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement Strings

PROGRAM/CODE:

Problem Statement 1:

WAP to find out number of uppercase & lowercase characters, blank spaces and
digits from the string

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

Scanner scanner = new Scanner(System.in);

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

String s = scanner.nextLine();

int lower = 0,upper = 0,blank = 0,digits=0;


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
for(int i = 0;i<s.length();i++){

char c = s.charAt(i);

if('A'<=c && c<='Z')

upper++;

else if('a'<=c && c<='z')

lower++;

else if('0'<=c && c<= '9')

digits++;

else if(c==' ')

blank++;

System.out.println("No. of upper case char: " + upper);

System.out.println("No. of lower case char: " + lower);

System.out.println("No. of digits: " + digits);

System.out.println("No. of blank spaces: " + blank);

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Problem Statement 2:

WAP to count the frequency of occurrence of a given character in a given line of


text

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

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

Scanner scanner = new Scanner(System.in);

String s = scanner.nextLine();

System.out.print("Enter the search character:");

char c = scanner.next().charAt(0);

int count = 0, i = 0;

while(s.indexOf(c,i) != -1){
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
count++;

i = s.indexOf(c,i)+1;

System.out.println("The frequency of the character is " + count);

Output:

Problem Statement 3:

WAP to check if a string is a palindrome or not using inbuild functions.

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

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

Scanner scanner = new Scanner(System.in);

String word = scanner.next();


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
StringBuffer sb = new StringBuffer(word);

sb.reverse();

if(word.equalsIgnoreCase(sb.toString()))

System.out.println("The word is a palindrome");

else

System.out.println("The word is not a palindrome");

Output:

CONCLUSION:

We have successfully studied and implemented concept of java Strings and its
inbuilt functions

Website References:​ (Give references to the cited material)


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 4

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement collections (Array List/ Vectors)

PROGRAM/CODE:

Problem Statement 1:

WAP to accept students name from command line and store them in vector.

Code:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
import java.util.*;

class Main{

public static void main(String args[]){

Vector<String> names = new Vector<String>();

for(String name : args){

names.addElement(name);

System.out.println("Entered names:");

Enumeration en = names.elements();

while(en.hasMoreElements()){

System.out.println(en.nextElement());

Output:

Problem Statement 2:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
WAP to add n strings in a vector array. Input new string and check if it is present
in the vector. If present delete it else add to the vector

Code:

import java.util.*;

class Main{

public static void main(String args[]){

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements:");

int length = scanner.nextInt();

scanner.nextLine();

Vector<String> strings = new Vector<String>();

System.out.println("Enter strings:");

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

strings.addElement(scanner.nextLine());

System.out.print("Enter the string to be added/removed:");

String s = scanner.nextLine();

if(strings.contains(s)){

int firstindex = strings.indexOf(s);

strings.removeElementAt(firstindex);

while(strings.contains(s)){

strings.removeElementAt(strings.indexOf(s));
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

else{

strings.addElement(s);

System.out.println("Updated set:");

Enumeration en = strings.elements();

while(en.hasMoreElements()){

System.out.println(en.nextElement());

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

CONCLUSION:

We have successfully studied and implemented concept of java collections and


its use cases such as Array List and Vector

Website References:​ (Give references to the cited material)


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 5

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement class with members and methods (static, non-static, recursive and
overloaded methods)

PROGRAM/CODE:

Problem Statement 1:

Create a class employee with data member’s empid, empname, designation and
salary. Write methods getemployee() to take user input, showgrade() to display
grade of employee based on salary, showemployee() to display details of
employee.

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

Employee em = new Employee();

em.getEmployee();

em.showEmployee();

em.showGrade();
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

class Employee{

private String empid;

private float salary;

private String designation;

private String empname;

public void getEmployee(){

System.out.println("Enter name, ID, designation and salary of employee:");

Scanner s = new Scanner(System.in);

empname = s.nextLine();

empid = s.nextLine();

designation = s.nextLine();

salary = s.nextFloat();

public void showGrade(){

if(salary>500000)

System.out.println("Grade: A");

else if(salary>100000)

System.out.println("Grade: B");

else

System.out.println("Grade: C");
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

public void showEmployee(){

System.out.println("Employee details:");

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

System.out.println("ID: " + empid);

System.out.println("Designation: " + designation);

System.out.println("Salary: " + salary);

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Problem Statement 2:

WAP to display area of square and rectangle using the concept of overloaded
functions

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

Scanner s = new Scanner(System.in);

System.out.println("Enter length of square and length and breadth of


rectangle:");

float len = s.nextFloat();

float rlen = s.nextFloat();

float rbre = s.nextFloat();

displayArea(len);

displayArea(rlen,rbre);

static void displayArea(float len){

System.out.println("Area of square is " + len*len);

static void displayArea(float len, float breadth){


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println("Area of rectangle is " + len*breadth);

}}

Output:

Problem Statement 3:

WAP to find value of y using recursive function (static), where y=x^n

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

Scanner s = new Scanner(System.in);

System.out.print("Enter x and n:");

float x = s.nextFloat();

int n = s.nextInt();

System.out.println("The value of x^n is " + pow(x,n));

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
static float pow(float x,int y){

if(y==0)

return 1;

return x*pow(x,y-1);

Output:

Problem Statement 4:

WAP to count the number of objects made of a particular class using static
variable and static method and display the same.

Code:

class Main{

public static void main(String args[]){

StringWrapper strings[] = new StringWrapper[args.length];

for(int i = 0;i<args.length;i++){
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
strings[i] = new StringWrapper(args[i]);

strings[i].count();

StringWrapper.showCount();

System.out.println("Value of StringWrappers:");

for(StringWrapper s : strings){

System.out.println(s);

class StringWrapper{

private static int count = 0;

private String string;

StringWrapper(String s){

string = s;

public static void showCount(){

System.out.println("Number of StringWrapper classes: " + count);

public String toString(){

return string;

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
public static void count(){

count++;

Output:

CONCLUSION:

We have successfully studied and implemented concept of java classes and


methods (static and non-static)

Website References:​ (Give references to the cited material)


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 6

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement array of objects and passing/ returning objects

PROGRAM/CODE:

Problem Statement 1:

WOOP to arrange the names of students in descending order of their total marks,
input data consists of students details such as names, ID.no, marks of maths,
physics, chemistry. (Use array of objects)

Code:

import java.util.Scanner;

class Main {
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of students: ");

Student students[] = new Student[scanner.nextInt()];

for(int i = 0;i<students.length;i++){

students[i] = new Student();

students[i].input();

for(int i =0;i<students.length-1;i++){

for(int j = 0;j<students.length-1;j++){

if(students[j].getTotal()<students[j+1].getTotal()){

Student temp = students[j];

students[j] = students[j+1];

students[j+1] = temp;

System.out.println("Data Set:");

Student.printFormat();

for(Student student : students){

System.out.println(student);

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

class Student {

private String name;

private int idno;

private int maths, phy, chem;

private int total;

public int getTotal() {

return total;

public void input() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter name:");

name = scanner.nextLine();

System.out.print("Enter ID no:");

idno = scanner.nextInt();

System.out.print("Enter physics marks:");

phy = scanner.nextInt();

System.out.print("Enter maths marks:");

maths = scanner.nextInt();

System.out.print("Enter chemistry marks:");

chem = scanner.nextInt();
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
total = phy + chem + maths;

scanner.nextLine();

System.out.println();

public static void printFormat() {

System.out.println("Name\tID\tPhy\tChem\tMaths\tTotal");

public String toString() {

String s = name + "\t" + idno + "\t" + phy + "\t" + chem + "\t" + maths + "\t" + total;

return s;

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Problem Statement 2:

WAP to perform mathematical operations on 2 complex numbers by passing and


returning object as argument. Show the use of this pointer.

Code:

import java.util.Scanner;
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
public class Main {

public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter x,y for first number:");

Complex a = new Complex(scanner.nextFloat(), scanner.nextFloat());

System.out.println("Enter x,y for second number:");

Complex b = new Complex(scanner.nextFloat(), scanner.nextFloat());

System.out.println("Enter the operation:");

System.out.println("1 for Addition");

System.out.println("2 for Subtraction");

System.out.println("3 for Multiplication");

System.out.println("4 for Division");

switch (scanner.next().charAt(0)) {

case '1':

System.out.print("Addition: ");

System.out.println(a.add(b));

break;

case '2':

System.out.print("Subraction: ");

System.out.println(a.sub(b));
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
break;

case '3':

System.out.print("Multiplition: ");

System.out.println(a.multiply(b));

break;

case '4':

System.out.print("Division: ");

System.out.println(a.divide(b));

break;

default:

System.out.println("Invalid Input");

break;

scanner.close();

class Complex {

private float x;

private float y;

Complex(float real, float img) {


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
this.x = real;

this.y = img;

public float getReal() {

return this.x;

public float getImaginary() {

return this.y;

public Complex add(Complex op) {

float x = this.x + op.x;

float y = this.y + op.y;

return new Complex(x, y);

public Complex sub(Complex op) {

float x = this.x - op.x;

float y = this.y - op.y;

return new Complex(x, y);

public Complex multiply(Complex op) {


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
float x = this.x * op.x - this.y * op.y;

float y = this.x * op.y + this.y * op.x;

return new Complex(x, y);

public Complex divide(Complex op) {

float x = this.x * op.x + this.y * op.y;

float y = this.y * op.x - this.x * op.y;

x /= op.x * op.x + op.y * op.y;

y /= op.x * op.x + op.y * op.y;

return new Complex(x, y);

public Complex conjugate() {

return new Complex(x, -y);

public String toString() {

String temp;

if (this.y < 0) {

temp = this.x + " - " + -this.y + "i";

} else {

temp = this.x + " + " + this.y + "i";


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

return temp;

Output:

CONCLUSION:

We have successfully studied and implemented concept of array of objects in


java

EXPERIMENT NO. 7

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
To implement Constructors and constructor overloading

PROGRAM/CODE:

Problem Statement 1:

WAOOP to count the no. of objects created of a class using constructors.

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

Count c1 = new Count();

Count c2 = new Count();

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

Count c3 = new Count();

Count c4 = new Count();

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

class Count{

static int count = 0;

Count(){

count++;

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Output:

Problem Statement 2:

WAP to display area of square and rectangle using the concept of overloaded
constructor (use parameterized, non-parameterized and copy constructor)

Code:

import java.util.Scanner;

class Main{

public static void main(String args[]){

Scanner scanner = new Scanner(System.in);

System.out.println("Enter length:");

Shape square = new Shape(scanner.nextDouble());

System.out.println("Enter length and breadth of rectangle:");

Shape rect = new Shape(scanner.nextDouble(),scanner.nextDouble());

Shape copysquare = new Shape();

copysquare = new Shape(square);

System.out.println(square);

System.out.println(rect);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println("Square copy:");

System.out.println(copysquare);

class Shape{

private double length,breadth,area;

Shape(){}

Shape(Shape copy){

this.length = copy.length;

this.breadth = copy.breadth;

this.area = copy.area;

Shape(double length){

this.length = length;

area = this.length * this.length;

Shape(double length,double breadth){

this.length = length;

this.breadth = breadth;

area = this.length * this.breadth;

public String toString(){


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
return breadth==0?"Area of square is " + area:"Area of rectangle is " + area;

Output:

CONCLUSION:

We have successfully studied and implemented the concept of constructor and constructor
overloading

Website References:​ (Give references to the cited material)


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 8

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement Inheritance and super keyword

PROGRAM/CODE:

Problem Statement 1:

WAP to demonstrate the role of Constructors in inheritance in the following class diagram.

Code:

class test{

public static void main(String args[]){

C c = new C();

class A{

int a = 0;

A(){

System.out.println("From A");

System.out.println("a = " + a);

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

class B extends A {

int a = super.a + 1;

int b = 0;

B(){

System.out.println("From B");

System.out.println("a = " + a);

System.out.println("b = " + b);

class C extends B {

int a = super.a + 1;

int b = super.b + 1;

int c = 0;

C(){

System.out.println("From C");

System.out.println("a = " + a);

System.out.println("b = " + b);

System.out.println("c = " + c);

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
OUTPUT:

Problem Statement 2:

WAP to create a super class having a variable. Let the variable be initialized to some value within a
constructor. This class should have a method display () to display the initial value of the variable.
Derive a sub class that accesses the constructor, variable and method of the super class using super
keyword.

Code:

class test{

public static void main(String args[]){

SubClass s = new SubClass();

s.display();

class SuperClass{
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
int x;

SuperClass(){

x = 234567;

public void display(){

System.out.println("The value in SuperClass is " + x);

class SubClass extends SuperClass{

SubClass(){

super();

public void display(){

super.display();

System.out.println("The value in SubClass is " + super.x);

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Problem Statement 3:

Display data of the specialized classes given in the following class diagram.

Code:

import java.util.Scanner;

class test {

public static void main(String args[]) {

Teacher t = new Teacher();

Regular r = new Regular();

Casual c = new Casual();

Officer o = new Officer();

System.out.println("----------------------------------------------");

t.read();

System.out.println("----------------------------------------------");

r.read();
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println("----------------------------------------------");

c.read();

System.out.println("----------------------------------------------");

o.read();

System.out.println("----------------------------------------------");

System.out.println();

System.out.println("Details");

System.out.println();

System.out.println("----------------------------------------------");

t.display();

System.out.println("----------------------------------------------");

r.display();

System.out.println("----------------------------------------------");

c.display();

System.out.println("----------------------------------------------");

o.display();

System.out.println("----------------------------------------------");

class Staff {

protected int code;

protected String name;


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

class Teacher extends Staff {

private String subject;

private float exp;

public void read() {

System.out.println("Enter Teacher details:");

System.out.println("Enter name and code:");

Scanner scanner = new Scanner(System.in);

name = scanner.nextLine();

code = scanner.nextInt();

System.out.println("Enter Subject and Experience:");

subject = scanner.next();

exp = scanner.nextFloat();

scanner.nextLine();

public void display() {

System.out.println("Teacher Details:");

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

System.out.println("Code: " + code);

System.out.println("Subject: " + subject);

System.out.println("Experience: " + exp);

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

class Typist extends Staff {

protected float speed, exp;

class Regular extends Typist {

private float sal;

public void read() {

System.out.println("Enter Regular Typist details:");

System.out.println("Enter name and code:");

Scanner scanner = new Scanner(System.in);

name = scanner.nextLine();

code = scanner.nextInt();

System.out.println("Enter salary, speed, experience:");

sal = scanner.nextFloat();

speed = scanner.nextFloat();

exp = scanner.nextFloat();

scanner.nextLine();

public void display() {

System.out.println("Regular Typist Details:");

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

System.out.println("Code: " + code);


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println("Speed: " + speed);

System.out.println("Experience: " + exp);

System.out.println("Salary: " + sal);

class Casual extends Typist {

private float daily_wages;

public void read() {

System.out.println("Enter Casual Typist details:");

System.out.println("Enter name and code:");

Scanner scanner = new Scanner(System.in);

name = scanner.nextLine();

code = scanner.nextInt();

System.out.println("Enter daily wages, speed, experience:");

daily_wages = scanner.nextFloat();

speed = scanner.nextFloat();

exp = scanner.nextFloat();

scanner.nextLine();

public void display() {

System.out.println("Casual Typist Details:");

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


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println("Code: " + code);

System.out.println("Speed: " + speed);

System.out.println("Experience: " + exp);

System.out.println("Daily wages: " + daily_wages);

class Officer extends Staff {

private String dept, grade;

public void read() {

System.out.println("Enter Officer details:");

System.out.println("Enter name and code:");

Scanner scanner = new Scanner(System.in);

name = scanner.nextLine();

code = scanner.nextInt();

scanner.nextLine();

System.out.println("Enter department and grade:");

dept = scanner.nextLine();

grade = scanner.nextLine();

public void display() {

System.out.println("Officer Details:");
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println("Name: " + name);

System.out.println("Code: " + code);

System.out.println("Department: " + dept);

System.out.println("Grade: " + grade);

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

CONCLUSION:

We have successfully studied and implemented concept of inheritance and super keyword.

Website References:​ (Give references to the cited material)


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 9

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement multiple inheritance using interfaces and method overriding.

PROGRAM/CODE:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Problem Statement 1:

Design an interface with a method reversal. This method takes a string as input and returns the
reversed string. Create a class that implements the above interface.

Code:

interface StringManipulation {

String reversal(String input);

class StringReversal implements StringManipulation {

@Override

public String reversal(String input) {

StringBuilder reversedString = new StringBuilder();

for (int i = input.length() - 1; i >= 0; i--) {

reversedString.append(input.charAt(i));

return reversedString.toString();

public class test {

public static void main(String[] args) {

StringManipulation stringManipulation = new StringReversal();

String input = "Hello, world!";

String reversed = stringManipulation.reversal(input);


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println("Original string: " + input);

System.out.println("Reversed string: " + reversed);

}}

Output:

Problem Statement 2:

WAP to implement three classes namely Student, Test and Result. Student class has member as
rollno, and read(). Test class has members as sem1_marks and sem2_marks and read(). Result class
has member as total. Create an interface named sports that has a member score (). Derive Test class
from Student and Result class has multiple inheritances from Test and Sports. Total is formula based
on sem1_marks, sem2_mark and score. Use super keyword.

Code:

import java.util.*;

class Student {

protected String Name;

public Student() {

this.Name = "";

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
public Student(String name) {

this.Name = name;

class Exam extends Student {

protected int m1, m2, m3;

public Exam() {

super();

this.m1 = 0;

this.m2 = 0;

this.m3 = 0;

public Exam(String name, int m1, int m2, int m3) {

super(name);

this.m1 = m1;

this.m2 = m2;

this.m3 = m3;

public void accept() {

Scanner sc = new Scanner(System.in);

System.out.println("Enter name of student and marks in 3 subjects:");


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
this.Name = sc.nextLine();

this.m1 = sc.nextInt();

this.m2 = sc.nextInt();

this.m3 = sc.nextInt();

interface Sports {

int m = 10;

void IP();

class Result extends Exam implements Sports {

private int total;

private double percent;

public Result() {

super();

this.total = 0;

this.percent = 0.0;

public Result(String name, int m1, int m2, int m3) {

super(name, m1, m2, m3);

this.total = 0;
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
this.percent = 0.0;

public void IP() {

Scanner sc = new Scanner(System.in);

int ip;

System.out.println("1.Successful in state/national level sports\n2.Not applicable\nEnter


your choice:");

ip = sc.nextInt();

if (ip == 1) total = total + m;

if (total > 300) total = 300;

public void calc() {

total = m1 + m2 + m3;

public void display() {

percent = total / 300.0 * 100;

System.out.println("Name:" + Name + "\nTotal=" + total + "\nPercentage=" + percent);

class test {

public static void main(String args[]) {


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Result r = new Result();

r.accept();

r.calc();

r.IP();

r.display();

Output:

Conclusion:

We have successfully studied the programs to implement multiple inheritance using


interfaces and method overriding.
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 10

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement dynamic polymorphism, final keyword and garbage collection

PROGRAM/CODE:

Problem Statement 1:

Demonstrate using a suitable example that a base class reference variable can point to a child class
object or a base class object using the concept of dynamic method dispatch (dynamic
polymorphism).

Code:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
class Animal {

public void sound() {

System.out.println("Animal makes a sound");

}}

class Dog extends Animal {

public void sound() {

System.out.println("Dog barks");

}}

class Cat extends Animal {

public void sound() {

System.out.println("Cat meows");

}}

public class test {

public static void main(String[] args) {

Animal animal1 = new Dog();

Animal animal2 = new Cat();

animal1.sound();

animal2.sound();

}}

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Problem Statement 2:

Adwita , 8th Grade student wants to write a functions to calculate simple interest, compound
interest. She wants to keep same (final) rate of interest for every input of principal and time. She
wants to ensure that the declared functions are not overridden in any subclasses and the class is not
inherited by any other class. Help her to declare the variables methods and classes and write the
code for the same using final keyword.

Code:

public final test{

private final double rate;

public InterestCalculator(double rate){

this.rate = rate;

public final double calculateSimpleInterest(double principal, double time) {

return (principal * rate * time) / 100;

public final double calculateCompoundInterest(double principal, double time) {

return principal * Math.pow((1 + rate / 100), time) - principal;

public static void main(String[] args) {

InterestCalculator calculator = new InterestCalculator(5.0);


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
double principal = 1000;

double time = 2;

double simpleInterest = calculator.calculateSimpleInterest(principal, time);

double compoundInterest = calculator.calculateCompoundInterest(principal, time);

System.out.println("Simple Interest: " + simpleInterest);

System.out.println("Compound Interest: " + compoundInterest);

Output:

Problem Statement 3:

WAP to create an object of a class, delete the same object by calling System. gc () and display a
message that the “object has been deleted”.

Code:

class MyClass {

public MyClass() {

System.out.println("Object created");

protected void finalize() throws Throwable {


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
System.out.println("Object has been deleted");

super.finalize();

public class test {

public static void main(String[] args) {

MyClass obj = new MyClass(); // Creating an object

obj = null; // Making the object eligible for garbage collection

System.gc(); // Requesting garbage collection

Output:

Conclusion:

We have successfully studied the programs to implement multiple inheritance using


interfaces and method overriding.
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 11

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement Abstract classes and packages.

PROGRAM/CODE:

Problem Statement 1:

To implement Abstract classes and packages.

Code:

abstract class Shape {

abstract double calculateArea();

class Circle extends Shape {

double radius;

Circle(double radius) {

this.radius = radius;

double calculateArea() {

return Math.PI * radius * radius;

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

class Rectangle extends Shape {

double length, width;

Rectangle(double length, double width) {

this.length = length;

this.width = width;

double calculateArea() {

return length * width;

class Triangle extends Shape {

double base, height;

Triangle(double base, double height) {

this.base = base;

this.height = height;

double calculateArea() {

return 0.5 * base * height;

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
public class test {

public static void main(String[] args) {

Circle circle = new Circle(5);

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

Rectangle rectangle = new Rectangle(4, 6);

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

Triangle triangle = new Triangle(3, 8);

System.out.println("Area of Triangle: " + triangle.calculateArea());

Output:

Problem Statement 2:

WAP to create a package called vol having Cylinder class and volume (). WAP that imports this
package to calculate volume of a Cylinder.

Code:

package vol;

public class Cylinder {

public static double volume(double radius, double height) {


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
return Math.PI * radius * radius * height;

import vol.Cylinder;

public class Main {

public static void main(String[] args) {

double radius = 3.5;

double height = 8.2;

double volume = Cylinder.volume(radius, height);

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

Output:

Conclusion:

From above examples we learnt to implement exceptions in Java (read input using DataInputStream/
BufferedReader classes).
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
EXPERIMENT NO. 12

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement exceptions in Java (read input using DataInputStream/ BufferedReader classes)

PROGRAM/CODE:

Problem Statement 1:

Code:

import java.io.IOException;

public class test {

public static void checkedExceptionDemo() {

try {

Class.forName("NonExistentClass");
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
} catch (ClassNotFoundException e) {

System.out.println("Class not found: " + e.getMessage());

public static void checkedIOExceptionDemo() {

try {

throw new IOException("An IOException occurred");

} catch (IOException e) {

System.out.println("IOException occurred: " + e.getMessage());

public static void uncheckedNumberFormatExceptionDemo() {

String str = "abc";

try {

int num = Integer.parseInt(str);

} catch (NumberFormatException e) {

System.out.println("NumberFormatException occurred: " + e.getMessage());

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

public static void uncheckedArithmeticExceptionDemo() {

try {

int result = 10 / 0;

} catch (ArithmeticException e) {

System.out.println("ArithmeticException occurred: " + e.getMessage());

public static void uncheckedArrayIndexOutOfBoundsExceptionDemo() {

try {

int[] arr = new int[5];

int value = arr[10];

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("ArrayIndexOutOfBoundsException occurred: " + e.getMessage());

public static void uncheckedNullPointerExceptionDemo() {

try {

String str = null;


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
int length = str.length();

} catch (NullPointerException e) {

System.out.println("NullPointerException occurred: " + e.getMessage());

public static void main(String[] args) {

checkedExceptionDemo();

checkedIOExceptionDemo();

uncheckedNumberFormatExceptionDemo();

uncheckedArithmeticExceptionDemo();

uncheckedArrayIndexOutOfBoundsExceptionDemo();

uncheckedNullPointerExceptionDemo();

Output:

Problem Statement 2:
Write a Java Program to Create a User Defined Exception class MarksOutOfBoundsException, If
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Entered marks of any subject is greater than 100 or less than 0, and then program should create a
user defined Exception of type MarksOutOfBoundsException and must have a provision to handle it.

Code:

class MarksOutOfBoundsException extends Exception {

public MarksOutOfBoundsException(String message) {

super(message);

public class test {

public static void validateMarks(int marks) throws MarksOutOfBoundsException {

if (marks < 0 || marks > 100) {

throw new MarksOutOfBoundsException("Marks should be between 0 and 100.");

public static void main(String[] args) {

try {

int marks = 110;

validateMarks(marks);

System.out.println("Marks are valid: " + marks);

} catch (MarksOutOfBoundsException e) {

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

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

Output:

Conclusion:

We have successfully studied and implemented program to throw and handle exceptions in
java.
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

EXPERIMENT NO. 13

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement Multithreading.

PROGRAM/CODE:

Problem Statement 1:

Write a multithreaded program a java program to print Table of Five, Seven and Thirteen using
Multithreading (Use Thread class for the implementation).

Code:

import java.util.*;

class Multi extends Thread{

public void run(){

for(int i=1;i<=10;i++){

try{

System.out.println(5*i);

Thread.sleep(1000);}

catch(Exception e){

System.out.print(e);}

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}}

class Multi2 extends Thread{

public void run(){

for(int i=1;i<=10;i++){

try{

System.out.println(7*i);

Thread.sleep(1000);}

catch(Exception e){

System.out.print(e);}

}}

class Multi3 extends Thread{

public void run(){

for(int i=1;i<=10;i++){

try{

System.out.println(13*i);

Thread.sleep(1000);}

catch(Exception e){

System.out.println(e);}

}}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
class test{

public static void main(String args[]){

Multi t1=new Multi();

t1.start();

Multi2 t2=new Multi2();

t2.start();

Multi3 t3=new Multi3();

t3.start();

}}

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Problem Statement 2:

Write a multithreaded program to display /*/*/*/*/*/*/*/* using 2 child threads.

Write a multithreaded program to display /*/*/*/*/*/*/*/* using 2 child threads.

Code:

import java.util.*;

class Multi implements Runnable{

public void run(){

if(Thread.currentThread().getName().equals("slash")){

for(int i=1;i<=8;i++){

try{

System.out.print("/");

Thread.sleep(1000);}

catch(Exception e){

System.out.println(e);}

}}

else if(Thread.currentThread().getName().equals("star")){

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

try{

System.out.print("*");

Thread.sleep(1000);}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
catch(Exception e){

System.out.print(e);}

}}

}}

class test{

public static void main(String args[]){

Thread t1, t2;

t1=new Thread(new Multi());

t2=new Thread(new Multi());

t1.setName("slash");

t2.setName("star");

t1.start();

t2.start();

}}

Output:

Problem Statement 3:

Write a program to demonstrate thread methods: wait notify suspend resume join setpriority
getpriority setname getname

Code:

class MyThread extends Thread {


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
public MyThread(String name) {

super(name);

public void run() {

synchronized(this) {

System.out.println(Thread.currentThread().getName() + " is running.");

try {

Thread.sleep(2000);

System.out.println(Thread.currentThread().getName() + " is waiting.");

wait();

System.out.println(Thread.currentThread().getName() + " is notified.");

} catch (InterruptedException e) {

e.printStackTrace();

public class test {

public static void main(String[] args) {

MyThread t1 = new MyThread("Thread 1");

MyThread t2 = new MyThread("Thread 2");


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
t1.start();

t2.start();

try {

t1.join();

t2.join();

} catch (InterruptedException e) {

e.printStackTrace();

t1.setPriority(Thread.MAX_PRIORITY);

System.out.println("Thread 1 Priority: " + t1.getPriority());

t1.suspend();

System.out.println("Thread 1 is suspended.");

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

t1.resume();

System.out.println("Thread 1 is resumed.");

t1.setName("New Thread Name");

System.out.println("Thread 1 Name: " + t1.getName());


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

Output:

Problem Statement 4:
Write a multithreaded program that generates the Fibonacci sequence. This program should work as
follows: create a class Input that reads the number of Fibonacci numbers that the program is to
generate. The class will then create a separate thread that will generate the Fibonacci numbers,
placing the sequence in an array. When the thread finishes execution, the parent thread (Input class)
will output the sequence generated by the child thread. Because the parent thread cannot begin
outputting the Fibonacci sequence until the child thread finishes, the parent thread will have to wait
for the child thread to finish.

Code:

import java.util.*;

class FibThread extends Thread{

int no,fib1=0,fib2=1,fib3, fib[ ];

FibThread(int n){

no=n;

public void run(){

synchronized(this){
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
fib=new int[no];

fib[0]=fib1;

fib[1]=fib2;

System.out.print("Fibonacci series of "+no+ " elements");

for(int i=2;i<no;i++)

try{

fib3=fib1+fib2;

fib[i]=fib3;

fib1=fib2;

fib2=fib3;

System.out.println("...");

Thread.sleep(1000);

catch(Exception e){

System.out.print(e);

notify();

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
public void display(int n){

System.out.println("Fibonacci Series: ");

for(int i=0;i<n;i++)

System.out.println(fib[i]);

class test{

public static void main(String args[]){

int n;

Scanner sc=new Scanner(System.in);

System.out.print("Enter no of terms in fibonacci series: ");

n=sc.nextInt();

FibThread f=new FibThread(n);

f.start();

synchronized(f){

try{

System.out.println("Parent thread waiting for fibonacci thread to generate all numbers in


series");

f.wait();
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

catch(Exception e){

System.out.println(e.getMessage());

f.display(n);

}}

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Problem Statement 5:

WAP to prevent concurrent booking of a ticket using the concept of thread synchronization.

Code:
import java.util.*;

class TicketBooking{

Scanner sc=new Scanner(System.in);

synchronized public void bookTicket(){

int fare;

try{

System.out.print("Enter fare: ");

fare=sc.nextInt();

System.out.print("You ticket booking is in progress");

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

System.out.print("...\n");

Thread.sleep(500);

System.out.println("Ticket booking confirmed");

catch(Exception e){

System.out.println(e);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

}}

class Passenger extends Thread{

TicketBooking ticket;

Passenger(TicketBooking ticket){

this.ticket= ticket;

public void run(){

ticket.bookTicket();

}}

class test{

public static void main(String args[]){

TicketBooking ob=new TicketBooking();

Passenger p1=new Passenger(ob);

Passenger p2=new Passenger(ob);

p1.start();

p2.start();

}}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Output:

Conclusion:
We have successfully studied and implemented program of Multithreading.
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
EXPERIMENT NO. 14

ROLL NO. : C043 SAP ID: 60004230015

NAME: DHRUV SHAH BATCH: C1-2

AIM / OBJECTIVE:

To implement basic Swing programs with event handling

PROGRAM/CODE:

Problem Statement 1:

To implement basic Swing programs with event handling.

Code:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class test extends JFrame implements ActionListener {

JLabel loginLabel, passwordLabel, outputLabel;

JTextField loginField, passwordField, outputField;

JButton OKButton, resetButton;

public test() {

// Text labels
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
loginLabel = new JLabel("Login:");

passwordLabel = new JLabel("Password:");

outputLabel = new JLabel("Output:");

outputLabel.setVisible(false); // Initially hidden

// Text fields for user input

loginField = new JTextField(10);

passwordField = new JTextField(10);

outputField = new JTextField(10);

outputField.setVisible(false); // Initially hidden

// Buttons

OKButton = new JButton("OK");

resetButton = new JButton("RESET");

// Set layout manager

JPanel panel = new JPanel(new GridLayout(4, 2))

// Add components to the panel

panel.add(loginLabel);

panel.add(loginField);

panel.add(passwordLabel);

panel.add(passwordField);

panel.add(outputLabel);

panel.add(outputField);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
panel.add(OKButton);

panel.add(resetButton);

// Add panel to the frame

add(panel);

// Register action listener for buttons

OKButton.addActionListener(this);

resetButton.addActionListener(this);

public void actionPerformed(ActionEvent e) {

if (e.getSource() == OKButton) {

String loginText = loginField.getText();

String passwordText = passwordField.getText();

outputField.setText("Login: " + loginText + ", Password: " + passwordText);

outputLabel.setVisible(true);

outputField.setVisible(true);

} else if (e.getSource() == resetButton) {

loginField.setText("");

passwordField.setText("");

outputField.setText("");

outputLabel.setVisible(false);

outputField.setVisible(false);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

public static void main(String[] args) {

test frame = new test();

frame.setTitle("Registration Form");

frame.setSize(300, 150);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Problem Statement 2:

Write a program to create a basic calculator.

Code:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class Main {

public static void main(String[] args){

new calculator();

class calculator extends JFrame implements ActionListener{

JTextField t1;

JButton[] numberButtons = new JButton[10];

JButton[] functionButtons = new JButton[9];

JButton add, sub, mul, div;

JButton dec, del, clr, solve, neg;

JPanel panel;
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Font myFont = new Font("Ink free", Font.PLAIN, 30);

double num1 = 0, num2 = 0, result = 0;

char operator;

calculator(){

super("Calculator");

this.setSize(420,550);

this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);

this.setLayout(null);

this.setResizable(false);

// this.getContentPane().setBackground(Color.black);

t1 = new JTextField();

t1.setBounds(50,25,300,50);

t1.setFont(myFont);

t1.setEditable(false);

add = new JButton("+");

sub = new JButton("-");

mul = new JButton("*");


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
div = new JButton("/");

dec = new JButton(".");

clr = new JButton("clr");

del = new JButton("del");

solve = new JButton("=");

neg = new JButton("(-)");

functionButtons[0] = add;

functionButtons[1] = sub;

functionButtons[2] = mul;

functionButtons[3] = div;

functionButtons[4] = dec;

functionButtons[5] = solve;

functionButtons[6] = del;

functionButtons[7] = clr;

functionButtons[8] = neg;

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

functionButtons[i].setFont(myFont);

functionButtons[i].setFocusable(false);

functionButtons[i].addActionListener(this);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

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

numberButtons[i] = new JButton(String.valueOf(i));

numberButtons[i].setFocusable(false);

numberButtons[i].setFont(myFont);

numberButtons[i].addActionListener(this);

neg.setBounds(50,430,100,50);

del.setBounds(150,430,100,50);

clr.setBounds(250,430,100,50);

panel = new JPanel();

panel.setBounds(50,100,300,300);

panel.setLayout(new GridLayout(4,4,10,10));

panel.add(numberButtons[1]);

panel.add(numberButtons[2]);

panel.add(numberButtons[3]);

panel.add(add);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

panel.add(numberButtons[4]);

panel.add(numberButtons[5]);

panel.add(numberButtons[6]);

panel.add(sub);

panel.add(numberButtons[7]);

panel.add(numberButtons[8]);

panel.add(numberButtons[9]);

panel.add(mul);

panel.add(dec);

panel.add(numberButtons[0]);

panel.add(solve);

panel.add(div);

this.add(panel);

this.add(neg);

this.add(del);

this.add(clr);

this.add(t1);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
this.setVisible(true);

public void actionPerformed(ActionEvent e){

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

if (e.getSource() == numberButtons[i]) {

t1.setText(t1.getText().concat(String.valueOf(i)));

if(e.getSource() == dec){

t1.setText(t1.getText().concat(String.valueOf(".")));

if(e.getSource() == neg){

Double temp = Double.parseDouble(t1.getText());

temp *= -1;

t1.setText(String.valueOf(temp));

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
if(e.getSource() == add){

num1 = Double.parseDouble(t1.getText());

operator = '+';t1.setText("");

if(e.getSource() == sub){

num1 = Double.parseDouble(t1.getText());

operator = '-';

t1.setText("");

if(e.getSource() == mul){

num1 = Double.parseDouble(t1.getText());

operator = '*';

t1.setText("");

if(e.getSource() == div){

num1 = Double.parseDouble(t1.getText());

operator = '/';

t1.setText("");
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

if(e.getSource() == solve){

num2 = Double.parseDouble(t1.getText());

switch(operator){

case '+':

result = num1 + num2;

break;

case '-':

result = num1 - num2;

break;

case '*':

result = num1 * num2;

break;

case '/':

result = num1 / num2;

break;
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
}

t1.setText(String.valueOf(result));

if(e.getSource() == clr){

t1.setText("");

if(e.getSource() == del){

String str = t1.getText();

t1.setText("");

for(int i = 0; i < str.length() - 1; i++){

t1.setText(t1.getText() + str.charAt(i));

}
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
Output:

Problem Statement 3:

Code:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class Form extends JFrame implements ActionListener

{
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

JLabel name,gen,interest,place,details;

JTextField tname;

JRadioButton male, female;

JComboBox cplace;

JButton submit,exit;

JTextArea tadd;

JCheckBox music,swim;

ButtonGroup gengp;

public Form()

setTitle("Form");

setBounds(200, 80, 800, 800);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setResizable(false);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

setLayout(null);

name = new JLabel("Name");

name.setFont(new Font("Arial", Font.PLAIN, 15));

name.setSize(100, 20);

name.setLocation(100, 100);

add(name);

tname = new JTextField();

tname.setFont(new Font("Arial", Font.PLAIN, 15));

tname.setSize(190, 20);

tname.setLocation(200, 100);

add(tname);

gen = new JLabel("Gender");

gen.setFont(new Font("Arial", Font.PLAIN, 15));

gen.setSize(100, 20);

gen.setLocation(100, 150);

add(gen);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

male = new JRadioButton("Male");

male.setFont(new Font("Arial", Font.PLAIN, 15));

male.setSelected(true);

male.setSize(80, 20);

male.setLocation(200, 150);

add(male);

female = new JRadioButton("Female");

female.setFont(new Font("Arial", Font.PLAIN, 15));

female.setSize(80, 20);

female.setLocation(350, 150);

add(female);

gengp = new ButtonGroup();

gengp.add(male);

gengp.add(female);

interest = new JLabel("Interest");

interest.setFont(new Font("Arial", Font.PLAIN, 15));


Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
interest.setSize(100, 20);

interest.setLocation(100, 200);

add(interest);

music = new JCheckBox("Music");

music.setFont(new Font("Arial", Font.PLAIN, 15));

music.setSize(100, 20);

music.setLocation(200, 200);

add(music);

swim = new JCheckBox("Swim");

swim.setFont(new Font("Arial", Font.PLAIN, 15));

swim.setSize(100, 20);

swim.setLocation(350, 200);

add(swim);

place = new JLabel("Fav Place");

place.setFont(new Font("Arial", Font.PLAIN, 15));

place.setSize(100, 20);

place.setLocation(100, 250);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
add(place);

cplace = new JComboBox();

cplace.setFont(new Font("Arial", Font.PLAIN, 15));

cplace.setSize(150, 20);

cplace.setLocation(200, 250);

add( cplace);

cplace.addItem("India");

cplace.addItem("USA");

cplace.addItem("Bhutan");

cplace.addItem("Srilanka");

cplace.addItem("Maldives");

details = new JLabel("Details");

details.setFont(new Font("Arial", Font.PLAIN, 15));

details.setSize(100, 20);

details.setLocation(100, 300);

add(details);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

tadd = new JTextArea();

tadd.setFont(new Font("Arial", Font.PLAIN, 15));

tadd.setSize(200, 200);

tadd.setLocation(200, 300);

tadd.setLineWrap(true);

tadd.setEditable(false);

add(tadd);

submit = new JButton("Submit");

submit.setFont(new Font("Arial", Font.PLAIN, 15));

submit.setSize(100, 20);

submit.setLocation(150, 550);

submit.addActionListener(this);

add(submit);

exit = new JButton("Reset");

exit.setFont(new Font("Arial", Font.PLAIN, 15));

exit.setSize(100, 20);
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
exit.setLocation(270, 550);

exit.addActionListener(this);

add(exit);

setVisible(true);

public void actionPerformed(ActionEvent e)

if(e.getSource() == submit)

String data = "Name : " + tname.getText() + "\n" +

" Gender : " +(male.isSelected()==true?"Male":"Female") +


"\n" +

" Interests : "+ (music.isSelected()==true?"Music ":"")+

(swim.isSelected()==true?"Swimming":"") +"\n" +

" Favorite Place : " +


cplace.getItemAt(cplace.getSelectedIndex());
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24
tadd.setVisible(true);

tadd.setText(data);

//tadd.setEditable(false);

else if(e.getSource() == exit)

tadd.setText("");

class test {

public static void main(String[] args) throws Exception

Form f = new Form();

Output:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
Academic Year 2023-24

Conclusion:
We have successfully studied and implemented the programs to run GUI applications using
Java Swing.

You might also like