String replace() returns extra space in Java

  • A+


System.out.println(new String(new char[10]).replace("/0", "hello")); 

has output:



System.out.println(new String(new char[10]).replace("", "hello"));  

has output:

hello hello hello hello hello hello hello hello hello hello 

Where is the extra space coming from?


It is not a space. It is how your IDE/console shows /0 character which new char[10] is filled with by default.

You are not replacing /0 with anything, so it stays in string. Instead with .replace("", "hello") you are replacing only empty string "". Important thing is that Java assumes that "" exists at:

  • start of the string,
  • end of string,
  • and between each of the characters

since we can get "abc" with:

"abc" = "" + "a" + "" + "b" + "" + "c" + ""`;       //^          ^          ^          ^ 

Now .replace("", "hello") replaces each of those "" with "hello", so for string of length 10 it will place additional 11 hellos (not 10), without modifying /0, which will be shown at your output like spaces.

Maybe this will be easier to grasp:

System.out.println("aaa".replace("", "X")); 
  • lets represent each "" with as |. We will get "|a|a|a|" (notice that there are 4 |)
  • so replacing "" with X will result in "XaXaXaX" (but in your case instead of a your console will print /0 using character which will look like space)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: