A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.
"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 | |
Compare primitive types. true will be displayed on the screen. |
2 | |
Compare references. true will be displayed on the screen. Both variables store references to the same object. |
3 | |
Compare references. true will be displayed on the screen. Both variables store references to the same object. |
4 | |
Compare references. false will be displayed on the screen. The two variables reference identical Cat objects, but not the same one. |
5 | |
Compare references. false will be displayed on the screen. The two variables reference identical String objects, but not the same one. |
6 | |
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:"
GO TO FULL VERSION