Tuesday, 13 January 2015

equals And equalsIgnoreCase In Java

If you want to make a case sensitive comparison between two string variables in Java, you can do so using equals as shown in prog80 below:

andrew@UBUNTU:~/Java$ cat prog80.java
public class prog80
{
public static void main (String args[])
  {
  String andrew = "andrew";
  String ANDREW = "ANDREW";
  if (andrew.equals(ANDREW))
    System.out.println("andrew = ANDREW");
  else
    System.out.println("andrew != ANDREW");
  }
}
andrew@UBUNTU:~/Java$ javac prog80.java
andrew@UBUNTU:~/Java$ java prog80
andrew != ANDREW
andrew@UBUNTU:~/Java$


If you need to do a case insensitive comparison, you can use equalsIgnoreCase instead:

andrew@UBUNTU:~/Java$ cat prog81.java
public class prog81
{
public static void main (String args[])
  {
  String andrew = "andrew";
  String ANDREW = "ANDREW";
  if (andrew.equalsIgnoreCase(ANDREW))
    System.out.println("andrew = ANDREW");
  else
    System.out.println("andrew != ANDREW");
  }
}
andrew@UBUNTU:~/Java$ javac prog81.java
andrew@UBUNTU:~/Java$ java prog81
andrew = ANDREW
andrew@UBUNTU:~/Java$