0% found this document useful (0 votes)
24 views67 pages

Java Control Statements Assignment

This is java exp
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)
24 views67 pages

Java Control Statements Assignment

This is java exp
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

NAME. SAHISHNU S GUPTA ROLL NO.

I016 SAP ID :- 60003240158


BATCH :- I1-1
1. To implement Java control statements, loops, and command line arguments
a. 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 [Link];
public class p1
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
int n; [Link]("Enter a
number : "); n = [Link](); if
(n%2!=0) {
[Link]("Wierd"); } else { if
(n>=2 && n<=5) {
[Link]("Not Wierd"); }
if(n>=6 && n<=20) {
[Link]("Wierd"); } if
(n>20) { [Link]("Not
Wierd"); } }

}
}
OUTPUT :-
CONCLUSION :- The program uses if-else statements to classify a number as Weird or Not
Weird demonstrating Java’s unconditional logic.
b. WAP to find largest of 3 numbers using nested if else and nested ternary operator.

CODE :- (Using nested if else)

import [Link];
public class p1b
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
int n1, n2, n3;
[Link]("Enter first number: ");
n1 = [Link]();
[Link]("Enter second number: ");
n2 = [Link]();
[Link]("Enter third number: ");
n3 = [Link]();
if(n1>n2 && n1>n3)
{
[Link](n1+" is greater number.");
}
else if (n2>n3 && n2>n1)
{
[Link](n2+" is greater number.");
}
else
{
[Link](n3+" is greater number.");
}
}
}
OUTPUT :-

CODE :- (Using Nested Ternary Operator)

import [Link];
public class p1b2
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
int n1, n2, n3;
[Link]("Enter first number: ");
n1 = [Link]();
[Link]("Enter second number: ");
n2 = [Link]();
[Link]("Enter third number: ");
n3 = [Link]();
int max;
max = (n1>n2)?((n1>n3)?n1:n3):((n2>n3)?n2:n3);
[Link]("The maximum number is "+max);
}
}
OUTPUT :-
CONCLUSION :- The program finds the largest of three numbers using nested if-else and
nested ternary operators, showcasing Java’s decision making constructs effeciently.
c. 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 :-
import [Link];
public class p1c
{

public static void main(String[]args)


{
int n = [Link](args[0]);
int count = 0;
while(n!=0)
{
count++;
n=n/10;
}
[Link]("The number of digits is "+count);
}
}

OUTPUT :-

CONCLUSION :- This program reads a positive integer from the command line and count it
digits using integer parsing and loops, demonstrating Java’s command line input handling and
basic arithmetic operations.

d. Write a menu driven program using switch case to perform mathematical operations.
CODE :-

import [Link];
public class p1d
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
[Link]("1 :- Addition");
[Link]("2 :- Subtraction");
[Link]("3 :- Multiplication");
[Link]("4 :- Division");
int a,b,c;
[Link]("Enter the first number: ");
a = [Link]();
[Link]("Enter the second number: ");
b = [Link]();
[Link]("Choose operation: ");
c = [Link]();
switch(c)
{
case 1:
{
[Link]("The output is "+(a+b));
break;
}
case 2:
{
[Link]("The output is "+(a-b));
break;
}
case 3:
{
[Link]("The output is "+(a*b));
break;
}
case 4:
{
[Link]("The output is "+(a/b));
break;
}
default:
{}
[Link]("Invalid Operation.");

}
}
}

OUTPUT :-
CONCLUSION :- This program implements a menu driven approach using switch case to
perform basic mathematical operations, demonstrating user input handling and control flow
in Java.

e. WAP to find grade of student from input marks using if else ladder and switch case.
CODE :-
import [Link];
public class p1e
{

public static void main(String[]args)


{
Scanner sc = new Scanner([Link]);
int m; [Link]("Enter your
marks : "); m = [Link](); if(m>=90
&& m<=100) { } else if(m>=80 &&
m<=89) { } else if(m>=70 && m<=79)
{ } else if(m>=60 && m<=69) { } else
if(m>=50 && m<=59) {
[Link]("You secured Grade O.");

[Link]("You secured Grade A.");

[Link]("You secured Grade B.");

[Link]("You secured Grade C.");

[Link]("You secured Grade D.");


} else if(m>=40 &&
m<=49) { } else { }

[Link]("You secured Grade E.");

[Link]("Your secured Grade F. You failed.");

}
}
OUTPUT :-

CONCLUSION :- This program determines a student’s grade based on input marks using if
– else ladder and switch case.
f. WAP to print the sum of following series 1+1/2^2+1/3^2+1/4^2……+1/n^2

CODE :-

import [Link];
public class p1f
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
int n;
float sum = 0;
[Link]("Enter the last term: ");
n = [Link]();
for(int i=1;i<=n;i++)
{}
[Link]("The
sum = sum + 1.0f/(i*i);sum is
%.5f.",sum);
}
}

OUTPUT :-
CONCLUSION :- This program highlights Java’s looping structures.

g. WAP to display the following patterns:


1
21
123
4321
12345
654321
1234567

CODE :-
import [Link];
public class p1g1
{

public static void main(String[]args)


{
Scanner sc = new Scanner([Link]);
int n,i,j;
[Link]("Enter the value of rows: ");
n = [Link]();
for(i=1;i<=n;i++)
{
if(i%2 != 0)
{
for(j=1;j<=i;j++
){}
[Link](j + " ");

}
else
{
for(j=i;j>=1;j--)
{}
[Link](j + " ");

}
[Link]();
}
}
}
OUTPUT :-
A
CB
FED
JIHG
CODE :-

import [Link];
public class p1g
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
int n,i,j,k,p = 65;
[Link]("Enter the value of rows: ");
n = [Link]();
char c = 'A';
for(i=1;i<=n;i++)
{
for(j=n-1;j>=1;j--)
{
} [Link](" ");

for(k=1;k<=i;k++)
{
} [Link]((char)(p+i-k));

p = p+i;
[Link]();
}
}
}
OUTPUT :-
CONCLUSION :- Demonstrates pattern printing in Java.
Write Program to implement Arrays
a. 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
CODE :-
import [Link].*;
public class p2a
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]); int
n,i,sum = 0; [Link]("Enter the size of
the array : "); n = [Link](); int arr1[] = new
int[n]; int arr2[] = new int[n];
[Link]("Enter the array elements :
"); for(i=0;i<n;i++) {

arr1[i] = [Link]();
sum = sum + arr1[i];
}
[Link]("The resultant array is : ");
for(i=0;i<n;i++)
{
arr2[i] = sum - arr1[i];
[Link](arr2[i] + " ");
}
sum = 0;
}
}
OUTPUT :-
CONCLUSION :-
The program shows effectiveness of arrays and helps us to learn array manipulation.
b. The annual examination results of 5 students are tabulated as follows:
Roll No Subject1 Subject2 Subject3
WAP to read the data and determine the following
Total marks obtained by each student
The student who obtained the highest total marks
CODE :-
import [Link];
public class p2b0000000005
{

public static void main(String[]args)


{
Scanner sc = new Scanner([Link]);
int[][] data = new int[5][5];
int sum = 0;
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<4;j++)
{
if(j==0)
{
[Link]("Enter Roll no. ");
}
else
{
[Link]("Enter marks of Subject "+j+":");
}
data[i][j] = [Link]();
sum = sum + data[i][j];
}
data[i][4] = sum - data[i][0];
sum = 0;
}
[Link]("Roll no.\tSubject 1\tSubject 2\tSubject 3\tTotal Marks");
int max = data[0][4];
int rn = 0;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
[Link](""+data[i]
[j]); [Link]("\t\t");
if(j==4) { if(data[i][j] > max) {
max = data[i][j]; rn = data[i]
[0]; } }

}
[Link]();
}
[Link]("Roll no. "+rn+" scored maximum marks "+max+".");
}
}
OUTPUT :-
CONCLUSION :-
This program demonstrates the effective uses of 2D array.
c. WAP to display following pattern using irregular arrays (jagged arrays)
1
12
1 2 3 ……….
CODE :-
import [Link];
public class p2c
{

public static void main(String[]args)


{
Scanner sc = new Scanner([Link]);
int n,i,j;
[Link]("Enter the value of rows: ");
n = [Link]();
int jarr[][] = new int[n][];
for(i=0;i<n;i++)
{
jarr[i] = new int[i+1];
for(j=0;j<=i;j++)
{

jarr[i][j] = j+1;
[Link](jarr[i][j]+"\t");
}
[Link]();
}
}
}
OUTPUT :-

CONCLUSION :-
This program constructively uses jagged arrays to print the required pattern as per need.
EXPERIMENT NO. 3
Aim/Objective: To implement Strings (CO1)
Question a: WAP to find out number of uppercase & lowercase characters, blank spaces and
digits from the string.
Code:
import [Link];
public class p3a
{

public static void main(String[] args) {


Scanner scanner = new
Scanner([Link]);
[Link]("Enter a string: "); String
input = [Link](); int
uppercaseCount = 0; int lowercaseCount
= 0; int digitCount = 0; int spaceCount =
0; for (int i = 0; i < [Link](); i++)

{
char ch = [Link](i);
if ([Link](ch))
{
uppercaseCount++;
}
else if ([Link](ch))
{
lowercaseCount++;
}
else if ([Link](ch))
{
digitCount++;
}
else if ([Link](ch))
{
spaceCount++;
}
}
[Link]("Uppercase letters: " + uppercaseCount);
[Link]("Lowercase letters: " + lowercaseCount);
[Link]("Digits: " + digitCount);
[Link]("Blank spaces: " + spaceCount);
}
}
Output:

