| Author |
args[] and ==
|
Michel ten Voorde
Greenhorn
Joined: Dec 30, 2010
Posts: 26
|
|
This following code is based on Practice Exam 2, question 6 from K&B's new book OCP Java SE 6 Programmer Practice Exams:
Giving:
args[0] is x
However, args[0]=="x" is false
We do: args[0]="x"...
...and strangely, now args[0]=="x" is true
Can anyone explain?
|
 |
Sandra Bachan
Ranch Hand
Joined: Feb 18, 2010
Posts: 434
|
|
Line # 6 will make args[0] point to the exact same address as x, hense args[0] == x becomes true
Can someone elaborate....
|
Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
|
 |
Michel ten Voorde
Greenhorn
Joined: Dec 30, 2010
Posts: 26
|
|
But then, where did args[0] point to before? I would think that it already pointed to an 'x', since that's what the println says.
Btw, I forgot to mention that the program is invoked with 'java Test x', but perhaps that was obvious.
|
 |
Piotr Nowicki
Ranch Hand
Joined: Jul 13, 2010
Posts: 610
|
|
AFAIK, the String Literal Pool is created when the class is loaded. At this point the JVM doesn't know what String will you type when you will execute the class. Every value you type is treated as a new object, therefore it acts just like you would type new String("test").
Edit: Oh, and try changing
to
Just for fun :-)
|
OCP Java SE 6 Programmer, OCM Java SE 6 Developer, OCE Java EE 6 JSPSD, OCE Java EE 6 EJBD, OCE Java EE 6 JPAD, Spring 3.0 Core Professional.
|
 |
Michel ten Voorde
Greenhorn
Joined: Dec 30, 2010
Posts: 26
|
|
|
Thanks for the explanation. Kinda tough concepts for OCPJP, I'd say... but then again, the questions in the book are supposed to be a little harder than the real exam, if I've read correctly.
|
 |
Piotr Nowicki
Ranch Hand
Joined: Jul 13, 2010
Posts: 610
|
|
Michel, yea, the questions in Kathy and Bert's book are a bit tougher than the real exam ones.
By the way, try running this as java Test xx (or better - try to guess what will be the output before running). I think this example will give you the better feeling of what is happening in this weird String Literal Pool thing ;-)
Cheers!
|
 |
 |
|
|
subject: args[] and ==
|
|
|