Examples Java

Addition of two numbers in Java

Writing a Java program for adding two numbers is quite easy. There are numerous ways that you can write a java code for adding two numbers. Here are a few ways that you can add two numbers in java.

1.Addition of two numbers using Pre-defined values.

In this program, the value of both numbers to be added are specified in the program itself. Once running this program you will get the sum of the predefined values.

public class AddingTwoNumbers {

   public static void main(String[] args) {
        
      int n1 = 4, n2 = 11, sum;
      sum = n1 + n2;

      System.out.println("Sum = "+sum);
   }
}

Output

Sum = 15

2.Addition of two numbers using Scanner.

The scanner is a class in java that provides a way to take input fro the keyboard. Here the users can give value through their keyboard. The program takes value from the user and performs the calculations and prints the sum.

import java.util.Scanner;
public class AddingTwoNumbers {

    public static void main(String[] args) {
        
        int n1, n2, sum;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter First Number: ");
        n1 = sc.nextInt();
        
        System.out.println("Enter Second Number: ");
        n2 = sc.nextInt();
        
        sc.close();
        sum = n1 + n2;
        System.out.println("Sum of the given numbers are: "+sum);
    }
}

Output

Enter First Number: 
10
Enter Second Number: 
5
Sum of the given numbers are: 15

About the author

Castro K Joseph

Leave a Comment