top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How == works in java?

+4 votes
169 views

When I am creating String s="hello"; and String s1=new String("hello"); hashcode for s and s1 are same but when == than value become false. Please explain?

posted Mar 22, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

In this code segment whenever

String s1= new String("Hello");

This statement creates a String object in the Heap Memory.

String s= "Hello";

This statement creates a String literal with value "Hello" in the String Pool. when

String s1 = "Hello";
String s= new String("Hello");

Since s1 and s are reference variables, they would be pointing at their respective memory locations so s1 points to String Pool's location and s points to Heap Memory location. Now testing if they're equal:

if(s == s1) 

would return false, as the reference variables are checked. Where as

s.equals(s1) 

will return true as equals function checks the individual characters in both the reference variables.

answer Feb 13, 2016 by Shivam Kumar Pandey
Similar Questions
+4 votes

We pass the argument to inbuilt method then how its internally works?

ex : if we pass large no of character array to subString() method then how this method store this long size character aaray? in this case memory leakage problem occurred?

+2 votes

Can someone explain in detail how race condition works in Java hashmap?

...