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;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.print("Enter first number: ");8 double a = sc.nextDouble();910 System.out.print("Enter second number: ");11 double b = sc.nextDouble();1213 double sum = a + b;14 System.out.println("Sum = " + sum);1516 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.