Recent Posts

All Posts →

Java Autoboxing: How It Compiles and How the Integer Cache Works

How javac compiles autoboxing into Integer.valueOf() and intValue() calls, checked in JDK 25 bytecode, plus the -128 to 127 IntegerCache, JLS 5.1.7, -XX:AutoBoxCacheMax, boxing costs in loops, and what changed from JDK 5 to JDK 25.

When you mix int and java.lang.Integer, the JDK’s javac inserts the boxing and unboxing code for you. Knowing which method calls that code turns into lets you predict the result of an == comparison and the cost of creating objects in a loop.

The way javac translates boxing has not changed since autoboxing arrived in JDK 5, but the cache implementation and the deprecation status of the wrapper constructors have changed from version to version. I checked the bytecode and the run results in this article on JDK 25 (Temurin 25+36).

Bytecode Generated for Boxing and Unboxing

The code below assigns between int and Integer in both directions and compares them with ==.

Boxing.java
public class Boxing {
    public static void main(String[] args) {
        int a = 1;
        Integer b = 1;
        int c = b;
        System.out.println(a == b);
        System.out.println(a == c);
    }
}

Running javap -c Boxing.class with the javap tool included in the JDK prints the following bytecode.

javap -c Boxing.class
  public static void main(java.lang.String[]);
    Code:
         0: iconst_1
         1: istore_1
         2: iconst_1
         3: invokestatic  #7    // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
         6: astore_2
         7: aload_2
         8: invokevirtual #13   // Method java/lang/Integer.intValue:()I
        11: istore_3
        12: getstatic     #17   // Field java/lang/System.out:Ljava/io/PrintStream;
        15: iload_1
        16: aload_2
        17: invokevirtual #13   // Method java/lang/Integer.intValue:()I
        20: if_icmpne     27
        ...

There is no bytecode instruction dedicated to boxing or unboxing. The JDK’s javac compiles a conversion from int to Integer into a call to Integer.valueOf(), and a conversion from Integer to int into a call to intValue().

When one side of == is an int and the other is an Integer, as in a == b, the Integer side is unboxed and the comparison is by value (if_icmpne). When both sides are Integer, no unboxing happens and the comparison is by reference (if_acmpne), so the result depends on the cache range covered in the next section.

Decompiling shows the result of the conversion as Java code. However, modern decompilers restore valueOf() and intValue() calls to autoboxing syntax and show code almost identical to the source. In CFR, the --sugarboxing false option turns off this restoration and shows the method calls as they are.

java -jar cfr-0.152.jar --sugarboxing false Boxing.class
public class Boxing {
    public static void main(String[] stringArray) {
        int n = 1;
        Integer n2 = Integer.valueOf((int)1);
        int n3 = n2.intValue();
        System.out.println((n == n2.intValue() ? 1 : 0) != 0);
        System.out.println((n == n3 ? 1 : 0) != 0);
    }
}

The casts that were not in the source, such as (int) in Integer.valueOf((int)1), and expressions such as (... ? 1 : 0) != 0 come from the decompiler. Bytecode has no instructions that operate only on boolean values, so javac produces the result of a comparison with an if_icmpne branch and the integers 0 and 1. The decompiler carries that flow over and shows it in this form. The lines to look at are the two assignments. Integer n2 receives the return value of Integer.valueOf(), and int n3 receives the return value of intValue().

Without the --sugarboxing option, the output matches the original source apart from the variable names, as shown below. Decompiled output alone therefore cannot tell you the cost of boxing.

java -jar cfr-0.152.jar Boxing.class
public class Boxing {
    public static void main(String[] stringArray) {
        int n = 1;
        Integer n2 = 1;
        int n3 = n2;
        System.out.println(n == n2);
        System.out.println(n == n3);
    }
}

Integer.valueOf() Cache and Reference Comparison

The new Integer(int) constructor creates a new object every time, but Integer.valueOf() can reuse cached instances. In JDK 25, java.lang.Integer keeps the instances from -128 to 127 in IntegerCache.

java/lang/Integer.java (JDK 25)
    private static final class IntegerCache {
        static final int low = -128;
        static final int high;

        @Stable
        static final Integer[] cache;
        static Integer[] archivedCache;

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            ...
        }
    }

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

The default upper bound of the cache is 127, and it can be raised through a saved property that the VM keeps separately. When a CDS (Class Data Sharing) archive is available, the archived array is loaded. If there is no archive, or the archive is smaller than the requested cache size, the whole cache or the missing part is built at run time.

The Java Language Specification (JLS) does not require an implementation called IntegerCache. JLS 5.1.7 specifies that when the value being boxed comes from a constant expression, the results of two boxing conversions must be the same reference under the conditions below. The JDK meets this requirement with the cache. Separately, the API contract of Integer.valueOf(int) guarantees that -128 to 127 are always cached, whether or not the argument is a constant expression.

If the value p being boxed is the result of evaluating a constant expression of type boolean, byte, char, short, int, or long, and the result is true, false, a character in the range '\u0000' to '\u007f' inclusive, or an integer in the range -128 to 127 inclusive, then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

— Java Language Specification
5.1.7. Boxing Conversion

Because of the cache range, the result of the code below depends on the size of the value.

Identity.java
public class Identity {
    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        Integer c = 128;
        Integer d = 128;
        System.out.println("a == b : " + (a == b));
        System.out.println("c == d : " + (c == d));
        System.out.println("c.equals(d) : " + c.equals(d));
    }
}
Output of Identity
a == b : true
c == d : false
c.equals(d) : true

With the default settings, 128 is outside the cache range, so each boxing creates a new Integer. That makes c == d false. This is why boxed types must be compared with equals() rather than ==.

The cache range differs by type. As of JDK 25, Long, Short, and Byte cache -128 to 127, and Character caches '\u0000' through '\u007f'. Boolean reuses Boolean.TRUE and Boolean.FALSE.

Adjusting the Cache Range with -XX:AutoBoxCacheMax

For Integer, the HotSpot option -XX:AutoBoxCacheMax=<max> raises the upper bound of the cache. This option is available in HotSpot builds that include the C2 compiler. Running the earlier example again with the same class file changes the result.

Running Identity with and without -XX:AutoBoxCacheMax
$ java Identity
a == b : true
c == d : false
c.equals(d) : true

$ java -XX:AutoBoxCacheMax=1000 Identity
a == b : true
c == d : true
c.equals(d) : true

The same code gives a different == result depending on a runtime option, which is another reason not to compare boxed types with ==. This option applies only to Integer and has no effect on Long or Short.

In the OpenJDK implementation, -Djava.lang.Integer.IntegerCache.high=<max> has the same effect, but this value is a saved property kept by the VM, not a public system property that System.getProperty() can read. It is therefore safer to use the -XX:AutoBoxCacheMax option than to depend on this name. If you specify both, the VM overwrites this property with the -XX:AutoBoxCacheMax value, so the -XX option wins.

Wrapper Constructors Deprecated Since JDK 9

new Integer(int) has carried @Deprecated since JDK 9. Before that, javac did not warn about this code. You could find it only with a static analyzer such as FindBugs or with IntelliJ IDEA inspections. With the FindBugs plugin installed in Eclipse, the Problems view showed a warning like the following.

FindBugs warning in the Eclipse Problems view
M P Bx: Method study.Test.testInteger() invokes inefficient new Integer(int) constructor;
        use Integer.valueOf(int) instead

Today javac tells you itself. With the -Xlint:deprecation option, it also reports the location.

javac warnings with -Xlint:deprecation
$ javac -Xlint:deprecation OldStyle.java
OldStyle.java:3: warning: [deprecation] Integer(int) in Integer has been deprecated
        Integer c = new Integer(1);
                    ^
OldStyle.java:4: warning: [deprecation] Double(double) in Double has been deprecated
        Double d = new Double(1.0);
                   ^
2 warnings

The JDK 25 source carries @Deprecated(since="9"). There is no forRemoval, so this API is not scheduled for removal, but there is no reason to use it in new code.

java/lang/Integer.java (JDK 25)
    /**
     * @deprecated
     * It is rarely appropriate to use this constructor. The static factory
     * {@link #valueOf(int)} is generally a better choice, as it is
     * likely to yield significantly better space and time performance.
     */
    @Deprecated(since="9")
    public Integer(int value) {

SpotBugs, the successor to FindBugs, keeps the same rule as DM_NUMBER_CTOR. Its description is almost the same as in the FindBugs days.

Using new Integer(int) is guaranteed to always result in a new object whereas Integer.valueOf(int) allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster.

Values between -128 and 127 are guaranteed to have corresponding cached instances and using valueOf is approximately 3.5 times faster than using constructor. For values outside the constant range the performance of both styles is the same.

Unless the class must be compatible with JVMs predating Java 5, use either autoboxing or the valueOf() method when creating instances of Long, Integer, Short, Character, and Byte.

— SpotBugs
DM_NUMBER_CTOR: Method invokes inefficient Number constructor; use static valueOf instead

However, the figure of "approximately 3.5 times" in the quote and the statement that performance is the same outside the cache range are not guarantees of the Java API. The actual difference can vary with an extended cache range, just-in-time (JIT) optimization, and the runtime environment.

Built-in IDE checks can also find this code. In Eclipse, the "Deprecated API" item under "Deprecated and restricted API" in Java > Compiler > Errors/Warnings defaults to Warning, so Eclipse shows deprecation warnings without a plugin. IntelliJ IDEA has the inspection "Number constructor call with primitive argument" (CachedNumberConstructorCall) in the Java > Numeric issues group. It finds code that passes a primitive value to a Long, Integer, Short, or Byte constructor and suggests replacing it with valueOf(). By default the option "Report only when constructor is @Deprecated" is on, so it reports only on JDK 9 and later, where the constructors are deprecated.

Cost of Boxed Types in Loops

Once you know that boxing and unboxing compile to method calls, you can also predict what happens when a boxed type is the accumulator in a loop. The following example is adapted to this article’s measurement code from Item 6 of Effective Java, 3rd edition, "Avoid creating unnecessary objects."

Boxed accumulator in a loop
static long boxed() {
    Long sum = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
        sum += i;
    }
    return sum;
}

