Java All Exp
Java All Exp
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.
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{
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)
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];
[Link]();
}
}
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)
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;
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)
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];
[Link](85);
[Link](90);
[Link](78);
[Link](88);
[Link](92);
[Link]("Marks of students:");
for (int m : marks) {
[Link](m);
}
[Link](2, 80);
[Link]("After inserting 80 at index 2: " + marks);
[Link](3);
[Link]("After removing element at index 3: " + marks);
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)
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();
}
CODE:
class ObjectCounter
{ static int count =
0; ObjectCounter()
{
count++;
}
[Link]();
}
}
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2025-26)
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);
}
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;
Counter() {
count++;
[Link]("Object " + count + " created.");
}
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 {
Area() {
length = 1;
breadth = 1;
Area(int l, int b)
{ length = l;
breadth = b;
Area(Area a)
{ [Link] =
[Link];
[Link] = [Link];
void displayArea() {
if (length == breadth)
else
class AreaDemo {
[Link]();
int l1,b1;
l1=[Link]();
b1=[Link]();
[Link]();
int l2,b2;
l2=[Link]();
b2=[Link]();
[Link]();
[Link]();
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)
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);
}
}
// 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 display()
{ [Link]("Code: " + code);
[Link]("Name: " + name);
}
}
CODE:
import [Link].*;
interface
ReverseString{ public String
reverse(String s);
}
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]();
}
}
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)
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];
class Interest10b {
public static void main(String args[])
{ Scanner sc = new Scanner([Link]);
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");
}
}
[Link]();
obj = null;
[Link]();
CODE :
import [Link];
{
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 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;
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)
CODE:
import [Link].*;
// ClassNotFoundException
try {
[Link](className);
} catch (ClassNotFoundException e)
e);
} catch (IOException e) {
// IOException
try {
} catch (IOException e)
e);
// NumberFormatException
try {
} catch (NumberFormatException e) {
[Link]("Caught NumberFormatException: " + e);
} catch (IOException e)
// ArithmeticException
try {
} catch (ArithmeticException e)
//ArrayIndexOutOfBoundsException
try {
} catch (ArrayIndexOutOfBoundsException e)
// NullPointerException
try {
if ([Link]("yes")) {
} catch (NullPointerException e)
e);
} catch (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]();
OUTPUT:
Object Oriented Programming using Java Laboratory (DJS23FLES201)
F.Y B. Tech, Semester: II
Experiments
(AY: 2024-25)
[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;
[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)
CODE:
import [Link].*;
import [Link].*;
import [Link].*;
JFrame registartion,f;
JLabel login,password;
JButton ok,reset;
JTextField id,user;
JPasswordField pwd;
Expt14a()
f=new JFrame();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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);
if([Link]()==ok)
String login_id=[Link]();
String login_pwd=[Link]([Link]());
else if([Link]()==reset)
[Link]("");
[Link]("");
[Link]("");
{
Expt14a form=new Expt14a();
OUTPUT:
b. Write a program to create a basic calculator.
CODE:
import [Link].*;
import [Link].*;
import [Link].*;
{ JTextField tf;
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);
i);
btns[i].addActionListener(this);
add(btns[i]);
}
add = new JButton("+"); sub = new JButton("-");
[Link](this); [Link](this);
[Link](this); [Link](this);
[Link](this); [Link](this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
{ 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 "/":
else [Link]("Err");
break;
} else if ([Link]("C")) {
[Link]("");
n1 = n2 = 0;
op = "";
{ new Calc();
}
OUTPUT:
c. Display the selected fields in Details after submit button is clicked
CODE:
import [Link].*;
import [Link].*;
import [Link].*;
{ JTextField name;
JComboBox<String> place;
JTextArea details;
ButtonGroup genderGroup;
public Exp14c(){
setTitle("Welcome to classroom");
setSize(400, 400);
setLayout(null);
add(l1);
add(name);
add(l2);
[Link](male);
[Link](female);
add(male); add(female);
add(music); add(swim);
add(l4);
add(place);
add(l5);
80); [Link](false);
add(details);
[Link](this);
add(submit);
add(exit);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
{ String n = [Link]();
String result = "Name: " + n + "\nGender: " + g + "\nInterests: " + interests + "\nFavourite Place: " +
p;
[Link](result);
}
OUTPUT: