File Java 10-40
File Java 10-40
AIM : Write a Program to Initialize an integer array with ASCII values and print the
corresponding character values in a single row.
THEORY : ASCII assigns integer values to characters, facilitating their representation and
manipulation in computers.
CODE :
package LAB_CLG;
}
OUTPUT :
PROGRAM – 11
AIM : Write a program to reverse the elements of a given 2*2 array. Four integer numbers
need to be passed as Command-Line arguments
THEORY :
The program effectively demonstrates the concept of matrix transposition by swapping
rows with columns in a 2x2 matrix and printing both the original and transposed matrices.
CODE :
package LAB_CLG;
System.out.println("Original Matrix:");
printMatrix(originalMatrix);
System.out.println("\nTransposed Matrix:");
printMatrix(transposedMatrix);
}
OUTPUT :
PROGRAM – 12
THEORY : In Java, stacks and queues are implemented using the java.util.Stack and
java.util.Queue interfaces, respectively. These interfaces provide methods for common
stack and queue operations such as push/pop for stacks and enqueue/dequeue for queues.
CODE :
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
System.out.println("Stack:");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
System.out.println("\nQueue:");
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
OUTPUT:
PROGRAM – 13
AIM : Write a java program to produce the tokens from given long string.
THEORY : Tokens are the smallest units of a program, such as keywords, identifiers,
operators, and punctuation marks, which are recognized by the compiler or interpreter.
CODE :
package LAB_CLG;
import java.util.StringTokenizer;
OUTPUT :
PROGRAM – 14
AIM : Using the concept of method overloading Write method for calculating the area of
triangle, circle and rectangle.
THEORY :
Method overloading allows for more intuitive method names while providing flexibility in
handling different types of calculations within the same class.
CODE :
package LAB_CLG;
}
OUTPUT :
PROGRAM – 15
AIM:
Create a class Box that uses a parameterized constructor to initialize the dimensions of a box. The dimensions of
the Box are width, height, depth. The class should have a method that can return the volume of the box. Create
an object of the Box class and test the functionalities.
THEORY:
Box class is created with attributes width, height, depth Parameterized constructor is used to initialize attributes
getVolume() method returns volume main() takes user input and passes to constructor to create Box object Volume
is calculated by accessing method to test the class.
SOURCE CODE:
package LAB_CLG;
import java.util.Scanner;
class Box {
double width;
double height;
double depth;
this.width = width;
this.height = height;
this.depth = depth;
double getVolume() {
OUTPUT:
PROGRAM – 16
AIM:
WAP to display the use of this keyword.
THEORY:
In the constructor: 'this' keyword is used to refer the instance variables rollNo and name, to avoid confusion with
local parameters. In display() method: Instance variables can be accessed directly but using 'this' makes code more
readable. So 'this' keyword allows referring current object which helps avoiding confusions and improves
readability.
SOURCE CODE:
package LAB_CLG;
import java.util.Scanner;
int rollNo;
String name;
this.rollNo = rollNo;
this.name = name;
void display() {
std.display();
OUTPUT:
PROGRAM – 17
AIM:
Write a program that can count the number of instances created for the class.
THEORY:
Static variables are shared among all objects of a class. Here count is declared as static variable of Counter class.
Constructor is invoked every time new object is created. So we are incrementing static count variable in
constructor to keep track of number of objects created. Finally count gives total objects created for Counter class.
So key points are: Use static variable to store instance count Increment static count in constructor Print value of
static count This way we can get number of instances/objects created for a class by using static variable and
constructor.
SOURCE CODE:
package LAB_CLG;
import java.util.Scanner;
class Counter {
Counter(){
count++;
int n = sc.nextInt();
}
OUTPUT:
PROGRAM – 18
AIM:
Java Program to get the cube of a given number using the static method.
THEORY:
Static methods belong to the class rather than object. They are loaded in the memory only once when the class is
loaded. Can be called without needing to create an object of class. Static methods can only access static data
members and call other static methods. Cannot use non-static or instance variables inside them. Commonly used
for reusable logic that doesn't need object level data. Can be called directly by using ClassName.MethodName()
syntax.
In this program:
getCube() is declared static since it only depends on the passed parameter. It calculates cube in a reusable way
without needing any object data. It is called directly using Main.getCube() So static methods improve optimization
of memory usage and allows reusable logic. The core advantage is no need to create objects just to execute a piece
of code.
SOURCE CODE:
package LAB_CLG;
import java.util.Scanner;
return x*x*x;
}
OUTPUT:
PROGRAM – 19
AIM:
WAP that implements method overriding
THEORY:
Method overriding allows a subclass to provide a specific implementation of a method already provided by its
parent class. When a method in a subclass has the same signature as a method in its parent class, it is said to
override the method. The overriding method must have the same method name, parameter list, and return type as
the parent class method. Overriding allows polymorphism, where a subclass can be substituted for its parent class.
The version of the method that gets executed depends on the actual object, not the declared type of the variable.
Overriding methods allows subclasses to give their own specific implementation for inherited behaviors.
SOURCE CODE:
package LAB_CLG;
import java.util.Scanner;
class Shape {
void input() {
width = sc.nextDouble();
height = sc.nextDouble();
double area() {
return 0;
@Override
double area() {
}
}
@Override
double area() {
Shape s;
s = new Triangle();
s.input();
s = new Rectangle();
s.input();
OUTPUT:
PROGRAM – 20
AIM:
WAP to illustrate simple inheritance.
THEORY:
Inheritance is a mechanism where a new class inherits properties and behavior from an existing class. The existing
class is called the superclass or parent class. The new class is called the subclass or child class. Using the extends
keyword, the subclass can inherit attributes and methods from the parent class. Inheritance supports code
reusability - common properties and behaviors can be defined in the parent class and reused in subclasses.
Subclasses can also add their own properties and methods to specialize the parent class.
SOURCE CODE:
package LAB_CLG;
class Animal {
void eat() {
System.out.println("Eating...");
void bark() {
System.out.println("Barking...");
d.bark();
d.eat();
}
OUTPUT:
PROGRAM – 21
AIM:
WAP to illustrate multilevel inheritance.
THEORY:
Multilevel inheritance occurs when a class inherits from another class, which in turn inherits from yet another
class. It forms a chain of parent-child relationships. Here’s how it works: A parent class (also known as the
grandparent class) has features. A child class inherits features from the parent class. An intermediate class (the
child of the parent and parent of another child) can also exist. In multilevel inheritance, the inheritance linkage is
linear, and at least three classes are involved.
SOURCE CODE:
package LAB_CLG;
class Person {
Person() {
System.out.println("Person constructor");
void nationality() {
System.out.println("Indian");
void place() {
System.out.println("Mumbai");
Emp() {
System.out.println("Emp constructor");
void organization() {
System.out.println("IBM");
}
void place() {
System.out.println("New York");
Manager() {
System.out.println("Manager constructor");
void subordinates() {
System.out.println(12);
void place() {
System.out.println("London");
m.nationality();
m.organization();
m.subordinates();
m.place();
}
OUTPUT:
PROGRAM – 22
AIM:
WAP illustrating all uses of super keywords.
THEORY:
The super keyword in Java is used to refer to the superclass (parent class) of the current object. It can be used in
several ways:
Accessing Superclass Members: You can use super to access methods or fields from the superclass that have been
overridden or hidden by the subclass.
Invoking Superclass Constructor: You can use super() to call the constructor of the superclass. This is useful when
the superclass constructor needs to be executed before the subclass constructor.
Accessing Superclass Constructor with Parameters: You can use super(...) to call a specific constructor of the
superclass with parameters.
SOURCE CODE:
package LAB_CLG;
class Animals {
String name;
Animals(String name) {
this.name = name;
void eat() {
String breed;
void display() {
dog.display();
OUTPUT:
PROGRAM – 23
AIM:
WAP to show dynamic polymorphism and interface.
THEORY:
Dynamic polymorphism in Java is achieved through method overriding. When a subclass provides a specific
implementation of a method that is already provided by its superclass, it is known as method overriding. This
allows a subclass to provide its own implementation of a method that is already defined in its superclass. Interfaces
in Java define a contract for classes that implement them, specifying the methods that implementing classes must
provide.
SOURCE CODE:
package college_lab;
interface Animal {
void eat();
System.out.println("Dog is eating");
void bark() {
System.out.println("Dog is barking");
System.out.println("Cat is eating");
void meow() {
System.out.println("Cat is meowing");
}
public class LAB_23 {
animal1.eat();
((Dog) animal1).bark();
System.out.println();
animal2.eat();
((Cat) animal2).meow();
OUTPUT:
PROGRAM:-25
AIM:-Write a java package to show dynamic polymorphism and interfaces .
THEORY:-
The Shape interface defines the common methods getArea() and getPerimeter() that all shapes must
implement. The ClosedShape abstract class implements the Shape interface and provides a color property
common to closed shapes. The Rectangle and Circle classes are concrete implementa ons of ClosedShape,
providing their own implementa ons of getArea() and getPerimeter(). The ShapeDemo class contains a
printShapeInfo() method that demonstrates dynamic polymorphism. This method takes a Shape object as input
and calls its getArea() and getPerimeter() methods. If the Shape object is also an instance of ClosedShape, it
prints the color as well. In the main method, instances of Rectangle and Circle are created and passed to the
printShapeInfo() method, demonstra ng dynamic polymorphism.
SOURCE CODE :-
interface Shape {
double getArea();
double getPerimeter();
this.color = color;
return color;
super(color);
this.length = length;
this.width = width;
@Override
public double getArea() {
@Override
super(color);
this.radius = radius;
@Override
@Override
printShapeInfo(rect);
System.out.println();
printShapeInfo(circle);
OUTPUT:-
PROGRAM:-26
AIM:- Write an applica on that creates an ‘interface’ and implements it.
THEORY:-
Interfaces in Java are used to define a contract or a set of methods that classes must implement.
They promote abstrac on, loose coupling, and code reusability. By crea ng classes that implement
an interface, you can write code that works with objects of those classes through the interface,
without needing to know the specific implementa on details of each class.
SOURCE CODE:-
interface Movable {
private int x;
private int y;
this.x = x;
this.y = y;
@Override
this.x += x;
this.y += y;
car.move(10, 5);
car.move(-3, 2);
}
OUTPUT:-
PROGRAM:-27
AIM:- Write an interface called Playable, with a method void play();Let this interface be placed in a
package called music. Write a class called Veena which implements Playable interface. Let this class
be placed in a package music.string .Write a class called Saxophone which implements Playable
interface. Let this class be placed in a package music.wind .Write another class Test in a package
called live. Then, (a). Create an instance of Veena and call play() method (b). Create an 4 instance of
Saxophone and call play() method (c). Place the above instances in a variable of type Playable and
then call play()
THEORY:-
Interfaces in Java:
An interface is a reference type in Java that defines a contract for classes to follow. It specifies
a set of methods that any class implemen ng the interface must provide.In our case, we have
the Playable interface with a single method: void play(). Any class that implements Playable
Packages:
Packages in Java are used to organize classes into namespaces. They help avoid naming
conflicts and provide a hierarchical structure. The music package contains the Playable
interface. The music.string package contains the Veena class. The music.wind package contains
the Saxophone class. The live package contains the Test class. Veena and Saxophone Classes:
Both Veena and Saxophone classes implement the Playable interface. They override the play()
method, providing their own specific implementa on. When an instance of either class calls
Test Class:
The Test class demonstrates how to use the Veena and Saxophone classes. It creates instances
of both instruments and calls their play() methods. It also showcases polymorphism by
assigning instances to a variable of type Playable and invoking the play() method.
SOURCE CODE:-
package music;
void play();
package music.string;
import music.Playable;
@Override
System.out.println("Veena is playing...");
package music.wind;
import music.Playable;
@Override
System.out.println("Saxophone is playing...");
package live;
import music.Playable;
import music.string.Veena;
import music.wind.Saxophone;
veenaInstance.play();
saxophoneInstance.play();
playableInstance.play();
playableInstance = saxophoneInstance;
playableInstance.play();
}
OUTPUT:-
PROGRAM:-28
AIM:- Write a program to accept name and age of a person from the command prompt(passed as arguments
when you execute the class) and ensure that the age entered is >=15 and < 60.Display proper error messages.
The program must exit gracefully a er displaying the error message in case the arguments passed are not
proper. (Hint : Create a user defined excep on class for handling errors.)
THEORY:-
In Java, excep ons are used to handle excep onal or error condi ons that may arise during the execu on of a
program. Java provides built-in excep on classes to handle various types of excep ons, such as
ArrayIndexOutOfBoundsExcep on, NullPointerExcep on, Arithme cExcep on, and more. However, in some
cases, you may need to define your own custom excep on classes to handle specific error condi ons in your
applica on. User-defined excep ons are created by extending the Excep on class or one of its subclasses. In
the given program, we define a custom excep on class called AgeExcep on that extends the Excep on class.
This excep on is thrown when the age entered by the user is not within the valid range (between 15 and 60).
The main method of the AgeValidator class first checks if the correct number of arguments (two, represen ng
name and age) is provided. If not, it throws an IllegalArgumentExcep on with an appropriate error message.
Next, it tries to parse the second argument (age) as an integer using Integer.parseInt. If the age is not in a valid
integer format, a NumberFormatExcep on is thrown.
SOURCE CODE:-
class AgeExcep on extends Excep on {
super(message);
try {
if (args.length != 2) {
} catch (AgeExcep on e) {
System.err.println(e.getMessage());
} catch (IllegalArgumentExcep on e) {
System.err.println(e.getMessage());
OUTPUT:-
PROGRAM:-29
AIM:- Create a customized excep on and also make use of all the 5 excep on keywords.
THEORY:-
In Java, excep ons are used to handle excep onal or error condi ons that may arise during the execu on of a
program. Java provides built-in excep on classes for various types of excep ons, but you can also create your
own custom excep ons by extending the Excep on class or one of its subclassesHere's an explana on of the
five excep on keywords used in the program: try: The try block is used to enclose the code that might throw an
excep on. In this case, it wraps the calls to the validateAge method. catch: The catch block is used to handle
the excep ons that may be thrown within the try block. In this program, it catches the InvalidAgeExcep on and
prints the error message. throw: The throw keyword is used to manually throw an excep on. In the validateAge
method, we use throw new InvalidAgeExcep on("Invalid age: " + age); to throw a new instance of the
InvalidAgeExcep on when the age is invalid. throws: The throws keyword is used in a method signature to
declare the types of excep ons that the method may throw. In this program, the validateAge method uses
throws InvalidAgeExcep on to indicate that it can throw an InvalidAgeExcep on. finally: The finally block is
used to specify code that should be executed regardless of whether an excep on is thrown or not. In this
program, it prints a message indica ng that the finally block has been executed.
SOURCE CODE:-
class InvalidAgeExcep on extends Excep on {
super(message);
} else {
try {
} catch (InvalidAgeExcep on e) {
OUTPUT:-
PROGRAM:-30
AIM:- Write an Applet that displays “Hello World” (Background color -black, text color -blue and your name
in the status window.)
THEORY:-
This applet sets the background color to black in the init() method, then in the paint() method, it sets the text
color to blue and draws the "Hello World" message. In the start() method, it sets the status window to display
your name, and in the stop() method, it clears the status window .
SOURCE CODE:-
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
setBackground(Color.BLACK);
setForeground(Color.BLUE);
OUTPUT:-
PROGRAM:-31
AIM:- Create a customized excep on and also make use of all the 5 excep on keywords.
THEORY:-
Use Thread.sleep(int) to delay the execu on by entered me in milliseconds. Create a circle for the clock and
label the hours on it. Each hour on the clock is equivalent to 30 degrees. The angle of hours hand from the y=0
line, is ((30*hour)-90) degrees. Each minute on the clock is equivalent to 6 degrees. The angle of minutes hand
from the y=0 line, is ((6*minute)-90) degrees. Each second on the clock is equivalent to 6 degrees. The angle of
seconds hand from the y=0 line, is ((6*second)-90) degrees. To get the posi on of the hands of clock, it is
required to convert the angles to radians. To do this, use Math.toRadians func on. The x co-ordinate of any
point on a circle with center (a,b) and radius ‘r’ measuring an angle θ from the center is given as x = a + r * cosθ
. The y co-ordinate of any point on a circle with center (a,b) and radius ‘r’ measuring an angle θ from the center
is given as y = v + r * sinθ .
SOURCE CODE:-
/*Java Program to Display a Clock using Applet*/
import java.applet.*;
import java.awt.*;
Thread t;
setBackground(Color.white);
t = new Thread(this);
t.start();
while(true)
{
try
repaint();
//Delay by 1 sec
Thread.sleep(1000);
catch(Excep on e)
Calendar me = Calendar.getInstance();
double angle;
int x,y;
g.drawOval(100,100,300,300);
String s="12";
int i=0;
while(i<12)
angle = Math.toRadians(30*(i-3));
x = 250+(int)(Math.cos(angle)*135);
y = 250+(int)(Math.sin(angle)*135);
g.drawString(s,x,y);
i++;
s=String.valueOf(i);
g.setColor(Color.green);
angle = Math.toRadians((30*hour)-90);
x = 250+(int)(Math.cos(angle)*100);
y = 250+(int)(Math.sin(angle)*100);
g.drawLine(250,250,x,y);
g.setColor(Color.red);
angle = Math.toRadians((6*minute)-90);
x = 250+(int)(Math.cos(angle)*115);
y = 250+(int)(Math.sin(angle)*115);
g.drawLine(250,250,x,y);
g.setColor(Color.blue);
angle = Math.toRadians((6*second)-90);
x = 250+(int)(Math.cos(angle)*130);
y = 250+(int)(Math.sin(angle)*130);
g.drawLine(250,250,x,y);
/*
</applet>
*/
OUTPUT:-
PROGRAM:-32
AIM:- Write a java program to show mul threaded producer and consumer applica on.
THEORY:-
The producer-consumer problem is a classic example of a mul -process synchroniza on
problem. It involves two types of processes: producers and consumers. Producers produce data
items and place them in a shared buffer, while consumers consume the data items from the
same buffer. In a mul threaded environment, the producer-consumer problem can be solved
using shared buffers, semaphores, or monitors. The shared buffer acts as a queue where
producers add data items and consumers remove data items. Semaphores or monitors are used
to ensure mutual exclusion and synchroniza on between producers and consumers, preven ng
race condi ons and ensuring data integrity. The producer-consumer problem can lead to two
poten al issues:
Buffer Underflow: This occurs when a consumer a empts to remove an item from an empty
buffer.
Buffer Overflow: This occurs when a producer a empts to add an item to a full buffer
SOURCE CODE:-
import java.u l.LinkedList;
@Override
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedExcep on e) {
e.printStackTrace();
}
buffer.add(i);
lock.no fyAll();
@Override
while (true) {
synchronized (lock) {
while (buffer.isEmpty()) {
try {
lock.wait();
} catch (InterruptedExcep on e) {
e.printStackTrace();
lock.no fyAll();
producer.start();
consumer.start();
OUTPUT:-
PROGRAM:-33
AIM:- Write an applica on that executes two threads. One thread displays “An” every 1000
milliseconds and other displays “B” every 3000 milliseconds. Create the threads by extending the
Thread class.
THEORY:-
In Java, threads can be created by extending the Thread class or implemen ng the Runnable
interface. Extending the Thread class is a straigh orward approach, but it has the limita on that a
class can extend only one class (due to Java's single inheritance nature). Therefore, the Runnable
interface is generally preferred for crea ng threads, as it allows for be er code reusability and
flexibility.In this example, we create two separate thread classes: ThreadA and ThreadB. Each class
extends the Thread class and overrides the run() method, which defines the behavior of the
thread.The sleep() method from the Thread class is used to pause the execu on of a thread for a
specified dura on. It is used here to introduce the desired me delays between the prin ng of "An"
and "B".
SOURCE CODE:-
public class ThreadExample {
threadA.start();
threadB.start();
@Override
try {
while (true) {
System.out.print("An ");
} catch (InterruptedExcep on e) {
e.printStackTrace();
}
}
@Override
try {
while (true) {
System.out.print("B ");
} catch (InterruptedExcep on e) {
e.printStackTrace();
OUTPUT:-
PROGRAM:-34
AIM:- Create class of SalesPersons as a thread that will display fives sales persons name.Create a
class as Days as other Thread that has array of seven days.Call the instance of SalesPersons in Days
and start both the threads ,suspend SalesPersons on Sunday and resume on wednesday Note: use
suspend, resume methods from thread.
THEORY:-
In Java, the Thread class provides methods like suspend() and resume() to control the execu on of
threads. However, these methods are deprecated since Java 2, version 1.2, as they are inherently
unsafe and can lead to issues like deadlocks or thread starva on. Instead of using suspend() and
resume(), it is recommended to use alterna ve mechanisms like wait/no fy or semaphores for
thread synchroniza on and control. These mechanisms provide a safer and more robust way to
manage thread execu on. Despite being deprecated, this example uses suspend() and resume() for
demonstra on purposes and to fulfill the given requirements.
SOURCE CODE:-
public class ThreadExample {
salesPersons.start();
days.start();
@Override
try {
} catch (InterruptedExcep on e) {
e.printStackTrace();
}
}
"Saturday", "Sunday"};
SalesPersons salesPersons;
Days(SalesPersons salesPersons) {
this.salesPersons = salesPersons;
@Override
if (day.equals("Sunday")) {
salesPersons.suspend();
} else if (day.equals("Wednesday")) {
salesPersons.resume();
try {
} catch (InterruptedExcep on e) {
e.printStackTrace();
}
OUTPUT:-
PROGRAM:-35
AIM:- : WAP in java that illustrates how to process mouse click, enter,exit, press and release
events.The background colorchanges when the mouse isentered, clicked, pressed,released or exited.
THEORY:-
MouseListener and MouseMo onListener is an interface in java.awt.event package. Mouse
events are of two types. MouseListener handles the events when the mouse is not in mo on.
While MouseMo onListener handles the events when mouse is in mo on. There are five
types of events that MouseListener can generate. There are five abstract func ons that
SOURCE CODE:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
};
frame.add(panel);
panel.add(label);
frame.addMouseListener(mouseListener);
frame.setSize(400, 300);
frame.setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
OUTPUT:-
PROGRAM:-37
AIM:- : Write a program that read from a file and write to file.
THEORY:-
Reading from and wri ng to files is a common task in programming, especially for handling
data persistence. In Java, file reading and wri ng can be accomplished using various classes
from the java.io package. Here's a brief overview of the main classes used in the program:
FileReader: This class is used to read characters from a file. It is typically wrapped in a
BufferedReader: This class reads text from a character-input stream, buffering characters to
SOURCE CODE:-
import java.io.*;
try {
String line;
bufferedWriter.write(line);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
OUTPUT:-
PROGRAM:-38
AIM:- Convert the content of a given file into the uppercase content of the same file. JDBC
(Database connec vity with MS-Access).
THEORY:-
JDBC (Java Database Connec vity) is an API that provides Java programs the capability to interact
with databases. To connect to an MS-Access database using JDBC, you need to specify the database
URL (jdbc:ucanaccess://path/to/your/database.accdb), username, and password. Use
DriverManager.getConnec on() to establish a connec on. Use Prepared Statement to execute SQL
queries and update the content of the file in the database.
SOURCE CODE:-
import java.io.*;
try {
String line;
contentBuilder.append(line).append("\n");
fis.close();
fos.write(upperCaseContent.getBytes());
fos.close();
} catch (IOExcep on e) {
}
}
OUTPUT:-
PROGRAM:-39
AIM:- Create runnable jar file in java.
THEORY:-
A JAR (Java Archive) file is a package file format used to bundle mul ple Java class files, along with
associated metadata and resources (such as images, configura on files, etc.) into a single archive. JAR
files are essen al for distribu ng Java applica ons and libraries, as they allow you to package all the
necessary components into a single file.
To create a runnable JAR file, you need to specify the entry point (the main class with the main
method) and include all the required dependencies (other class files and libraries) within the JAR file.
This way, the JAR file can be executed directly without requiring addi onal setup or classpath
configura on.
SOURCE CODE:-
public class HelloWorld {
System.out.println("Hello, World!");
javac HelloWorld.java
Main-Class: HelloWorld
OUTPUT:-
PROGRAM:-40
AIM:- Develop Scien fic Calculator using Swing.
THEORY:-
Swing: Swing is a GUI toolkit for Java. It provides a set of components for building graphical
JFrame: JFrame is a class in Swing that represents a window with decora ons such as borders,
tle, and bu ons for closing, minimizing, and maximizing the window.
JPanel: JPanel is a container that can hold other components. It is used to organize components
within a window.
JTextField: JTextField is a text component that allows the user to enter and edit a single line of
text.
JBu on: JBu on is a component that represents a clickable bu on. It is used to trigger ac ons
when clicked.
bu on.
SOURCE CODE:-
import javax.swing.*;
import java.awt.*;
setTitle("Scien fic Calculator");
setSize(400, 400);
setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);
textField.setEditable(false);
panel.add(textField);
String[] bu ons = {
"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+", "sin", "cos",
"tan", "sqrt"
};
btn.addAc onListener(this);
panel.add(btn);
add(panel);
setVisible(true);
ac on.equals("sqrt")) {
case "sin":
result = Math.sin(value);
break;
case "cos":
result = Math.cos(value);
break;
case "tan":
result = Math.tan(value);
break;
case "sqrt":
result = Math.sqrt(value);
break;
}
textField.setText(String.valueOf(result));
secondNumber = Double.parseDouble(textField.getText());
switch (operator) {
case "+":
break;
case "-":
break;
case "*":
break;
case "/":
break;
textField.setText(String.valueOf(result));
} else {
if (textField.getText().equals("")) {
firstNumber = 0;
} else {
firstNumber = Double.parseDouble(textField.getText());
operator = ac on;
textField.setText("");
}
OUTPUT:-