Addition Of Two Numbers In Java
Add Two Numbers in Java
Overview
- How to add two numbers in Java will show addition of given two numbers.
Scope of Article
- This article provides information about addition of two numbers in Java.
- Examples of different ways of summing are given.
- Uses the ( + ) operator to add two numbers.
- Let's see how we can add two numbers in Java.
Method 1: Sum of two numbers
This is the simplest way to add two numbers in Java. We will initialize and declare the value in the program itself. Here no input value is taken from the user.
Example :
Output
Explanation In the above program we have taken three variables and two of them have initialized values in the program. And addition of two initialised variables is taken as sum variable. Two constant numbers are displayed through the program.
Method 2 : Add Two Numbers in Java With User Input
In Java, let's see how to take user input and sum it using the Scanner class.
Example :
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int e1 , f2 , sum;
System.out.println("Enter A First Number = ");
e1 = in.nextInt(); //Input Operation
System.out.println("Enter A Second Number = ");
f2 = in.nextInt();
sum = e1 + f2; //Addition Operation
System.out.println("Addition of "+e1+" + "+f2+" = "+sum);
}
}
Explanation We use the scanner class to take input from the user, the line in.nextInt() reads the user input as an integer and saves its value variables E1 and F2. The sum of E1 and F2 is saved in the variable sum. and displayed on the screen.
Method 3 : Sum of 3 Numbers in Java
3 numbers are added here as 2 numbers are added. For this we need three variables.
Example :
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int e1 , f2 , g3 , sum;
System.out.println("Enter A first Number = ");
e1 = in.nextInt(); //Input Operation
System.out.println("Enter A Second Number = ");
f2 = in.nextInt();
System.out.println("Enter A Third Number = ");
g3 = in.nextInt();
sum = e1 + f2 + g3; //Addition Operation
System.out.println("Addition Is = "+sum);
}
}
Output
Comments
Post a Comment