"I'd like to tell you a bit about comparing variables in Java."

"You already know the simplest comparison operators – less than (<) and greater than (>)."

"Yep."

"There are also operators like equal to (==) and not equal to (!=). As well as, less than or equal to (<=) and greater than or equal to (>=)."

"Now this is getting interesting."

"Note that there are no =< or => operators in Java!"

"The = sign is used for assignment operations. That's why two equal signs (==) are used to test equality. To check that variables aren't equal, use the != operator."

"I see."

"When comparing two variables in Java using the == operator, we are comparing the contents of the variables."

"Thus, for primitive variables, their values are compared."

"For reference variables, the references are compared. Suppose we have identical but distinct objects. Because references to them are different, a comparison will show that they are not equal, i.e. the comparison result will be false. A comparison of references will be true only if both references point to the same object."

"To compare objects' internal contents, we use the special equals method. This method (and all methods of the Object class) are added to your class by the compiler even if you don't declare them. Let me show you some examples:"

Code Explanation
1
int a = 5;
 int b = 5;
 System.out.println(a == b);
Compare primitive types.
true will be displayed on the screen.
2
Cat cat1 = new Cat("Oscar");
 Cat cat2 = cat1;
 System.out.println(cat1 == cat2);
Compare references.
true will be displayed on the screen.
Both variables store references to the same object.
3
String s = new String("Mom");
 String s2 = s;
 System.out.println(s == s2);
Compare references.
true will be displayed on the screen.
Both variables store references to the same object.
4
Cat cat1 = new Cat("Oscar");
 Cat cat2 = new Cat("Oscar");
 System.out.println(cat1 == cat2);
Compare references.
false will be displayed on the screen.
The two variables reference identical Cat objects, but not the same one.
5
String s = new String("Mom");
 String s2 = new String("Mom");
 System.out.println(s == s2);
Compare references.
false will be displayed on the screen.
The two variables reference identical String objects, but not the same one.
6
Cat cat1 = new Cat("Oscar");
 Cat cat2 = new Cat("Oscar");
 System.out.println(cat1.equals(cat2));
Compare objects.
true will be displayed on the screen.
The two variables reference identical Cat objects
7
String s = new String("Mom");
 String s2 = new String("Mom");
 System.out.println(s.equals(s2));
Compare objects.
true will be displayed on the screen.
The two variables reference identical String objects

"Oh, I almost forgot! Here are some exercises for you:"