In Java, when we pass an object to a method, the object is passed by reference. This means that the method receives a reference to the object, and any changes made to the object inside the method are reflected in the original object outside of the method.
To illustrate this concept, let’s consider the following example:
public class PassByReferenceDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
changeString(sb);
System.out.println(sb); // prints "World"
}
public static void changeString(StringBuilder s) {
s.append(" World");
}
}
Output:
Hello World
In the main
method, we create a StringBuilder
object with the value “Hello” and pass it to the changeString
method. Inside the changeString
method, we modify the StringBuilder
object by appending the string ” World” to it.
After the changeString
method is called, if we print the value of the StringBuilder
object in the main
method, it will be “World”. This is because the object was passed by reference, and the changes made to it inside the changeString
method were reflected in the original object.
It’s important to note that this is only applicable to objects in Java. Primitive data types (such as int
, float
, etc.) are passed by value in Java, meaning that any changes made to the value inside a method will not be reflected in the original value outside of the method.
In summary, pass by reference in Java means that when an object is passed to a method, the method receives a reference to the object and any changes made to the object inside the method are reflected in the original object. This is in contrast to pass by value, where the value of a primitive data type is passed to a method and any changes made to the value inside the method are not reflected in the original value.
Leave a Reply