-3

Okay, so I am trying to be able to explain the answer to the question below to a friend, but I don't know how. I know that the process method doesn't change s and that the answer is ABCD (s is unchanged), but I don't know why. Is it because strings are immutable? My friend thinks it should be CBA. Any help?

public void process(String s) 
{
    s = s.substring(2, 3) + s.substring(1, 2) + s.substring(0, 1);
}

What is printed as a result of executing the following statements (in a method in the same class)?

String s = “ABCD”;
process(s);
System.out.println(s);

2 Answers2

0

You are assigning a new value to the variable s. This does not change the value of s which is passed to the process() method, so the program prints

ABCD
cdbbnny
  • 330
  • 2
  • 9
0

that happens, because you are calling it by it's value, and it doesn't change

you can rewrite your method such as :

public static String process(String s) 
{
    return s.substring(2, 3) + s.substring(1, 2) + s.substring(0, 1);
}

and then you can use it like this :

String s = "ABCD";
s = process(s);
System.out.println(s);
Mohsen_Fatemi
  • 2,183
  • 2
  • 16
  • 25