Passing Strings By Reference in Java
Last Updated :
14 May, 2023
In Java, variables of primitive data types, such as int, char, float, etc., are passed by value, meaning that a copy of the variable’s value is passed to a method or function. However, when it comes to passing objects, including Strings, the concept of passing by reference versus passing by value can be confusing. In this blog post, we will explore the concept of passing Strings by reference in Java, and provide a clear understanding of how it works.
Passing by Reference vs Passing by Value
Before diving into the details of passing Strings by reference in Java, let’s first understand the basic concepts of passing by reference and passing by value.
Passing by Value
When a variable of a primitive data type is passed as an argument to a method or function, a copy of the variable’s value is passed. Any changes made to the parameter within the method or function have no effect on the original variable outside the method or function.
Passing by Reference
When an object, including Strings, is passed as an argument to a method or function, the reference to the memory location of the object is passed, rather than a copy of the object itself. This means that any changes made to the object within the method or function are reflected in the original object outside the method or function.
Understanding String as an Object in Java
In Java, unlike primitive data types, String is not a primitive data type but rather an object. String objects are instances of the String class, which is a part of the Java standard library. This means that when you create a String variable, you are actually creating an object that represents a sequence of characters.
Now, let’s see how passing Strings by reference works in Java:
Example
Consider the following example:
Java
import java.io.*;
class GFG {
public static void main(String[] args){
String str = "Hello" ;
System.out.println( "Before calling modifyString() method: " + str);
modifyString(str);
System.out.println( "After calling modifyString() method: " + str);
}
public static void modifyString(String s) {
s += " World!" ;
System.out.println( "Inside modifyString() method: " + s);
}
}
|
Output
Before calling modifyString() method: Hello
Inside modifyString() method: Hello World!
After calling modifyString() method: Hello
Explanation
In the above example, we have a main() method that creates a String variable str with the value “Hello”. We then pass this String variable to the modifyString() method. Inside the modifyString() method, we concatenate ” World!” to the original String using the += operator, and print the modified String. However, when we print the value of str again in the main() method after calling the modifyString() method, we see that the original String “Hello” remains unchanged.
This is because, in Java, Strings are immutable, meaning that their values cannot be changed after they are created. When we pass a String to a method or function, a new String object is created with the same value, and any changes made to the parameter within the method or function have no effect on the original String object outside the method or function. In other words, although we passed the String by reference, the reference itself is passed by value, and the original String object remains unchanged.
Workaround to Pass String by “Reference” in Java
If you really need to modify the original String object inside a method or function, there is a workaround you can use. Instead of using the += operator, which creates a new String object, you can use the StringBuilder or StringBuffer class, which are mutable classes in Java, to modify the original String object. Here’s an example:
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
StringBuilder sb = new StringBuilder( "Hello" );
System.out.println( "Before calling modifyString() method: " + sb.toString());
modifyString(sb);
System.out.println( "After calling modifyString() method: " + sb.toString());
}
public static void modifyString(StringBuilder sb) {
sb.append( " World!" );
System.out.println( "Inside modifyString() method: " + sb.toString());
}
}
|
Output
Before calling modifyString() method: Hello
Inside modifyString() method: Hello World!
After calling modifyString() method: Hello World!
Explanation
In this example, we replaced the String parameter with a StringBuilder object in both the main() method and the modifyString() method. StringBuilder is a mutable class in Java, so when we modify the StringBuilder object inside the modifyString() method by calling the append() method, it directly modifies the original object. As a result, the change is reflected in the StringBuilder object outside the method, and the final output shows the modified String “Hello World!”.
Conclusion
In Java, String objects are passed by reference, meaning that the reference to the memory location of the object is passed. However, due to the immutability of Strings, any changes made to the parameter within a method or function do not affect the original String object outside the method or function. To modify the original String object, you can use mutable classes like StringBuilder or StringBuffer. It’s important to understand this concept to avoid confusion and ensure correct behavior when passing Strings in Java.
Similar Reads
How to pass integer by reference in Java
Java is pass by value and it is not possible to pass integer by reference in Java directly. Objects created in Java are references which are passed by value. Thus it can be achieved by some methods which are as follows: By creating Wrapper Class: As we know that Integer is an immutable class, so we
4 min read
Types of References in Java
In Java there are four types of references differentiated on the way by which they are garbage collected. Strong References Weak References Soft References Phantom References Prerequisite: Garbage Collection Strong References: This is the default type/class of Reference Object. Any object which has
4 min read
Passing and Returning Objects in Java
Although Java is strictly passed by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are pass
6 min read
C/C++ Pointers vs Java References
Java doesn't have pointers; Java has references. Reference: A reference is a variable that refers to something else and can be used as an alias for that something else. Pointer: A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at that addr
5 min read
Different Ways to Achieve Pass By Reference in Java
There are two types of parameters one is Formal parameters and the second is Actual Parameters. Formal parameters are those parameters that are defined during function definition and Actual parameters are those which are passed during the function call in other Function. Showcasing the formal and ac
5 min read
How to Pass a String to a Function using Call by Reference?
Passing a string by reference in various programming languages involves using specific mechanisms or constructs to allow the function to modify the original string directly, rather than working with a copy. Here, I'll explain how to achieve this in C++, C#, Python, and JavaScript. Table of Content H
4 min read
java.lang.ref.Reference Class in Java
java.lang.ref.Reference Class is an abstract base class for reference object. This class contains methods used to get information about the reference objects. This class is not a direct subclass because the operations on the reference objects are in close co-operation with the garbage collector. Cla
3 min read
Java is Strictly Pass by Value!
In order to understand more of how the java is processing the parameter in methods and functions, lets compare the java program with a C++ code which would make it more clear and helps you get the major difference between how the parameters are being passed to any methods or functions wrt passing pa
6 min read
Message Passing in Java
What is message passing and why it is used? Message Passing in terms of computers is communication between processes. It is a form of communication used in object-oriented programming as well as parallel programming. Message passing in Java is like sending an object i.e. message from one thread to a
3 min read
java.lang.ref.WeakReference Class In Java
When we create an object in Java, an object isn't weak by default. To create a Weak Reference Object, we must explicitly specify this to the JVM. Why Weak Reference Objects are used: Unlike C/C++, Java supports Dynamic Garbage Collection. This is performed when the JVM runs the Garbage Collector. In
3 min read