equal() and equalsIgnoreCase() return false for equal strings

That would be very strange indeed :) Can you change the above code to this:

if ("debug_mode".equalsIgnoreCase("debug_mode")) 
    debug_mode = true;

confirm it works fine and then double check why your values[0] is not "debug_mode".

Here's what comes to my mind right now as a list of things to check:

  • Check that values[0].length() == "debug_mode".length()
  • I highly doubt, but let me put it on the table anyway - are you by any chance using Unicode?
  • Can you print each character and do .equals() between that character and the respective character of the "debug_mode" string?
  • If this is in a bigger project, can you do the same in a simple Java project and confirm it works there?

To clarify, the problem is actually using DataInputStream.readLine. From javadoc (http://download.oracle.com/javase/1.6.0/docs/api/java/io/DataInputStream.html):

readLine()
      Deprecated. This method does not properly convert bytes to characters. ...

It actually has to do with Unicode in a subtle way - when you do writeChar you actually write two bytes 0 and 97, big-endian Unicode for the letter a.

Here's a self-contained snippet that shows the behavior:

import java.io.*;
import java.util.*;

public class B {
  public static void main(String[] args) throws Exception {
    String os = "abc";

    System.out.println("---- unicode, big-endian");
    for(byte b: os.getBytes("UTF-16BE")) {
      System.out.println(b);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);

    for(char c: os.toCharArray()) {
      dos.writeChar(c);
    }

    byte[] ba = baos.toByteArray();

    System.out.println("---- ba");
    for(byte b: ba) {
      System.out.println(b);
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(ba);
    DataInputStream dis = new DataInputStream(bais);

    System.out.println("---- dis");
    String s = dis.readLine();
    System.out.println(s);
    System.out.println("String length is " + s.length() 
      + ", but you would expect " + os.length() 
      + ", as that is what you see printed...");
  }
}

Moral of the story - don't use deprecated api... Also, whitespace is the silent killer: http://www.codinghorror.com/blog/2009/11/whitespace-the-silent-killer.html


I have just had this exact same issue, using equalsIgnoreCase.

After hours of staring at the screen, debugging the code it dawned on me that my if statement had a ; at the end,

i.e.

if ("stupid".equalsIgnoreCase.("STupid");
{
     //it always gets here 

}

Hope this helps someone in future.