Here is a Java program to find sum of two numbers. To add two numbers in a java program, we will first take two integers as input from user using Scanner and store them in a integer variable num1 and num2. Then we add num1 and num2 using + arithmetic operator and store it in integer variable "sum". Finally, we print the sum of two given integers on screen.
Java Program to Find Sum of Two Numbers
package com.tcc.java.programs; import java.util.*; public class SumTwoNumbers { public static void main(String[] args) { int num1, num2, sum; Scanner scanner; scanner = new Scanner(System.in); // Take two integer input from user and // store it in variable num1 and num2 System.out.println("Enter First Number"); num1 = scanner.nextInt(); System.out.println("Enter Second Number"); num2 = scanner.nextInt(); // Add two numbers using + operator sum = num1 + num2; System.out.println("Sum of " + num1 + " and " + num2 + " = " + sum); } }Output
Enter First Number 5 Enter Second Number 7 Sum of 5 and 7 = 12
Java Programs to Find Sum of Two Numbers using Function
This Java program is similar to above program except here we are using a user defined function getSum to calculate the sum of two integers. The function getSum takes two integer arguments and returns the sum of both input parameters.
package com.tcc.java.programs; import java.util.*; public class SumTwoNumbersFunction { public static void main(String[] args) { int num1, num2, sum; Scanner scanner; scanner = new Scanner(System.in); // Take two integer input from user and // store it in variable num1 and num2 System.out.println("Enter First Number"); num1 = scanner.nextInt(); System.out.println("Enter Second Number"); num2 = scanner.nextInt(); /* * Call getSum by passing num1 and num2 as parameter */ sum = getSum(num1, num2); System.out.println("Sum of " + num1 + " and " + num2 + " = " + sum); } public static int getSum(int num1, int num2) { int sum; sum = num1 + num2; return sum; } }Output
Enter First Number 9 Enter Second Number 12 Sum of 9 and 12 = 21
Recommended Posts