JavaHow To Add Two Numbers
Add Two Numbers
Learn how to add two numbers in Java:
Example
int x = 5;int y = 6;int sum = x + y;System.out.println(sum); // Print the sum of x + yTry it Yourself »Explanation: We create two integer variables (x andy) and assign them values. The expressionx + y is stored in the variablesum. Finally, we print the result withSystem.out.println().
Add Two Numbers with User Input
Learn how to add two numbers with user input:
Example
import java.util.Scanner; // Import the Scanner classclass MyClass { public static void main(String[] args) { int x, y, sum; Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Type a number:"); x = myObj.nextInt(); // Read user input System.out.println("Type another number:"); y = myObj.nextInt(); // Read user input sum = x + y; // Calculate the sum of x + y System.out.println("Sum is: " + sum); // Print the sum }}Run Example »Explanation: Here we use theScanner class to read two numbers from the keyboard. The methodnextInt() reads an integer from the user. We then add the two numbers together and print the result.

