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
temp
= 'h'w[0]
= (temp + "ow")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
Post a Comment