0

When I pass an argument to my Main method via the BlueJ entry box, it works fine. When I pass it as a command-line parameter, it has problems.

  • It can be printed out correctly from args[0]
  • It is type String as expected
  • args.length > 0 is correctly "true"
  • it is not correctly recognized by if(args[0] == "myArg")

Simplified code:

command-line: java src.main.MyClass myArg

public static void main(String[] args)
        { 
            System.out.println(args[0]);                      //prints "myArg" correctly
            
            if (args.length == 0) {
                throw new IllegalArgumentException();
            }
            else if (args.length > 0) {
                System.out.println("made it to > 0");          //prints fine
                if(args[0] == "myArg") {                       //does not correctly eval "true"
                    System.out.println("evaluated correctly"); // does not print
                    
            }
         }

Again, using the BlueJ argument entry, the argument functions correctly, but from the command line, it is read correctly, enters my method correctly, but somehow is not being correctly evaluated as "myArg"

Answered
by Juan, below.

Humbling mistake of using == instead of .equals() to compare strings. I am not sure why this incorrect code would still work when passing the argument via the BlueJ interface, but on to more important issues. Thank you stackoverflow.

Michael Conlin
  • 679
  • 1
  • 6
  • 14
  • 3
    The argument is a String you have to use equals() to compare Strings, not "==". – Juan May 06 '22 at 22:05
  • This is correct. Silly mistake. However, any idea why it might still work via the BlueJ interface? Less important, but this is what threw me. – Michael Conlin May 06 '22 at 22:11
  • 1
    @MichaelConlin It depends on how the source code is and how bluej will create/use the string argument. It might be from the same instance, so `==` will work in this case, see https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Progman May 06 '22 at 22:28

0 Answers0