0

I have the following code:

    System.out.println("12" + 34);    // prints "1234"

    System.out.println(1 + 2 + "34"); // prints "334"

I was expecting an error, instead, my int values got concatenated to the String without error.

Can someone explain in detail what goes on above?

  1. Does Java implicitly convert int to String type when it notices an int AND String data type in a "+" operation?

  2. Why isn't there an error thrown due to wrong data types when using the + operator?

  3. If there were indeed implicit conversion going on, why does Java do that and not throw an error?

dian jin
  • 195
  • 3
  • 12

2 Answers2

2

This answer addresses your second example:

 System.out.println(1 + 2 + "34"); // prints "334"

What is happening here is that the expression 1 + 2 is happening first, due to the left-to-right precedence of the + operator. Actually, any operator has left to right precedence all other things being of the same precedence. So, first 1 + 2 evaluates as integer addition to 3, leaving us with:

 System.out.println(3 + "34"); // prints "334"

Next, 3 + "34" evaluates as string concatenation, similar to your first example, printing "334".

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I understand precedence, what i'm asking is 1. why did java evaluate it as a string concatenation instead of throwing an error? 2. did an implicit conversion happen to the int value? – dian jin Sep 11 '20 at 04:33
  • Java must be, at some point, internally using `toString` on the integer literal. Anyway, interpreting `+` as string concatentation is the only operation which makes sense, right? – Tim Biegeleisen Sep 11 '20 at 04:35
  • the following [link](https://stackoverflow.com/questions/47605/string-concatenation-concat-vs-operator) answers my question: you were right! at some point it uses the toString() method :) – dian jin Sep 11 '20 at 04:54
0

It is java concatenate. please refer the link.

concatenating string and numbers Java