0
String word1 = "Hello";
String word2 = "World";
        
String message = word1 + " " + word2  + " " + 2022 +"!";
System.out.println(message);

Output on console: Hello World 2022!

Note that I didn't add double quotes in 2022 (so it's not a String nor a variable) and even then the code ran without errors. Why?

If I had typed something like:

String message = word1 + " " + word2  + " " + welcome +"!";

I would obviously have gotten an error since welcome is not a String nor a variable, but why doesn't this error happen when you concatenate integers (not a primitive integer value, but literally an integer number) like in the previous example that had 2022 concatenated with word1 and word2 variables?

Corvo
  • 47
  • 10
  • 3
    I think Java can auto convert int and double into a string if you concatenate int or double after some string – Nguyễn Nhân Jan 19 '22 at 04:23
  • So when it sees an int or double after some string it calls `toString()` method? Anyway, I think the third answer of [this question](https://stackoverflow.com/questions/46439339/int-to-string-while-string-concatenation-in-java) already clarified me :) tnx – Corvo Jan 19 '22 at 04:36
  • 2
    `2022` is an existing construct in Java (a number literal), `welcome` is an identifier but there is no existing variable. There is no rule that the arguments have to be a string or variable. And this has nothing to do with string concatenation at all. Regardless of where you write `welcome`, as long as there is no variable of that name, you get an error. – Holger Jan 19 '22 at 11:53
  • @Holger What is a construct in this context? – Corvo Jan 19 '22 at 17:36
  • 2
    The literal English meaning, not a formal term at all. The formal term would be “literal”, as given in the brackets. I wrote “number literal” but the specification uses the terms “integer literals” and “floating-point literals”. – Holger Jan 19 '22 at 17:47

0 Answers0