Why does this java string comparison prints false? -


this question has answer here:

i beginning learn java,so please pardon if question seems silly, going through online examples.

i found string question, should not output true ?

as comparing 2 strings equal.

public class helloworld{       public static void main(string []args)      {       string morning2 = new string("morning");       system.out.println("morning" == morning2);      } } 

similarly program, should not print true

public class helloworld{       public static void main(string []args)      {         string str1 = new string("paul");         string str2 = new string("paul");         system.out.println(str1 == str2);      } } 

but program, prints true.

public class helloworld{       public static void main(string []args)      {         string str3 = "harry";         string str4 = "harry";         system.out.println(str3 == str4);      } } 

can explain why there difference in output ?

i have seen question , answer how compare strings in java? not fit explanation.

the reason why 1st program

public class helloworld{       public static void main(string []args)      {       string morning2 = new string("morning");       system.out.println("morning" == morning2);      } } 

prints false because in these lines

string morning2 = new string("morning"); system.out.println("morning" == morning2); 

you creating different object(by new keyword) , comparing string, eventhough strings same, you here comparing 2 different objects.

thats how java allocates strings in string pool.

similary second program.

but 3rd program, happening is, when execute line

string str3 = "harry";

the string object harry allocated in string pool, when execute next line,

string str4 = "harry";

java searches if string objects available in string pool, since available not create new string object, , references object itself.

so true in 3rd program.

hope have cleared query.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -