Java passes parameter by values. In your case you just changed the value copy in the function.
If you need the behavior you want, you can either make the character a return value, as:
public char changeLetters(char letterFrom){
return 'D';
}
Or encapsulate the value in a class object and pass that object, like:
class Container {
public char letter;
}
public char changeLetters(Container letterFrom){
letterFrom.letter = 'D';
}
EDIT
I have to clarify the method using Character
class suggested by others are incorrect.
Just test below code, it will happily print a
instead of d
.
class a {
public static void changeLetter(Character ch) {
ch = 'D';
}
public static void main(String[] args) throws Exception {
Character d = 'a';
changeLetter(d);
System.out.println(d);
}
}
The reason is the same: because Java passes EVERYTHING by value. Even you used the Character
object to pass parameter, when you do assignment like ch = 'D'
, you are only changing the inside copy of the reference ch
.