bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java How To's
Java•Java How To's

Java How 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 + y

Explanation: We create two integer variables ( x and y ) and assign them values. The expression x + y is stored in the variable sum . Finally, we print the result with System.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 class
class 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
 }
}

Explanation: Here we use the Scanner class to read two numbers from the keyboard. The method nextInt() reads an integer from the user. We then add the two numbers together and print the result.

Previous

Java How To's

Next

Java How To Swap Two Variables

This chapter

Overview
40

Lessons

80m

Read time

1. Java How To's2. Java How To Add Two Numbers3. Java How To Swap Two Variables4. Java How To Find Even or Odd Numbers5. Java How To Reverse a Number6. Java How To Find Positive or Negative Numbers7. Java How To Find the Square Root of a Number8. Java How To Get the Area of a Rectangle9. Java How To - Convert Celsius to Fahrenheit10. Java How To - Sum of Digits11. Java How To Check Armstrong Number12. Java How To Generate Random Numbers13. Java How To Count Words14. Java How To - Count Vowels in a String15. Java How To Remove Vowels from a String16. Java How To Count Digits in a String17. Java How To Reverse a String18. Java How To - Palindrome Check19. Java How To Check Anagram Strings20. Java How To Convert a String to an Array21. Java How To - Remove Whitespace from a String22. Java How To - Character Frequency in a String23. Java How To Calculate the Sum of Elements24. Java How To Find the Average of Array Elements25. Java How To Sort an Array26. Java How To - Smallest Element in an Array27. Java How To - Largest Element in an Array28. Java How To - Second Largest Array Element29. Java How To Find Min and Max in Array30. Java How To - Merge Two Arrays31. Java How To - Remove Duplicates from an Array32. Java How To Find Duplicates in an Array33. Java How To - Shuffle an Array34. Java How To - Calculate Factorial of a Number35. Java How To - Fibonacci Sequence36. Java How To Find the GCD37. Java How To - Check if a Number Is Prime38. Java How To Loop Through an ArrayList39. Java How To Loop Through a HashMap40. Java How To Loop Through an Enum

On this page

Add Two NumbersAdd Two Numbers with User Input