Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could I change the reference inside one method with this reference as argument in Java?

private static void changeString(String s) {
    s = new String("new string");
}

public static void main(String[] args) {
    String s = new String("old string");
    changeString(s);
    System.out.println(s); // expect "new string"
}

How could I make the output of "new string" happen with s as the only argument to method changeString?

thanks.

like image 943
Jichao Avatar asked Dec 22 '09 14:12

Jichao


People also ask

Can we change argument of main method in Java?

Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args) . You can only change the name of String array argument, for example you can change args to myStringArgs .

How can we pass argument to the method by reference in Java?

In order to pass the reference, we pass the object of the class in the place of the actual parameter and the formal parameter of a class object type has the same reference to each other that's why with the help of the formal parameter object of class any changes will be reflected in both objects formal and actual ...

How do you change the value of an argument in Java?

Pass-by-value means that when you call a method, a copy of each actual parameter (argument) is passed. You can change that copy inside the method, but this will have no effect on the actual parameter. Unlike many other languages, Java has no mechanism to change the value of an actual parameter.

Do arguments in Java get passed by reference or by value?

Arguments in Java are always passed-by-value. During method invocation, a copy of each argument, whether its a value or reference, is created in stack memory which is then passed to the method.


1 Answers

In Java arguments are passed by value, object arguments pass a reference to the object, this means that you can change the reference of the argument, but that does not change the object you passed the reference to. You have two possibilities, return the new object (preferred) or pass reference to a container that can receive the new reference (collection, array, etc.) For example:

private static String changeStringAndReturn(String s) {
    return new String("new string");
}
private static void changeStringInArray(String[] s) {
    if (null != s && 0 < s.length) {
        s[0] = new String("new string");
    }
}
like image 176
rsp Avatar answered Nov 15 '22 22:11

rsp