Java Tutorial 1 – Sum of 2 numbers using Applet

sum of numbers

Hello guys today I am gonna show how to add 2 numbers using Java Applet.

Even though Java Swing is hardly used, this exercise may still be useful for students. Since we are using Applet, the first thing we should do is extend the Applet class.

public class sum_of_numbers extends Applet implements ActionListener

Here we extend the Applet class and then we implement the ActionListener interface. We need ActionListener because it provides us the methods to interact with buttons to find the sum of the numbers. After that we declare our variables :

  • 2 textfields to hold the numbers
  • 2 buttons, 1 to get the sum and the other one to reset the fields
  • 3 labels : label_1 for telling the user to input the first number, label_2 for telling the user to input the first number and label_3 for displaying the sum
private TextField text1 , text2;
private Button sum,reset;
private Label label1, label2 , label3;

The next step is to construct our declared variables one by one.

label1 = new Label("Input First Number : ");
text1 = new TextField(10);
label2 = new Label("Input Second Number : ");

text2 = new TextField(10);

sum = new Button("Sum");

reset = new Button("Reset Values");

label3 = new Label("Sum is : ");


You can see in the last line that we also set the size of our Applet where 800 is the width and 200 is the height.

So now we have our variables. All we need to do is to call the actionPerformed method of the ActionListener interface and we are good to go.

In this method we need to tell the program what to do if the sum button or reset button is clicked.

  1. sum button is clicked

Since we input the numbers in a textfield, we need to cast them and get their Integer value. Afterwards we add the number and display their sum.

2. reset button is clicked

Here we reset the textfield values so that the user can input them again. We also reset the value of the label which displays us the sum.


public void actionPerformed(ActionEvent e) 
		if(e.getSource() == sum)
			int nr1 = Integer.parseInt(text1.getText());
			int nr2 = Integer.parseInt(text2.getText());
			int sum1 = nr1 + nr2;
		else if(e.getSource() == reset)
			text1.setText(" ");
			text2.setText(" ");
			label3.setText(" ");

The full code :

That is all. Please don’t forget to like and subscribe and most if you have any questions feel free to leave a comment below.


Please enter your comment!
Please enter your name here