java - Can you explain the output of the following source code? -


as strings objects immutable in java how code output coming now heat, why not how neat? in advance.

class solution {    public static void main(string args[])     {         string[] words = {"how", "neat"};         twist(words);         system.out.println(words[0] + " " + words[1]);        }     public static void twist(string[] w)     {          string temp = w[0].substring(0, 1);          w[0] = w[1].substring(0, 1) + w[0].substring(1);          w[1] = temp + w[1].substring(1);     } } 

basically code doing is switching first characters of both first letters of each string. here step step explanation

  1. temp = 'h'
  2. w[0] = (temp + "ow")
  3. w[1] = heat (temp + "eat")

edit: duffymo said:

the array reference immutable, array points not. created new strings , made array point them.

this means everytime reassigned, created new string.


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -