• Register
1 vote
31 views

Problem:

Hello, the good people of Kodlogs,

I am struggling with confusion for the last hour. What is the basic and main difference between the (==) and .equal() in java? Can I use the operator == to check whether two variables refer to the same array? If it is possible, please give me an example. Both usages of them are much appreciated in a single program.

Thanks.

12 7 7
15,250 points

1 Answer

1 vote
 
Best answer

Solution:

Hello Gavin,

Let’s understand what is the == operator and .equal() in java first. Generally, both the == and .equal() use for comparison of objects equality, but they still have some differences. The very first inequality of them is, the == is an operator and the .equal() is a function. The .equal() function is used for the comparison of the values of the object, but the other one is used for checking the memory location of both objects.

Let’s write a code using both the operator and function in a single program as you requested above:

public class TestClass { 
    public static void main(String[] args) 
    { 
        String str1 = new String("I am Gavin"); 
        String str2 = new String("I am Gavin"); 
        System.out.println(str1 == str2); 
        System.out.println(str1.equals(str2)); 
    } 
}

This program will produce the output :

false
true

Because we created two string object str1 and str2 assigned both of them with the same value. As we know the == operator checks the memory location of two objects and .equals() check the values of two objects.

 

I hope you get the point. Thanks. Keep coding.

13 9 6
94,240 points

Related questions

0 votes
1 answer 13 views
13 views
Explain in context of strings in Java?
asked Sep 20 jagruthi 560 points
0 votes
1 answer 10 views
0 votes
1 answer 7 views
7 views
What is the difference between servlets and rest services in Java ?
asked Sep 16 rm02 310 points
1 vote
2 answers 23 views
0 votes
1 answer 4 views
4 views
What is the difference between this and super keyword in java?
asked Oct 11 sikandar 2.4k points