Difference between comparing String using == and .equals() method in JavaWhen comparing strings in Java, it is important to understand the difference between the == operator and the .equals() method. In Java, a string is an object, and comparing objects requires considering whether you want to compare their references (memory addresses) or their actual contents. The == operator checks for reference equality. It compares the memory addresses of two string objects to determine if they refer to the same location in memory. If two string objects reference the same memory address, == will return true, indicating that the objects are equal. The .equals() method in Java is used to compare the actual content of two string objects, focusing on the sequence of characters they contain, rather than considering other factors like references or memory addresses. It checks if the characters in both strings are the same. If the content of the strings is identical, .equals() will return true, indicating that the objects are equal.
Filename: StringComparisonExample.java Output: true false true true Equality operator(==)When used to compare strings, the equality operator compares the references (memory addresses) of the string objects rather than their contents. It determines whether two string objects refer to the exact same memory location. It returns true if the references are identical, meaning they point to the same memory address, and false if they do not. It is primarily used to compare primitive types and object references. Filename: EqualityOperatorExample.java Output: true false true .equals() MethodThe .equals() method in Java is defined in the Object class, which is the root class for all objects in Java. It compares the content (values) of two objects for equality. The primary purpose of the .equals() method is to determine if two objects are meaningfully equivalent based on their internal state. Filename: EqualsMethodExample.java Output: true true false false Difference between comparing String using == and .equals() method Table
|
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India