0% found this document useful (0 votes)
9 views106 pages

Java All Exp

The document outlines a series of Java programming experiments for a first-year B.Tech course, focusing on Object-Oriented Programming, Arrays, Strings, and Collections. Each experiment includes specific tasks, sample code, and expected outputs, covering topics like control statements, loops, arrays, string manipulation, and vector operations. The document is structured with student details and experiment numbers for easy reference.

Uploaded by

ramyaravi802
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views106 pages

Java All Exp

The document outlines a series of Java programming experiments for a first-year B.Tech course, focusing on Object-Oriented Programming, Arrays, Strings, and Collections. Each experiment includes specific tasks, sample code, and expected outputs, covering topics like control statements, loops, arrays, string manipulation, and vector operations. The document is structured with student details and experiment numbers for easy reference.

Uploaded by

ramyaravi802
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Object Oriented Programming using Java Laboratory (DJS23FLES201)

F.Y B. Tech, Semester: II


Experiment list
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265

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

OUTPUT:
b. WAP to find largest of 3 numbers using nested if else and nested ternary operator.

b.1) Using Nested If-Else


CODE:
import [Link];
class Largest1{
public static void main(String args[])
{ int a,b,c;
Scanner sc=new Scanner([Link]);
[Link]("Enter three numbers");
a=[Link]();
b=[Link]();
c=[Link]();
if(a>b){
if(a>c){
[Link](a+" is the greatest number");
}
else{
[Link](c+" is the greatest number");
}
}
if(b>a){
if(b>c){
[Link](b+" is the greatest number");
}
else{
[Link](c+" is the greatest number");
}
}
}}
OUTPUT:

b.2) Using Ternary Operator


CODE:
import [Link].*;
class Largest2{
public static void main(String args[])
{ Scanner sc=new Scanner([Link]);
int a,b,c,largest;
[Link]("Enter 1st number: ");
a=[Link]();
[Link]("Enter 2nd number: ");
b=[Link]();
[Link]("Enter 3rd number: ");
c=[Link](); largest=(a>b)?((a>c)?a:c):((b>c)?
b:c);
[Link]("The largest number is: "+largest);
}}

OUTPUT:
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:
class CommandLine{
public static void main(String args[]){
int n,count=0,num;
n=[Link](args[0]);
if(n>0)
{
num=n; while(n!
=0){
n=n/10;
count++;
}
[Link]("The number "+num+", has "+count+" digits");
}
else
{
[Link]("Entered number needs to be a positive integer");
}
}
}
OUTPUT:
d. Write a menu driven program using switch case to perform mathematical operations.
CODE:
import [Link];
class Calculator
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int a,b,c;
char ch;
[Link]("Enter an operator");
ch=[Link]().charAt(0);
[Link]("Enter 2 numbers");
a=[Link]();
b=[Link]();
switch(ch)
{
case '+' :
c=a+b;
[Link](c);
break;
case '-' :
c=a-b;
[Link](c);
break;
case '*' :
c=a*b;
[Link](c);
break;
case '/' :
c=a/b;
[Link](c);
break;
default :
[Link]("Invalid Choice");
}
}
}

OUTPUT:
e. WAP to find grade of student from input marks using if else ladder.
CODE:
import [Link];
class Marks{
public static void main(String args[])
{
Scanner mk=new Scanner([Link]);
[Link]("Enter Percentage");
float marks=[Link]();
if(marks>=90)
{
[Link]("Grade A");
}
else if(marks>=70 && marks<90)
{
[Link]("Grade B");
}
else if(marks>=40 && marks<70)
{
[Link]("Grade C");
}
else
{
[Link]("Fail");
}
}
}
OUTPUT:
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];

