Add Two Numbers in Java - The Coding Shala

Home >> Java Programs >> Add Two Numbers

 In this post, we will learn how to add two numbers in Java. Here we will write a Java program to add two numbers using Scanner(user input) and without the scanner.

Add Two Number in Java

First, we will add two numbers without using a Scanner or without taking any user inputs.

Java Program: 
public class AddTwoNumbers {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 35;
        int sum;
        sum = num1 + num2;
        System.out.println("sum of " + num1 + " and " + num2 +
                            " is: " + sum);
    }
}

Output: 
sum of 10 and 35 is: 45

Add Two Numbers using Scanner

In this Java program will take two user inputs and then print their sum.

Java Program: 
import java.util.Scanner;

public class AddTwoNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter first number");
        int num1 = sc.nextInt();
        System.out.println("Enter second number");
        int num2 = sc.nextInt();
        int sum = num1 + num2;
        System.out.println("sum of " + num1 + " and " + num2 +
                            " is: " + sum);
    }
}

Output: 
Enter first number
22
Enter second number
89
sum of 22 and 89 is: 111


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala