Add Two Numbers Using Scanner in Java
Problem
Console input lets a program read values typed by the user while it's running, instead of relying only on hard-coded values.
Read two integers from the console and print their sum.
Java Program
import java.util.Scanner;
public class SumTwoNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt(); // reads and parses the typed number
System.out.println(a); // echo back — this compiler doesn't echo typed input itself
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.println(b);
System.out.println("Sum: " + (a + b));
}
}Output
Core Logic
Scanner handles the console input here — read two numbers and add them together.
- 1
new Scanner(System.in)creates a reader attached to the console. - 2
System.out.print(...)shows a prompt without a trailing newline, so the value read next appears to continue that same line. - 3
sc.nextInt()reads the next number typed and parses it directly into anint. - 4
System.out.println(a)immediately echoes the value back — most online compilers don't echo typed input themselves the way a real terminal does, so the program prints it explicitly. - 5The same read-then-echo pair happens twice — once for each number — and the two ints are added and printed together.
4 then 7 prints Enter first number: 4, Enter second number: 7, and finally Sum: 11.Key Point: nextInt() only consumes the numeric token — it leaves the trailing newline in the buffer, which matters if you later mix in a nextLine() call.
Key Concepts
Approach 2: BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class SumTwoNumbersBufferedReader {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter first number: ");
// readLine() returns a String, so parse it into an int explicitly
int a = Integer.parseInt(br.readLine());
System.out.println(a); // echo back — this compiler doesn't echo typed input itself
System.out.print("Enter second number: ");
int b = Integer.parseInt(br.readLine());
System.out.println(b);
System.out.println("Sum: " + (a + b));
}
}
Output
Core Logic
BufferedReader is a common alternative to Scanner — read each line as text, then parse it into a number yourself.
- 1
new BufferedReader(new InputStreamReader(System.in))wraps standard input in a buffered character reader. - 2
br.readLine()reads one entire line of text at a time, returning it as aString. - 3
Integer.parseInt(...)converts that string into anint, sincereadLine()— unlikeScanner.nextInt()— has no built-in numeric parsing. - 4
System.out.println(a)echoes the parsed value back out, since online compilers typically don't echo typed input themselves the way a real terminal does. - 5The method signature adds
throws IOException, sincereadLine()can throw a checked exception on an I/O failure.
4 then 7 on separate lines parses to the ints 4 and 7, echoed back and followed by Sum: 11.Key Point: BufferedReader is noticeably faster than Scanner for reading large volumes of input, which is why it's the preferred choice in competitive programming — the trade-off is the extra manual parsing step.
Key Concepts
Approach 3: Java 8
import java.util.Scanner;
import java.util.function.IntBinaryOperator;
public class SumTwoNumbersLambda {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.println(a); // echo back — this compiler doesn't echo typed input itself
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.println(b);
// The addition logic is kept separate from how the numbers were read
IntBinaryOperator add = (x, y) -> x + y;
System.out.println("Sum: " + add.applyAsInt(a, b));
}
}
Output
Core Logic
Reading stays the same — Scanner still reads the two typed numbers — but the addition itself is pulled out into a reusable IntBinaryOperator lambda.
- 1
Scannerreadsaandbexactly as in the direct version, echoing each back. - 2
IntBinaryOperator add = (x, y) -> x + y;stores the addition logic separately from the input-reading code. - 3
add.applyAsInt(a, b)combines the two values read from the console, and the result is printed with the same label.
4 then 7 still prints the same prompts and echoes, with add.applyAsInt(4, 7) producing Sum: 11.Key Point: Separating 'how the numbers get in' (Scanner) from 'what happens to them' (the lambda) keeps the input logic and the business logic independent — useful once the operation needs to change without touching any input code.
Key Concepts
Interview Questions
How do you handle input that isn't a number?
Check scanner.hasNextInt() before calling nextInt(), or catch InputMismatchException.
How would you sum any number of inputs?
Read values in a loop until there's no more input (while (scanner.hasNextInt())) and add each one to a running total.