5
Variables passed in Java
String
Reference
Java / C++
Pass-by-value
Variables

One of the most simple yet confusing sometimes in programming world is when we deal with Strings. The below code fragment makes the comment much more interesting

public static void main(String[] args) {
    String x = new String("ab");
    myMethod(x);
    System.out.println("Value in main " + x);
}

public static void myMethod(String x) {
    x = "cd";
        System.out.println("Value in myMethod " + x);
}

Output:

Value in myMethod cd

Value in main ab

It creates a new String and stores it in the local variable 'x'. The reference outside the method is not changed by this.

The key point here is that:

In Java, all method arguments are passed by value.

Methods have a local stack where all their data is stored, including the method arguments.

When we assign a new object to a variable that was passed into a method, we are only replacing the address in the local stack, with the address of the new object created unless we are returning from the method. The actual object address outside of the method remains the same.

String:Java pass by value

So in the the above case,when the string "ab" is created, Java allocates the amount of memory required to store the string object. Then, the object is assigned to variable x, the variable is actually assigned a reference to the object. This reference is the address of the memory location where the object is stored.

The variable x contains a reference to the string object. x is not a reference itself. It is just a variable that stores a reference(memory address). Since,Java is pass-by-value.So when x is passed to the myMethod() method, a copy of value of x (a reference) is passed. The method myMethod() creates another object "cd" and it has a different reference. It is the variable x that changes its reference(to "cd"), not the reference itself.

Author

Notifications

?