Write a java program for addition of two number.
[Initialization of Variables).
Answers
Java Program to Add two Numbers
Here we will see two programs to add two numbers, In the first program we specify the value of both the numbers in the program itself. The second programs takes both the numbers (entered by user) and prints the sum.
First Example: Sum of two numbers
public class AddTwoNumbers {
public static void main(String[] args) {
int num1 = 5, num2 = 15, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Sum of these numbers: 20
Second Example: Sum of two numbers using Scanner
The scanner allows us to capture the user input so that we can get the values of both the numbers from user. The program then calculates the sum 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);
}
}
Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140
Enjoyed this post? Try these related posts
Java Program to Find Factorial using For and While loop
Java Program for Selection Sorting
Java program for linear search – Example
Java Program to Calculate Area of Rectangle
Java Program to get input from user
Java program to find the occurrence of a character in a string
Question:-
Write a program in Java to perform addition of two numbers.
Program:-
class Addition
{
public static void main(String args[])
{
double a=20.0;
double b=10.0;
System.out.println("Result is: "+a-b);
}
}