Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Immutability Example (Java OCA 8 Programmer I Study Guide, Sybex)

 
Aleksandra Pestova
Ranch Hand
Posts: 36
2
Firefox Browser Java Notepad
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the study guide there's a following example:
What does this print out?

String s1 = "1";
String s2 = s1.concat("2");
s2.concat("3");
System.out.println(s2);


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.


Have I understood correctly, what's going on here:
1. A reference to the object "1" is stored in s1.
2. After String s2 = s1.concat("2");  a new object "12" is created (according to the Java documentation about concat() ) and reference to it is stored in s2.
3. After s2.concat("3"); an object "123" is created , however a reference to it isn't stored, so the object is unreachable and due to that can't be used.
?




 
Tim Cooke
Sheriff
Pie
Posts: 3208
142
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct.
 
Aleksandra Pestova
Ranch Hand
Posts: 36
2
Firefox Browser Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Tim!
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aleksandra Pestova wrote:Have I understood correctly, what's going on here?

Yes, you definitely have Have a cow for providing an excellent explanation! You could have added this as well: And because no reference to the object "123" is stored, this object will immediately become eligible for garbage collection.

Time for another (free) pop quiz question. What will be the result if we replace all concat() methods with the String concatenation operator?

Hope it helps!
Kind regards,
Roel
 
Aleksandra Pestova
Ranch Hand
Posts: 36
2
Firefox Browser Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Than you very much, Roel!

Yeah, I was thinking about the garbage collection.

Thanks for the quiz question, it turned out that I don't understand expressions and statements quite well.

Here are my thoughts:
1. On line 1 an object "1" is created and a reference to it is stored in s1.
2. Line 2 - concatenation of "1" and "2" results in a new object "12" and a reference to it is stored in s2.
3. Hmm here I thought that a similar thing would happen as in the example above - Java would create a new object "123", but since it wouldn't be referenced, it would be immediately available for the garbage collection.
    But then I tried to compile it and got an error: not a statement (about line 3). As far as I understand s2+"3" is an expression and needs to be assigned to a variable. Then it would be a statement and could be compiled.
    Now I started thinking that if this line even doesn't compile then an object is not created and my explanation above is false.

    Would be very grateful, if you could explain me the line 3.


 
Joe Bishara
Ranch Hand
Posts: 175
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not all expressions are statements. This tutorial discusses the differences between an expression and a statement.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aleksandra Pestova wrote:Would be very grateful, if you could explain me the line 3.

Not a problem at all! That's exactly what these pop quiz questions are all about

As the link provided by Joe clearly illustrates, not every expression is a statement and the Java compiler expects (valid) statements. If it's not a (valid) statement, the code will not compiler and a compiler error will be given. So s2 + "3" is an expression, but not a statement and therefore the code doesn't compile. If the code doesn't compile, no .class file will be produced (because that's the result of a successful compilation). And if you don't have a .class file, you can't run your code. And if your code can't be run, no objects will be created at all (because all these statements will only be executed at runtime not at compile time). And don't forget you should be able to indicate compiler errors at the actual exam (and select the "Compilation fails" option).

There are many alternatives to fix that code snippet and make sure it compiles successfully: a) remove that line of codeb) assign the expression to a variable (assignment statement)c) use the expression in a method invocation statementIf we compile and execute the last code snippet, the output will be:
123
12


And here is yet another (free) pop quiz question. What will be the result of this code snippet?

Hope it helps!
Kind regards,
Roel
 
Aleksandra Pestova
Ranch Hand
Posts: 36
2
Firefox Browser Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joe for a good article and Roel for a detailed explanation. My answer to the quiz question is below. I would appreciate, if someone could check it.

I also read about statements in the book "Java in a nutshell". It explains them very detailed.

However, I still have some questions:

1. In the book the for loop is defined as follows:    for ( init ; test ; increment ) statement
Are init, test and increment expressions or statements?
In the book it's said, that they're expressions. But here init, test and increment are said to be statements.

2. In the switch statement does every case label indicate a labeled statement?
For example here


do lines 3 and 4 form a labeled statement? If no, what are case labels then? Expressions or statements?


*************My answer to the quiz question*********************************

Using concat() method as here would cause a NullPointerException, because
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
(From Java documentation about String class.)

 
Campbell Ritchie
Sheriff
Posts: 51439
87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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? . . .
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.
for (int i = 0; i < 10; )
{
    System.out.println(i++);
}

You can find the corresponding section about the switch statement here in the JLS, and that is a bit simpler. It tells you whether the labels are expressions or statements. I don't know whether it will come up in your exam, but it is, again, something you hardly ever need to know.
 
Campbell Ritchie
Sheriff
Posts: 51439
87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aleksandra Pestova wrote:. . .
1. In the book the for loop is defined as follows:    for ( init ; test ; increment ) statement
. . .
It means that what follows the increment) is one statement. As you know, you can use a block to represent a statement.
 
Aleksandra Pestova
Ranch Hand
Posts: 36
2
Firefox Browser Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!

Sometimes I get totally confused, how detailed I should know the material, so thank you for clarification.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aleksandra Pestova wrote:Are init, test and increment expressions or statements?

If you really want to know, you have to check and go through the Java Language Specification (JLS). Note that the JLS is written in a very specific language and it is generally considered to be difficult to understand and interpret. Furthermore you will not encounter this kind of questions on the certification exam. So you can spend your time much better to learn about much more important rules: e.g. the test expression should always evaluate to a boolean; although you have a section called "increment" and it's often used to increment the loop counter, any valid statement is allowed; all parts (init, test and increment) are optional; and so on. Here is a little code example to illustrate some of these rulesA possible output would be:
2: KM
4: GFRZ
6: OOYLFF
8: SGEVROJJ
10: DLBBMCEXMX
12: HCAIFJRUQGEX
14: YVIWTEKOMNMMDO
16: YWQAVPEVCYIBENYT
18: RRJHNMURWXOZJFOOMM
20: CTNZJTZSAUPXSEZZWKVJ


Aleksandra Pestova wrote:2. In the switch statement does every case label indicate a labeled statement?

And the same advice applies to the switch statement as well. In this topic, this one and this one you'll find plenty of (useful) information about switch statements.

Hope it helps!
Kind regards,
Roel
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aleksandra Pestova wrote:Using concat() method as here would cause a NullPointerException

You are spot-on!

And what happens if we replace the concat() method again with the String concatenation operator?
 
Aleksandra Pestova
Ranch Hand
Posts: 36
2
Firefox Browser Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for your examples, Roel!

Roel De Nijs wrote:
And what happens if we replace the concat() method again with the String concatenation operator?


This time the output will be "null2".
For "+" Java uses internally Stringbuilder and its method apend(). And if null is passed to append(), it is treated as a String "null".
1. A temporary empty Stringbuilder object is created.
2. Using append() "null" and "2" are appended to the empty object.
3. "null2" is converted back to String.

 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aleksandra Pestova wrote:This time the output will be "null2".

Spot-on!

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".

Although that's true, it doesn't happen always. It depends on a set of compiler optimizations. And that's why you should not know this for the certification exams. You only need to know that "+" will concatenate values and that in this code snippet "null2" will be printed (and thus no NullPointerException will be thrown at runtime).
 
Aleksandra Pestova
Ranch Hand
Posts: 36
2
Firefox Browser Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for your quizzes!

Because of them I've understood very well, how Strings work!   
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aleksandra Pestova wrote:Thanks a lot for your quizzes!

Glad to hear you like them!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic