Program to add in java

Java program to add two numbers

Java program to add two numbers, a user enters two integers, and we calculate their sum and display it. Using int data type, we can add numbers up to a limit (range of int data type). If you want to add very large numbers, then you may use BigInteger class.

Addition of two numbers in Java

class AddNumbers
<
public static void main ( String args [ ] )
<
int x, y, z ;

System . out . println ( «Enter two integers to calculate their sum» ) ;
Scanner in = new Scanner ( System . in ) ;

x = in. nextInt ( ) ;
y = in. nextInt ( ) ;
z = x + y ;

System . out . println ( «Sum of the integers color: #339933;»>+ z ) ;
>
>

You can use the float data type to add two floating-point numbers.

Download Add numbers program class file. You can also create a method that returns the sum of two integers that are passed to it as arguments.

Output of Java program to add two numbers

Output of program:

Java program to add two numbers using BigInteger class

class AddingLargeNumbers <
public static void main ( String [ ] args ) <
String number1, number2 ;
Scanner in = new Scanner ( System . in ) ;

System . out . println ( «Enter first large number» ) ;
number1 = in. nextLine ( ) ;

System . out . println ( «Enter second large number» ) ;
number2 = in. nextLine ( ) ;

BigInteger first = new BigInteger ( number1 ) ;
BigInteger second = new BigInteger ( number2 ) ;
BigInteger sum ;

System . out . println ( «Result of addition color: #339933;»>+ sum ) ;
>
>

Enter first large number
11111111111111
Enter second large number
99999999999999
Result of addition = 111111111111110

In the program, we create two objects of BigInteger class of java.math package. Input should be digit strings otherwise an exception will be thrown; also you cannot just use ‘+’ operator to add objects of BigInteger class, you have to use the add method for addition of two objects.

Download Adding Large numbers program class file.

Источник

Addition Program in Java

Addition Program in Java | An Addition program in Java is the basic program, which is used to introduce to beginners. The Addition program in Java simply adds two numbers and displays them to the output screen.

Addition of Two Numbers in Java without using Scanner

It is a simple Java addition program that adds two numbers and displays the results. The values are hardcoded by the programmer.

In this program, we take three variables of the int data type. The variables’ names are num1, num2, and sum. After declaring the variables, num1 and num2 variables are initialized with 10 and 20 respectively. The variables num1 and num2 hold the value of the input. After initializing the variables, the sum is calculated as num1 + num2. Finally, the sum value is displayed using the println() method of the System class.

Читайте также:  Python интеграция с sql

Simple Java Program to Add Two Numbers

In the previous program, the values of numbers are hardcoded. But we can also pass these values dynamically to the program. There are various ways to get input from the user in Java. In the below program we use the Scanner class to take input from the user.

To get input from the user first we need to import the Scanner class as below:-
import java.util.Scanner;

After import, we can create an object of Scanner class which will be used to get input from the user as:- Scanner scan = new Scanner(System.in);

Here, Scanner is a class, the scan is a user-defined identifier and new is a keyword used to create an object. For each type of data type separate method is given.

Simple Java Program to Add Two Numbers

import java.util.Scanner; public class Addition < public static void main(String[] args) < // create Scanner class object // to take the input Scanner scan = new Scanner(System.in); // declare variables int number1, number2, sum; // take input for first number System.out.print("Enter first number: "); number1 = scan.nextInt(); // take input for second number System.out.print("Enter second number: "); number2 = scan.nextInt(); // calculate the sum sum = number1 + number2; // display the result System.out.println("Sum = " + sum); >>

Enter first number: 15
Enter second number: 25
Sum = 40

Enter first number: -50
Enter second number: 75
Sum = 25

In the above program, we take two integer data types as input. We can also take double data type as input, for this purpose simply use the nextDouble() method. The above program can be written in different ways. The below program takes floating-point numbers and displays the sum to the output screen.

import java.util.Scanner; public class Addition < public static void main(String[] args) < // create Scanner class object // to take input values Scanner scan = new Scanner(System.in); // declare variables double number1, number2, sum; // take input values System.out.print("Enter two floating-point numbers: "); number1 = scan.nextDouble(); number2 = scan.nextDouble(); // display result System.out.println("Sum = " + (number1 + number2)); >>

Enter two floating-point numbers: 12.5 17.5
Sum = 30.0

Enter two floating-point numbers: 25.2 8.1
Sum = 33.3

Addition of Two Numbers in Java Using Method

Using the method we can also calculate the sum of two numbers. Methods are similar to functions in C/C++. it takes parameters and returns a value to the caller method. The below program uses a method add() to calculate the sum of two numbers. The add() method takes two double data type value, calculate the sum value and return it to the caller method.

import java.util.Scanner; public class Addition < public static void main(String[] args) < // create Scanner class object // to take input values Scanner scan = new Scanner(System.in); // declare variables double num1, num2, sum; // take input values System.out.print("Enter two floating-point numbers: "); num1 = scan.nextDouble(); num2 = scan.nextDouble(); // method call sum = add(num1, num2); // display result System.out.println("Sum = " + sum); >// method to add two numbers private static double add(double n1, double n2) < // calculate sum and return it return n1 + n2; >>

Sum of Two Numbers Using Command Line Arguments In Java

The command line is used to pass the arguments at the run time. Similar to other methods main() is also a method with a specialty that every Java program execution starts with the main method. The main() method takes the String array value as input and returns void i.e. nothing.

Читайте также:  Php массив поменять местами индексы

The passed parameters are in String so, first, we need to convert it into actual value and then calculate the sum value.

While executing this program, pass the values.

> javac Addition.java
> java Addition 10 20

If you don’t pass exactly two arguments then it will throw java.lang.ArrayIndexOutOfBoundsException.

Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Addition.main(Addition.java:10)

We have passed only one value, but our program calculates the sum of two numbers. Since the second number is not given so it throws an exception.

Similarly, if the passed value is not a number then JVM can’t convert to a number and throws java.lang.NumberFormatException

Exception in thread «main» java.lang.NumberFormatException: For input string: «a»
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)

Since a and b are not a number that’s why we got an Exception.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Java Program to Add two Numbers

In this tutorial, you will learn how to write a Java program to add two numbers. We will see three programs: In the first program, the values of the two numbers are given. In the second program, user is asked to enter the two numbers and the program calculates the sum of the input numbers. In the third program, we will calculate the sum of two non-integer numbers.

Example 1: Sum of two numbers

Example 2: Sum of two numbers using Scanner

The Scanner class provides the methods that allows us to read the user input. The values entered by user is read using Scanner class and stored in two variables num1 and num2 . The program then calculates the sum of input numbers and displays it.

import java.util.Scanner; public class AddTwoNumbers2 < public static void main(String[] args) < int num1, num2, sum; Scanner sc = new Scanner(System.in); System.out.println("Enter First Number: "); num1 = sc.nextInt(); System.out.println("Enter Second Number: "); num2 = sc.nextInt(); sc.close(); sum = num1 + num2; System.out.println("Sum of these numbers: "+sum); >>

In this program, the statement Scanner sc = new Scanner(System.in); creates an instance of Scanner class. This instance calls nextInt() method to read the number entered by user. The read values are stored in variables num1 and num2. Once the values are stored in variables. The addition is performed on these variables and result is displayed.
Output:

Enter First Number: 121 Enter Second Number: 19 Sum of these numbers: 140

Example 3: Program to add two non-integer numbers

In this example, we are calculating the sum of non-integer numbers. Here you can enter float numbers such as 10.5, 16.667 etc.

import java.util.Scanner; public class JavaExample < public static void main(String[] args) < double num1, num2, sum; Scanner sc = new Scanner(System.in); System.out.print("Enter First Number: "); num1 = sc.nextDouble(); System.out.print("Enter Second Number: "); num2 = sc.nextDouble(); sc.close(); sum = num1 + num2; System.out.println("Sum of "+num1+" and "+num2+" is: "+sum); >>

Java Program to Add two Numbers

Output:

Читайте также:  Simple slider

Practice the same program in C language here.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Java GUI Program to Add Two Numbers Using AWT

dumb it dude cover pic

Remember that program we did to add two numbers? We are going to simply uptrade! We will create a Java GUI program to add two numbers using AWT and it’s gonna be fun.

Adding two numbers doesn’t have too much of a logic. But when you are doing so while using AWT things become a little challenging. Snice a text field in Java takes in String as input we need to first parse it into the form of Integer.

We are going to create two text fields and a label where the output will be seen. A button will be used to trigger the event.

Java GUI Program to Add Two Numbers Using AWT

Here is the addition program:

Share this:

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of «Songs of a Ruin» and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like.

Java Demo Program | First Java Program

What is Super Keyword in Java | How to Use Super

Java Loop | For Loop Java | While and Do-While Loop

7 Responses

“b.addActionListener(new ActionListener() <
public void actionPerformed(ActionEvent e) <
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
int c = a + b;
l1.setText(“Their sum is = ” + String.valueOf(c)); “” if i want to add more than one button such as “add” ,”sub” ,”mul” etc..
so what is step to add more button

Initialize a new button like: Button b2 = new Button(“LABEL OF THE BUTTON”); and then set its bounds by using: b2.setBounds(150,250,80,70); Then finally use add(b2); to include it. Eventually, you have to create a new Action Listener Anonymous class b2.addActionListener(new ActionListener()< >); and then specify what should happen when you click the button inside a method. – Scottshak

Hi Santhosh, If you want to bring it to the centre you can try: setLocationRelativeTo(null); set default close operation can be performed by: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Hope that helps. Cheers

[…] Also, you could use Java GUI or AWT to make an interesting looking program. I have created an addition program using GUI here. […] […] a Checkbox in Java GUI is quite a simple process. Here, unlike the buttons we saw in a Java GUI program to add two numbers there is no addActionListener. We have addItemListener instead. Checkbox in Java GUI comes really […]

Источник

Оцените статью