class Series{

public static void main(String args[])

{ Scanner sc=new Scanner([Link]);

int i,n;

float sum=0.0f;

[Link]("Enter n");

n=[Link](); for(i=1;i<=n;i+

+){ sum=sum+(1.0f/(i*i));

[Link](sum);

OUTPUT:
g. WAP to display the following patterns:
1
2 1
1 2 3
4 3 2 1
1 2 3 4 5
6 5 4 3 2 1
1 2 3 4 5 6 7
CODE:
import [Link];
class Pattern1{
public static void main(String args[])
{ Scanner pt=new Scanner([Link]);
int i,j,n;
[Link]("Enter Number of Rows");
n=[Link]();
for(i=1;i<=n;i++)
{ if(i
%2==0)
{
for(j=i;j>=1;j--){
[Link]( j);
}
[Link]();
}
else
{
for(j=1;j<=i;j++){
[Link]( j );
}
[Link]();
}
}
}}
OUTPUT:

[Link])

A
CB
FED
JIHG
CODE:

import [Link].*;
class Pat2{
public static void main(String args[])
{ Scanner sc=new Scanner([Link]);
int n,i,j;
char ch='A';
[Link]("Rows : ");
n=[Link]();
for(i=1;i<=n;i++)
{ for(j=i;j<=n-1;j++)
{ [Link]("
");
}
char k=ch;
for(j=1;j<=i;j++)
{ [Link](k--
);
}
ch+=(i+1);
[Link]();
}}}
OUTPUT:

***
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiment list
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO.2
2. To implement Arrays (CO1)
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];
class Arrays2{
public static void main(String args[])
{ int n,i,sum=0;
int a[]=new int[10];
int b[]=new int[10];
Scanner sc=new Scanner([Link]);
[Link]("Enter the size of array");
n=[Link]();
[Link]("Enter elements of array");
for(i=0;i<n;i++){
a[i]=[Link]();
}
for(i=0;i<n;i++)
{ sum=sum+a[i];
}
for(i=0;i<n;i++){
b[i]=sum-a[i];
}
[Link]("New Arrays is : ");
for(i=0;i<n;i++)
{ [Link](b[i]);
}
}}
OUTPUT:
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];
class Topper{
public static void main(String args[])
{ int n=5;
int i;
int maxin=0;
float max;
int[]roll=new int[10];
float[]s1=new float[10];
float[]s2=new float[10];
float[]s3=new float[10];
float[]marks=new float[10];
Scanner sc=new Scanner([Link]);
[Link]("Enter 5 Student's data:\nRoll number Subject 1(Marks) Subject 2(Marks)
Subject 3(Marks)");
for(i=0;i<n;i++)
{ roll[i]=[Link]();
s1[i]=[Link]();
s2[i]=[Link]();
s3[i]=[Link]();
}

for(i=0;i<n;i++){ marks[i]=s1[i]+s2[i]
+s3[i];
}
max=marks[0];
for(i=0;i<n;i++){
if (marks[i]>max)
{
max=marks[i];
}}
for(i=0;i<n;i++)
{ if(max==marks[i])
{ maxin=i;
}
}
for(i=0;i<n;i++){
[Link](roll[i]+" Scored: "+marks[i]);
}
[Link]("\nRoll Number of student who got highest total marks is "+roll[maxin]);
}}
OUTPUT:
c. WAP to display following pattern using irregular arrays (jagged arrays).
1
12
1 2 3 ………..
CODE:
import [Link];

public class JaggedPattern {


public static void main(String[] args)
{ Scanner sc = new Scanner([Link]);

[Link]("Enter the number of rows: ");


int rows = [Link]();

int[][] jaggedArray = new int[rows][];

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


{ jaggedArray[i] = new int[i +
1];

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


{ jaggedArray[i][j] = j +
1;
}
}

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


for (int j = 0; j < jaggedArray[i].length; j++) {
[Link](jaggedArray[i][j] + " ");
}
[Link]();
}

[Link]();
}
}

OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO. 3
3. To implement Strings (CO1)
a. WAP to find out number of uppercase & lowercase characters, blank spaces and digits from
the string.
CODE:
import [Link].*;

class Counter3a{
public static void main(String args[])
{ Scanner sc=new
Scanner([Link]);
[Link]("Enter a string");
String s=[Link]();
int upper=0, lower=0, space=0, other=0, digit=0;

for(char ch: [Link]()){


if([Link](ch)){
upper++;
}
else if([Link](ch)){
lower++;
}
else if([Link](ch)){
digit++;
}
else if([Link](ch)){
space++;
}
else{
other++;
}
}
[Link]("\nRESULT\n");
[Link]("Uppercase: "+upper);
[Link]("Lowercase: "+lower);
[Link]("Blank Spaces: "+space);
[Link]("Digits: "+digit);
[Link]("Other Characters: "+other);
}
}
OUTPUT:
b. WAP to count the frequency of occurrence of a given character in a given line of text.
CODE:
import [Link];
class Exp3{
public static void main(String args[])
{ Scanner sc=new Scanner([Link]);
char ch1;
[Link]("Enter a string");
String text=new String();
text=[Link]();
[Link]("Enter a
character"); ch1=[Link]().charAt(0);
int i,count=0;
for(i=0;i<[Link]();i++)
{ if([Link](i)==ch1)
{ count++;
}}
[Link]("Frequency of entered character is "+count);
}}

OUTPUT:
c. WAP to check if a string is a palindrome or not using inbuilt functions.

CODE:
import [Link];
class Palindrome1{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
String s1=new String();
[Link]("Enter a string");
s1=[Link]();
StringBuffer sb=new StringBuffer(s1);
[Link]();
String str=[Link]();
if([Link](str)){
[Link](s1+" is a palindrome");
}
else{
[Link](s1+" is not a palindrome");
}}}
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: RAMYA RAVI ROLL NO.: D130


BATCH: D3 (Batch-1) SAP ID: 60009250191
EXPERIMENT NO. 4
AIM: To implement collections (Array List/ Vectors) (CO1)
a. WAP to accept students name from command line and store them in vector.
CODE:
import [Link].*;
public class VectorExp{
public static void main(String args[])
{ Vector<String> vecs=new Vector<String>();
for(int i=0;i<[Link];i++){
[Link](args[i]);
}
[Link]("Vector Elements are: ");
for(String element : vecs){
[Link](element);
}
}}
OUTPUT:
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].*;
public class VectorExp2{
public static void main(String args[])
{ Vector<String> vec=new Vector<String>();
Scanner sc=new Scanner([Link]);
int i,n,f=0;
String ele=new String();
[Link]("Enter number of elements");
n=[Link]();
[Link]("Enter Names");
for(i=0;i<n;i++)
{
[Link]([Link]());
}
[Link]("\nEnter Name to be removed");
ele=[Link]();
for(i=0;i<[Link]();i++)
{ if([Link]([Link](i)))
{
[Link](i); f+
+;
}}

if(f>0){
[Link]("\nUpdated list is");
for(String element : vec){
[Link](element);
}
}
else{
[Link]("No Record Found");
[Link](ele);
[Link]("Updated list is");
for(String element : vec){
[Link](element);
}
}
}}

OUTPUT:
c. A university wants to store and manage the marks of students in a subject using Java Vector collection.
Write a Java program that performs the following operations using a Vector<Integer>: Create a Vector to
store integer marks. Add marks of 5 students to the Vector. Display all the marks stored in the Vector.
Display total number of elements using size(), Capacity of the Vector using capacity(), Insert a new mark at
a given index, Remove a mark from a specified index, Check whether a particular mark exists in the Vector,
Display the first and last mark in the Vector.

CODE:

import [Link];

public class StudentMarks {


public static void main(String[] args) {

Vector<Integer> marks = new Vector<>();

[Link](85);
[Link](90);
[Link](78);
[Link](88);
[Link](92);

[Link]("Marks of students:");
for (int m : marks) {
[Link](m);
}

[Link]("Total number of elements: " + [Link]());

[Link]("Capacity of the Vector: " + [Link]());

[Link](2, 80);
[Link]("After inserting 80 at index 2: " + marks);

[Link](3);
[Link]("After removing element at index 3: " + marks);

int searchMark = 90;


if ([Link](searchMark)) {
[Link](searchMark + " exists in the Vector.");
} else {
[Link](searchMark + " does not exist in the Vector.");
}

[Link]("First mark: " + [Link]());


[Link]("Last mark: " + [Link]());
}
}

OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO.5
AIM: To implement class with members and methods (static, non-static, recursive and
overloaded methods) (CO1)
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 Employee5a{
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 >= 75000)
{ [Link]("Grade:
A");
} else if (salary >= 50000)
{ [Link]("Grade:
B");
} else {
[Link]("Grade: C");
}
}

void showEmployee()
{ [Link]("Employee ID: " + empid);
[Link]("Employee Name: " +
empname); [Link]("Designation: " +
designation); [Link]("Salary: " + salary);
showGrade();
}

public static void main(String[] args)


{ Employee5a e = new
Employee5a(); [Link]();
[Link]();
}
}
OUTPUT:
b. WAP to display area of square and rectangle using the concept of overloaded functions.
CODE:
import [Link];
class AreaCalculator {

void area(int side) {


[Link]("Area of Square: " + (side * side));
}

void area(int length, int breadth) {


[Link]("Area of Rectangle: " + (length * breadth));
}

public static void main(String[] args)


{ AreaCalculator ac = new
AreaCalculator();
Scanner sc=new Scanner([Link]);
int a,b,c;
[Link]("Enter length and breadth of rectangle");
a=[Link]();
b=[Link]();
[Link]("Enter side of square");
c=[Link]();
[Link](c);
[Link](a, b);
}
}
OUTPUT:
c. WAP to find value of y using recursive function (static), where y=x^n
CODE:
import [Link];
class PowerRec {

static int power(int x, int n)


{ if (n == 0)
return 1;
else
return x * power(x, n - 1);
}
public static void main(String[] args) {
int x , n ;
Scanner sc=new Scanner([Link]);
[Link]("Enter a number");
x=[Link]();
[Link]("Enter its power");
n=[Link]();
int result = power(x, n);
[Link]("y= "+x + "^" + n + " = " + result);
}
}
OUTPUT:
d. WAP to count the number of objects made of a particular class using static variable and static
method and display the same.

CODE:
class ObjectCounter
{ static int count =
0; ObjectCounter()
{
count++;
}

static void showCount() {


[Link]("Number of objects created: " + count);
}

public static void main(String[] args)


{ ObjectCounter obj1 = new ObjectCounter();
ObjectCounter obj2 = new ObjectCounter();
ObjectCounter obj3 = new ObjectCounter();

[Link]();
}
}
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2025-26)

NAME: RAMYA RAVI ROLL NO.: D130


BATCH: D3 (Batch-1) SAP ID: 60009250191
EXPERIMENT NO. 6
AIM: To implement array of objects and passing/ returning objects (CO1)
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].*;

class
Student{ Str
ing name;
String id;
int maths, physics, chemistry;

Student(String name, String id, int maths, int physics, int chemistry)
{ [Link] = name;
[Link] = id;
[Link] = maths;
[Link] = physics;
[Link] = chemistry;
}

int totalMarks() {
return maths + physics + chemistry;
}

void display() {
[Link]("ID: " + id + ", Name: " + name + ", Total Marks: " + totalMarks());
}
}

class StudentSort {
public static void main(String[] args)
{ Scanner sc = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link]();
Student[] students = new Student[n];
[Link]();
for (int i = 0; i < n; i++) {
[Link]("\nEnter details for Student " + (i + 1) + ":");
[Link]("Name: ");
String name = [Link]();
[Link]("ID: ");
String id = [Link]();
[Link]("Maths Marks: ");
int m = [Link]();
[Link]("Physics Marks: ");
int p = [Link]();
[Link]("Chemistry Marks: ");
int c = [Link]();
[Link]();
students[i] = new Student(name, id, m, p, c);
}

[Link](students, (s1, s2) -> [Link]() - [Link]());


[Link]("\nStudents in Descending Order of Total Marks:");
for (Student s : students) {
[Link]();
}
}
}
OUTPUT:
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;

Complex(int r, int i)
{ [Link] = r;
[Link] = i;
}

Complex add(Complex c) {
return new Complex([Link] + [Link], [Link] + [Link]);
}

Complex subtract(Complex c) {
return new Complex([Link] - [Link], [Link] - [Link]);
}

Complex multiply(Complex c) {
int r = [Link] * [Link] - [Link] * [Link];
int i = [Link] * [Link] + [Link] * [Link];
return new Complex(r, i);
}

void display() {
[Link]([Link] + " + " + [Link] + "i");
}
}
public class ComplexCalci {
public static void main(String[] args)
{ Scanner sc=new Scanner([Link]);
int r1,i1,r2,i2;

[Link]("For First Complex Number:\nEnter real part : ");


r1=[Link]();
[Link]("Enter imaginary part : ");
i1=[Link]();

[Link]("For Second Complex Number:\nEnter real part : ");


r2=[Link]();
[Link]("Enter imaginary part : ");
i2=[Link]();

Complex c1 = new Complex(r1, i1);


Complex c2 = new Complex(r2, i2);

Complex sum = [Link](c2);


Complex diff = [Link](c2);
Complex prod = [Link](c2);

[Link]("Complex Number 1: ");


[Link]();
[Link]("Complex Number 2: ");
[Link]();
[Link]("Sum: ");
[Link]();
[Link]("Difference: ");
[Link]();
[Link]("Product: ");
[Link]();
}
}
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO. 7
AIM: To implement Constructors and constructor overloading (CO1)
a. WAOOP to count the no. of objects created of a class using constructors.
CODE:
class Counter {
static int count = 0;

Counter() {
count++;
[Link]("Object " + count + " created.");
}

static void displayCount() {


[Link]("Total objects created: " + count);
}
}

class ObjectCounter {
public static void main(String args[]) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

[Link]();
}
}

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

CODE:

import [Link].*;

