learner98
learner98

Reputation: 39

Why is it concatenating instead of arithmetic operation?

Scanner sal = new Scanner(System.in);
System.out.print("Enter first_salary: ");
int Salary1 = sal.nextInt();

System.out.print("Enter second_salary : ");
int Salary2 = sal.nextInt();

System.out.print("Combined Salary is " + Salary1 + Salary2);

I am trying to get user input twice, and then print the sum. Instead, the output is concatenating the numbers instead of actually adding them.

Upvotes: 2

Views: 1096

Answers (2)

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

As to why this happens, @MadPhysicist's answer covers that.

As to how to avoid this you can either use parentheses as they said or you can use string formatting, like this:

System.out.println("Combined Salary is %d".formatted(Salary1 + Salary2));

String has had the formatted method since Java 15. If you're stuck with an older version you can use the static format method instead:

System.out.println(String.format("Combined Salary is %d", Salary1 + Salary2));

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114280

Because the + operator associates left to right. Your argument is equivalent to the explicit

(("Combined Salary is " + Salary1) + Salary2)

Since ("Combined Salary is " + Salary1) results in a string, you will concatenate strings. To group differently, adjust the order of operations with parentheses:

System.out.print("Combined Salary is " + (Salary1 + Salary2));

Upvotes: 7

Related Questions