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;
1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 If String is mutable and has method such as setVlaue(newString), then that would work ;)
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.