bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To Add Two Numbers

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java How To Add Two Numbers?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ sum = x + y;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Explanation: Here we use the Scanner class to read two numbers from the keyboard.
Explanation: We create two integer variables ( x and y ) and assign them values.
Add Two Numbers with User Input

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