What does this print out?
String s1 = "1";
String s2 = s1.concat("2");
Did you say "12"? Good. The trick is to see if you forget that the String class is immutable by throwing a method at you.
Aleksandra Pestova wrote:Have I understood correctly, what's going on here?
Aleksandra Pestova wrote:Would be very grateful, if you could explain me the line 3.
(From Java documentation about String class.)
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
None of those sources is authoritative. The authoritative source is the Java® Language Specification (=JLS). As you will see by looking at that link about for statements, sometimes they are expressions and sometimes statements and sometimes declarations. I shall leave you to plough through the JLS. I assure you it will be a total waste of time because nobody will ever be interested whether the bits of code underlined in this for loop are statements or not.
Aleksandra Pestova wrote:. . . In the book the for loop is defined as follows: for ( init ; test ; increment ) statement
Are init, test and increment expressions or statements? . . .
2. In the switch statement does every case label indicate a labeled statement? . . . what are case labels then? Expressions or statements? . . .
It means that what follows the increment) is one statement. As you know, you can use a block to represent a statement.
Aleksandra Pestova wrote:. . .
1. In the book the for loop is defined as follows: for ( init ; test ; increment ) statement
. . .
Aleksandra Pestova wrote:Are init, test and increment expressions or statements?
Aleksandra Pestova wrote:2. In the switch statement does every case label indicate a labeled statement?
Aleksandra Pestova wrote:Using concat() method as here would cause a NullPointerException
Roel De Nijs wrote:
And what happens if we replace the concat() method again with the String concatenation operator?
Aleksandra Pestova wrote:This time the output will be "null2".
Aleksandra Pestova wrote:For "+" Java uses internally Stringbuilder and its method apend(). And if null is passed to append(), it is treated as a String "null".