The single line sum += i compiles to code that goes through both unboxing and boxing. Decompiling shows that this line has turned into longValue() and Long.valueOf() calls.

java -jar cfr-0.152.jar --sugarboxing false SumTest.class
    static long boxed() {
        Long l = Long.valueOf((long)0L);
        for (long i = 0L; i < Integer.MAX_VALUE; ++i) {
            l = Long.valueOf((long)(l.longValue() + i));
        }
        return l.longValue();
    }

The bytecode shows the same flow.

javap -c SumTest.class
  static long boxed();
    Code:
         0: lconst_0
         1: invokestatic  #7    // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
         4: astore_0
         5: lconst_0
         6: lstore_1
         7: lload_1
         8: ldc2_w        #15   // long 2147483647l
        11: lcmp
        12: ifge          32
        15: aload_0
        16: invokevirtual #17   // Method java/lang/Long.longValue:()J
        19: lload_1
        20: ladd
        21: invokestatic  #7    // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
        24: astore_0
        25: lload_1
        26: lconst_1
        27: ladd
        28: lstore_1
        29: goto          7

Each iteration extracts the value with longValue(), adds to it, and boxes the result again with Long.valueOf(). Once the accumulated value exceeds 127, Long.valueOf() returns a new Long instance. The actual object allocation may still be removed by JIT optimization.

Changing only the accumulator’s type to long removes the boxing. I ran a program that times each version once three times on JDK 25, and the difference was about tenfold.

Three runs on JDK 25
Long: 5122 ms, long: 507 ms
Long: 4987 ms, long: 516 ms
Long: 4919 ms, long: 513 ms

These values come from single System.nanoTime() measurements in each run, not from a benchmark tool such as JMH (Java Microbenchmark Harness), so the absolute numbers should not be taken at face value.

Double and Float Without a Cache

Unlike the integer types, Double and Float have no cache. JLS 5.1.7 does not require reference identity for float and double either. In JDK 25, Double.valueOf() still just calls the constructor.

java/lang/Double.java (JDK 25)
    public static Double valueOf(double d) {
        return new Double(d);
    }

Double.valueOf() in JDK 25 therefore does not return a cached instance, even for small values. Values from -128 to 127, which an integer type would cache, become a new object at every boxing.

Changes by JDK Version

The way javac compiles boxing and unboxing into valueOf() and intValue() calls has not changed since JDK 5. What has changed, as the table below shows, is the cache implementation, the deprecation status of the constructors, and the range guaranteed by the language specification.

JDK Version Change

JDK 5

Autoboxing and unboxing introduced. Factory methods such as valueOf(int) added, and -128 to 127 cached from the start

JDK 7

IntegerCache changed to read the java.lang.Integer.IntegerCache.high value passed by the HotSpot -XX:AutoBoxCacheMax option and use it as the cache upper bound (JDK-6807702)

JDK 9

@Deprecated(since="9") added to the wrapper class constructors. The reference identity condition in JLS 5.1.7 changed from the "literals" of SE 8 to "the result of evaluating a constant expression," and long joined the covered types

JDK 12

IntegerCache and the other box caches stored in the CDS archive and loaded from it at run time when the archive is available (JDK-8209120, JDK-8213033)

JDK 14

byte restored to the list of types covered by the reference identity guarantee in JLS 5.1.7 (present in SE 7, missing from SE 8 through 13)

JDK 16

Wrapper classes designated as value-based classes by JEP 390, and their constructors marked forRemoval = true

JDK 22

@Stable added to the box cache arrays so that the JIT compiler can constant-fold them (JDK-8295555)

JDK 25

forRemoval mark removed from the constructors, returning them to ordinary deprecated status (JDK-8354335)

The JDK versions in this table are those of the first integration into OpenJDK mainline. The IntegerCache upper bound setting (JDK-6807702) was backported to 6u14, the CDS archiving (JDK-8209120) to 11.0.6, and the @Stable change to the box caches (JDK-8295555) to 21.0.2.

From JDK 16 through JDK 24, while forRemoval was set, compiling without any option produced a removal warning. Compiling the same code on JDK 21 and JDK 25 shows the difference.

OldStyle.java compiled with JDK 21 and JDK 25
$ ~/.sdkman/candidates/java/21.0.8-tem/bin/javac OldStyle.java
OldStyle.java:3: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
        Integer c = new Integer(1);
                    ^
OldStyle.java:4: warning: [removal] Double(double) in Double has been deprecated and marked for removal
        Double d = new Double(1.0);
                   ^
2 warnings

$ ~/.sdkman/candidates/java/25-tem/bin/javac OldStyle.java
Note: OldStyle.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

The wording of JLS 5.1.7 also differed between editions. The third edition of the JLS (Java 5 and 6) and Java SE 7 stated, regardless of whether the value was a literal, that boxing true, false, a byte value, a char value from '\u0000' to '\u007f', or an int or short value from -128 to 127 yields the same reference. Java SE 8 narrowed the wording to literals.

If the value p being boxed is an integer literal of type int between -128 and 127 inclusive, or the boolean literal true or false, or a character literal between '\u0000' and '\u007f' inclusive, then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

— Java Language Specification SE 8
5.1.7. Boxing Conversion

Java SE 9 changed the condition to the result of evaluating a constant expression and added long to the covered types. A constant expression that is not a literal, such as the one in Integer x = 100 + 27;, is covered in SE 9, unlike in SE 8. The JDK implementation has cached -128 to 127 in valueOf() since JDK 5, so the actual behavior was the same under every edition’s wording.

Summary

  • The JDK’s javac compiles autoboxing into valueOf() calls and unboxing into calls from the intValue() family. No dedicated bytecode instruction exists.

  • Integer.valueOf() always caches -128 to 127, and JLS 5.1.7 requires boxing a constant expression in this range to yield the same reference. For Integer only, -XX:AutoBoxCacheMax can raise the upper bound of the cache.

  • Compare boxed types with equals(), not ==. The result of == depends on the size of the value and on runtime options.

  • Wrapper class constructors have been deprecated since JDK 9. Through JDK 8, javac gave no warning and you had to rely on FindBugs or IDE checks. Today javac reports the deprecation, and Eclipse and IntelliJ IDEA warn with their default settings.

  • Use primitive types where possible, and use boxed types only where an object is required, such as Collection elements or generic type arguments (Effective Java, 3rd edition, Item 61, "Prefer primitive types to boxed primitives").

How Java Optimizes String Concatenation

How javac and the JDK runtime optimize String concatenation with + across versions: StringBuffer in JDK 1.4, StringBuilder in JDK 5, invokedynamic in JDK 9, and hidden classes in JDK 24, with bytecode checked on JDK 25.

The compiler and the JVM optimize code that joins Strings with the + operator. Up to JDK 1.4, javac translated it at compile time into code that uses StringBuffer. From JDK 5 through JDK 8, it used StringBuilder instead. Since JDK 9, javac emits an invokedynamic instruction by default, and the actual concatenation code is linked at run time. Knowing which cases are optimized automatically gives you a clear rule: keep using + outside loops, and write a StringBuilder yourself only when you accumulate a string inside a loop.

The Java Language Specification defines the result and the evaluation order of string concatenation, but leaves the implementation to the compiler. The version boundaries in this article therefore refer to the default bytecode of the JDK javac and to the OpenJDK runtime implementation. [1]

Concatenation of Compile-Time Constant Expressions

A compile-time constant expression of type String is evaluated at compile time into a single string. That string is registered in the string pool and shared, as if String.intern() had been called on it. String.intern() returns the canonical reference in the string pool for a given content. The heap may hold several String instances with the same content, but the string pool registers only one representative instance per content, and the canonical reference points to that instance. Interning two strings with the same content therefore yields the same instance. This does not mean that every String object on the heap with the same content is merged into the pool automatically. Besides string literals, such constant expressions can include primitive literals and constant variables (for example, SIZE declared as static final int SIZE = 10;). [2] For example, the two declarations below compile to the same code.

Two declarations that compile to the same constant
String str1 = "It's" + " a string" + "....";
String str2 = "It's a string....";

This rule is the same in every JDK version this article covers. The JDK 25 bytecode shown later also has both variables load the same constant pool entry (ldc #7). Because the two variables refer to the same instance in the string pool, str1 == str2 is true, not just equals(). The result of a non-constant concatenation, on the other hand, is a new String that is not interned automatically. Comparing it with == against a literal or a separately created string with the same content gives false.

StringBuffer and StringBuilder for Concatenation with Variables

When you compile an expression that mixes constants and String variables with javac up to JDK 8, it becomes calls to the append() and toString() methods of StringBuffer or StringBuilder. The JDK 1.4 javac used StringBuffer. The StringBuffer javadoc of CLDC 1.1, a Java ME document from the same period, describes how compilers of that time translated the operator.

String buffers are used by the compiler to implement the binary string concatenation operator. For example, the code: x = "a" + 4 + "c" is compiled to the equivalent of: x = new StringBuffer().append("a").append(4).append("c").toString() which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.

From JDK 5 through JDK 8, javac uses StringBuilder instead of StringBuffer. The methods of StringBuilder are not synchronized, so each append() call does not take a lock. You can confirm this in the bytecode or in decompiled output. Take the following source.

Source with constant and variable concatenation
String str0 = "It's a string....";
String str1 = "It's" + " a string" + "....";
String str2 = "It's a string...." + str0 + "000";
str2 = str0 + str1 + "1111" ;
str2 = str2 + "1111";
str2 += "1111";
for (int i=0;i<10;i++){
    str2 = str2 + "1111";
    str2 += "1111";
}

Compiling it with javac from JDK 5 to JDK 8 and decompiling the class gives the following result.

Decompiled output of a class compiled with javac from JDK 5 to JDK 8
String str0 = "It's a string....";
String str1 = "It's a string....";
String str2 = (new StringBuilder("It's a string....")).append(str0).append("000").toString();
str2 = (new StringBuilder(String.valueOf(str0))).append(str1).append("1111").toString();
str2 = (new StringBuilder(String.valueOf(str2))).append("1111").toString();
str2 = (new StringBuilder(String.valueOf(str2))).append("1111").toString();
for(int i = 0; i < 10; i++) {
    str2 = (new StringBuilder(String.valueOf(str2))).append("1111").toString();
    str2 = (new StringBuilder(String.valueOf(str2))).append("1111").toString();
}
Note

Depending on its options, a decompiler may reconstruct something close to the original source, so the + operators appear unchanged. The CFR decompiler is one example. The javap -c command shows the bytecode accurately.

String Concatenation Accumulated in a Loop

The loop is the part of the decompiled output that deserves attention. The bytecode creates a new StringBuilder on every iteration and calls toString() to produce the String passed to the next iteration. The HotSpot C2 JIT compiler has the OptimizeStringConcat optimization, enabled by default, which recognizes chains of append() and toString() calls and can eliminate the heap allocation of this temporary StringBuilder. The number of new instructions in the bytecode is therefore not always the number of objects actually allocated. The other problem remains, though: each iteration copies the ever-growing previous result into the new one.

So when a performance-sensitive loop accumulates many strings, use a single StringBuilder directly instead of +. If you append a fixed-length string repeatedly, the total amount copied by the + approach grows with the square of the iteration count, while StringBuilder reuses its internal buffer. With a small count such as 100 iterations, the difference is small (see the measurements below), so you can pick whichever reads better. [3]

Accumulating with a single StringBuilder
StringBuilder sb = new StringBuilder(str2);
for (int i = 0; i < 10; i++) {
    sb.append("1111");
}
str2 = sb.toString();

I measured the difference between the two approaches on JDK 25 (Temurin 25+36). The code appends a 4-character string n times. After 200 warm-up runs for the JIT, I ran each condition 20 times (5 times for 100,000 iterations) and recorded the shortest time. The benchmark code is in examples/string-concat. [4]

Iterations + concatenation StringBuilder used directly Ratio

100

0.008ms

0.001ms

about 10x

1,000

0.53ms

0.009ms

about 56x

10,000

10.6ms

0.023ms

about 471x

100,000

1,485ms

0.22ms

about 6,667x

Each time the iteration count grew tenfold, the + time grew by about 66, 20, and 140 times, while the StringBuilder time grew by 10 times or less. If the total copy volume is proportional to the square of the iteration count, the time should grow 100 times per tenfold step. The measurements fluctuate because of the JIT and GC, but they follow the trend described above. At 100 iterations, both approaches finish in under 0.01ms, so the difference is hard to notice.

The invokedynamic Approach Since JDK 9

Starting with JDK 9, JEP 280: Indify String Concatenation changed the default translation of javac completely. Instead of generating StringBuilder calls, the compiler leaves an invokedynamic call site, and the actual concatenation method is linked at run time.

How invokedynamic Works

invokedynamic is a bytecode instruction that decides which method to call at run time. Other invocation instructions such as invokevirtual and invokestatic have their targets fixed in the class file. invokedynamic instead delegates the decision of which method a call site links to, to Java code at run time. It was added in JDK 7 through JSR 292 to support dynamic languages on the JVM, and JDK 8 also uses it to implement lambda expressions.

The code that performs this linking is the bootstrap method. The class file records the bootstrap method for each invokedynamic call site. Before a call site runs for the first time, the JVM calls its bootstrap method to link it, and the bootstrap method returns a CallSite that points to the method to execute. If several threads run the same call site for the first time concurrently, the bootstrap method may be invoked concurrently, but the JVM installs only one of the results in the call site. For string concatenation, the bootstrap method is StringConcatFactory.makeConcatWithConstants(), which builds the concatenation code and returns it wrapped in a CallSite.

A MethodHandle, in the java.lang.invoke package, is a reference to something to execute. It can point to a method, a constructor call, or a field access, and its argument and return types are held in a MethodType object. It serves a purpose similar to a reflective Method, but it checks access only once, when the MethodHandle is created, and it is called directly through methods such as invokeExact(). Methods such as MethodHandles.filterArguments() and MethodHandles.foldArguments() can also combine several MethodHandles into a new one. Among the concatenation strategies described later, the three whose names start with MH build the concatenation code with this combinator feature.

A CallSite, from the same package, holds a single MethodHandle for the method to run in a property called the target. CallSite.getTarget() returns the current target MethodHandle. The JVM attaches the CallSite returned by the bootstrap method to the call site; this is called linking. Once linked, executing invokedynamic is equivalent to invoking the target MethodHandle at that moment. Some implementations, such as MutableCallSite, can switch the target to another MethodHandle while the program runs, but string concatenation uses ConstantCallSite, whose target never changes. After linking, the call site behaves like an ordinary method call and the JIT compiler can inline it.

invokedynamic Bytecode Checked on JDK 25

I compiled the following source with JDK 25.

Body of an instance method in StringTest.java
String str0 = "It's a string....";
String str1 = "It's" + " a string" + "....";
String str2 = str0 + str1 + "1111";
for (int i = 0; i < 10; i++) {
    str2 = str2 + "1111";
}

The bytecode shown by javap -c StringTest contains invokedynamic instructions instead of StringBuilder calls.

The method in the javap -c StringTest output (compiled with JDK 25)
 0: ldc           #7    // String It's a string....
 2: astore_1
 3: ldc           #7    // String It's a string....
 5: astore_2
 6: aload_1
 7: aload_2
 8: invokedynamic #9,  0  // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
13: astore_3
14: iconst_0
15: istore        4
17: iload         4
19: bipush        10
21: if_icmpge     37
24: aload_3
25: invokedynamic #13,  0 // InvokeDynamic #1:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;
30: astore_3
31: iinc          4, 1
34: goto          17
37: return

Compiling the same source with javac --release 8 produces the same StringBuilder calls seen in the decompiled output of the previous section.

The advantage of this approach is that the concatenation strategy lives in the JDK runtime, not in the compiled class file. The class file keeps only a recipe string that lists argument slots and constants. For example, str0 + str1 + "1111" above becomes a recipe of two \u0001 characters, each marking an argument slot, followed by 1111. You can see it under BootstrapMethods in the javap -v output. A class compiled once therefore picks up the concatenation strategy of a newer runtime when you upgrade the JDK it runs on, without recompiling. A class compiled with JDK 11 and run on JDK 25 uses the hidden class-based general path introduced in JDK 24. JDK 9/JEP 280: String Concatenations Will Never Be the Same explains the background in more detail.

Changes in StringConcatFactory Strategies

StringConcatFactory in JDK 9 had six concatenation strategies, selectable with the java.lang.invoke.stringConcat system property. In the strategy names, BC means bytecode generation at run time, MH means MethodHandle combination, SB means use of StringBuilder, SIZED means an estimated initial buffer capacity, and SIZED_EXACT means an exactly computed capacity.

Strategy Description

BC_SB

Generates, at run time, the bytecode of a class that calls StringBuilder. The code has the same shape as what javac up to JDK 8 produced at compile time.

BC_SB_SIZED

Same as BC_SB, but sets the initial capacity of StringBuilder to an estimate to reduce growth of the internal buffer.

BC_SB_SIZED_EXACT

Computes the lengths of the arguments in advance and sets the initial capacity of StringBuilder to the exact value.

MH_SB_SIZED

Builds the StringBuilder calls by combining MethodHandles instead of generating bytecode. The initial capacity is an estimate.

MH_SB_SIZED_EXACT

Same approach as MH_SB_SIZED, but computes the initial capacity exactly.

MH_INLINE_SIZED_EXACT

The default strategy. Skips StringBuilder, creates a byte array of the final length, and writes the arguments straight into it.

The default strategy, MH_INLINE_SIZED_EXACT, creates the String from the filled byte array without an extra copy, so it produces the fewest temporary objects and copies. The generateMHInlineCopy() method in StringConcatFactory.java implements it. Simple forms, such as adding two reference values, also use special paths like simpleConcat() in StringConcatHelper.java.

The five non-default strategies and the java.lang.invoke.stringConcat property were removed in JDK 15 by JDK-8245455. In this article, I call the path that most concatenations take by default the general path, excluding fast paths dedicated to special forms such as simpleConcat(). From JDK 15 through JDK 22, the general path is the inline-copy MethodHandle approach that descends from MH_INLINE_SIZED_EXACT. It combines several MethodHandles into a concatenation method that creates a byte array of the exact final length and copies each argument straight into it, with no intermediate buffer (inline copy).

JDK 23 added, through JDK-8327247, a path that generates bytecode calling StringBuilder for concatenations whose argument count exceeds the default threshold of 20. With many arguments, the MethodHandle expression tree grew large, and in extreme cases the C2 compiler used up to 2GB of memory to compile it. The change avoids that problem.

In JDK 24, JDK-8336856 changed the main general path again, this time to generating a hidden class per argument shape.

Hidden classes are special classes added in JDK 15 by JEP 371: Hidden Classes. They are defined with Lookup.defineHiddenClass(), cannot be found by class name, and can be unloaded individually once no longer referenced. This makes them a good fit for code that frameworks or the JDK generate at run time. Since JDK 15, the implementation classes of lambda expressions are also hidden classes. In the JDK 25 implementation, the argument shape that serves as the key of the hidden class cache is a MethodType made of the number of dynamic arguments and their normalized types. Reference types are normalized to Object, and byte and short to int. The contents and positions of constants are not part of the cache key; each call site stores them in its own String[]. So in the bytecode above, the call site for str0 + str1 + "1111" has the signature (String, String) → String, but the cache uses the shape (Object, Object) → String. The call site for str2 + "1111" inside the loop uses the shape (Object) → String, so the two call sites have different shapes. With hidden classes per argument shape, a generated concatenation class can be cached and reused by other call sites of the same shape. The cache uses soft references, so if a cached class is reclaimed, a class for the same shape may be generated again. Because the result is plain bytecode that the JIT compiler handles easily, instead of a deeply nested MethodHandle tree, linking and warmup costs go down.

StringConcatFactory in JDK 25 first checks for a fast path for simple concatenations and handles everything else with InlineHiddenClassStrategy by default. This strategy uses a prebuilt dedicated handler when there is a single dynamic argument and a hidden class per argument shape for the other general cases. The concatenation code fills a byte array of the final size and creates a String from that array. You can confirm this in StringConcatFactory.java in JDK 25.

As the bytecode above shows, the invokedynamic instruction inside the loop calls the already linked concatenation method on every iteration and creates a new result String. The bootstrap method of StringConcatFactory does not run again each time. Neither the compiler nor the runtime hoists a single accumulating StringBuilder out of the loop, so the advice to use a StringBuilder directly in loops that accumulate many strings still holds after JDK 9.

Summary

JDK version How + concatenation is handled

Up to JDK 1.4

javac translates it at compile time into StringBuffer append() and toString() calls

JDK 5 to 8

javac translates it at compile time into calls to the unsynchronized StringBuilder

JDK 9 to 14

javac emits an invokedynamic call site. On first linking, StringConcatFactory links a concatenation method, with a choice of six strategies

JDK 15 to 22

The alternative strategies are removed, and the inline-copy MethodHandle approach is the general path

JDK 23

Concatenations with many arguments use a path that generates bytecode calling StringBuilder

JDK 24 and 25

A fast path for simple concatenations, a dedicated implementation for a single argument, and a general path based on hidden classes per normalized argument shape

Folding a compile-time constant expression of type String into a single constant works the same in every version. Code that adds one or two strings outside a loop can be optimized by javac and the JDK runtime, so keep the more readable + operator there. Neither the compiler nor the runtime turns a loop into a single accumulating StringBuilder, though. If a loop accumulates strings over 1,000 or more iterations, use a StringBuilder directly. In the measurements above, the gap was about 56 times at 1,000 iterations and about 471 times at 10,000.


1. Even in the SE 25 edition, JLS 15.18.1 only says that a compiler may use StringBuffer or a similar technique. StringBuilder and invokedynamic both count as such a similar technique.
2. See JLS 15.29 for the exact scope of compile-time constant expressions.
3. For another performance test, see String concatenation with Java 8.
4. This is a simple System.nanoTime() measurement without JMH, so the small numbers may be inaccurate. From 10,000 iterations on, the gap is several hundred times or more, so the conclusion does not change.

Call by Value vs. Call by Reference

Defines call by value and call by reference from the Dragon Book and Strachey, then compares how Java, Kotlin, JavaScript, C, C++, C#, Python, Go, Rust, and Ada pass arguments to functions.

You often hear that "in Java method calls, primitive types are passed by call by value and objects are passed by call by reference." Java, however, has only call by value. When you pass an object to a method, the value that gets copied is simply a reference that points to the object. This article lays out the definitions of the two terms and compares how Java, Kotlin, JavaScript, C, C++, C#, Python, Go, Rust, and Ada pass arguments.

Call by Value and Call by Reference

Call by value initializes a separate variable, the parameter, with the value passed as the argument. The value is usually copied, though some languages such as Rust move ownership instead. Assigning a different value to the parameter inside the function does not affect the caller’s variable.

Call by reference passes the variable itself. The parameter becomes an alias of the caller’s variable, so assigning a new value to the parameter inside the function also changes the caller’s variable.

These definitions follow the standard treatment in programming language theory.

Section 1.6.6 of Compilers: Principles, Techniques, and Tools, 2nd edition, describes the two mechanisms as follows.

In call-by-value, the actual parameter is evaluated (if it is an expression) or copied (if it is a variable). The value is placed in the location belonging to the corresponding formal parameter of the called procedure. This method is used in C and Java, and is a common option in C++, as well as in most other languages. …​

In call-by-reference, the address of the actual parameter is passed to the callee as the value of the corresponding formal parameter. Uses of the formal parameter in the code of the callee are implemented by following this pointer to the location indicated by the caller. Changes to the formal parameter thus appear as changes to the actual parameter.

— Alfred V. Aho, Monica S. Lam, Ravi Sethi, Jeffrey D. Ullman
Compilers: Principles, Techniques, and Tools, 2nd edition, Section 1.6.6

The "actual parameter" in the quote corresponds to what this article calls an argument, and the "formal parameter" corresponds to what this article calls a parameter. Together with its 1977 predecessor Principles of Compiler Design, this book has served as the standard textbook for university compiler courses. Its cover illustration earned it the nickname "the Dragon Book."

Cover of Compilers: Principles, Techniques, and Tools, 2nd edition
Figure 1. Cover of Compilers: Principles, Techniques, and Tools, 2nd edition (image source: Open Library)

Christopher Strachey explained the distinction in terms of L-values and R-values in Section 3.4.2 of Fundamental Concepts in Programming Languages, his 1967 lecture notes. He called passing the R-value of an expression to a parameter call by value, and passing its L-value call by reference.

When the function is used (or called or applied) we write f[ε] where ε can be an expression. If we are using a referentially transparent language all we require to know about the expression ε in order to evaluate f[ε] is its value. There are, however, two sorts of value, so we have to decide whether to supply the R-value or the L-value of ε to the function f. Either is possible, so that it becomes a part of the definition of the function to specify for each of its bound variables (also called its formal parameters) whether it requires an R-value or an L-value. These alternatives will also be known as calling a parameter by value (R-value) or reference (L-value).

— Christopher Strachey
Fundamental Concepts in Programming Languages, Section 3.4.2

An L-value is the storage location denoted by an expression on the left side of an assignment, and an R-value is the value stored in that location, denoted by an expression on the right side. These lecture notes are a classic of programming language theory and are still cited as the origin of terms such as L-value, R-value, and first-class object.

A practical test for telling the two mechanisms apart fits in one sentence: When a function assigns a new value to its parameter, does the caller’s variable change? If it does, the mechanism is call by reference; if it does not, it is call by value. The test holds under the assumptions of this article: only these two mechanisms are compared, the argument is a reassignable variable, and the parameter can be assigned to. Once other evaluation strategies such as call by copy-restore and call by name come into play, this question alone cannot classify every argument-passing mechanism.

The assignment in this test means putting a different value into the parameter variable itself, as in targetTv = new Tv(). If the parameter points to an object, this makes it point to a different object. Changing the internal state of the object the parameter points to, as in targetTv.setChannel("Rock"), is a separate matter. The misconception discussed later comes from confusing the two.

The Terms "Pass by" and "Call by"

Call by value and call by reference are also called pass by value and pass by reference. The call by ~ form dates back to the ALGOL 60 report published in 1960. Section 4.7.3 of the revised report of 1963 specifies how parameters are passed, with 4.7.3.1 titled "Value assignment (call by value)" and 4.7.3.2 titled "Name replacement (call by name)." The pass by ~ form is also widely used in practice and in textbooks. This article uses call by ~ throughout.

Call by Sharing

The argument-passing behavior of Java, JavaScript, and Python, which shares an object rather than the caller’s variable itself, is sometimes called call by sharing. The term comes from the design document of CLU, a language created in the mid-1970s by a team led by Barbara Liskov. The object-argument behavior of Java, Kotlin, JavaScript, and Python and the passing of class instances in C#, all covered later, fall into this category. The term "call by object reference" used in the Python tutorial means the same thing. The same structure appears when you pass a map or a pointer in Go, or a pointer in C.

"Call by value" can mislead people into thinking the whole object is copied, and "call by reference" can mislead them into thinking that reassignment is reflected in the caller’s variable. Call by sharing is a good term for avoiding both misconceptions. Some sources use it, such as the MDN JavaScript documentation quoted later, but it has not become a standard term in textbooks or language specifications. This article therefore continues with only the two categories of call by value and call by reference.

Java

Result of the swap Method

The output of the following code shows how Java passes arguments.

Testing a swap method
public class ReferenceTest {
    public static void main(String[] args) {
        String x1 = "Hello";
        String y1 = "World";
        swap(x1, y1); // (1)
        System.out.println(x1); // Hello

        int x2 = 1;
        int y2 = 2;
        swap(x2, y2); // (2)
        System.out.println(x2); // 1
    }

    static void swap(Object x, Object y) {
        Object temp = x;
        x = y; // (3)
        y = temp;
    }

    static void swap(int x, int y) {
        int temp = x;
        x = y;
        y = temp;
    }
}
  1. Copies of the reference values held by x1 and y1 are assigned to the parameters x and y.

  2. The int values are copied into the parameters of the swap(int, int) overload. Without this overload, references to autoboxed Integer objects would be passed to the Object parameters, with the same result.

  3. Assigning each other’s values to the parameters x and y inside the method does not change the caller’s x1, y1, x2, or y2.

By the test defined above, Java behaves as call by value for both primitive types and objects.

Why Reassigning a Parameter Does Not Affect the Caller’s Variable

Let’s look more closely at passing an object as a method parameter.

Reassigning a parameter inside a method
class Tv {
    private String channel;

    void setChannel(String channel) { this.channel = channel; }
    String getChannel() { return channel; }
}

public class ReassignTest {
    public static void main(String[] args) {
        var myTv = new Tv();
        myTv.setChannel("Classic");

        reassign(myTv); // (1)
        System.out.println(myTv.getChannel()); // Classic
    }

    static void reassign(Tv targetTv) {
        targetTv = new Tv(); // (2)
        targetTv.setChannel("Rock");
    }
}
  1. The reference value held by myTv in the main method is copied and assigned to the parameter targetTv of the reassign method. The two variables point to the same object, but they are different variables.

  2. A new object is assigned to the parameter targetTv. Only the parameter targetTv now points to the new object, and myTv in the main method still points to the original object. That is why the output is Classic.

After the reference value is copied

Mutating Object State: The Source of the Misconception

If you change the internal state of the object the parameter points to, instead of reassigning the parameter, the changed state is visible through the caller’s variable.

Changing object state inside a method without reassigning the parameter
public class ChangeStateTest {
    public static void main(String[] args) {
        var myTv = new Tv();
        myTv.setChannel("Classic");

        changeState(myTv); // (1)
        System.out.println(myTv.getChannel()); // (3)
    }

    static void changeState(Tv targetTv) {
        targetTv.setChannel("Rock"); // (2)
    }
}
  1. As in the previous example, the reference value held by myTv is copied and assigned to the parameter targetTv of the changeState method. The two variables point to the same object.

  2. Without reassigning the parameter targetTv, the method changes the channel of the object the parameter points to Rock. This is the very object that myTv in the main method points to.

  3. Reading the channel through myTv in the main method prints Rock. The variable did not change, but the state of the object it points to did.

Both variables point to the same object

Because the changed state is visible through the caller’s variable, the claim that "objects are passed by call by reference" sounds plausible. As explained above, however, the practical test for the two mechanisms is whether a value assigned to the parameter is reflected in the caller’s variable. The changed state is visible through the caller’s variable only because both variables point to the same object, and what is passed is still a copy of the reference value. In other words, it is call by value.

Head First Java explains object references with the analogy of a TV remote control. Passing an object does not copy the TV (the object); it copies the remote control (the reference value) that operates the TV. If you change the channel with the copied remote (changing object state), the person holding the original remote sees the new channel too. If you pair the copied remote with a new TV (reassignment, targetTv = new Tv()), that remote can no longer operate the original TV, and the original remote is still paired with the original TV.

Java References and Terminology Confusion

James Gosling, the creator of Java, addressed this misconception directly in The Java Programming Language, which he coauthored.

Some people will say incorrectly that objects are passed "by reference." …​ The Java programming language does not pass objects by reference; it passes object references by value.

— Ken Arnold, James Gosling, David Holmes
The Java Programming Language, 4th edition
Cover of The Java Programming Language, 4th edition
Figure 2. Cover of The Java Programming Language, 4th edition (image source: Open Library)

Dev.java, the current official Java learning site, says the same thing.

Reference data type parameters, such as objects, are also passed into methods by value. …​ when the method returns, the passed-in reference still references the same object as before.

— Dev.java
Calling Methods and Constructors

The Dragon Book quoted earlier also states in the same section that Java uses call by value exclusively. In the call-by-reference entry that follows, however, it writes that Java behaves as if it used call by reference for anything other than basic types.

Even though Java uses call-by-value exclusively, whenever we pass the name of an object to a called procedure, the value received by that procedure is in effect a pointer to the object. Thus, the called procedure is able to affect the value of the object itself. …​

As we noted when discussing call-by-value, languages such as Java solve the problem of passing arrays, strings, or other objects by copying only a reference to those objects. The effect is that Java behaves as if it used call-by-reference for anything other than a basic type such as an integer or real.

— Alfred V. Aho, Monica S. Lam, Ravi Sethi, Jeffrey D. Ullman
Compilers: Principles, Techniques, and Tools, 2nd edition, Section 1.6.6

"Behaves as if it used call-by-reference" refers to the effect: the object is not copied as a whole, and changes the called method makes to the object’s state are visible to the caller. The phrase assumes what the book stated earlier, that the actual mechanism is not call by reference.

The word "reference" itself seems to have fed the misconception that Java passes objects by call by reference. Java calls a value that points to an object a "reference," and that word overlaps with the "reference" in "call by reference." Put more precisely, Java passes the reference value that points to an object by call by value.

A Java reference is a value that identifies and gives access to an object. You can think of it as a pointer. The following Java object access

Accessing a Java object
var myTv = new Tv();
myTv.setChannel("Rock");

is similar to this C++ code that uses a pointer.

C++ pointer
Tv *myTv = new Tv();
myTv->setChannel("Rock");

The Java variable myTv holds not the object itself but a value that points to the object. When you pass myTv as an argument to another method, this reference value is copied and passed. The C++ code above is an analogy for object access and pointer reassignment only; it does not mean that object lifetime management or the actual representation of references are the same.

Let’s look at the relevant wording in the JLS (Java Language Specification). The JLS also uses the word "pointer." Section 4.3.1. Objects defines reference values as pointers to objects.

The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

— Java Language Specification
4.3.1. Objects

This describes language-level semantics; it does not guarantee that a reference value has the same format as a raw memory address. JVMS (Java Virtual Machine Specification) 2.7 does not mandate any particular internal structure for objects, and notes that in some implementations a reference may point to a handle rather than to the object data. A handle here is a small intermediate structure between the reference and the object data. The reference points to the handle, and pointers inside the handle in turn point to the object data and the method table. In other words, a reference value may not be the memory address where the object resides.

This description of handles originally described "Sun’s current implementation" in the first edition of the JVMS (1997). The second edition changed the wording to "some of Sun’s implementations," and editions after the Oracle acquisition to "some of Oracle’s implementations," but the content stayed the same. At the time of the first edition, Sun’s JVM was the Classic VM of JDK 1.0 and 1.1, and the "Handleless Objects" section of The Java HotSpot Performance Engine Architecture explains that the Classic VM used indirect handles. According to the same section, HotSpot, which today’s Oracle JDK and OpenJDK share, does not use handles and implements object references as direct pointers to objects.

How arguments are passed in a method call is described in Section 8.4.1. Formal Parameters. It says only that the "values" of the argument expressions initialize newly created parameter variables. Nothing in it says that a parameter becomes an alias of the caller’s variable, as call by reference was defined above.

When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.

— Java Language Specification
8.4.1. Formal Parameters

A New Frame for Every Method Invocation

The JLS also describes, step by step, how a method invocation is executed. Section 15.12.4.5. Create Frame, Synchronize, Transfer Control says that once the method to invoke has been determined, a new activation frame is created and the argument values are placed in it. An activation frame is a region of memory that holds the execution state of a method call, such as its parameters, local variables, and return address, and that disappears when the call ends.

Now a new activation frame is created, containing the target reference (if any) and the argument values (if any), as well as enough space for the local variables and stack for the method to be invoked …​ The effect of this is to assign the argument values to corresponding freshly created parameter variables of the method, and to make the target reference available as this, if there is a target reference.

— Java Language Specification
15.12.4.5. Create Frame, Synchronize, Transfer Control

The argument "values" are assigned to parameter variables freshly created in the new frame, not to the caller’s variables. This reaches the same conclusion as Section 8.4.1. The reference to the object on which an instance method is invoked (the target reference) is placed in the new frame in the same way and becomes this.

The JVMS defines this frame at the virtual machine level. Section 2.6. Frames says that a new frame is created on the thread’s JVM stack every time a method is invoked, and that each frame has its own array of local variables.

A new frame is created each time a method is invoked. …​ Frames are allocated from the Java Virtual Machine stack (§2.5.2) of the thread creating the frame. Each frame has its own array of local variables (§2.6.1), …​

— Java Virtual Machine Specification
2.6. Frames

Parameters are passed through this local variable array, as Section 2.6.1. Local Variables explains.

The Java Virtual Machine uses local variables to pass parameters on method invocation. On class method invocation, any parameters are passed in consecutive local variables starting from local variable 0. On instance method invocation, local variable 0 is always used to pass a reference to the object on which the instance method is being invoked (this in the Java programming language). Any parameters are subsequently passed in consecutive local variables starting from local variable 1.

— Java Virtual Machine Specification
2.6.1. Local Variables

Let’s trace how the reference value of myTv in the earlier reassign example is copied into the parameter targetTv within this structure. Two concepts are needed first.

  • Operand stack: a last-in, first-out stack, one per frame, that serves as the workspace where JVM instructions pop operands and push results. It is also used to prepare the arguments passed to a method.

  • Bytecode: the JVM instructions that javac compiles Java source into and stores in class files. Two instructions appear in this example’s call sequence.

    • aload_1: pushes the reference value held in local variable 1 of the current frame onto the operand stack.

    • invokestatic: invokes a static method. It pops the argument values from the operand stack, creates a new frame, and stores those values in the new frame’s local variables starting from local variable 0.

With these concepts, the call to reassign looks like the figure below. Because reassign is a static method, the parameter targetTv is local variable 0 of the reassign frame. The reference value held by myTv, which javac assigned to local variable 1 of the main frame, is copied into this slot. The JVMS dictates that parameters start at slot 0, but the compiler decides which slot each non-parameter local variable occupies. At the bytecode level, the aload_1 instruction pushes this reference value onto the operand stack of the main frame, and the invokestatic instruction pops it and stores it in local variable 0 of the new frame. The two slots are separate storage belonging to different frames, so assigning a new object to targetTv leaves myTv in the main frame pointing to the original object.

The reassign frame and the main frame each have their own local variable array

Keep in mind that the JVMS defines an abstract machine. It is a model that specifies the rules for how instructions behave, not the memory layout of a particular implementation. The introduction to Chapter 2 of the JVMS leaves the memory layout of run-time data areas to the implementor’s discretion. For example, machine code produced by a JIT compiler may keep parameters in CPU registers. Even so, the language semantics, in which the caller’s variable and the parameter are separate variables, do not change.

Kotlin

Kotlin does not support call by reference either. In Kotlin, however, you cannot even run this article’s test of whether assigning a new value to a parameter changes the caller’s variable. The Function declaration section of the Kotlin Language Specification states that each parameter is introduced as the name of a value inside the function body, so parameters are final and cannot be changed inside the function.

Each parameter pi: Pi = vi introduces pi as a name of value with type Pi available inside function body b; therefore, parameters are final and cannot be changed inside the function.

— Kotlin Language Specification
Function declaration

Code that assigns a new value to a parameter is a compile error.

Reassigning a parameter and changing object state in Kotlin
class Tv(var channel: String)

fun main() {
    val myTv = Tv("Classic")
    changeState(myTv)
    println(myTv.channel) // Rock
}

fun reassign(targetTv: Tv) {
    targetTv = Tv("Rock") // (1)
}

fun changeState(targetTv: Tv) {
    targetTv.channel = "Rock" // (2)
}
  1. This is a compile error with the message "'val' cannot be reassigned."

  2. Changing a property of the object the parameter points to makes the new value visible to the caller. If you delete the reassign function that fails to compile and run the code, it prints Rock.

Apart from reassignment being forbidden, Kotlin behaves like Java. On the JVM, what is passed is a copy of the reference value, as in Java. Because final parameters are part of the language specification, this does not change when you compile to non-JVM platforms such as Kotlin/JS or Kotlin/Native.

JavaScript

JavaScript behaves the same way as Java. Here is the swap example first.

JavaScript swap function
function swap(x, y) {
  const temp = x;
  x = y;
  y = temp;
}

let x1 = "Hello";
let y1 = "World";
swap(x1, y1);
console.log(x1); // Hello

When an object is passed, reassigning the parameter or changing the object’s state inside the function also gives the same results as in Java.

Reassignment and state change when passing an object in JavaScript
const myTv = { channel: "Classic" };

reassign(myTv);
console.log(myTv.channel); // Classic

changeState(myTv);
console.log(myTv.channel); // Rock

function reassign(targetTv) {
  targetTv = { channel: "Rock" }; // (1)
}

function changeState(targetTv) {
  targetTv.channel = "Rock"; // (2)
}
  1. Assigning a new object to the parameter targetTv does not change the caller’s myTv.

  2. Changing a property of the object the parameter points to makes the new value visible through the caller’s myTv.

Replace the Tv object in the two Java figures above with an object literal, and they describe JavaScript’s behavior.

The Functions page on MDN summarizes this behavior in the same terms: arguments are always passed by value, and object arguments are, more precisely, passed by sharing.

Arguments are always passed by value and never passed by reference. This means that if a function reassigns a parameter, the value won’t change outside the function. More precisely, object arguments are passed by sharing, which means if the object’s properties are mutated, the change will impact the outside of the function.

— MDN Web Docs
Functions - Passing arguments

The ECMAScript specification also describes this behavior as initializing new parameter bindings with argument values, not as creating aliases of the caller’s variables. ArgumentListEvaluation obtains values from the argument expressions with GetValue and builds a list of ECMAScript language values, and FunctionDeclarationInstantiation initializes the parameter bindings of the new function environment from that list.

Unlike Java, the ECMAScript specification does not call the value used to access an object a "reference value." Object is one of the eight ECMAScript language types, the kinds of values a program manipulates directly, and an object itself is a value of that type. The "copied reference value" in this article is therefore best understood as a model for explaining the observed behavior.

TypeScript passes arguments the same way as JavaScript. The TypeScript Handbook states that, as a principle, TypeScript does not change the runtime behavior of JavaScript code.

As a principle, TypeScript never changes the runtime behavior of JavaScript code.

— TypeScript Handbook
TypeScript for the New Programmer - Runtime Behavior

After type checking, the TypeScript compiler erases the type information and emits plain JavaScript, so argument passing is identical to the JavaScript behavior described above. TypeScript also has no syntax for reference parameters like C#'s ref and out, which are covered later.

The By Reference Wording in JavaScript: The Definitive Guide

Some sources make it easy to mistake JavaScript function calls for call by reference if you read only part of them. JavaScript: The Definitive Guide, 4th edition, written by David Flanagan and long regarded as the standard JavaScript book, has a summary table in Section 11.2, "By Value Versus by Reference," stating that objects are copied, passed, and compared by reference. From that table alone, it looks as if you could describe JavaScript as call by reference.

Read the explanation of the behavior in the same section, however, and the book’s "by reference" turns out to mean something different from the call by reference defined at the beginning of this article. The book uses the phrase to mean that a reference to the object is passed instead of the whole object value being copied, and it also explains that reassigning the parameter is not reflected in the caller’s variable.

A function can use the reference to modify properties of the object or elements of the array. But if the function overwrites the reference with a reference to a new object or array, that modification is not visible outside of the function. Readers familiar with the other meaning of this term may prefer to say that objects and arrays are passed by value, but the value that is passed is actually a reference rather than the object itself.

— David Flanagan
JavaScript: The Definitive Guide, 4th edition, 11.2 By Value Versus by Reference

The example that follows this explanation is titled "References themselves are passed by value." The observed behavior the book describes is the same as in this article; only the name for what is passed differs.

C

C has no syntax like C++ reference parameters, so it has only call by value. Paragraph 4 of 6.5.2.2 Function calls in the C11 working draft N1570 states that, in preparing a function call, the arguments are evaluated and each parameter is assigned the value of the corresponding argument.

In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument.

— C11 Working Draft N1570
6.5.2.2 Function calls, paragraph 4

Footnote 93, attached to the same paragraph, explains that a function may change the values of its parameters, but these changes cannot affect the values of the arguments; on the other hand, it is possible to pass a pointer to an object, and the function may then change the value of the object pointed to.

swap implemented with C pointer parameters
void swap(int* x, int* y) {
    int temp = *x;
    *x = *y; // (1)
    *y = temp;
}

int a = 1;
int b = 2;
swap(&a, &b); // (2)
  1. Writing to the variable the pointer points to changes the caller’s a. Assigning a different address to x, however, leaves the caller’s a unchanged.

  2. & is just the address-of operator, and copies of the pointer values are assigned to the parameters x and y. After the call, a is 2 and b is 1.

Applying the test from above, assigning a new value to a pointer parameter does not change the caller’s variable, so this is call by value. It has the same structure as Java passing a reference value to an object.

C++

C++ provides reference parameters, which are call by reference as this article defines it.

swap implemented with C++ reference parameters
void swap(int& x, int& y) { // (1)
    int temp = x;
    x = y; // (2)
    y = temp;
}

int a = 1;
int b = 2;
swap(a, b); // (3)
  1. Declaring the parameter with type int& makes x an alias of the caller’s variable a.

  2. An assignment inside the function actually changes the caller’s variable.

  3. Unlike C’s swap(&a, &b), nothing at the call site indicates that an address is passed. After the call, a is 2 and b is 1.

Pointer Parameters vs. Reference Parameters

C++ also has the pointer parameters (for example, int*) inherited from C, so the two need to be distinguished. Pointer parameters are call by value in C++ too. A function that takes pointers, such as void swap(int* x, int* y), receives copies of the pointer values in its parameters, exactly as in the C example. Assigning a different address to x inside the function is not reflected in the caller’s variable.

An int& reference parameter, on the other hand, has no syntax for reseating it at all. x = y; is not a statement that rebinds the reference to another variable; it assigns a value to the object the reference refers to. Applying the test from above to the two cases gives different results. Assigning to a pointer parameter (int*) leaves the caller’s variable unchanged, while assigning to a reference parameter (int&) changes it.

References in the C++ Standard

The C++ standard also describes a reference as an alias, not as a value that is passed. A note in [dcl.ref] says that a reference can be thought of as "a name of an object." Paragraph 4 of the same section explicitly leaves unspecified whether a reference requires storage.

It is unspecified whether or not a reference requires storage ([basic.stc]).

— C++ Working Draft N4950
[dcl.ref] paragraph 4

Even though compilers usually implement references as addresses, the standard does not even specify whether a reference has storage.

If you judge by what is copied at the machine level, no language would have call by reference at all. The two terms distinguish the semantics a language defines, not the compiled result.

That said, the C++ standard does not call reference parameters call by reference. Searching the entire standard turns up no occurrence of "call by value," "call by reference," or "pass by value," and only four occurrences of "passed by reference," all in notes or library clauses rather than normative definitions. Instead of naming evaluation strategies, the standard specifies behavior. Paragraph 6 of [expr.call] says only that each parameter is initialized with its corresponding argument.

When a function is called, each parameter ([dcl.fct]) is initialized ([dcl.init], [class.copy.ctor]) with its corresponding argument.

— C++ Working Draft N4950
[expr.call] paragraph 6

How a parameter of reference type is initialized is governed separately by the reference binding rules. Call by value and call by reference are not standard terms of any particular language; they are programming language theory terms for comparing argument-passing mechanisms across languages.

C#

Like C++, C# supports call by reference in its syntax. The Method parameters page of the C# reference states that C# passes arguments by value by default, and that a method receives a copy of the value for value types such as structs and a copy of the reference for reference types such as classes.

By default, C# passes arguments to functions by value. This approach passes a copy of the variable to the method. For value (struct) types, the method gets a copy of the value. For reference (class) types, the method gets a copy of the reference.

— C# reference
Method parameters and modifiers

The page goes on to explain that when a reference type is passed by value, reassigning the parameter inside the method does not change the caller’s variable, while changing an instance member is visible through the caller’s variable because both variables refer to the same instance. So far, this is the same as Java.

To pass a parameter by reference, you add the ref, out, in, or ref readonly modifier. Of these, only ref and out allow assigning to the caller’s variable. The same page explains that a parameter passed by reference has no value of its own; it is a reference variable that refers to another variable, the referent. This is call by reference as defined in this article: the parameter becomes an alias of the caller’s variable.

Swap implemented with C# ref parameters
void Swap(ref int x, ref int y) // (1)
{
    int temp = x;
    x = y; // (2)
    y = temp;
}

int a = 1;
int b = 2;
Swap(ref a, ref b); // (3)
  1. The parameter x, declared with the ref modifier, becomes an alias of the caller’s variable a.

  2. Assigning to the parameter changes the caller’s variable.

  3. Unlike C++, the call site also needs ref. After the call, a is 2 and b is 1.

Because a ref parameter requires ref at both the method declaration and the call site, you can tell from the call expression alone that the caller’s variable may change, unlike with C++ reference parameters. out is a variant in which the caller passes an uninitialized variable and the method must assign a value to it, and in and ref readonly are read-only references that the method cannot modify.

ref also works with variables of reference types. Passing a class instance as is copies the reference, as in Java, so reassigning the parameter is not reflected in the caller’s variable. Passing it with ref makes the parameter an alias of the caller’s variable, so reassignment can change which object the caller’s variable points to.

Replacing the caller’s reference-type variable with a C# ref parameter
var myTv = new Tv();
myTv.Channel = "Classic";

Replace(ref myTv); // (1)
Console.WriteLine(myTv.Channel); // Rock

void Replace(ref Tv targetTv)
{
    targetTv = new Tv(); // (2)
    targetTv.Channel = "Rock";
}

class Tv
{
    public string Channel { get; set; } = "";
}
  1. If you declare it as Replace(Tv targetTv) without ref and call Replace(myTv), it behaves like Java’s reassign(myTv) and prints Classic. If the declaration has ref and you omit only the ref at the call site, it is a compile error.

  2. Assigning a new object to the ref parameter makes the caller’s myTv point to the new object. Running it on .NET 8 prints Rock.

C# distinguishes in its syntax between "passing a reference type by value" and "passing a variable by reference with ref," two different behaviors.

Python

Like Java, Python has only call by value. Section 4.8 Defining Functions of the official tutorial explains that arguments are introduced into the local symbol table of the called function, so they are passed using call by value, where the value is always an object reference.

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object).

— The Python Tutorial
4.8 Defining Functions

A footnote on this sentence adds that "call by object reference" would be a better description, because when a mutable object is passed, the caller sees any changes made to it. The Python FAQ answers more directly: arguments are passed by assignment, and since assignment just creates references to objects, there is no alias between an argument name in the caller and in the callee, and so no call by reference.

Python swap function and passing an object
def swap(x, y):
    x, y = y, x  # (1)

a, b = 1, 2
swap(a, b)
print(a)  # 1


class Tv:
    def __init__(self, channel):
        self.channel = channel


def main():
    my_tv = Tv("Classic")
    reassign(my_tv)
    print(my_tv.channel)  # Classic
    changeState(my_tv)
    print(my_tv.channel)  # Rock


def reassign(targetTv):
    targetTv = Tv("Rock")  # (2)


def changeState(targetTv):
    targetTv.channel = "Rock"  # (3)


main()
  1. This only rebinds the local names x and y to different objects, so the caller’s a stays 1.

  2. Rebinding the parameter targetTv to a new object leaves the caller’s my_tv unchanged, and Classic is printed.

  3. Changing an attribute of the object targetTv points to makes the change visible through the caller’s my_tv, and Rock is printed.

The results are the same as Java’s Tv example and JavaScript’s reassign and changeState examples.

