5. If-statements and string equality

If-statements in Java

We can use if-statements to print out different messages depending on the value of a variable. I've added the equivalent Python program for comparison.

// java
class Conditionals {
    public static void main(String[] args) {
        int x = 5;

        if (x < 0) {
            System.out.println("x less than 0");
        }
        else if (x == 0) {
            System.out.println("x equals 0");
        }
        else {
            System.out.println("x greater than 0");
        }
    }
}
# python
 
def main():
    x = 5

    if x < 0:
        print("x less than 0")

    elif x == 0:
        print("x equals 0")

    else:
        print("x greater than 0")


main()

There's a few differences between if-statements in Java and if-statements in Python:

All the usual comparison operators <=, >=, >, and < are the same. != and == are the same too, except when it comes to strings.

The problem with strings

Let's take a look at this program.

String x = "abcdef";
String y = x.substring(0, 3) + "def"; // substring(0, 3) returns characters [0, 3) in x, so "abc"

System.out.println(x == y);

You'd expect this program to print true, just like a similar program using ints would.

int x = 123;
int y = 100 + 20 + 3;

System.out.println(x == y); // prints true

But you'd be wrong - the program with strings prints false (you can check it yourself). Let's look at why.

String equality

Remember how String isn't a primitive like int, double, and the others are? That's because String isn't just a special built-in keyword for the language - it's a class, too. String variables are objects. Primitive variables are not.

We can call methods on Strings

String x = "abc";
System.out.println(x.length()); // calls x's length method

which we can't do on primitives because primitives don't have methods - only objects do.

int x = 123;
System.out.println(x.length()); // doesn't work - ints don't have any methods

Object creation

When we make two different String variables, we're making two separate objects.

(Technically, this isn't true. Java doesn't create a new String object every time we make a new String variable because it does special things to pool strings and save memory resources. But we can force Java to create a genuinely new String object by using the new keyword, which we'll talk about later).

// two separate String objects
String x = new String("a");
String y = new String("a");

Every time we create a new object, that object goes into its own unique place in memory. When we refer to that object's variable name, Java goes to the memory address associated with the name and retrieves the object.

Even though x and y have the same value ("a"), they aren't the same object, because they're at different places in memory.

The two roles of ==

== does different things to objects and primitives.

On primitives, == tests for value equality. That is, it checks to see if the values of the variables are the same.

boolean a = true;
boolean b = true;
System.out.println(a == b); // true, because true equals true

On objects, == tests for reference equality. That is, it checks to see if the two objects are literally the same object, i.e. if they're both have the same memory address. It doesn't care about their values, just their addresses.

String x = new String("a");
String y = new String("a");
System.out.println(x == y); // prints false

Even though x and y have the same value, they're both different objects, so x == y is false.

Checking for value equality with objects

So how do we tell if two objects have the same value? By using the equals method.

String x = new String("a");
String y = new String("a");
System.out.println(x.equals(y)); // prints true

All objects have an equals method which compares the values of the objects. If the objects have the same values, then equals returns true.

Using equals with Strings

Thus, whenever you're comparing two String values, use equals, not ==.

String name1 = "Galen";
String name2 = "Galen";

if (name1.equals(name2)) {
    System.out.println("The names are the same.");
} else {
    System.out.println("The names are different.");
}

Exercises

Don't worry if you're still confused about the reference and value equality stuff. The only thing you really need to remember is to use equals for objects and == for primitives. You'll pick up the rest as you keep practicing.


  1. Predict the output of this program:

    // java
    class Age {
        public static void main(String[] args) {
            int age = 18;
    
            if (age < 13) {
                System.out.println("That's kind of young.");
            }
            else if (age == 13) {
                System.out.println("13, eh? Good luck.");
            }
            else if (age <= 18) { 
                System.out.println("That's rough.");
            }
            else if (age < 21) {
                System.out.println("You're almost 21!");
            }
            else {
                System.out.println("You're getting old.");
            }
        }
    }
  2. Given this starter code for a rock paper scissors game

    class RockPaperScissors {
        public static void main(String[] args) {
            String user = "rock";
            String comp = "scissors";
            // ...
        }
    }

    write a series of if-statements that prints User win! if the user move beats the comp move, Computer win! if the comp move beats the user move, or Tie! if the moves are the same.

    Test your program by changing the values of user and comp. Google the rules of rock paper scissors if you don't know them.

  3. Write a program that prints YAY if a String variable contains the string melon (e.g. melon, watermelon, winter melon, etc.), and otherwise prints NAY. Google around for String methods that help you search for specific substrings inside strings.

  4. Why does this program print true

    System.out.println("test" == "te" + "st");

    but this program prints false?

    String x = "test";
    String y = x.substring(0, 2) + substring(2, 4);
    System.out.println(x == y);

    Don't worry if you can't figure this out. It's enough to make a decent attempt. The real goal is to practice looking up stuff and reading the Java vocabulary.

  5. Can you find any other examples where two different Strings with the same value are == (like "test" == "te" + "st")? Stack Overflow will probably be helpful.