0% found this document useful (0 votes)
40 views

Java All 5 Practical Questions with Answers

Uploaded by

rawataparna73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Java All 5 Practical Questions with Answers

Uploaded by

rawataparna73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Java Practical

Program 1
Write a Java program to handle rational numbers. The program should:
1. Acceptinputforthenumeratoranddenominatorofarationalnumber.
2. Displaytheoriginalrationalnumber.
3. Simplifytherationalnumbertoitsreducedform.
4. Displaythereducedform.
Example:
NUMERATOR=60
DENOMINATOR=20
BEFORE SIMPLIFICATION=60/20
Reduced form=3/1

ANSWER

import java.util.Scanner;
public class RationalNumber {
private int numerator;
private int denominator;

public RationalNumber(int numerator, int denominator) {


if (denominator == 0) {
throw new IllegalArgumentException("Denominator can
not be zero.");
}
this.numerator = numerator;
this.denominator = denominator;
}

public void displayOriginal() {


System.out.println("BEFORE SIMPLIFICATION = " + numerat
or + "/" + denominator);

Java Practical 1
}

public void simplify() {


int gcd = findGCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}

public void displayReduced() {


System.out.println("Reduced form = " + numerator + "/"
+ denominator);
}

private int findGCD(int a, int b) {


if (b == 0) {
return a;
}
return findGCD(b, a % b);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("NUMERATOR = ");
int numerator = scanner.nextInt();

System.out.print("DENOMINATOR = ");
int denominator = scanner.nextInt();

RationalNumber rationalNumber = new RationalNumber(nume


rator, denominator);
rationalNumber.displayOriginal();
rationalNumber.simplify();
rationalNumber.displayReduced();

scanner.close();
}
}

Java Practical 2
Output:

Experiment 2
Develop a user-defined package in Java named Date, which consists of a class
named CurrentDate. This package should contain methods to display the
current
date in the format "day/month/year" and the current time in the format
"hour:minute
AM/PM".

Write an application program that imports this package and uses the
CurrentDate
class to display the current date and time.

ANSWER

Here's how you can create the package and the application program concisely:

Step 1: Create the Package and Class


1. File: Date/CurrentDate.java

package Date;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentDate {


public void displayCurrentDate() {
LocalDateTime now = LocalDateTime.now();
System.out.println(now.format(DateTimeFormatter.ofP

Java Practical 3
attern("dd/MM/yyyy")));
}

public void displayCurrentTime() {


LocalDateTime now = LocalDateTime.now();
System.out.println(now.format(DateTimeFormatter.ofP
attern("hh:mm a")));
}
}

Step 2: Create the Application Program


1. File: Main.java

import Date.CurrentDate;

public class Main {


public static void main(String[] args) {
CurrentDate currentDate = new CurrentDate();
currentDate.displayCurrentDate();
currentDate.displayCurrentTime();
}
}

Output:

Experiment 3

Write a Java program to demonstrate inheritance. Create a base class and a


derived class. The base class should have some attributes and methods. The
derived class should inherit from the base class and add additional attributes
and

Java Practical 4
methods. Instantiate objects of both classes and demonstrate inheritance by
accessing attributes and methods of both classes.

class Base{
int a=2;
public void baseMethod(){
System.out.println("This is from base class");
}
public void baseMethodforDerivedClass(){
System.out.println("This is from base class");
}
}
class derived extends Base{
int b=3;
void derivedMethod(){
System.out.println("This is from derived class");
}
}
public class p3_Inheritance {
public static void main(String[] args) {
Base b1 = new Base();
derived d1 = new derived();
b1.baseMethod();
System.out.println("This is the attribute of base c
lass: "+ b1.a);

d1.derivedMethod();
d1.baseMethodforDerivedClass();
System.out.println(d1.b);

Output:

Java Practical 5
Experiment 4
Write a Java program to create a scientific calculator using Swing. The
calculator
should have functionalities for basic arithmetic operations (+, -, *, /),
trigonometric
functions (sin, cos, tan), and square root. The GUI should display the
calculation as
it progresses and should include necessary buttons for user interaction.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Math;

public class ScientificCalculator extends JFrame implements


ActionListener {
JTextField display;
JButton[] numButtons = new JButton[10];
JButton addButton, subButton, mulButton, divButton, sin
Button, cosButton, tanButton, sqrtButton, eqButton, clrButt
on;
String operator = "";
double num1 = 0, num2 = 0;

public ScientificCalculator() {
setLayout(new BorderLayout());

display = new JTextField();


add(display, BorderLayout.NORTH);

Java Practical 6
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4));
add(panel, BorderLayout.CENTER);

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


numButtons[i] = new JButton(String.valueOf(i));
numButtons[i].addActionListener(this);
panel.add(numButtons[i]);
}

addButton = new JButton("+"); subButton = new JButt


on("-");
mulButton = new JButton("*"); divButton = new JButt
on("/");
sinButton = new JButton("sin"); cosButton = new JBu
tton("cos");
tanButton = new JButton("tan"); sqrtButton = new JB
utton("sqrt");
eqButton = new JButton("="); clrButton = new JButto
n("C");

JButton[] functionButtons = {addButton, subButton,


mulButton, divButton, sinButton, cosButton, tanButton, sqrt
Button, eqButton, clrButton};
for (JButton btn : functionButtons) {
btn.addActionListener(this);
panel.add(btn);
}

setTitle("Scientific Calculator");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


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

Java Practical 7
if (e.getSource() == numButtons[i]) {
display.setText(display.getText() + i);
}
}
if (e.getSource() == addButton) { operator = "+"; n
um1 = readDisplay(); clearDisplay(); }
if (e.getSource() == subButton) { operator = "-"; n
um1 = readDisplay(); clearDisplay(); }
if (e.getSource() == mulButton) { operator = "*"; n
um1 = readDisplay(); clearDisplay(); }
if (e.getSource() == divButton) { operator = "/"; n
um1 = readDisplay(); clearDisplay(); }
if (e.getSource() == sinButton) { display.setText(S
tring.valueOf(Math.sin(Math.toRadians(readDisplay())))); }
if (e.getSource() == cosButton) { display.setText(S
tring.valueOf(Math.cos(Math.toRadians(readDisplay())))); }
if (e.getSource() == tanButton) { display.setText(S
tring.valueOf(Math.tan(Math.toRadians(readDisplay())))); }
if (e.getSource() == sqrtButton) { display.setText
(String.valueOf(Math.sqrt(readDisplay()))); }
if (e.getSource() == eqButton) {
num2 = readDisplay();
switch (operator) {
case "+": display.setText(String.valueOf(nu
m1 + num2)); break;
case "-": display.setText(String.valueOf(nu
m1 - num2)); break;
case "*": display.setText(String.valueOf(nu
m1 * num2)); break;
case "/": display.setText(String.valueOf(nu
m1 / num2)); break;
}
}
if (e.getSource() == clrButton) { clearDisplay(); }
}

private double readDisplay() {


return Double.parseDouble(display.getText());

Java Practical 8
}

private void clearDisplay() {


display.setText("");
}

public static void main(String[] args) {


new ScientificCalculator();
}
}

Output:

Experiment 5

The task is to implement a simple Lisp-like list in Java. Lisp is a programming


language known for its extensive use of lists as fundamental data structures.

Java Practical 9
The
task involves implementing two functions:

1. car: This function should return the first element of the list.

2. cdr: This function should return the rest of the list after removing the first
element.

LispList.java

import java.util.ArrayList;
import java.util.List;

public class LispList {


private List<Object> list;

public LispList(Object... elements) {


list = new ArrayList<>();
for (Object elem : elements) {
list.add(elem);
}
}

public Object car() {


return list.isEmpty() ? null : list.get(0);
}

public LispList cdr() {


if (list.isEmpty()) return null;
LispList tail = new LispList();
tail.list = list.subList(1, list.size());
return tail;
}

@Override
public String toString() {
return list.toString();
}

Java Practical 10
public static void main(String[] args) {
LispList list = new LispList(1, 2, 3, 4, 5);
System.out.println("List: " + list);
System.out.println("car: " + list.car());
System.out.println("cdr: " + list.cdr());
}
}

Output:

Java Practical 11

You might also like