class Area {

int length, breadth;

Area() {

length = 1;

breadth = 1;

[Link]("Default constructor called (Square of 1x1)");

Area(int l, int b)

{ length = l;

breadth = b;

[Link]("Parameterized constructor called");

Area(Area a)

{ [Link] =

[Link];

[Link] = [Link];

[Link]("Copy constructor called");


}

void displayArea() {

int area = length * breadth;

if (length == breadth)

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

else

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

class AreaDemo {

public static void main(String[] args) {

Area square1 = new Area();

[Link]();

int l1,b1;

Scanner sc=new Scanner([Link]);

[Link]("Enter dimensions lengths and breadth");

l1=[Link]();

b1=[Link]();

Area rect1 = new Area(l1,b1);

[Link]();
int l2,b2;

[Link]("Enter square dimensions lengths and breadth");

l2=[Link]();

b2=[Link]();

Area square2 = new Area(l2,b2);

[Link]();

Area rect2 = new Area(rect1);

[Link]();

OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: RAMYA RAVI ROLL NO.: D130


BATCH: D3 (Batch-1) SAP ID: 60009250191
EXPERIMENT NO. 8
AIM:
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");
}
}

class Constructor8a {
public static void main(String args[])
{ [Link]("Creating object of Class
C:"); C obj = new C();
}
}
OUTPUT:
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 method of the super class using super
keyword.

CODE:
class SuperClass
{ int num;

SuperClass() {
num = 180;
[Link]("SuperClass constructor called.");
}

void display() {
[Link]("Value of number in SuperClass: " + num);
}
}

class SubClass extends SuperClass {

// Constructor
SubClass() {
super();
[Link]("SubClass constructor called.");
}

void output() {
[Link]("Accessing superclass variable using super: " +
[Link]); [Link](); }
}
class Super8b{
public static void main(String args[]) {
SubClass obj = new SubClass();
[Link]();
}
}

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

CODE:
import [Link];

class Staff
{ String
code; String
name;

void read(Scanner sc)


{ [Link]("Enter Code: ");
code = [Link]();
[Link]("Enter Name: ");
name = [Link]();
}

void display()
{ [Link]("Code: " + code);
[Link]("Name: " + name);
}
}

class Teacher extends Staff {


String sub;
int exp;

public void read(Scanner sc)


{ [Link]("Enter Teacher Code:
"); code = [Link]();
[Link]("Enter Teacher Name: ");
name = [Link]();
[Link]("Enter Teacher Subject: ");
sub = [Link]();
[Link]("Enter Teacher Experience: ");
exp = [Link]();
}

public void display()


{ [Link]("**Teacher
Information**"); [Link]();
[Link]("Teacher Subject: " + sub);
[Link]("Teacher Experience: " + exp);
}
}

class Typist extends Staff {


int speed, exp;

public void display() {


[Link]();
[Link]("Typing Speed: " + speed);
[Link]("Experience: " + exp);
}
}

class Regular extends Typist


{ int sal;

public void read(Scanner sc)


{ [Link]("Enter Regular Typist Code: ");
code = [Link]();
[Link]("Enter Regular Typist Name: ");
name = [Link]();
[Link]("Enter Typing Speed: ");
speed = [Link]();
[Link]("Enter Experience: ");
exp = [Link]();
[Link]("Enter Regular Typist Salary: ");
sal = [Link]();
}

public void display() {


[Link]("**Regular Typist Information**");
[Link]();
[Link]("Salary: " + sal);
}
}

class Casual extends Typist


{ int daily_wages;

public void read(Scanner sc)


{ [Link]("Enter Casual Typist Code: ");
code = [Link]();
[Link]("Enter Casual Typist Name: ");
name = [Link]();
[Link]("Enter Typing Speed: ");
speed = [Link]();
[Link]("Enter Experience: ");
exp = [Link]();
[Link]("Enter Casual Typist Salary: ");
daily_wages = [Link]();
}

public void display() {


[Link]("**Casual Typist Information**");
[Link]();
[Link]("Salary: " + daily_wages);
}
}

class Officer extends Staff


{ String dept, grade;

public void read(Scanner sc)


{ [Link]("Enter Officer Code:
"); code = [Link]();
[Link]("Enter Officer Name: ");
name = [Link]();
[Link]("Enter Officer Department: ");
dept = [Link]();
[Link]("Enter Officer Grade: ");
grade = [Link]();
}

public void display()


{ [Link]("Officer
Information"); [Link]();
[Link]("Officer Department: " + dept);
[Link]("Officer Grade: " + grade);
}
}

public class Exp8c {


public static void main(String[] args)
{ Scanner sc = new
Scanner([Link]); Teacher teacher =
new Teacher(); Officer officer = new
Officer(); Regular regular = new
Regular(); Casual casual = new
Casual(); [Link](sc);
[Link](sc);
[Link](sc);
[Link](sc);
[Link]("\n STAFF DETAILS\n");
[Link]();
[Link]("\n");
[Link]();
[Link]("\n");
[Link]();
[Link]("\n");
[Link]();
[Link]();
}
}
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO. 9
AIM: To implement multiple inheritance using interfaces and method overriding (CO1)
a. 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:
import [Link].*;

interface
ReverseString{ public String
reverse(String s);
}

class StringRev implements ReverseString{


public String reverse(String s)
{ StringBuffer s1=new StringBuffer(s);
String sr;
[Link]();
sr=[Link]();
return sr;
}
}

class Maine9{
public static void main(String args[]){
Scanner sc=new
Scanner([Link]); String s,s2;
[Link]("Enter a string");
s=[Link]();
[Link]("Reversed string is
"); ReverseString obj=new StringRev();
s2=[Link](s);
[Link](s2);
}
}

OUTPUT:
b. 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 [Link].*;

interface Sports {
int score();
}
class Student
{ int rollno;
void read() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Roll No: ");
rollno = [Link]();
}
}

class Test extends Student


{ int sem1_marks,
sem2_marks; void read() {
[Link]();
Scanner sc = new Scanner([Link]);
[Link]("Enter Semester 1 Marks: ");
sem1_marks = [Link]();
[Link]("Enter Semester 2 Marks: ");
sem2_marks = [Link]();
}
}

class Result extends Test implements Sports


{ int total;
int s;
public int score() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Sports Score: ");
s=[Link]();
return s;
}

void calculateTotal() {
total = sem1_marks + sem2_marks + score();
}
void displayResult() { [Link]("\
n RESULT "); [Link]("Roll
No: " + rollno);
[Link]("Semester 1 Marks: " + sem1_marks);
[Link]("Semester 2 Marks: " + sem2_marks);
[Link]("Sports Score: " + s);
[Link]("Total Marks: " + total);
}
}

class Main9b {
public static void main(String[] args) {
Result r = new Result();
[Link]();
[Link]();
[Link]();
}
}

OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO. 10
AIM: To implement dynamic polymorphism, final keyword and garbage collection (CO1)
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 Person
{
void role()
{
[Link]("Person class");
}
}
class Student extends Person
{
void role()
{
[Link] ("Student class is executed");
}
}
class Teacher extends Person
{
void role()
{
[Link]("Teacher class is executed");
}
}
class Person10a{
public static void main(String args[])
{ Person t= new Teacher();
[Link]();
Person t1= new Student();
[Link]();
}
}

OUTPUT:
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 InterestCalculator {


final double rate = 0.15 ;

final double simpleInterest(double principal, double time)


{ return principal * time * rate;
}

final double compoundInterest(double principal, double time)


{ return principal * [Link]((1 + rate), time) - principal;
}
}

class Interest10b {
public static void main(String args[])
{ Scanner sc = new Scanner([Link]);

[Link]("Enter the principal amount: ");


double principal = [Link]();

[Link]("Enter the time period (in years): ");


double time = [Link]();
InterestCalculator ic = new InterestCalculator();

double si = [Link](principal, time);


double ci = [Link](principal, time);

[Link]("\n Calculation Results:");


[Link]("Simple Interest for %.2f rupees over %.1f years: Rs. %.2f%n", principal,
time, si);
[Link]("Compound Interest for %.2f over rupees %.1f years: Rs. %.2f%n",
principal, time, ci);
}
}

OUTPUT:
c. WAP to create an object of a class, and delete the same object by calling System. gc () and display a
message that the “object has been deleted”.
CODE:
import [Link].*;
class Collector
{
protected void cleaner() throws Throwable
{
[Link]("object has been deleted ");
}
}
class GarCollect10c {
public static void main(String args[])
{
Collector obj= new Collector();
[Link]("object has been created... ");
obj=null;
[Link]();
[Link]("garbage collection is requested...");
}
}
OUTPUT:
CODE 2:
class GarbageExample
{ String name;

GarbageExample(String name)
{ [Link] = name;
[Link]("Object " + name + " is created");
}

void destroy() {
[Link]("Object " + name + " is ready to be deleted");
}
}

public class GCDemo {


public static void main(String[] args) {
GarbageExample obj = new GarbageExample("TestObject");

[Link]();

obj = null;
[Link]();

[Link](" Object set to null and [Link]() called.");


}
}
OUTPUT 2:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2025-26)

NAME: RAMYA RAVI ROLL NO.: D130


BATCH: D3 (Batch-1) SAP ID: 60009250191
EXPERIMENT NO. 11
AIM: To implement Abstract classes and packages (CO1)
a. Write an abstract class program to calculate area of circle, rectangle and triangle.

CODE :
import [Link];

abstract class Shape {


public abstract void calculateArea();
}

class Circle extends Shape {

public void calculateArea() {


Scanner sc = new Scanner([Link]);
[Link]("Enter radius of the circle: ");
double radius = [Link]();
double area = [Link] * radius * radius;
[Link]("Area of Circle: " + area);
}
}

class Rectangle extends Shape

{ public void calculateArea()

{
Scanner sc = new Scanner([Link]);
[Link]("Enter length of the rectangle: ");
double length = [Link]();
[Link]("Enter width of the rectangle: ");
double width = [Link]();
double area = length * width;
[Link]("Area of Rectangle: " + area);
}
}

class Triangle extends Shape


{ public void calculateArea()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter base of the triangle: ");
double base = [Link]();
[Link]("Enter height of the triangle: ");
double height = [Link]();
double area = 0.5 * base * height;
[Link]("Area of Triangle: " + area);
}
}

class AreaCalci{
public static void main(String[] args)
{ Scanner sc = new Scanner([Link]);

Shape sh;
sh = new Circle();
[Link]();
sh = new Rectangle();
[Link]();
sh = new Triangle();
[Link]();
}
}
OUTPUT:
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:
// creating a package

package CylinderMath;

public class Cylinder{


public void volume(double r,double h)
{ double vol;
vol= 3.14*r*r*h;
[Link]("The volume of cylinder is "+vol);
}
}

//For using the package

import [Link];
import [Link].*;
public class Cylinder11b{
public static void main(String args[])
{ Scanner sc=new Scanner([Link]);
[Link]("Enter radius and height of the cylinder");
double r,h;
r=[Link]();
h=[Link]();
Cylinder obj=new Cylinder();
[Link](r,h);
}
}
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO. 12
1. AIM: To implement exceptions in Java (read input using DataInputStream/ BufferedReader
classes) (CO1, CO2)
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].*;

public class InbuiltExceptions {

public static void main(String[] args) {

BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

// ClassNotFoundException

try {

[Link]("Enter a class name to load: ");


String className = [Link]();

[Link](className);

[Link]("Class " + className + " loaded successfully.");

} catch (ClassNotFoundException e)

{ [Link]("Caught ClassNotFoundException: " +

e);

} catch (IOException e) {

[Link]("IOException while reading class name: " + e);

// IOException

try {

[Link]("Enter any sentence (to demonstrate IOException): ");

String line = [Link]();

[Link]("You entered: " + line);

} catch (IOException e)

{ [Link]("Caught IOException: " +

e);

// NumberFormatException

try {

[Link]("Enter a number: ");

String numStr = [Link]();

int number = [Link](numStr);

[Link]("Parsed number: " + number);

} catch (NumberFormatException e) {
[Link]("Caught NumberFormatException: " + e);

} catch (IOException e)

{ [Link]("IOException: " + e);

// ArithmeticException

try {

[Link]("Enter a numerator: ");

int num = [Link]([Link]());

[Link]("Enter a denominator: ");

int denom = [Link]([Link]());

int result = num / denom;

[Link]("Result = " + result);

} catch (ArithmeticException e)

{ [Link]("Caught ArithmeticException: " + e);

} catch (IOException | NumberFormatException e) {

[Link]("Input error: " + e);

//ArrayIndexOutOfBoundsException

try {

int[] array = {10, 20, 30};

[Link]("Enter array index (0-2): ");


int index = [Link]([Link]());

[Link]("Value at index " + index + ": " + array[index]);

} catch (ArrayIndexOutOfBoundsException e)

{ [Link]("Caught ArrayIndexOutOfBoundsException: " + e);

} catch (IOException | NumberFormatException e) {

[Link]("Input error: " + e);

// NullPointerException

try {

[Link]("Do you want to initialize the string? (yes/no): ");

String choice = [Link]();

String str = null;

if ([Link]("yes")) {

str = "Hello Nacheeket!";

[Link]("String length: " + [Link]());

} catch (NullPointerException e)

{ [Link]("Caught NullPointerException: " +

e);

} catch (IOException e)

{ [Link]("IOException: " + e);

}
}

OUTPUT:
b. Write a Java Program to Create a User Defined Exception class 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
{ public MarksOutOfBoundsException(String message) {
super(message);
}
}
class MarksValidator {
public static void main(String[] args)
{ Scanner scanner = new
Scanner([Link]); int[] marks = new
int[3];

try {
for (int i = 0; i < [Link]; i++) {
[Link]("Enter marks for subject " + (i + 1) + ": ");
marks[i] = [Link]();

if (marks[i] < 0 || marks[i] > 100) {


throw new MarksOutOfBoundsException("Invalid marks: " + marks[i] + ". Must be
between 0 and 100.");
}
}

[Link]("All marks entered successfully!");


} catch (MarksOutOfBoundsException e)
{ [Link]("Exception occurred: " +
[Link]());
} catch (Exception e) {
[Link]("Some unexpected error occurred: " + e);
}
}
}

OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO. 13
AIM: To implement Multithreading (CO1, CO2)
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 TableThread extends Thread {
int number;
public void run() {
for (int i = 1; i <= 10; i++) {
[Link](number + " x " + i + " = " + (number * i));
}
}
}
class Table13a{
public static void main(String args[])
{ TableThread thread1 = new
TableThread(); [Link] = 5;
TableThread thread2 = new TableThread();
[Link] = 7;
TableThread thread3 = new TableThread();
[Link] = 13;

[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
b. Write a multithreaded program to display /*/*/*/*/*/*/*/* using 2 child threads.
CODE:
class SlashPrinter extends Thread
{ public void run() {
for (int i = 0; i < 8; i++) {
[Link]("/");
try {
[Link](100);
} catch (Exception e) {}
}
}
}
class StarPrinter extends Thread
{ public void run() {
for (int i = 0; i < 8; i++) {
[Link]("*");
try {
[Link](100);
} catch (Exception e) {}
}
}
}
public class Pattern13b {
public static void main(String[] args)
{ SlashPrinter s1 = new SlashPrinter();
StarPrinter s2 = new StarPrinter();
[Link]("SlashThread");
[Link]("StarThread");
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (Exception e) {}
[Link]("\nPattern printed by 2 child threads.");
}
}
OUTPUT:
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[] fibonacci;
private int count;
public FibonacciGenerator(int count) {
[Link] = count;
fibonacci = new int[count];
}
public void run() {
if (count == 0) return;
if (count >= 1) fibonacci[0] = 0;
if (count >= 2) fibonacci[1] = 1;

for (int i = 2; i < count; i++) {


fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
}
}
public int[] getFibonacci()
{ return fibonacci;
}
}
public class Input13c {
public static void main(String[] args)
{ Scanner scanner = new
Scanner([Link]);
[Link]("Enter how many Fibonacci numbers to generate: ");
int count = [Link]();
FibonacciGenerator fibThread = new FibonacciGenerator(count);
[Link]();
try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
[Link]("Fibonacci Sequence:");
for (int num : [Link]()) {
[Link](num + " ");
}
}
}
OUTPUT:
d. WAP to prevent concurrent booking of a ticket using the concept of thread synchronization.
CODE:
class TicketBooking {
private int availableTickets = 1;

public synchronized void bookTicket(String userName) {


if (availableTickets > 0) {
[Link](userName + " is booking the ticket...");
try {
[Link](1000);
} catch (InterruptedException e)
{ [Link]("Booking interrupted for " +
userName);
}
availableTickets--;
[Link]("Ticket successfully booked by " + userName);
} else {
[Link]("Sorry " + userName + ", ticket already booked.");
}
}
}
class User extends Thread
{ private String userName;
private TicketBooking bookingSystem;
public User(String userName, TicketBooking bookingSystem)
{ [Link] = userName;
[Link] = bookingSystem;
}
public void run() {
[Link](userName);
}
}
public class Main13d {
public static void main(String[] args) {
TicketBooking bookingSystem = new TicketBooking();
User u1 = new User("Nacheeket", bookingSystem);
User u2 = new User("Nick", bookingSystem);
User u3 = new User("Tom", bookingSystem);
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
e. Write a program to demonstrate thread methods: wait notify suspend resume join setpriority
getpriority setname getname
CODE:
class ThreadMethod extends Thread
{ public void run() {
[Link](getName() + " started.");
[Link](getName() + " priority: " + getPriority());
setPriority(Thread.MAX_PRIORITY);
[Link](getName() + " priority after set: " +
getPriority()); synchronized (this) {
try {
wait(1000); // Wait for 1 second
[Link](getName() + " resumed.");
} catch (InterruptedException e)
{ [Link](getName() + "
interrupted.");
}
}
}
}
public class Exp13e {
public static void main(String[] args) throws InterruptedException {
ThreadMethod t1 = new ThreadMethod();
ThreadMethod t2 = new ThreadMethod();

[Link]("Thread-1");
[Link]("Thread-2");
[Link](Thread.MIN_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link]();
[Link]();
[Link]();
[Link]();
synchronized (t1) {
[Link](1000);
[Link]();
[Link]("Notified " + [Link]());
}
}
}
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)

NAME: NACHEEKET SHAH ROLL NO.: D180


BATCH: D3 (Batch-2) SAP ID: 60009240265
EXPERIMENT NO. 14
AIM: To implement basic Swing programs with event handling (CO1, CO3)
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 Expt14a extends JFrame implements ActionListener

JFrame registartion,f;

JLabel login,password;

JButton ok,reset;

JTextField id,user;

JPasswordField pwd;
Expt14a()

registartion=new JFrame("Registration Form");

f=new JFrame();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

login=new JLabel("Login ID: ");

password=new JLabel("Password: ");

ok=new JButton("OK");

reset=new JButton("RESET");

id=new JTextField(10);

pwd=new JPasswordField(8);

user=new JTextField(50);

[Link](new FlowLayout());

[Link](login);

[Link](id);

[Link](password);

[Link](pwd);

[Link](ok);

[Link](reset);

[Link](user);

[Link](this);
[Link](this);

[Link](500,200);

[Link](true);

public void actionPerformed(ActionEvent e)

if([Link]()==ok)

String login_id=[Link]();

String login_pwd=[Link]([Link]());

[Link]("Login ID: "+login_id+"\nPassword: "+login_pwd);

else if([Link]()==reset)

[Link]("");

[Link]("");

[Link]("");

public static void main(String args[])

{
Expt14a form=new Expt14a();

OUTPUT:
b. Write a program to create a basic calculator.

CODE:

import [Link].*;

import [Link].*;

import [Link].*;

public class Calc extends JFrame implements ActionListener

{ JTextField tf;

JButton[] btns = new JButton[10];

JButton add, sub, mul, div, eq, clr;

String op = "";

double n1 = 0, n2 = 0;

public Calc() {

setTitle("Calculator");

setSize(250, 300);

setLayout(new FlowLayout());

tf = new JTextField(20);

[Link](false);

add(tf);

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

{ btns[i] = new JButton("" +

i);

btns[i].addActionListener(this);

add(btns[i]);

}
add = new JButton("+"); sub = new JButton("-");

mul = new JButton("*"); div = new JButton("/");

eq = new JButton("="); clr = new JButton("C");

[Link](this); [Link](this);

[Link](this); [Link](this);

[Link](this); [Link](this);

add(add); add(sub); add(mul); add(div); add(eq); add(clr);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

public void actionPerformed(ActionEvent e)

{ String txt =

((JButton)[Link]()).getText(); if

([Link]("[0-9]")) {

[Link]([Link]() + txt);

} else if ([Link]("[+\\-*/]")) {

n1 = [Link]([Link]());

op = txt;

[Link]("");

} else if ([Link]("=")) {

n2 = [Link]([Link]());

switch (op) {

case "+": [Link]("" + (n1 + n2)); break;

case "-": [Link]("" + (n1 - n2)); break;


case "*": [Link]("" + (n1 * n2)); break;

case "/":

if (n2 != 0) [Link]("" + (n1 / n2));

else [Link]("Err");

break;

} else if ([Link]("C")) {

[Link]("");

n1 = n2 = 0;

op = "";

public static void main(String[] args)

{ new Calc();

}
OUTPUT:
c. Display the selected fields in Details after submit button is clicked

CODE:

import [Link].*;

import [Link].*;

import [Link].*;

public class Exp14c extends JFrame implements ActionListener

{ JTextField name;

JRadioButton male, female;

JCheckBox music, swim;

JComboBox<String> place;

JTextArea details;

JButton submit, exit;

ButtonGroup genderGroup;

public Exp14c(){

setTitle("Welcome to classroom");
setSize(400, 400);

setLayout(null);

JLabel l1 = new JLabel("Name:");

[Link](30, 30, 100, 20);

add(l1);

name = new JTextField();

[Link](140, 30, 200, 20);

add(name);

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

[Link](30, 60, 100, 20);

add(l2);

male = new JRadioButton("Male");

female = new JRadioButton("Female");

[Link](140, 60, 70, 20);

[Link](220, 60, 80, 20);

genderGroup = new ButtonGroup();

[Link](male);

[Link](female);

add(male); add(female);

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

[Link](30, 90, 100, 20);


add(l3);

music = new JCheckBox("Music");

swim = new JCheckBox("Swimming");

[Link](140, 90, 80, 20);

[Link](230, 90, 100, 20);

add(music); add(swim);

JLabel l4 = new JLabel("Favourite Place:");

[Link](30, 120, 120, 20);

add(l4);

String[] places = {"Russia", "India", "Japan", "USA"};

place = new JComboBox<>(places);

[Link](140, 120, 200, 20);

add(place);

JLabel l5 = new JLabel("Details:");

[Link](30, 150, 100, 20);

add(l5);

details = new JTextArea();

[Link](140, 150, 200,

80); [Link](false);

add(details);

submit = new JButton("Submit");


[Link](100, 250, 80, 30);

[Link](this);

add(submit);

exit = new JButton("Exit");

[Link](200, 250, 80, 30);

[Link](e -> [Link](0));

add(exit);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

public void actionPerformed(ActionEvent e)

{ String n = [Link]();

String g = [Link]() ? "Male" : ([Link]() ? "Female" : "Not selected");

String interests = "";

if ([Link]()) interests += "Music ";

if ([Link]()) interests += "Swimming ";

String p = (String) [Link]();

String result = "Name: " + n + "\nGender: " + g + "\nInterests: " + interests + "\nFavourite Place: " +
p;

[Link](result);

public static void main(String[] args) {


new Exp14c();

}
OUTPUT:

You might also like