Question b: WAP to count the frequency of occurrence of a given character in a given line of
text.
Code:
import [Link];
public class p3b
{

public static void main(String[] args)


{
Scanner scanner = new Scanner([Link]);
[Link]("Enter a line of text: ");
String text = [Link]();
[Link]("Enter the character to count: ");
char ch = [Link]().charAt(0);
int count = 0;
for (int i = 0; i < [Link](); i++)
{
if ([Link](i) == ch)
{
count++;
}
}
[Link]("The character '" + ch + "' appears " + count + " time(s) in the
given text.");
}
}
Output:
Question c: WAP to check if a string is a palindrome or not using inbuild functions.
Code:

import [Link];
public class p3c
{

public static void main(String[] args)


{
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
String reversed = new StringBuilder(str).reverse().toString();
if ([Link](reversed))
{
[Link]("The string is a palindrome.");
}
else
{
[Link]("The string is not a palindrome.");
}
}
}
Output:

Conclusion:
These programs demonstrate basic string handling in Java. The first counts how often a
specific character appears in a given text using a loop. The second checks if a string is a
palindrome by comparing characters manually. The third achieves the same using built-in
functions like [Link]() and equals(), offering a more concise solution.
Together, they showcase essential string operations and user input handling.
EXPERIMENT NO. 4
Aim/Objective:To implement collections (Array List/ Vectors) (CO1)
Question a: WAP to accept students name from command line and store them in vector.
Code:
import [Link];
public class p4a
{

public static void main(String[] args)


{
Vector<String> students = new Vector<>();
for (String name : args)
{
[Link](name);
}
[Link]("Student names: " + students);
}
}
Output:

Question b: 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 [Link];
import [Link];
public class p4b
{

public static void main(String[] args)


{
Scanner scanner = new Scanner([Link]);
Vector<String> strings = new Vector<>();
[Link]("Enter the number of strings: ");
int n = [Link]();
[Link]();
for (int i = 0; i < n; i++)
{
[Link]("Enter string " + (i + 1) + ": ");
[Link]([Link]());
}
[Link]("Enter a new string: ");
String newString = [Link]();
if ([Link](newString))
{
[Link](newString);
[Link]("String was present and has been removed.");
}
else
{
[Link](newString);
[Link]("String was not present and has been added.");
}
[Link]("Final Vector: " + strings);
}
}
Output:

Conclusion:
These programs demonstrate key concepts of Java programming including string
manipulation, use of vectors, and command-line or user input handling. From counting
character frequency and checking for palindromes using both manual and built-in methods, to
managing dynamic lists of strings using Vector, each program reinforces practical skills in
conditional logic, loops, and data structures. Together, they offer a well-rounded foundation
for working with text and collections in Java.
EXPERIMENT NO. 5
Aim/Objective: To implement class with members and methods (static, non-static, recursive and
overloaded methods) (CO1)
Question a: 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 [Link];
class Employee
{

int empid;
String empname;
String designation;
double salary;
void getemployee()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Employee ID: ");
empid = [Link]();
[Link]();
[Link]("Enter Employee Name: ");
empname = [Link]();
[Link]("Enter Designation: ");
designation = [Link]();
[Link]("Enter Salary: ");
salary = [Link]();
}
void showgrade()
{
if (salary >= 100000)
{
[Link]("Grade: A");
}
else if (salary >= 50000)
{
[Link]("Grade: B");
}
else
{
[Link]("Grade: C");
} } void showemployee() {
[Link]("Employee Details:");
[Link]("ID: " + empid);
[Link]("Name: " + empname);
[Link]("Designation: " +
designation); [Link]("Salary: " +
salary); }

}
public class p5a
{
public static void main(String[] args)
{
Employee emp = new Employee();
[Link]();
[Link]();
[Link]();
}
}
Output:

Question b: WAP to display area of square and rectangle using the concept ofoverloaded
functions.
Code:
class AreaCalculator
{
void area(int side)
{
int result = side * side;
[Link]("Area of square: " + result);
}
void area(int length, int breadth)
{
int result = length * breadth;
[Link]("Area of rectangle: " + result);
}
}
public class p5b
{
public static void main(String[] args)
{
AreaCalculator obj = new AreaCalculator();
[Link](5);
[Link](4, 6);
}
}
Output:

Question c: WAP to find value of y using recursive function (static), where y=x^n
Code:
import [Link];
public class p5c
{
static int power(int x, int n)
{
if (n == 0)
return 1;
return x * power(x, n - 1);
}
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter base (x): ");
int x = [Link]();
[Link]("Enter exponent (n): ");
int n = [Link]();
int y = power(x, n);
[Link]("y = " + x + "^" + n + " = " + y);
}
}
Output:
Question d: WAP to count the number of objects made of a particular class using static
variable and static method and display the same.
Code:

public class p5d


