Is Java pass-by-value or pass-by-reference?




public class Transfer {
public static void main(String[] args) {
/*
* The effect of passing the parameters of the basic type is obvious, which is a copy of the passed memory address value.
* The original value does not change
* The variable of the basic data type is assigned after the assignment What is passed is the value of the variable.
* */
int i = 1;
change(i);
System.out.println(i);

/*
* Do not change the pointer to the memory address value of the builder object, and find that the original object has changed.
* */
StringBuilder builder = new StringBuilder("hello");

/*System.out.println("Before changing:"+builder.toString());
changeStr(builder);
System.out.println("After changing: "+builder.toString());*/


/*
* Changed the pointer of the memory address value of the builder object, and found that the value of the original object has not changed
* Indicates that the address value of the object is passed
* */
System.out.println(" Before changing: "+builder.toString());
changeStr2(builder);
System.out.println("After change:"+builder.toString());

}

public static int change(int nn){
return nn=10;
}

public static void changeStr(StringBuilder builder){
builder .append(" world");
}

public static void changeStr2(StringBuilder builder2){
builder2 = new StringBuilder("hello2");
builder2.append(" world");
}

/*
* Summary: basic data types pass variables value of .
* The reference data type passes the memory address value of the variable.
* Parameter passing is actually the = operation.
* java is only pass-by-value.
* The meaning of passing by value and passing by reference is not the essential type of the parameter, but the evaluation strategy when calling the parameter.
* The value of passing by value is allocated on the stack, and the passing by reference refers to the allocation on the heap.
*
* */
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327040397&siteId=291194637