0% found this document useful (0 votes)
49 views11 pages

Java Practical Programming Exercises

Uploaded by

rawataparna73
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)
49 views11 pages

Java Practical Programming Exercises

Uploaded by

rawataparna73
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

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 [Link];
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.");
}
[Link] = numerator;
[Link] = denominator;
}

public void displayOriginal() {


[Link]("BEFORE SIMPLIFICATION = " + numerat
or + "/" + denominator);

Java Practical 1
}

public void simplify() {


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

public void displayReduced() {


[Link]("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([Link]);

[Link]("NUMERATOR = ");
int numerator = [Link]();

[Link]("DENOMINATOR = ");
int denominator = [Link]();

RationalNumber rationalNumber = new RationalNumber(nume


rator, denominator);
[Link]();
[Link]();
[Link]();

[Link]();
}
}

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/[Link]

package Date;

import [Link];
import [Link];

public class CurrentDate {


public void displayCurrentDate() {
LocalDateTime now = [Link]();
[Link]([Link]([Link]

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

public void displayCurrentTime() {


LocalDateTime now = [Link]();
[Link]([Link]([Link]
attern("hh:mm a")));
}
}

Step 2: Create the Application Program


1. File: [Link]

import [Link];

public class Main {


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

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(){
[Link]("This is from base class");
}
public void baseMethodforDerivedClass(){
[Link]("This is from base class");
}
}
class derived extends Base{
int b=3;
void derivedMethod(){
[Link]("This is from derived class");
}
}
public class p3_Inheritance {
public static void main(String[] args) {
Base b1 = new Base();
derived d1 = new derived();
[Link]();
[Link]("This is the attribute of base c
lass: "+ b1.a);

[Link]();
[Link]();
[Link](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 [Link].*;
import [Link].*;
import [Link].*;
import [Link];

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, [Link]);

Java Practical 6
JPanel panel = new JPanel();
[Link](new GridLayout(5, 4));
add(panel, [Link]);

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


numButtons[i] = new JButton([Link](i));
numButtons[i].addActionListener(this);
[Link](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) {
[Link](this);
[Link](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 ([Link]() == numButtons[i]) {
[Link]([Link]() + i);
}
}
if ([Link]() == addButton) { operator = "+"; n
um1 = readDisplay(); clearDisplay(); }
if ([Link]() == subButton) { operator = "-"; n
um1 = readDisplay(); clearDisplay(); }
if ([Link]() == mulButton) { operator = "*"; n
um1 = readDisplay(); clearDisplay(); }
if ([Link]() == divButton) { operator = "/"; n
um1 = readDisplay(); clearDisplay(); }
if ([Link]() == sinButton) { [Link](S
[Link]([Link]([Link](readDisplay())))); }
if ([Link]() == cosButton) { [Link](S
[Link]([Link]([Link](readDisplay())))); }
if ([Link]() == tanButton) { [Link](S
[Link]([Link]([Link](readDisplay())))); }
if ([Link]() == sqrtButton) { [Link]
([Link]([Link](readDisplay()))); }
if ([Link]() == eqButton) {
num2 = readDisplay();
switch (operator) {
case "+": [Link]([Link](nu
m1 + num2)); break;
case "-": [Link]([Link](nu
m1 - num2)); break;
case "*": [Link]([Link](nu
m1 * num2)); break;
case "/": [Link]([Link](nu
m1 / num2)); break;
}
}
if ([Link]() == clrButton) { clearDisplay(); }
}

private double readDisplay() {


return [Link]([Link]());

Java Practical 8
}

private void clearDisplay() {


[Link]("");
}

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.

[Link]

import [Link];
import [Link];

public class LispList {


private List<Object> list;

public LispList(Object... elements) {


list = new ArrayList<>();
for (Object elem : elements) {
[Link](elem);
}
}

public Object car() {


return [Link]() ? null : [Link](0);
}

public LispList cdr() {


if ([Link]()) return null;
LispList tail = new LispList();
[Link] = [Link](1, [Link]());
return tail;
}

@Override
public String toString() {
return [Link]();
}

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

Output:

Java Practical 11

Common questions

Powered by AI

The Java scientific calculator utilizes GUI components such as `JTextField` for display, `JButton` for numerical and operation inputs, and a `JPanel` organized with a `GridLayout` to arrange these components. It supports basic arithmetic operations (addition, subtraction, multiplication, division), trigonometric functions (sin, cos, tan), and the square root operation. User interaction is achieved through `ActionListener` which captures button events to perform calculations .

Java implements inheritance through a base class that contains common attributes and methods, and a derived class that extends the base class, adding additional attributes and methods. In the provided example, the base class `Base` contains an integer attribute `a` and a method `baseMethod`. The derived class `derived` extends `Base` with an additional integer attribute `b` and a method `derivedMethod`. Inheritance is demonstrated by instantiating objects of both classes and accessing their respective methods and attributes .

Java employs strategies for managing list operations equivalent to Lisp's car and cdr functions through carefully designed methods within the `LispList` class. The `car` method retrieves the first element, respecting list bounds by returning null if empty, thereby maintaining stability. The `cdr` method constructs a sublist by slicing the list beyond the first element, using `subList`, ensuring that the original list integrity is maintained and not directly altered. These methods encapsulate list manipulation while adhering to the immutability principles .

The key functionalities for handling rational numbers in Java include accepting input for the numerator and denominator, displaying the original rational number, simplifying the rational number to its reduced form, and displaying the reduced form. Simplification is programmatically achieved by finding the greatest common divisor (GCD) of the numerator and denominator and dividing both by the GCD, as shown in the `simplify` method of the `RationalNumber` class .

Encapsulation in implementing a date and time display package in Java is achieved by creating a class `CurrentDate` within the `Date` package, which contains private methods that encapsulate the logic for formatting and displaying the date and time. The package structure hides these implementation details, exposing only the methods `displayCurrentDate` and `displayCurrentTime` for external use, thereby controlling access and modification from outside the package .

Handling a zero denominator in Java rational number calculations requires preventive error handling. The program must detect a zero denominator and throw an `IllegalArgumentException`, as division by zero is undefined and would cause a runtime error. The `RationalNumber` constructor includes a conditional check to throw the exception if the denominator is zero, protecting the integrity of calculations and ensuring proper program execution .

Java's implementation of a Lisp-like list involves creating a `LispList` class that stores elements in a `List<Object>`. The `car` function is replicated using a method that returns the first element of the list, or null if the list is empty. The `cdr` function returns a new `LispList` containing all elements except the first, leveraging `subList` to achieve this. This approach mirrors the functionality seen in Lisp where car and cdr detach the head and tail of a list .

The Java scientific calculator ensures the accuracy of trigonometric calculations by converting angles from degrees to radians, which is the standard input for trigonometric functions in Java's `Math` library. This conversion is achieved using `Math.toRadians()`. Trigonometric functions `Math.sin()`, `Math.cos()`, and `Math.tan()` then compute the trigonometric values based on the converted input .

The use of `GridLayout` in the Java scientific calculator GUI is crucial for arranging components in a structured and consistent manner. It provides a visually organized interface, aligning buttons in rows and columns, which enhances usability by making the calculator functions easy to locate and interact with. This layout simplifies the user experience, reducing the cognitive load by maintaining a predictable arrangement, crucial for efficient and error-free user interaction .

Creating a user-defined package in Java involves defining a package name, creating the necessary classes, and importing the package into an application program. For displaying the current date and time, a package named `Date` is created containing a class `CurrentDate` with methods `displayCurrentDate` and `displayCurrentTime`, which use `LocalDateTime` and `DateTimeFormatter`. The package is imported into `Main.java`, where an instance of `CurrentDate` is created to use these methods .

You might also like