Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 590
learner98 Avatar asked Nov 24 '25 20:11

learner98


1 Answers

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));
like image 111
Mad Physicist Avatar answered Nov 26 '25 10:11

Mad Physicist