Add Two Numbers in Java

Scanner gives numbers. Forget nextDouble() and you are concatenating strings.

BeginnerModule 1: Basic Java ProgramsExample 2 of 20
add-two-numbers.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter first number: ");
8 double a = sc.nextDouble();
9
10 System.out.print("Enter second number: ");
11 double b = sc.nextDouble();
12
13 double sum = a + b;
14 System.out.println("Sum = " + sum);
15
16 sc.close();
17 }
18}

Output

Enter first number: 10
Enter second number: 20
Sum = 30.0

What's going on

Scanner reads from System.in. nextDouble() turns the line into a number. Skip that and "10" + "20" is not a thing here — but next() would leave you with strings.

sc.close() is polite. Closing System.in too early in a bigger app is a footgun. Fine for this page.

10 + 20 prints 30.0 because these are doubles.