Write a Program for Sum of Numbers in Java-techworld4u09

Sum of Two Numbers in Java

Table of Contents

In Java, finding the sum of two or more numbers is very easy. First, declare and initialize two variables to be added. Another variable to store the sum of numbers. Apply mathematical operator (+) between the declared variable and store the result. The following program calculates and prints the sum of two numbers.

public class FirstActivity  
{  
public static void main(String args[])   
{  
int n1 = 225, n2 = 115, sum;  
sum = n1 + n2;  
System.out.println("The sum of two numbers is: "+sum);  
}  
}  

Output:



The sum of numbers is: 340

Sum of Two Numbers in Java Using Method

import java.util.Scanner;  
public class FirstActivity  
{  
public static void main(String args[])  
{  
int x, y, sum;  
Scanner sc = new Scanner(System.in);  
System.out.print("Enter the first number: ");  
x = sc.nextInt();  
System.out.print("Enter the second number: ");  
y = sc.nextInt();  
sum = sum(x, y);  
System.out.println("The sum of two numbers x and y is: " + sum);  
}  
//Method that calculates the sum  
public static int sum(int a, int b)  
{  
int sum = a + b;  
return sum;  
}  
}  

Output:

Enter the first number: 34
Enter the second number: 12
The sum of two numbers x and y is: 46

Leave a Comment