DifferenceModerate2 marks
State the difference between == operator and equals() method.
Topic: == operator and equals() method
Previous-year question practice database
Answer
Exam answer
The difference is shown in the table.
Explanation
The practical consequence is the point of the question: two Strings holding identical text may give false with == because they are different objects in memory, while equals() correctly gives true. The rule to carry away: ALWAYS compare Strings with equals() or equalsIgnoreCase(), never with ==. Use == only for primitives such as int and char.
Comparison
| == operator | equals() method |
|---|---|
| A relational operator; when used with objects it compares their memory addresses (references). | A method of the String class; it compares the actual contents of the two strings. |
| Returns true only if both references point to the SAME object. | Returns true whenever the characters match, whatever the objects. |
More from String Manipulation
To extract the word NOW from the word "ACKNOWLEDGEMENT", the Java statement "ACKNOWLEDGEMENT".substring(3, ____) is used. Choose the correct number to fill in the blank.2026String a[] = {"Atasi", "Aditi", "Anant", "Amit", "Ahana"};
System.out.println(a[1].charAt(1) + "*" + a[2].charAt(2));
The output of the above statement is:2026Which of the following String methods returns a negative value?2026Assertion (A): The substring() method modifies the original String.
Reason (R): The substring() method can extract part of a String starting from a specific index.2026Give the output of the following program segment:
String S = "GRACIOUS".substring(4);
System.out.println(S);
System.out.println("GLAMOROUS".endsWith(S));2026Name the following:
(a) The return data type of the method equals().
(b) The String method which has no parameter and returns a String.2026