{
static int count = 0; p5d() { count++; } static void
displayCount() { [Link]("Total objects
created: " + count); } public static void
main(String[] args) { p5d obj1 = new p5d(); p5d
obj2 = new p5d();

p5d obj3 = new p5d();


[Link]();
}
}
Output:

Conclusion:
The above programs demonstrate core object-oriented and functional programming concepts
in Java. Through method overloading, we calculate areas of different shapes using the same
method name with varied parameters. Recursive functions are used to compute powers,
illustrating elegant solutions for repetitive calculations. Static variables and methods help
track object creation, showcasing class-level data handling. Finally, a class-based structure is
used to manage employee details and display grades based on salary, reinforcing
encapsulation and modular code design. Together, these programs build a solid foundation in
Java’s key principles like recursion, overloading, static context, and class design.
EXPERIMENT NO. 6
Aim/Objective: To implement array of objects and passing/ returning objects (CO1)
Question a: WOOP to arrange the names of students in descending order of their total
marks, input data consists of students details such as names, [Link], marks of maths,
physics, chemistry. (Use array of objects)
Code:
import [Link];
import [Link];
class Student
{
String name;
int id;
int math, physics, chemistry;
int total;
void getDetails(Scanner scanner)
{
[Link]("Enter Student Name: ");
name = [Link]();
[Link]("Enter ID: ");
id = [Link]();
[Link]("Enter Marks in Math: ");
math = [Link]();
[Link]("Enter Marks in Physics: ");
physics = [Link]();
[Link]("Enter Marks in Chemistry: ");
chemistry = [Link]();
[Link](); // consume newline
total = math + physics + chemistry;
}
void displayDetails()
{
[Link]("Name: " + name + ", ID: " + id + ", Total Marks: " + total);
}
}
public class p6a
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link]();
[Link]();
Student[] students = new Student[n];
for (int i = 0; i < n; i++) {
[Link]("\nEnter details for student " + (i + 1) + ":");
students[i] = new Student();
students[i].getDetails(scanner);
}
[Link](students, (a, b) -> [Link] - [Link]);
[Link]("\nStudents in descending order of total marks:");
for (Student s : students)
{
[Link]();
}
}
}
Output:
Question b: WAP to perform mathematical operations on 2 complex numbers by passing and
returning object as argument. Show the use of this pointer.
Code:
import [Link];
class Complex
{

int real;
int imag;
void getData(Scanner scanner)
{
[Link]("Enter real part: ");
[Link] = [Link]();
[Link]("Enter imaginary part: ");
[Link] = [Link]();
}
Complex add(Complex c)
{
Complex result = new Complex();
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
return result;
}
Complex subtract(Complex c)
{
Complex result = new Complex();
[Link] = [Link] - [Link];
[Link] = [Link] - [Link];
return result;
}
void display(String msg)
{
[Link](msg + [Link] + " + " + [Link] + "i");
}
}
public class p6b
{
public static void main(String[] args) { Scanner
scanner = new Scanner([Link]); Complex c1 =
new Complex(); Complex c2 = new Complex();
[Link]("Enter first complex number:");
[Link](scanner); [Link]("Enter
second complex number:"); [Link](scanner);
Complex sum = [Link](c2); Complex difference =
[Link](c2);
[Link]("Sum = ");
[Link]("Difference = ");
}
}
Output:

Conclusion:
The two programs illustrate core object-oriented principles in Java using practical
mathematical and sorting operations. The first program demonstrates how to manage student
records using an array of objects, calculate total marks, and sort them in descending order—
reinforcing encapsulation, arrays of objects, and comparator-based sorting. The second
program models complex number arithmetic by passing and returning objects and uses the
this pointer to differentiate between instance and parameter variables, showcasing object
references and method chaining. Together, these programs highlight how Java handles data
organization, object interaction, and real-world problem modeling.
EXPERIMENT NO.
Aim/Objective: To implement Constructors and constructor overloading (CO1)
Question a: WAOOP to count the no. of objects created of a class using constructors.
Code:
public class ObjectCount
{
static int count = 0;
ObjectCount()
{
count++;
}
void displayCount()
{
[Link]("Total number of objects created: " + count);
}
}
Ppublic class p7a
{
public static void main(String[] args) {
ObjectCount obj1 = new
ObjectCount(); ObjectCount obj2 =
new ObjectCount(); ObjectCount obj3
= new ObjectCount();
[Link](); }

}
Output:

Question b:
Code:
class Area
{
int length, breadth;
Area()
{
length = 0;
breadth = 0;
}
Area(int l, int b)
{
length = l;
breadth = b;
}
Area(Area obj)
{
length = [Link];
breadth = [Link];
}
void displayArea()
{
int area = length * breadth;
if (length == breadth && length != 0)
[Link]("Area of square: " + area);
else if (length != 0 && breadth != 0)
[Link]("Area of rectangle: " + area);
else [Link]("Invalid dimensions (0 x 0), area cannot be

calculated.");
}
}
public class p7b
{
public static void main(String[] args)
{
Area square = new Area(5, 5);
Area rectangle = new Area(4, 6);
Area copy = new Area(square);
Area empty = new Area();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:

Conclusion:
The two programs effectively demonstrate key object-oriented principles in Java, focusing on
constructors and static members. The first program uses constructors alongside a static
variable to count and track how many objects are created, highlighting how constructors can
automate behavior during object instantiation. The second program showcases constructor
overloading using non-parameterized, parameterized, and copy constructors to calculate and
display the area of squares and rectangles. Together, these programs illustrate how
constructor logic and static context can be combined to manage object behavior and state
efficiently.
EXPERIMENT NO. 8
Aim/Objective: To implement Inheritance and super keyword (CO1)
Question a: WAP to demonstrate the role of Constructors in inheritance in the following class
diagram.

Code:
class A
{
A()
{
[Link]("Constructor of class A");
}
}
class B extends A
{

B()
{
[Link]("Constructor of class B");
}
}
class C extends B
{

C()
{
[Link]("Constructor of class C");
}
}
public class p8a
{

public static void main(String[] args)


{
C obj = new C();
}
}
Output:

Question b: 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
class SuperClass
method of
{
the super
intclass using
num;super keyword. Code:
SuperClass()
{ } void
display() { }= 100;
num

[Link]("Number in SuperClass: " + num);

}
class SubClass extends SuperClass
{
SubClass()
{
super();
[Link]("Accessing SuperClass variable: " + [Link]);
[Link]();
}
}
public class p8b
{

public static void main(String[]


args) { }
SubClass obj = new SubClass();

}
Output:
Question c: Display data of the specialized classes given in the following class diagram.

Code:
import [Link];
class Staff
{

String code, name;


void read(Scanner sc)
{
code = [Link]();
name = [Link]();
} void
display() { }

[Link]("Code: " + code + ", Name: " + name);

}
class Teacher extends Staff
{

String sub;
int exp;
void read(Scanner sc)
{
[Link](sc);
sub = [Link]();
exp = [Link]();
}
void display()
{
[Link]();
[Link]("Subject: " + sub + ", Experience: " + exp);
}

}
class Officer extends Staff
{

String dept;
char grade;
void read(Scanner sc)
{
[Link](sc);
dept = [Link]();
grade = [Link]().charAt(0);
}
void display()
{
[Link]();
[Link]("Department: " + dept + ", Grade: " + grade);
}
}
class Typist extends Staff
{

int speed,
exp;
void read(Scanner sc)
{
[Link](sc);
speed = [Link]();
exp = [Link]();
}
void display()
{
[Link]();
[Link]("Speed: " + speed + ", Experience: " + exp);
}
}
class Regular extends Typist
{
int sal;
void read(Scanner sc)
{
[Link](sc);
sal = [Link]();
}
void display()
{
[Link]();
[Link]("Salary: " + sal);
}
}
class Casual extends Typist
{

int daily_wages;
void read(Scanner sc)
{
[Link](sc);
daily_wages = [Link]();
}
void display()
{
[Link]();
[Link]("Daily Wages: " + daily_wages);
}
}
public class p8c
{

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
Teacher teacher = new Teacher();
[Link]("Enter Teacher details (code name subject experience):");
[Link](sc);
[Link]();
Officer officer = new Officer();
[Link]("Enter Officer details (code name department grade):");
[Link](sc);
[Link]();
Regular regular = new Regular();
[Link]("Enter Regular Typist details (code name speed experience
[Link](sc);
[Link]();
salary):"); Casual casual = new Casual();
[Link]("Enter Casual Typist details (code name speed experience

daily_wages):");
[Link](sc);
[Link]();
}

}
Output:
Conclusion:
The programs demonstrate the concepts of inheritance, the use of the super keyword to access
superclass members, and the structured display of data in specialized subclasses, effectively
illustrating how constructors, methods, and variables interact across hierarchical class
structures in Java.
EXPERIMENT NO. 9
Aim/Objective: To implement Abstract classes and packages. Question a:
Write an abstract class program to calculate area of circle, rectangle and
triangle. Code: interface Reversal
{}
class StringReversal implements Reversal
{

String reversal(String input);

@Override
public String reversal(String input)
{
StringBuilder reversedString = new StringBuilder(input);
return [Link]().toString();
}
}

public class p9a


{
public static void main(String[] args)
{
Reversal r = new StringReversal();
String input = "Hello, World!";
String reversed = [Link](input);
[Link]("Original String: " + input);
[Link]("Reversed String: " + reversed);
}
}
Output:

Question b:
WAP to create a package called vol having Cylinder class and volume (). WAP that imports
this package to calculate volume of a Cylinder.
Code:
import [Link].*;
interface Sports
{
int score();
}

class Student
{
int rollno;
public void read()
{
rollno = 123;
[Link]("Roll Number: " + rollno);
}
}
class Test extends Student
{
int sem1_marks, sem2_marks;
public void read()
{
[Link]();
sem1_marks = 80;
sem2_marks = 75;
[Link]("Semester 1 Marks: " + sem1_marks);
[Link]("Semester 2 Marks: " + sem2_marks);
}
}
class Result extends Test implements Sports
{
int total;
@Override
public int score()
{
return 20;
}
public void displayTotal()
{
total = sem1_marks + sem2_marks + score();
[Link]("Total Marks: " + total);
}
}

public class p9b


{
public static void main(String[] args)
{
Result studentResult = new Result();
[Link]();
[Link]();
}
}
Output:

Conclusion:

The Reversal program demonstrates interface implementation for consistent method usage.
The Student-Test-Result program illustrates multiple inheritance using interfaces and the
use of the super keyword for accessing parent class methods
EXPERIMENT NO. 10
Aim/Objective: To implement exceptions in Java (read input using DataInputStream/
BufferedReader classes)

Question a:
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:
import [Link].*;
class Animal
{
void sound()
{}
[Link]("Animal makes a sound");

}
class Dog extends Animal
{
@Override
void sound()
{}
[Link]("Dog barks");

}
class Cat extends Animal
{
@Override
void sound()
{}
[Link]("Cat meows");

}
public class p10a
{
public static void main(String[] args)
{
Animal animal = new Animal();
[Link]();
animal = new Dog();
[Link]();
animal = new Cat();
[Link]();
}
}
Output:

Question b:
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:

import [Link].*;
final class intcal
{
private final double roi = 5.0; public final double
calsi(double principal, double time) { } public final
double calci(double principal, double time) { }

return (principal * roi * time) / 100;

return principal * [Link]((1 + roi / 100), time) - principal;

}
public class p10b
{
public static void main(String[] args)
{
intcal calculator = new intcal();
double principal = 1000;
double time = 2;
double si = [Link](principal, time);
double ci = [Link](principal, time);
[Link]("Simple Interest: " + si);
[Link]("Compound Interest: " + ci);
}
}
Output:
Question c:
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 Demo
{
protected void finalize() throws
Throwable
{
} [Link]("Object has been deleted");

}
public class p10c
{
public static void main(String[] args)
{
Demo obj = new Demo();
obj = null;
[Link]();
try {
[Link](1000);
} catch (InterruptedException e)
{
[Link]();
}

[Link]("End of program");
}
}
Output:

Conclusion:
Dynamic method dispatch enables runtime polymorphism, allowing a base class reference
to point to child class objects, promoting flexibility. The final keyword ensures that
classes and methods cannot be inherited or overridden, maintaining data security. Java
handles memory management automatically using garbage collection, but explicit
cleanup can be requested using [Link]().
EXPERIMENT NO. 11
Aim/Objective:To implement Abstract classes and packages (CO1)
Write an abstract class program to calculate area of circle, rectangle and triangle.
Question a: Code:
import [Link];
abstract class Shape { }
class Circle extends Shape
{

abstract void calculateArea();

private double
radius; Circle(double
radius) { }
@Override
[Link]
= radius;
calculateArea() {

double area = [Link] * radius * radius;


[Link]("Area of Circle: " + area);
}

}
class Rectangle extends Shape
{

private double length, width;


Rectangle(double length, double width)
{
[Link] = length;
[Link] = width;
}
@Override
void calculateArea()
{

double area = length * width;


[Link]("Area of Rectangle: " + area);
}
}
class Triangle extends Shape
{

private double base, height;


Triangle(double base, double height)
{
[Link] = base;
[Link] = height;
}
@Override
void calculateArea()
{

double area = 0.5 * base * height;


[Link]("Area of Triangle: " + area);
}

}
public class p11a
{

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
[Link]("Enter radius of circle: ");
double radius = [Link]();
Shape circle = new Circle(radius);
[Link]();
[Link]("Enter length and width of rectangle: ");
double length = [Link]();
double width = [Link]();
Shape rectangle = new Rectangle(length, width);
[Link]();
[Link]("Enter base and height of triangle: ");
double base = [Link]();
double height = [Link]();
Shape triangle = new Triangle(base, height);
[Link]();
}

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

Code:
In package vol, [Link]
package vol;
public class Cylinder
{

private double radius, height;


public Cylinder(double radius, double height)
{
[Link] = radius;
[Link] = height;
} public double
volume() { }

return [Link] * radius * radius * height;

In same folder containing vol, [Link]


import [Link];
import [Link];
public class p11b
{

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]); [Link]("Enter
radius and height of the cylinder: "); double radius =
[Link](); double height = [Link](); Cylinder
cylinder = new Cylinder(radius, height);
[Link]("Volume of Cylinder: " +
[Link]());
}
}
Output:

Conclusion:
The first program uses an abstract class to implement polymorphism for calculating areas.
The second program demonstrates modular programming by organizing the Cylinder class in
a custom package and importing it to calculate volume.
EXPERIMENT NO. 12
Aim/Objective: To implement exceptions in Java (read input using DataInputStream/
BufferedReader classes) (CO1, CO2)
Question a: WAP to implement inbuild exceptions
i. Checked exceptions (compile time exceptions)
a. ClassNotFoundException
b. IOException
ii. Unchecked exceptions (run time exceptions)
a. NumberFormatException
b. ArithmeticException
c. ArrayIndexOutOfBounds
d. NullPointerException

Code:
import [Link].*;
import [Link];
public class p12a
{

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]); try {
[Link]("NonExistentClass"); } catch
(ClassNotFoundException e) { [Link]("Class not
found: " + e); } try { FileInputStream fis = new
FileInputStream("[Link]"); } catch (IOException e)
{ [Link]("IO Exception: " + e); } { int num =
[Link]("abc");

try
} catch (NumberFormatException e) {
[Link]("Number format exception: " +
e); } try { int result = 10 / 0; } catch
(ArithmeticException e) {
[Link]("Arithmetic exception: " + e); } {
int[] arr = new int[3]; arr[5] = 10; } catch
(ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of bounds: " +
e); } try { String str = null;
[Link]([Link]()); } catch
(NullPointerException e) { [Link]("Null
try pointer exception: " + e); }

}
Output:

b: Write a Java Program to Create a User Defined Exception class


Question
MarksOutOfBoundsException, If 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:
import [Link];
class MarksOutOfBoundsException extends Exception
{
MarksOutOfBoundsException(String
message) { }
super(message);

}
public class p12b
{

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
[Link]("Enter marks: ");
int marks = [Link]();
try
{
validateMarks(marks);
[Link]("Marks entered: " + marks);
} catch (MarksOutOfBoundsException
e) { }
[Link]([Link]());

}
static void validateMarks(int marks) throws MarksOutOfBoundsException
{
if (marks < 0 || marks > 100)
{
throw new MarksOutOfBoundsException("Marks out of bounds. Must be
between 0 and 100.");
}
}

}
Output:

Conclusion:
The first program demonstrates handling both checked and unchecked exceptions using
predefined exception classes in Java. The second program illustrates creating and handling a
user-defined exception to validate marks within a specific range, showcasing custom
exception handling.
EXPERIMENT NO. 13
Aim/Objective:To implement Multithreading (CO1, CO2)
Question a: Write a multithreaded program a java program to print Table of Five, Seven and
Thirteen using Multithreading (Use Thread class for the implementation).
Code:
class TableOfFive extends Thread
{
public void run()
{
for (int i = 1; i <= 10;
i++) { }
[Link]("5 x " + i + " = " + (5 * i));

}
}
class TableOfSeven extends Thread
{

public void run()


{
for (int i = 1; i <= 10;
i++) { }
[Link]("7 x " + i + " = " + (7 * i));

}
}
class TableOfThirteen extends Thread
{

public void run()


{
for (int i = 1; i <= 10;
i++) { }
[Link]("13 x " + i + " = " + (13 * i));

}
}
public class p13a
{

public static void main(String[] args)


{
TableOfFive t1 = new TableOfFive();
TableOfSeven t2 = new TableOfSeven();
TableOfThirteen t3 = new
TableOfThirteen(); [Link](); [Link]();
[Link]();

}
Output:

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


Code:
class PatternThread extends Thread
{
private String pattern;
PatternThread(String pattern)
{
[Link] = pattern;
}
public void run()
{
for (int i = 0; i < 4; i++)
{
[Link](pattern);
}
}

}
public class p13b
{

public static void main(String[] args)


{
PatternThread t1 = new
PatternThread("/"); PatternThread t2 =
new PatternThread("/"); [Link]();
[Link](); try { [Link](); [Link](); } catch
(InterruptedException e) {
[Link](); }
[Link]();

}
Output:

Question c: 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 [Link];
class FibonacciGenerator extends Thread
{
private int[] sequence;
private int count;
FibonacciGenerator(int count)
{
[Link] = count;
[Link] = new int[count];
}
public void run()
{
if (count > 0) sequence[0] = 0; if (count > 1)
sequence[1] = 1; for (int i = 2; i < count; i++)
{ sequence[i] = sequence[i - 1] + sequence[i -
2]; }

} public int[]
getSequence() { }

return sequence;

}
public class p13c
{

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]); [Link]("Enter the
number of Fibonacci numbers to generate: "); int count = [Link]();
FibonacciGenerator fibThread = new FibonacciGenerator(count);
[Link](); try { [Link](); } catch (InterruptedException
e) { [Link](); } int[] sequence = [Link]();
[Link]("Fibonacci Sequence: "); for (int num : sequence) {
[Link](num + " "); }
}
}
Output:

Question d: WAP to prevent concurrent booking of a ticket using the concept of thread
synchronization.
Code:

class TicketBooking
{
private int availableTickets = 1;
synchronized void bookTicket(String name, int tickets)
{
if (tickets <= availableTickets)
{
[Link](name + " successfully booked " + tickets + "
ticket(s)."); availableTickets -= tickets;

}
else
{
[Link]("Sorry, " + name + ". Not enough tickets
available.");
}
}
}
class BookingThread extends Thread
{

TicketBooking booking;
String name;
int tickets;
BookingThread(TicketBooking booking, String name, int tickets)
{
[Link] = booking;
[Link] = name;
[Link] = tickets;
}
public void run()
{
[Link](name, tickets);
}
}
public class Main
{

public static void main(String[] args) { TicketBooking booking =


new TicketBooking(); BookingThread user1 = new
BookingThread(booking, "User1", 1); BookingThread user2 =
new BookingThread(booking, "User2", 1); [Link]();
[Link](); }

}
Output:

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

class CustomThread extends Thread


{
public CustomThread(String
name) { } public void run() {
setName(name);

synchronized (this)
{
try
{
[Link](getName() + " is running with priority " +
getPriority());
wait();
[Link](getName() + " is resumed.");
} catch (InterruptedException e)
{
[Link](e);
}
}
}

}
public class p13e
{

public static void main(String[] args)


{
CustomThread t1 = new CustomThread("Thread-
1"); CustomThread t2 = new
CustomThread("Thread-2");
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link](); [Link](); try { [Link](1000);
synchronized (t1)

{
[Link]();
} [Link](); [Link](); } catch (InterruptedException e) {
[Link](e); } [Link]([Link]() + "
priority: " + [Link]()); [Link]([Link]()
+ " priority: " + [Link]());

}
Output:

Conclusion:
The programs showcase thread synchronization to prevent concurrent ticket booking and the
implementation of key thread methods like wait(), notify(), join(), and priority management
to control thread execution and interaction effectively in Java.
EXPERIMENT NO. 14
Aim/Objective: To implement basic Swing programs with event handling (CO1, CO3)
Question a: Write java program to create a registration form. Take Login id and Password
from the user and display it on the third Text Field which appears only on clicking OK
button and clear both the Text Fields on clicking RESET button.

Code:
import [Link].*;
import [Link].*;
import [Link].*;
class RegistrationForm extends JFrame implements ActionListener
{
JTextField loginField, passwordField, resultField;
JButton okButton, resetButton;
public RegistrationForm()
{
setTitle("Login");
setSize(400, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
add(new JLabel("Login :"));
loginField = new JTextField();
add(loginField);

add(new JLabel("Password :"));


passwordField = new JTextField();
add(passwordField);

okButton = new JButton("OK");


[Link](this);
add(okButton);

resetButton = new JButton("RESET");


[Link](this);
add(resetButton);
resultField = new JTextField();
[Link](false);
add(new JLabel());
add(resultField);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if ([Link]() == okButton)

{
String login = [Link]();
String password = [Link]();
[Link]("Login: " + login + " | Password: " + password);
[Link](true);
}
else if ([Link]() == resetButton)
{
[Link]("");
[Link]("");
}
}
}
public class p14a
{
public static void main(String[] args)
{
new RegistrationForm();
}
}
Output:
Question b: Write a program to create a basic calculator.

Code:
import [Link].*;
import [Link].*;
import [Link].*;
class Calculator extends JFrame implements ActionListener
{

JTextField num1, num2, result;


JButton add, sub, mul, div;
public Calculator()
{
setTitle("Calculator");
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
add(new JLabel("Number 1:"));
num1 = new JTextField();
add(num1);
add(new JLabel("Number 2:"));
num2 = new JTextField();
add(num2);
add = new JButton("Add");
[Link](this);
add(add);
sub = new JButton("Subtract");
[Link](this);
add(sub);
mul = new JButton("Multiply");
[Link](this);
add(mul);
div = new JButton("Divide");
[Link](this);
add(div);
add(new JLabel("Result:"));
result = new JTextField();
[Link](false);
add(result);
setVisible(true);
} public void actionPerformed(ActionEvent e) {
double n1 =
[Link]([Link]()); double n2
= [Link]([Link]()); double
res = 0; if ([Link]() == add)

{
res = n1 + n2;
}
else if ([Link]() == sub)
{
res = n1 - n2;
}
else if ([Link]() == mul)
{
res = n1 * n2;
} else if ([Link]() == div)
{

if (n2 != 0)
{
res = n1 / n2;
}
else
{
[Link]("Cannot divide by zero");
return;
}
}
[Link]([Link](res));
}

}
public class p14b
{
public static void main(String[] args)
{
new Calculator();
}
}
Output:
Question c: Display the selected fields in Details after submit button is clicked

Code:
import [Link].*;
import [Link].*;
import [Link].*;
class UserForm extends JFrame implements ActionListener
{

JTextField nameField;
JRadioButton male, female;
JCheckBox music, swimming;
JComboBox<String> countryBox;
JTextArea detailsArea;
JButton submit, exit;
ButtonGroup genderGroup;
public UserForm()
{
setTitle("Welcome to fahmidasclassroom");
setSize(500, 400); setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JLabel nameLabel = new JLabel("Name:");
[Link](30, 30, 100, 25);
add(nameLabel);

nameField = new JTextField();


[Link](140, 30, 300, 25);
add(nameField);

JLabel genderLabel = new JLabel("Gender:");


[Link](30, 70, 100, 25);
add(genderLabel);

male = new JRadioButton("Male");


[Link](140, 70, 70, 25);
female = new JRadioButton("Female");
[Link](220, 70, 80, 25);
genderGroup = new ButtonGroup();
[Link](male);
[Link](female);
add(male);
add(female);

JLabel interestLabel = new JLabel("Interest:");


[Link](30, 110, 100, 25);
add(interestLabel);

music = new JCheckBox("Music");


[Link](140, 110, 80, 25);
swimming = new JCheckBox("Swimming");
[Link](230, 110, 100, 25);
add(music);
add(swimming);
JLabel placeLabel = new JLabel("Favourite Place:");
[Link](30, 150, 120, 25);
add(placeLabel);

String[] places = {"Bangladesh", "India", "Japan", "USA",

"UK"};
countryBox = new JComboBox<>(places);
[Link](160, 150, 150, 25);
add(countryBox);
JLabel detailsLabel = new JLabel("Details:");
[Link](30, 190, 100, 25);
add(detailsLabel);
detailsArea = new JTextArea();
[Link](140, 190, 300, 80);
add(detailsArea);
submit = new JButton("Submit");
[Link](140, 290, 100, 30);
[Link](this);
add(submit);
exit = new JButton("Exit");
[Link](260, 290, 100, 30);
[Link](e -> [Link](0));
add(exit);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String name = [Link]();
String gender = [Link]() ? "Male" : ([Link]() ? "Female" : "Not

selected");
String interest = "";
if ([Link]()) interest += "Music ";
if ([Link]()) interest += "Swimming ";
String place = (String) [Link]();
String details = "Name: " + name + "\nGender: " + gender + "\nInterest: " + interest +

"\nFavourite Place: " + place;


[Link](details);
}
}
public class p14c
{
public static void main(String[] args)
{
new UserForm();
}
}
Output:
Conclusion:
Both Java Swing programs demonstrate the use of GUI components to interact with users
effectively. The calculator application handles numerical input and performs basic arithmetic
operations (addition, subtraction, multiplication, and division), showcasing event handling
and input validation. The user information form collects textual, selection-based, and
checkbox inputs, then dynamically displays a summary of the entered data, demonstrating the
integration of various GUI elements like radio buttons, checkboxes, combo boxes, and text
areas. Together, these programs illustrate how Java Swing can be used to build interactive,
event-driven desktop applications with both functional and data-entry capabilities.

You might also like