This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java main arg[] behaviour

 
Lucas Toledo
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following program

when I run it
java ArgIt x
it does not print x2.
Why is that? why is it that when the string passed as an argument to the program is not ==??? does the args have a different value?
why is then "x"=="x" when args[0] is not equal (==) to "x" ?

thanks in advance,
Lucas
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, you should never use == to compare Strings. You should always use equals(). However, because of the way the String pool is managed, == will sometimes give the right results. Line 5 is an example - using String literals will result in the same object being used, so == does what you expect. But this behaviour should never be relied on, and line 4 shows an example why.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A good read - ScjpTipLine-StringsLiterally
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic