0

Ok i need the string "H" to change to "KeyEvent.VK_+ (the string H thats entered)" And for some reason I can not get the variable to change from H to the new string in the main class. It does change in the other class though. Any help would be great.

Main Class

Convert ConvertObject = new Convert();
String word = "H"
ConvertObject.Convert(word);
System.out.println(word); // this keeps printing out H but it needs to print out  
                                                                 "KeyEvent.VK_H"

Convert Class

public static String Convert(String x) {
    x = "KeyEvent.VK_" + x;
    System.out.println(x);
    return x;
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
MahoreLee
  • 143
  • 1
  • 3
  • 12

2 Answers2

7

Since Java uses pass by value, any modification in the method is done to the local variable only. You need to save the result of the method to get the desired effect:

word = ConvertObject.Convert(word);
Keppil
  • 45,603
  • 8
  • 97
  • 119
0

Everything in Java is pass by value which means that a copy of the String is passed to your method and this is changed, not the original object in the Main class.

JamesB
  • 7,774
  • 2
  • 22
  • 21
  • To be precise: Not a copy of the String is passed to the method, but a copy of the reference to that String is passed to the method. That way you can change mutable objects in methods and the changes will persist after the method terminates. Strings are immutable, though. – jlordo May 11 '13 at 23:06