This is a Java Program to Find Square of a Given Number Using Applet
We have to write a program in Java such that it accepts a number and displays the square of the number using applet.
For finding square of a number using applet, we can have the following different sets of input and output.
1. To find the square of a number :
When the number 12 is entered, it is expected that the square of 12 that is 144 is displayed in the frame.
2. To find the square of a floating-point number :
When the number 10.5 is entered, it is expected that the square of 10.5 that is 110.25 is displayed in the frame.
1. Create an input text field to accept a number from user.
2. Create a button to confirm the number and calculate its square.
3. When the button is clicked, display its square in a text field.
Here is source code of the Java Program to find square of number using applet. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/*Java Applet to Find Square of Number using Applet*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Square_Num extends Applet implements ActionListener
{
TextField num,out;
//Initialize with required input fields
public void init()
{
Label label = new Label("Enter a number :");
this.add(label);
num = new TextField(5);
this.add(num);
Button calc = new Button("Calculate");
calc.addActionListener(this);
this.add(calc);
out = new TextField();
}
@Override
//Function to display the square of the number
public void actionPerformed(ActionEvent e)
{
double n = Double.valueOf(num.getText());
double sq=n*n;
out.setText("Square of "+n+" is "+sq);
this.add(out);
revalidate();
}
}
/*
<applet code = Square_Num.class width=500 height=500>
</applet>
*/
To execute the applet use the following commands:
>>>javac Square_Num.java >>>appletviewer Square_Num.java
1. Create a text field using TextField class of the java.awt package.
2. Create a button using Button class of the java.awt package.
2. Create a label using Label class of the java.awt package.
Here’s the run time test cases to Display Square of Number using Applet.
Test case 1 – To Display Square of a Number.
Test case 2 – To Display Square of a floating-point number.
Sanfoundry Global Education & Learning Series – Java Programs.
- Check Programming Books
- Practice Information Technology MCQs
- Apply for Java Internship
- Check Java Books
- Practice Programming MCQs