Computer Science, asked by Prakriti1304, 1 year ago

What is the difference between 'equals()' function and 'compareTo()' function in java programming?

Answers

Answered by bhushan3542
1
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.If a class does not override the equals method, then by default it uses equals(Object o) method of the closest parent class that has overridden this method. See this for detailCoding Example:// Java program to understand // the concept of == operatorpublic class Test {    public static void main(String[] args)    {        String s1 = new String("HELLO");        String s2 = new String("HELLO");        System.out.println(s1 == s2);        System.out.println(s1.equals(s2));    }}
Similar questions