Because the caller’s variable stays the same when you pass an integer or a string, but appears changed when you pass a list or a dictionary, it is easy to assume the passing rule depends on the type. The rule is the same. Integers and strings are immutable objects, so there is simply no way to change their internal state. Even with a list, rebinding the parameter inside the function, as in x = [1], leaves the caller unchanged.

Go

Go does not make the caller’s variable an implicit alias of a parameter in a function call either. The Calls section of the Go specification says that after the function value and arguments are evaluated, new storage is allocated for the function’s variables, including its parameters and results, and the arguments are assigned to the corresponding parameters. The Go FAQ answers more directly.

As in all languages in the C family, everything in Go is passed by value. That is, a function always gets a copy of the thing being passed, as if there were an assignment statement assigning the value to the parameter.

— Go FAQ
When are function parameters passed by value?

Taken literally, "all languages in the C family" is not accurate. C++ and C#, covered in this article, belong to the C family but support reference parameters in their syntax. Both languages still pass by value by default, though, and passing by reference is an exception that requires a modifier. The sentence is best read as "the default in C-family languages is pass by value, and Go has only that default." As in C, Go requires you to pass a pointer explicitly to change the caller’s variable.

swap implemented with Go pointer parameters
func swap(x, y *int) {
    *x, *y = *y, *x // (1)
}

a, b := 1, 2
swap(&a, &b) // (2)
  1. Writing to the variables the pointers point to changes the caller’s a and b. Assigning a different pointer to x inside the function does not change the caller’s a.

  2. To change the caller’s values with an ordinary function, you pass pointers as in C. Copies of the pointer values are assigned to the parameters x and y. After the call, a is 2 and b is 1.

Method calls, however, do not need & at the call site. The Calls section of the Go specification states that if x is addressable and the method set of &x contains m, then x.m() is shorthand for (&x).m(). For methods with pointer receivers, the compiler takes the address for you under this rule, so you cannot tell from the shape of the call expression alone whether the caller’s variable may change. Even then, what is passed is a pointer value.

Rust

Rust does not support call by reference in the sense defined in this article, a mechanism in which the parameter becomes an alias of the caller’s variable. Rust by Example calls passing a &T "passed by reference." A function call, however, does not create an alias of the caller’s variable, and a reference such as &mut T is itself a value that is passed by call by value. The Rust Book explains that passing a variable to a function moves or copies the value, just as assignment does.

Passing a variable to a function will move or copy, just as assignment does.

— The Rust Programming Language
4.1 What is Ownership? - Ownership and Functions

To understand "move" in this explanation, you need Rust’s concept of ownership. The Ownership Rules section of the Rust Book summarizes ownership in three rules: each value has a variable that is its owner, there can be only one owner at a time, and when the owner goes out of scope, the value is dropped. An assignment such as let s2 = s1; transfers ownership to s2, which is called a move, and using s1 after the move is a compile error.

Which types are copied is determined by the Copy trait. A trait declares behavior shared by multiple types, similar to an interface in other languages. Some traits have no methods and only tell the compiler about a property of the type; Copy is one of them.

Copy is a trait for types whose original variable remains usable after its value is assigned to another variable. The Stack-Only Data: Copy section of the Rust Book explains that variables of types implementing Copy are not moved but trivially copied, so they remain valid after assignment to another variable. Integers, floating-point numbers, bool, char, and tuples containing only Copy types belong to this group. Types that allocate heap memory or own resources, such as String and Vec, cannot be Copy, and adding Copy to a type that implements Drop, which performs cleanup when a value goes out of scope, is a compile error. In effect, only types that are safe to duplicate bit for bit can be Copy. So in let t = s;, if s is an i32 you can keep using s afterward, but if it is a String it is moved, as shown above.

A value of a non-Copy type such as String has its ownership moved into the parameter, and a value of a Copy type such as i32 is copied. When you pass a variable of type &mut T to a parameter of type &mut T, however, the compiler implicitly reborrows it, so you can use the variable again after the call even though &mut T is not Copy.

From this article’s perspective, moving and copying are the same mechanism, in which the parameter is initialized with the argument value, and neither creates an alias of the caller’s variable. The only difference is whether the caller’s variable remains usable after the call.

swap implemented with Rust mutable references
fn swap(x: &mut i32, y: &mut i32) { // (1)
    let temp = *x;
    *x = *y; // (2)
    *y = temp;
}

let mut a = 1;
let mut b = 2;
swap(&mut a, &mut b); // (3)
  1. What is passed to the parameter x is a value of type &mut i32.

  2. Writing to the variable the mutable reference points to changes the caller’s a.

  3. To change the caller’s values with an ordinary function, you pass mutable references like this. After the call, a is 2 and b is 1.

The standard library function std::mem::swap uses the same approach with the signature fn swap<T>(x: &mut T, y: &mut T). Passing mutable references is still not call by reference as defined in this article, in which reassigning the parameter itself changes the caller’s variable binding. To reassign x, you have to declare the parameter as mut x: &mut i32, and even then the reassignment has no effect on the caller’s a.

Like Go’s pointer-receiver methods, method calls in Rust do not need &mut at the call site. Under the method call rules in the Rust Reference, writing v.push(1) makes the compiler automatically borrow the receiver and pass &mut v, and what is passed is still a mutable reference value.

Ada: Call by Reference vs. Copy-Restore

The definitions section noted that the test "when a function assigns a new value to its parameter, does the caller’s variable change?" cannot classify every passing mechanism by itself. Ada is an example. Ada declares parameters with the modes in, in out, and out, and a value assigned to an in out or out parameter is reflected in the caller’s variable. Judged only by the result the caller observes, this is the same as C++ reference parameters.

Ada Reference Manual 6.2, however, decides whether a parameter is passed by copy or by reference mainly by its type, not its mode. Elementary types such as Integer are by-copy types and are passed by copy; by-reference types such as tagged types are passed by reference; and a formal parameter declared aliased is passed by reference regardless of its type. For parameters that fall into neither category, the manual does not specify whether they are passed by copy or by reference and leaves the choice to the implementation. For in out and out parameters passed by copy, 6.4.1 specifies that their values are copied back to the actual arguments when the subprogram completes normally. This is the call by copy-restore mentioned in the definitions section. The result, a changed caller variable, is the same as with call by reference, but the actual mechanism is copying.

The difference between passing by copy and passing by reference becomes visible when the procedure reads the variable passed as the actual argument directly. The example below passes the same variable Original to a procedure that receives it by copy and to one that receives it as aliased, and reads Original right after assigning to the parameter.

By-copy passing vs. aliased by-reference passing in Ada
with Ada.Text_IO; use Ada.Text_IO;

procedure Demo is
   Original : aliased Integer := 1;

   procedure By_Copy (Param : in out Integer) is
   begin
      Param := 2;
      Put_Line ("inside By_Copy: Original =" & Integer'Image (Original)); -- (1)
   end By_Copy;

   procedure By_Reference (Param : aliased in out Integer) is
   begin
      Param := 2;
      Put_Line ("inside By_Reference: Original =" & Integer'Image (Original)); -- (3)
   end By_Reference;
begin
   By_Copy (Original);
   Put_Line ("after By_Copy: Original =" & Integer'Image (Original)); -- (2)

   Original := 1;
   By_Reference (Original);
   Put_Line ("after By_Reference: Original =" & Integer'Image (Original));
end Demo;
  1. Integer is a by-copy type, so Param is a copy of Original. Right after 2 is assigned to Param, Original is still 1.

  2. When the procedure completes normally, the value of Param is copied back to Original, and Original becomes 2.

  3. An aliased parameter is passed by reference, so Param is an alias of Original. The moment 2 is assigned to Param, Original is 2 as well.

This is the output when compiled with GNAT 13.3, the Ada compiler included in GCC.

Output
inside By_Copy: Original = 1
after By_Copy: Original = 2
inside By_Reference: Original = 2
after By_Reference: Original = 2

After both calls return, the value is 2 in both cases, but reading Original inside the procedures gives different results. A language supporting parameter modes in its syntax and those modes being implemented as call by reference are two separate facts.

Summary

The following table summarizes how the languages covered in this article pass arguments.

Language Supports call by reference Passing mechanism Changing the caller’s variable through a parameter

Java

No

Call by value. For objects, a copy of the reference value is passed

Not possible. Only object state changes are shared

Kotlin

No

Call by value. Parameters are final, so reassignment is a compile error

Not possible. Only object state changes are shared

JavaScript

No

Call by value. The Object value is assigned to a separate parameter binding

Not possible. Only object state changes are shared

C

No

Call by value

Pass a pointer (swap(&a, &b))

C++

Yes, only for reference parameters (int&)

Call by value by default. Only reference parameters are call by reference

Declare a reference parameter. You can also pass a pointer as in C

C#

Yes, with ref, out, in, and ref readonly parameters. Of these, ref and out allow assigning to the parameter

Call by value by default. For class instances, a copy of the reference is passed

Declare a ref or out parameter. The call site also needs ref or out

Python

No

Call by value. The value is always an object reference

Not possible. Only object state changes are shared

Go

No

Call by value. Map and slice values behave like pointers

Pass a pointer (swap(&a, &b)). Pointer-receiver methods take the address automatically

Rust

No

Call by value. Depending on the type, the value is moved or copied as in assignment, and a mutable reference &mut T is also passed by value

Pass a mutable reference (swap(&mut a, &mut b)). Method calls borrow the receiver automatically

Ada

Partially. By-reference types and parameters declared aliased are passed by reference regardless of mode. For other types, the manual does not specify. in out and out parameters of by-copy types are copied back on normal completion (copy-restore)

By copy or by reference, depending on the type

Declare an in out or out mode

  • Java, Kotlin, JavaScript, and Python initialize a separate parameter variable or binding with the argument value. They do not support call by reference, in which the caller’s variable itself becomes an alias of the parameter.

    • Passing an object neither clones the object nor passes the caller’s variable itself. In Java, the reference value that points to the object, and in JavaScript, the Object value, is passed to a separate parameter, and the caller and callee can observe the same object.

    • Reassigning a parameter inside a function does not change the caller’s variable. Changing the internal state of the object the parameter points to, on the other hand, is visible through the caller’s variable. This difference is the source of the misconception that "objects are call by reference."

  • C and Go pass pointers, and Rust passes mutable references, to change the caller’s values. A call that takes the address or reference of a variable on the spot shows & or &mut, but when you pass a variable that already holds a pointer or reference, or when the compiler takes the address or borrows for you as in Go and Rust method calls, you cannot tell from the shape of the call expression alone. The only languages here in which a parameter becomes an alias of the caller’s variable are C++, C#, and Ada, and Ada sometimes passes by copy and copies back depending on the type.

  • This object-sharing behavior is sometimes called call by sharing. Some sources, such as JavaScript: The Definitive Guide, 4th edition, describe object sharing as "by reference," but it should be distinguished from call by reference in the sense of passing an alias of the caller’s variable.

References