Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

i'm bit curious about the concatenated string literals with +

 
Ahmed Rezk
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
specifically how many strings are created in the pool in the following

String text = "tex"+"t";

is it 1,2 or 3
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ahmed Rezk:
specifically how many strings are created in the pool in the following

String text = "tex"+"t";

is it 1,2 or 3


3 , if the pool already doesnot have object with value tex , t , text.
and all these objects would be created in the private native pool of string.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While a strict reading of the JLS would imply that all three should be in the pool, in reality only one is. Which is fine because nothing in the program has any need at all for the substrings "tex" and "t" by themselves. The whole thing is resolved at compile time as a single string "text", and that's what gets stored. You can see this with a test program and the javap tool.

Given

then typing

gives output

Note that both foo and barbaz appear in the constant table, but not bar or baz individually.

Incidentally, the reason I changed

into

is because I wanted the variable name to be different from the content, so that we could see that both were included. If you change this to be a local variable within a method, then the name foo will not be included in the constant table. I'll leave that as an excercise for anyone who wants to try it.
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is JLS ?
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry ; I got it ...java language seecification.
 
Ahmed Rezk
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Really many thanks for such engineering why of proof
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic