This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
Chetan Sama wrote:String s = "1+2" creates only 1 string which contains 1+2. Not 3, but 1+2 in string format.
I think that Mansukhdeep was asking the question rhetorically, so that the OP can figure out the problem herself.
Chetan Sama wrote:
String s = "1" + "2" creates three strings. One string is 1. second string is 2. Third string is the concatenation of the first and second string literal i.e 12.
To get in depth knowledge of how this works, you can study string pool and concatenation from any java book.
Actually, no. You forgot about the compile time constant optimizations. Since "1" + "2" is a concatenation of two compile time constants, which in turn, is another compile time constant, the compiler just puts "12" in the string pool. Only one string is created.
As per the program, you are trying to find out the position of '1' using indexof function, but you are not counting '+' as valid character in a string, See here is how it goes to store a total of ten characters