Wednesday 1 February 2012

Java Tips and Hints: Comparing Strings in Java with examples.

This might seem like an ever so obvious thing to most users of the good old Java, however it comes up in IRC and the /r/java subreddit all the time. so this brief post is to help them all out and me so I don't have to keep typing it.

OK so you should be reasonably familiar with the "if" statement well here is a program that uses it:
import java.util.Scanner; 
public class Variables {
        public static void main(String args[]) {
                Scanner input = new Scanner(System.in); 
                System.out.println("What is your name? ");
                String name = input.next();
   
                if(name == "bob")
                {
                    System.out.println("Your name is awesome, " + name);
                }
                else
                {
                    System.out.println("Your name sucks, " + name);
                }
        }
}
Well there you go that  program is syntactically correct it will compile and run, so we did it? well nope, There is a logical error in that code take a second to go compile it. no matter how you type bob it will not tell you that bob is an awesome name this is because we are comparing for a reference.

Instead of using "==" we need to be comparing for value equality, So we do that like this:
import java.util.Scanner;
public class Variables {
        public static void main(String args[]) {
                Scanner input = new Scanner(System.in); 
                System.out.println("What is your name? ");
                String name = input.next();
   
                if (name.equals("t"))
                {
                    System.out.println("Your name is awesome, " + name);
                }
                else
                {
                    System.out.println("Your name sucks, " + name);
                }
        }
}
Go ahead and check out the "if" statement now on line 18 you see that is how we compare Strings we are comparing the value equality in that string.

OK so now we have that we might find we have another issue you need to type "bob" because if you type  "Bob" with a capital letters in it then will return "Your name sucks" and we might not want that.

In that case we can use this ".equalsIgnoreCase" instead of just ".equals" that way we can Ignore the Case of the string.

OK then so now we have them what about more, well there are a lot so why don't you look in the Java documentation and leave a comments with the things you find.


No comments:

Post a Comment