OCPJP 6-100%; Preparing for GATE11
Gari Jain wrote:
Please Explain Why s3 is not == s4 and s3 is not == s5
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Gari Jain wrote:Please Explain Why s3 is not == s4 and s3 is not == s5
Abimaran Kugathasan wrote:Because, s1 and s2 are in the heap, not in the String literal pool, and the object, you've created as s3 is also in the heap. And s4 and s5 are in the String literal pool (One object "abcxyz", two references, s4 and s5).
When the compiler encounters a String literal, it checks the pool to sec if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.
Preparing for SCJP 6, target : March 2011.
When the compiler encounters a String literal, it checks the pool to sec if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.
"String literal pool" is the key here. s4 & s5 contain reference to same object ("abcxyz" string literal is in the pool). And == looks at the bit pattern (in this case) and bit battern of s4 & s5 is same. s3 is not part of the pool and contains reference to different string object, so bit pattern is different than s4 & s5 and == fail
OCPJP 6.0 93%
OCPJWCD 5.0 98%
mohitkumar gupta wrote:
why s3 is not part of the pool ?
once
is executed,i think s3 will refer to a object "abcxyz"
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
when you
come to the keyword "new," the JVM is obliged to create a new String object at run-time, rather than using the
one from the constant table.
the String object
referenced from the String Literal Pool is created when the class is loaded while the other String object is created
at runtime, when the "new String..." line is executed
OCPJP 6.0 93%
OCPJWCD 5.0 98%
mohitkumar gupta wrote:
so s3 would be assigned the value at runtime rather than at compile time
am i right ?
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
mohitkumar gupta wrote:so s3 would be assigned the value at runtime rather than at compile time
am i right ?
Abimaran Kugathasan wrote:Since, the s1 and s2 are in the heap, the object s3 is also in the heap.
OCPJP 6
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Abimaran Kugathasan wrote:
mohitkumar gupta wrote:
why s3 is not part of the pool ?
once
is executed,i think s3 will refer to a object "abcxyz"
Since, the s1 and s2 are in the heap, the object s3 is also in the heap. Read more about String Literal pool in this link.
OCPJP 6-100%; Preparing for GATE11