How + internally works on Strings in JAVA -


i read blogs internally java use stringbuilder concat string when use + operator. checking , found strange outputs.

public class stringdemo {      public static void main(string[] args) {          string = "hello world";         string b = "hello world";         string c = "hello";         string d =  c + " world".intern();         string e =  new stringbuilder().append(string.valueof(c)).append(" world").tostring().intern() ;         string f =  new stringbuilder(string.valueof(c)).append(" world").tostring().intern();          system.out.println(a == b);   // line 1 expected output true         system.out.println(a == d);   // line 2 output false         system.out.println(a == e);   // line 3 output true         system.out.println(a == f);   // line 4 output true      } } 

so using + operator concat 2 strings c & " world" , use intern() method move string in pool string d.

as per understanding java use stringbuilder, use stringbuilder concat string , use intern() method strings e , f. if both equivalent address of both string must same output of line 2 not matching line 4 & 5.

thanks in advance valuable feedback.

how + internally works in java

here post on same, give read compiler version : how string concatenation works in java.

and coming code inside

system.out.println(a == d);  

that should false only.

as per understanding expecting true. no. understanding wrong. there clear difference between

    string d =  c + " world".intern(); 

and

    string d =  (c + " world").intern(); 

in first line "world" got interned , second line "hello world" got interned

when (c + " world").intern(), you'll see output true.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -