Author Options:

In Java, how do you check if a command line argument is equal to a string? Answered

I'm learning the Java programming language and I have come to a rut in the road. Below is the simple "Hello Rusty" program, I want it do its usual thing, but if the argument is a certain word/number (42 in this case) it says something totally different. There are no errors while compiling the code, just when I type
"java hello 42"
the outcome  is
"Hello 42"
Instead of the expected 
"You have greeted the answer to life, the universe, and everything,
you deserve some cake."
I am almost certain the problem is in line 2, line 5 or both. 

1  class hello{
2   public static void main (String args[]){
3    /*Now let us say Hello*/
4    if (args.length > 0) {
5       if (args[0] == "42") {
6      System.out.println("You have greeted the answer to life, the universe, and everything,");
7      System.out.println("you deserve some cake.");
8     }
9     else{
10     System.out.println("Hello " + args[0] + "!");
11    }
12   }
13   else{
14    System.out.println("Hello whoever you are!");
15   }
16  }

Thank you in advance for the help


The forums are retiring in 2021 and are now closed for new topics and comments.

Best Answer 9 years ago

You either need to convert args[0] to an integer, or use the string object's "compareTo" method. So either

Integer.parseInt(args[0]) == 42


args[0].compareTo("42") == 0

inside your if statement.


Answer 9 years ago

Thanks, I tried them both and the second one worked great!

For everyone else who is trying to get something out of this question, I found that it also works with a string, not just and integer. here is my fixed code.

class hello{
public static void main (String args[]){
/*Now let us say Hello*/
if (args.length > 0) {
if (args[0].compareTo("thing") == 0) {
System.out.println("You have greeted the answer to life, the uni...,");
System.out.println("you deserve some cake, or pie.");
System.out.println("Hello " + args[0] + "!");
System.out.println("Hello whoever you are!");

Thanks again drknotter!