Printing String with an edited character using array of char instead of creating a new String object

Viewed 84

The objective of this code is to change the String "A Happy" to "A Hippy".

String originalStr = "A Happy";
char[] charOriStr = originalStr.toCharArray();
charOriStr[3] = 'i'; //simplified code, we are supposed to loop through the String

To print the revised String, I use:

System.out.println(charOriStr);

However the recommended solution is as below:

String revised = new String(charOriStr);
System.out.println(revised);

I'm a beginner and I'm not sure if I should follow the recommended solution as a best practice guideline? Appreciate some guidance on this, thank you.

3 Answers
Related