Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+14 votes

Can you compare two colors in java ? Such as comparing to see if a color X is black or not. Something like:

        Color X = new Color(R,G,B);
         if ( X == Color.BLACK) { 
              System.out.println("True");
         }
asked in CSC211_Winter2018 by (1 point)

1 Answer

+7 votes

Colors are objects, like Strings, so you should compare them using:

myColor.equals(Color.BLACK)

instead of

myColor == Color.BLACK

The second compares whether the two variables point to the exact same object in memory, whereas the first compares whether they are two different color objects that both the same shade of color (black).

In general, use == for primitive types (like int), and .equals(...) to compare object types.

answered by (3.4k points)
...