Perhaps it might help if you break out the code into two lines:
Then it is easier to see that there is one string created on line 2, and another on line 3.
Or, if we compile that method, and then look at the resultant bytecode in the created class file:
We can see here that the hard coded String "abc" is stored in location 1 (astore_1) at bytecode line 2 (physical line 4 in the above code block), and then a new String is created based on the contents of store location 1 then stored in location 2 (astore_2) at bytecode line 11 (physical line 9 in the above code block).
So there are 2 Strings: one in memory location 1 and one in memory location 2.
Does this help?
Joined: Feb 28, 2009
Andrew , thanks for the time you have taken to explain me the things .
But you know i still got more confused with youe new code
author and jackaroo
I'm about to go offline for a few days, so I'll quickly follow up on the bytecode, which I kind of dived right in without any explanation. If you don't understand this or care to understand this, then that's ok. If it makes the whole thing too confusing then just skip the bytecode explanations.
Lets start with a simple class:
Then look at what the HelloWorld.class file actually contains:
Where the command I entered to look at the contents of the class file was "javap -p <class name>"
You can see in that code that there is a default constructor (the first block of code) and then the method I created (public static void main).
In the main method:
At bytecode line 0 we get the reference to the static PrintStream that is stored in System.out
At bytecode line 3 we load from the runtime constant pool (ldc) the String "Hello, world"
At bytecode line 5 we invoke the println() method to print the string
At bytecode line 8 we do return from the "main" method (even though I had not put an explicit "return" statement in my code, Java puts one in for me
What I was trying to show with the bytecode from the compilation of my "someMethod()" class was that there are 2 Strings involved.
Joined: Feb 28, 2009
Thank you very much Andrew .
You really made a difference in understanding the concept.
(It took time as i did pratical as this requires some time rather than scan the article)