Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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));
over 4 years ago · Santiago Trujillo Relatório

0

Like the other answer says, + goes from left to right. It is a "good idea" to always use parentheses that explicitly show the desired order of operations, especially when mixing types.

Doing so can reduce hard to find errors.

For example if you want to print the sum of two integers, you would use:

System.out.println(num1 + num2);

If I wanted to add a useful string to the output I would add "Sum of num1 and num2 :" and then keep the sum in parentheses, giving:

System.out.println("Sum of num1 and num2:" + (num1 + num2));
over 4 years ago · Santiago Trujillo Relatório

0

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));
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda