InterviewSolution
Saved Bookmarks
| 1. |
Java equals() method vs == operator |
|
Answer» The equals() method and the == operator in JAVA are both used to find if TWO objects are equal. However, while equals() is a method, == is an operator. Also, equals() compares the object values while == checks if the objects point to the same memory location. A program that demonstrates the == operator is given as follows: public class DEMO { public static void main(String[] args) { System.out.println(67 == 67); System.out.println('u' == 'v'); System.out.println('A' == 65.0); System.out.println(false == true); } }The output of the above program is as follows: true false true falseA program that demonstrates the equals() method is given as follows: public class Demo { public static void main(String[] args) { String str1 = NEW String("apple"); String str2 = new String("apple"); String str3 = new String("mango"); System.out.println(str1.equals(str2)); System.out.println(str1.equals(str3)); } }The output of the above program is as follows: true false |
|