I have simple method doubleChar
that receives a String
, doubles each character and returns a String
. Then I have two invocations in main method. First straightforward invocation gives no result, but second invocation inside println
method gives the right string with doubled characters.
Can anyone explain how this works?
static String doubleChar(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
result = result + str.charAt(i) + str.charAt(i);
}
return result;
}
public static void main(String[] args) {
String dog = "Dog";
// 1st invocation
doubleChar(dog);
System.out.println(dog);//result is Dog
//2st invocation inside println
System.out.println(doubleChar(dog));//result is DDoogg
}