Mini Exercise: Sum Two Numbers in Java

Introduction

Great progress so far. In this chapter you will build your first small interactive Java program: ask the user for two numbers and print their sum. You will learn Scanner for console input, then combine variables and operators into real behavior.

This exercise is simple, but the pattern—input → process → output—appears in scripts, services, and tools everywhere.

Prerequisites

What You Will Build

A console program that:

  1. Prompts for two numbers
  2. Reads input with Scanner
  3. Computes the sum
  4. Prints a clear, encouraging result

Example session:

text
Enter the first number: 3
Enter the second number: 5
Awesome! 3 + 5 = 8

Tip

You Are Doing Real Programming

This is not “just a demo.” Collecting input, computing, and responding is the same core loop used in CLIs, APIs, and batch jobs—at larger scale.

Step 1: Meet Scanner

java.util.Scanner reads formatted input from the console (and other sources).

Common methods:

MethodReads
nextInt()int
nextDouble()double
nextLine()full line as String
hasNextInt()whether next token is an int (validation)

Import and create a Scanner tied to standard input:

java
import java.util.Scanner;
 
Scanner scanner = new Scanner(System.in);

Close the scanner when done to free resources:

java
scanner.close();

Modern style with try-with-resources (auto-close):

java
try (Scanner scanner = new Scanner(System.in)) {
    // use scanner here
}

Step 2: Write the Basic Version (Integers)

Create SumTwoNumbers.java:

java
import java.util.Scanner;
 
public class SumTwoNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        System.out.print("Enter the first number: ");
        int firstNumber = scanner.nextInt();
 
        System.out.print("Enter the second number: ");
        int secondNumber = scanner.nextInt();
 
        int sum = firstNumber + secondNumber;
 
        System.out.println("Awesome! " + firstNumber + " + " + secondNumber + " = " + sum);
 
        scanner.close();
    }
}

Run from IntelliJ (▶) or terminal:

bash
javac SumTwoNumbers.java
java SumTwoNumbers

Try 10 and 25 → you should see Awesome! 10 + 25 = 35.

Step 3: Version with Decimals

If users may enter values like 3.5, use nextDouble():

java
import java.util.Scanner;
 
public class SumTwoDecimals {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Please enter number 1: ");
            double firstNumber = scanner.nextDouble();
 
            System.out.print("Please enter number 2: ");
            double secondNumber = scanner.nextDouble();
 
            double sum = firstNumber + secondNumber;
 
            System.out.printf("Awesome! %.2f + %.2f = %.2f%n",
                    firstNumber, secondNumber, sum);
        }
    }
}

printf formats decimals to two places—handy for money-style output.

Step 4: Why Input Type Matters

Scanner reads tokens, not “math meaning” by itself. nextInt() expects an integer token; nextDouble() accepts decimals.

If the user types letters when an int is expected:

text
Exception in thread "main" java.util.InputMismatchException

That is normal while learning. Later chapters cover validation and exceptions. For now, type numeric input only.

nextInt() followed by nextLine() (heads-up)

After nextInt(), a newline may remain in the buffer. If you later read a full line with nextLine(), you might get an empty line. Patterns to fix this appear when you work with text names and numbers together in Strings. For two numbers only, the basic program above is enough.

Step 5: Add Friendly Prompts and Encouragement

Small wording changes improve learner experience:

java
System.out.println("=== Two Number Sum ===");
System.out.println("Let's add two numbers together.");

After a correct run, you might add:

java
System.out.println("Nice work — you just built interactive Java!");

Positive feedback matters when the console feels unfamiliar. You earned that message.

Practice Challenges

Try these upgrades:

  1. Print average as well as sum
  2. Ask whether to run again in a loop (preview of Loops)
  3. Use try-with-resources everywhere you use Scanner
  4. Reject non-numeric input with a friendly message (optional stretch)

Challenge skeleton (average):

java
double average = sum / 2.0;
System.out.println("Average: " + average);

Use 2.0 so Java performs floating-point division.

Confidence Check

If you finished this chapter, you can:

  • Import and use Scanner
  • Read int and double from the keyboard
  • Combine input with arithmetic
  • Print structured output
  • Recognize a basic InputMismatchException

You moved from static lines to programs that respond to users. That is a real milestone.

What’s Next

Learn text processing in Strings—concatenation, methods, and StringBuilder.

FAQ

Why import java.util.Scanner?

Scanner lives in the Java standard library package java.util. Imports tell the compiler where to find the class.

Should I use int or double for this exercise?

Use int for whole numbers only. Use double when decimals are allowed.

Why does 10 + 25 print without decimals but 3.5 + 2.5 shows .00 with printf?

Types follow the operations: int + int stays integral; double + double is floating-point. Formatting controls how results display.

Do I need to close Scanner?

Yes when you create it manually. try-with-resources closes it automatically at the end of the block.

Is this tiny program really important?

Yes. Input → transform → output is the backbone of user-facing tools, data scripts, and service handlers at every scale.