1

I've tried searching for an answer to this problem, but I'm not entirely sure what to search for. Basically what I want is for the user of my program to be able to type (into the command line):

java galaxySim HELP

and for my program to tell them some stuff about file formats and stuff. Otherwise the first argument is a filename. so the code I have to do this is:

if (args[0] == "HELP") {
  System.out.printf("Help Stuff...");
}else{
  filename = args[0];
  System.out.printf("Filename found");
}

which is encapsulated in error handling stuff that I don't believe affects this so haven't written. The problem is this: whatever I type as the first argument, it ALWAYS goes to the else statement.

I've experimented with adding spaces before and after the argument, but it never helps. I don't believe it to be a problem with my IF statement, as if I write

if(args[0] == args[0]){

then it does go to the correct statement. It seems as if

args[0] == "Help"

is always false. Is there perhaps some kind of encoding issue? I'm using win7, if that makes a difference.

It's not a vital part of the program, but... It would be nice if it worked. Anyone know what's wrong here?

Thanks!

AdamBourke
  • 53
  • 1
  • 9
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – assylias Jun 23 '12 at 16:40

3 Answers3

5

Compare Strings using equals

Change this:

if(args[0] == "HELP")

to

if(args[0].equals("HELP"))

== compares for reference equality, not value equality. You need to check the values, hence use equals().

Here's the link for further knowledge.

You might also want to read this for understanding difference between == and equals() method.

Community
  • 1
  • 1
Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
1

You need to compare String instances with equals(), not ==.

So use args[0].equals("Help")

When you use == you are checking to see if they are the exact same object (i.e. you are essentially checking to see if the spot in memory where the operands are stored is the same), rather than checking to see if they are equivalent instances according to the semantics of the class.

QuantumMechanic
  • 13,795
  • 4
  • 45
  • 66
0

Well, we all know Strings are objects so we can't compare them by == . in Objects oriented context, we use == operator to check whether two references point to the same object. So by this statement,

args[0] == "HELP"

you are telling JVM that reference args[0] and the reference returned by "HELP" string is pointing to the same object or not, which they are not for sure. Because Strings entered by user and "HELP" string are totally different objects.

If you want check two objects are literally (or meaningfully equal) you have equals() method.

So ultimately, you should write

args[0].equals("HELP")
Ahmad
  • 2,110
  • 5
  • 26
  • 36