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
}
I get doubled characters every time. I can prove it by running
jshell, which is a REPL provided with recent versions of Java:The reason you do not see doubled characters the first time is because you print out the variable, not the result:
One way to minimize errors like this is to annotate your output, like this:
Output is: