-1

Please follow the code below:

String s="helloworld";
String ss="hello";
String sss=ss+"world";
System.out.print(sss==s);

The output is false. Don't they get checked with the string pool rule for String? And what if we make them final?

A little explanation of internal working will help. Thanks in Advance.

String literals points to the same location if the content of them is same, that's what I got from different sources, am I right? If yes, then what's happening here? I'm a little confused about it.

EDIT:-

I think I didn't phrase it correctly. Let me rephrase it a little(Sorry for earlier attempt):-

    String ss="hello";
    System.out.print(ss+"world"=="helloworld");

This returns false. However these are String literals and as I have read they don't create two different objects for same value. They are just reference to a same value. Here, "helloworld" is the value for both sides of ==. I hope that I'm able to communicate it well.

  • 1
    As a side note `String` values should always be compared using `.equals`. – lealceldeiro Oct 03 '18 at 17:03
  • 1
    No! author is thinking abot refference comparisoon. He states: "hellowwolrd" should be same instance with result of "hello"+"world" – Jacek Cz Oct 03 '18 at 17:07
  • 1
    "String literals points to the same location if the content of them is same" - sure, string *literals*, but `ss+"world"` isn't a string literal. – user2357112 Oct 03 '18 at 17:22

1 Answers1

0

Because String is an object, it is comparing that the two objects are the same with ==, which will equate to false.

Using the object ss to concat into sss will not make s = sss.

If you set ss to s, then using == will equate to true since they are now the same object.

If you set a second String object with a string literal, using == will equate the true.

If you use the String object's function .equals(String), you will find that it equates to true.

If you compare two string literals, i.e. "helloworld" == "helloworld" or "helloworld" == "hello" + "world", these will also equate to true.

As lealceldeiro pointed out, strings should always be compared with .equals().

EDIT

A good thing to look at is this answer. It has good references and explanation.

Other resources:

JournalDev

Baeldung

CodeMonkey
  • 1,136
  • 16
  • 31
  • No! Question is about refferences and string pool – Jacek Cz Oct 03 '18 at 17:08
  • But, String literals point to the same location if the contents are same. Don't they? – user4955530 Oct 03 '18 at 17:10
  • no. it is depend on JVM implementation. you can't say equal string because of performance, point to the same address. You can force it to use new address by something like this (depend on JVM): `System.out.println(new String("a") == new String("a")) – Amin Oct 03 '18 at 17:16