How do I use the equality operator in Java?

Equality operator is used to compare two similar things (numbers, characters, boolean, primitives and object references). Equality operator will always result in boolean value (true or false).

For object reference, it will return true if only both reference variables refer to the same object.

package org.kodejava.example.fundamental;

public class EqualityDemo {
    public static void main(String[] args) {
        int value1 = 10, value2 = 10, number1 = 10;
        char a = 'a', b = 'b';
        double number2 = 10d;
        Cat kitty = new Cat("Kitty");
        Cat kitten = new Cat("Kitty");
        Cat sweetie = kitty;

        if (value1 == value2) {
            System.out.println("Equal");
        }

        if (a != b) {
            System.out.println("Not Equal");
        }

        //
        // though it have different type, but it have same value
        //
        if (number1 == number2) {
            System.out.println("Equal");
        }

        //
        // it's not refer to the same object, so it will return
        // false
        //
        if (kitty == kitten) {
            System.out.format("(kitty==kitten), the result is " +
                    (kitty == kitten));
        } else {
            System.out.println("(kitty==kitten), the result is " +
                    (kitty == kitten));
        }

        //
        // it's refer to the same object, so it will return true
        //
        if (kitty == sweetie) {
            System.out.println("(kitty==sweetie), the result is " +
                    (kitty == sweetie));
        }

        if (true != false) {
            System.out.println("true!=false");
        }

    }
}

class Cat {
    private String name;

    Cat(String name) {
        this.name = name;
    }
}

And here are the result of the program:

Equal
Not Equal
Equal
(kitty==kitten), the result is false
(kitty==sweetie), the result is true
true!=false
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply