Java Program to Add Two Numbers.

In this article, we are going to learn addition of two integer number in Java programming,  we will discuss two different approach of doing this one assigning value to variable and another by taking input value from the user. 


Java Program to Add Two Integer Number.

Step by steps approach:
  • Define a class called AddTwoNumbers.
  • Declare two integer variables num1 and num2 and initialize them to 5 and 7.
  • Calculate the sum of num1 and num2 and store it in an integer variable called sum.
  • Print out the sum using System.out.println().
  • The output should be "The sum of 5 and 7 is 12".
Java Code:
//Java code to add two int number
public class AddTwoNumbers {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 7;
        int sum = num1 + num2;
        System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
    }
}
Output:
The sum of 5 and 7 is 12

Java Program to Add Two Numbers Taking Input from User.

Here is the another approach of doing the same program in which we are taking two integer value as an input from the user and then printing the sum of those two value as an output.

Java Code:
//Java program to add two number from user
import java.util.Scanner;

public class AddTwoNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();
        int sum = num1 + num2;
        System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
        scanner.close();
    }
}
Output:
Enter the first number: 5
Enter the second number: 10
The sum of 5 and 10 is 15

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS