Professional Documents
Culture Documents
Oops Practical
Oops Practical
import java.io.*;
import java.util.Scanner;
if(d>0)
{
root1=(-b+Math.sqrt(d))/(2*a);
root2=(-b-Math.sqrt(d))/(2*a);
System.out.println("The root are real and difference");
System.out.format("root1=%.2f and root2%.2f",root1,root2);
}
else if(d==0)
{
root1=root2=-b/(2*a);
System.out.println("The root are real and equal");
System.out.format("root1=root2=%.2f ",root1);
}
else
{
double real=-b/(2*a);
double imaginary =Math.sqrt(-d)/(2*a);
System.out.println("The root are imaginary");
System.out.format("root1=%.2f + %.2f ",real,imaginary);
System.out.format("/n root2=%.2f .%2fi ",real,imaginary);
}
}
}
ii) Fibonacci series is a series of integers, where Nth term is equal to the sum of N-1 th and N-2 th (last two
terms). The first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent term is the sum
of the previous two terms. Write a program in Java to print Fibonacci series without recursion.
import java.util.Scanner;
2. i) Write a java program for sorting a given list of names in ascending order.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
names.add("John");
names.add("Alice");
names.add("Bob");
names.add("Eve");
names.add("Charlie");
Collections.sort(names);
ii) Write a program that prompts the user for an integer and then prints out all prime
numbers up to that integer.
import java.util.*;
class PrimeNumbers
{
public static void main(String[] args)
{
int n;
int flag;
Scanner s=new Scanner(System.in);
System.out.print("Enter a number: ");
n = s.nextInt();
System.out.print("The prime numbers are : ");
for(int i=2;i<n;i++)
{
if(i%j==0)
flag=1;
if(flag==0)
System.out.print(i+" ");
}
}
}
3. i) Write a Java program to Multiply two given matrices.
import java.io.*
import java.util.*;
if(q!=r)
{
System.out.println("Matrix multiplication is not possible");
}
else
{
int a[][]=new int[p][q];
int b[][]=new int[r][s];
int c[][]=new int[p][s];
for(int i=0;i<p;i++)
{
for(int j=0;j<q;j++)
{
a[i][j]=n.nextInt();
}
}
System.out.println("First matrix:");
for(int i=0;i<p;i++)
{
for(int j=0;j<q;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
for(int i=0;i<r;i++)
{
for(int j=0;j<s;j++)
{
b[i][j]=n.nextInt();
}
}
for(int k=0;k<q;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
}
import java.util.Scanner;
if (isArmstrongNumber(number)) {
System.out.println(number + " is an Armstrong number.");
}
else {
System.out.println(number + " is not an Armstrong number.");
}
}
4. Prepare an Electricity bill using Java. Create a class with the following members: Consumer number,
Consumer name, previous month reading, current month reading, type of EB connection.
Calculate the domestic connection bill amount using the following tariff:
import java.io.*;
import java.util.*;
class EbBill
{
public static void main(String args[])
{
double amt;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your
connection\n1.Domestic\n2.Commercial:");
int type = sc.nextInt();
switch(type)
{
case 1:
{
if(dunits <= 150)
amt = units * 2;
System.out.println("Customer no:"+cno+"\nCustomer
name:"+name+"\nunits:"+units+"\nBill amt:"+amt);
break;
}
default:
System.out.println("Customer no"+cno+"\nCustomername"+name);
}
sc.close();
}
}
5. Develop a Java application using packages to implement the following currency converter
– Dollar to Indian Rupees, Euro to Indian Rupees, and vice versa.
CONV-1:
package pack1;
import java.util.*;
switch(type)
{
case 1:
double usd;
usd=inr/83.0;
System.out.println("INR="+inr+" is USD="+usd);
break;
case 2:
double eur;
eur=inr/90.0;
System.out.println("INR="+inr+" is EUR="+eur);
break;
case 3:
double yen;
yen=inr*1.76;
System.out.println("INR="+inr+" is YEN="+yen);
break;
}
}
CURRENCY:
import pack1.Conv1;
import java.util.*;
if(opt=='a')
{
System.out.println("Enter the INR value in Rs.");
int inr = sc.nextInt();
c1.convert1(inr);
}
else
{
System.out.println("Select the option\na.USD\nb.EUR\nc.YEN\n");
char choice = sc.next().charAt(0);
c1.convert2(choice);
}
}
}
6. i) Develop a Java application using packages to implement the following time converter (hours to
minutes, seconds and vice versa)
package timeconverter;
ii) Write a Java program for sorting a given list of names in ascending order
import java.util.*;
class StringSorting
{
void sortStrings()
{
Scanner s = new Scanner(System.in);
class Strings
{
public static void main(String[] args)
{
StringSorting obj = new StringSorting();
obj.sortStrings();
}
}
7. Develop a java application with Employee class with Emp_name, Emp_id, Address, Mail_id, Mobile_no
as members. Inherit the classes, Programmer, Associate Professor from employee class. Add Basic Pay (BP)
as the member of all the inherited classes with 98% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1%
of BP for staff club fund. Generate pay slips for the employees with their gross and net salary.
import java.io.*;
import java.util.*;
import java.lang.*;
class Employee
{
String name, address,mail, mobile;
int id;
float da,hra,pf,scf,gross,net;
float b;
void getData()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter name:");
name = sc.next();
System.out.println("Enter id:");
id = sc.nextInt();
System.out.println("Enter address:");
address = sc.next();
System.out.println("Enter mail:");
mail = sc.next();
void display()
{
System.out.println("EMPLOYEE DETAILS");
System.out.println("Employee name:" + name);
System.out.println("Employee ID:" + id);
System.out.println("Employee address:" + address);
System.out.println("Employee mobile number:" + mobile);
System.out.println("Employee mail:" + mail);
System.out.println("Basic pay:" + b);
System.out.println("DA:" + da);
System.out.println("HRA:" + hra);
System.out.println("PF:" + pf);
System.out.println("Staff Club Fund:" + scf);
System.out.println("Gross Salary:" + gross);
System.out.println("Net Salary:" + net);
}
}
class programmer extends employee
{
float bp;
programmer()
{
bp=7500;
}
}
switch(choice)
{
case 1:
System.out.println("Enter the Programmer details:");
programmer ob1=new programmer();
ob1.getData();
ob1.calc(ob1.bp);
ob1.display();
break;
case 2:
System.out.println("Enter the Assistant Professor details:");
ap ob2=new ap();
ob2.getData();
ob2.calc(ob2.bp);
ob2.display();
break;
case 3:
System.out.println("Enter the Associative Professor details:");
asso ob3=new asso();
ob3.getData();
ob3.calc(ob3.bp);
ob3.display();
break;
}
}
}
8. Write a Java Program to create an abstract class named Shape that contains two integers and an empty
method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one
of the classes extends the class Shape. Each one of the classes contains only the method print Area () that
prints the area of the given shape.
import java.io.*;
import java.util.*;
int x1=a.nextInt();
int y1=a.nextInt();
9. Write a Java program that simulates a traffic light. The program lets the user select one of three lights:
Red, Yellow or Green with radio buttons. On selecting a button an appropriate message with “STOP “or
“READY” or “GO” should appear above the buttons in selected color. Initially, there is no message shown.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
jr1.addItemListener(this);
jr2.addItemListener(this);
jr3.addItemListener(this);
add(jr1);
add(jr2);
add(jr3);
b.add(jr1);
b.add(jr2);
b.add(jr3);
add(j1);
// To add a window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
// If state is Green
if (ie.getSource() == jr3) {
if (ie.getStateChange() == 1) {
msg = "Go!!";
z = 1;
repaint();
}
else {
msg = "";
}
}
j1.setText(msg);
}
// Case: Red
if (x == 1) {
g.setColor(Color.RED);
g.fillOval(120, 150, 60, 60);
g.setColor(Color.WHITE);
g.fillOval(120, 230, 60, 60);
g.setColor(Color.WHITE);
g.fillOval(120, 300, 60, 60);
x = 0;
}
// Case: Orange
if (y == 1) {
g.setColor(Color.WHITE);
g.fillOval(120, 150, 60, 60);
g.setColor(Color.YELLOW);
g.fillOval(120, 230, 60, 60);
g.setColor(Color.WHITE);
g.fillOval(120, 300, 60, 60);
y = 0;
}
// Case: Green
if (z == 1) {
g.setColor(Color.WHITE);
g.fillOval(120, 150, 60, 60);
g.setColor(Color.WHITE);
g.fillOval(120, 230, 60, 60);
g.setColor(Color.GREEN);
g.fillOval(120, 300, 60, 60);
z = 0;
}
}
10. ii) Write a Java program that reads a file and displays a file.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
try {
File file = new File(filePath);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
bufferedReader.close();
}
catch (IOException e) {
System.err.println("An error occurred while reading the file: " +
e.getMessage());
}
}
}
11. i) Write a java program to find factorial of a number. User is allowed to enter a number into the text
field whose factorial is to be determined. The result will get displayed in another text field.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
try {
int number = Integer.parseInt(inputField.getText());
long factorial = calculateFactorial(number);
resultField.setText(Long.toString(factorial));
}
catch (NumberFormatException ex) {
resultField.setText("Invalid input");
}
}
});
add(inputLabel);
add(inputField);
add(calculateButton);
add(resultLabel);
add(resultField);
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
display = new JTextField();
display.setEditable(false);
add(display, BorderLayout.NORTH);
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
add(buttonPanel, BorderLayout.CENTER);
currentInput = "";
firstOperand = 0;
operator = "";
setVisible(true);
}
if (Character.isDigit(command.charAt(0)) || command.equals(".")) {
currentInput += command;
display.setText(currentInput);
}
else if (command.equals("=")) {
calculateResult();
}
else {
if (!currentInput.isEmpty())
{
firstOperand = Double.parseDouble(currentInput);
operator = command;
currentInput = "";
}
}
}
switch (operator) {
case "+":
result = firstOperand + secondOperand;
break;
case "-":
result = firstOperand - secondOperand;
break;
case "*":
result = firstOperand * secondOperand;
break;
case "/":
if (secondOperand != 0) {
result = firstOperand / secondOperand;
} else {
display.setText("Error: Division by zero");
return;
}
break;
}
display.setText(Double.toString(result));
currentInput = "";
}
}
}
class Main
{
public static void main(String[] args)
{
String str = "Radar", reverseStr = "";
int strLength = str.length();
if (str.toLowerCase().equals(reverseStr.toLowerCase()))
{
System.out.println(str + " is a Palindrome String.");
}
else
{
System.out.println(str + " is not a Palindrome String.");
}
}
}
import javax.swing.*;
import java.awt.*;
import javax.swing.*;
import java.awt.*;
17. i) Write a Java program to implement an Array Index Out of Bounds Exception.
public class ArrayIndexOutOfBoundsDemo
{
public static void main(String[] args)
{
int[] numbers = {1, 2, 3, 4, 5};
try {
int value = numbers[6]; // Attempt to access an index that doesn't exist
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out of Bounds Exception caught: " +
e.getMessage());
}
}
}
ii) Develop a Java GUI program to Draw 3 circles on same line using Red, Green and Blue
colors on a Frame.
import javax.swing.*;
import java.awt.*;
g.setColor(Color.GREEN);
g.fillOval(150, 50, 50, 50);
g.setColor(Color.BLUE);
g.fillOval(250, 50, 50, 50);
}