File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

args[] and ==

 
Michel ten Voorde
Greenhorn
Posts: 26
Android Linux Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 434
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line # 6 will make args[0] point to the exact same address as x, hense args[0] == x becomes true

Can someone elaborate....
 
Michel ten Voorde
Greenhorn
Posts: 26
Android Linux Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 610
IntelliJ IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 :-)
 
Michel ten Voorde
Greenhorn
Posts: 26
Android Linux Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 610
IntelliJ IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!

 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic