samwellwang

samwellwang

coder
twitter

Is Java pass by value or pass by reference?

Is Java™ Pass-by-Value or Pass-by-Reference? Today, while writing code, I discovered something interesting: I passed two reference objects to a conversion function.

2020-03-30

Is Java™ Pass-by-Value or Pass-by-Reference?#

Today, while writing code, I discovered something interesting: I passed two reference objects to a conversion function. As a result, my function did not work!! At first, I thought it was a compilation issue, but after cleaning, it still didn't work. After going back and forth for almost an hour, I was really frustrated. Could it be that the basic parameter types are passed by value and reference types are passed by reference, as I always thought? After some learning, I found out that it is indeed not what I thought, but rather what the Java specification states!

Without further ado, here’s the conclusion: it is definitely pass-by-value!
Basic types are straightforward; a copy of the basic type is passed.
However, note that for reference types, a copy of the reference address is passed.
Here’s the code:

package com.dareway.demo;

public class Person{
	public String name;
	public int age;
	Person(){
		
	}
	Person(String n ,int a){
		this.name=n;
		this.age=a;
	}
}

public class Test{

	public static void main(String[] args) {
		Person one = new Person("wang",22);
		Person two = new Person("yang",23);
		switchEach(one,two);
		System.out.println("one's name :"+one.name);
		System.out.println("two's name :"+two.name);
		
	}

Output:

p1's name :yang
one's name :Jisoo
two's name :yang

This means that while the passed reference parameter can change the internal state, it cannot point to a new address. Because only a copy of the application address is made.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.