Search code examples
javashellcommand-lineargs

Java input from terminal strange behavior


I've got the following code which works except for the command line arguments, everytime i write "Insertion" it won't go in the if-statement so the output would be "Algorithm not found. Use: [ Insertion | Merge ]"

  public static void main(String[] args) throws IOException, InsertionAndMergeException, Exception {
    if( args.length < 2 ) {
      System.out.println("Use: <path> <algorithm> ");
      System.exit(1);
    }

    if(args[1] == "Insertion" || args[1] == "Merge"){

      testWithComparisonFunction(args[0], args[1], new RecordComparatorIntField());

    }else
      System.out.println("Algorithm not found. Use: [ Insertion | Merge ]");
  }  

In command-line i'm typing this, what am I doing wrong?

java insertionandmergeusagejava/InsertionAndMer
geUsage "/home/zenoraiser/Scrivania/Università/Secondo Anno/Algoritmi/1718/LAB/Progetto/Integers.txt" "Insertion"

Solution

  • You're confusing == with .equals, if you change your if statement to

    if ("Insertion".equals(args[1]) || "Merge".equals(args[1])) {
    

    You should get the expected result.

    In Java, the == operation takes the LHS value and compares it directly with the RHS value, this is fine for primitive types such as int, double, etc. Strings are a bit different though. Because a String is effectively an array of characters, it is stored as an Object, so the == operator will compare the pointers to the LHS/RHS (which in this case are not equal).

    You can observe seemingly strange behavior around this with code like:

    String a = "Test.";
    String b = "Test.";
    System.out.println(a == b); // true
    System.out.println(a.toLowerCase() == b.toLowerCase()); // false
    

    This is due to a process known as "String interning", which effectively stores multiple strings under the same pointer while they have the same value.

    Also note that by putting the String literal first in the comparison, you remove the possibility of a NullPointerException if args[1] were to be non-existent.