Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

java pass by reference

// Java is always pass-by-value. When passing a reference variable, 
// a copy of the value of the pointer was passed, not the object itself. 

import java.util.Arrays;
class Dog {
    public String name;
    public Dog() {}     //default constructor
    public Dog(String name) {this.name = name;}
}
public class Main {
    public static void update_obj(Dog myDog) {
        myDog.name = "Changed";
    }
    public static void update_obj_v2(Dog myDog) {
        myDog = new Dog();
        myDog.name = "Changed v2";
    }
    public static void update_int(int i) {i++;}
    public static void update_Integer(Integer i) {i++;}
    public static void update_String_to_lower(String str) {str.toLowerCase();}
    public static void update_array(String[] ary) {ary[0] = "Changed";}

    public static void main(String[] args) {

        // ---------- Custom mutable objects, arrays, changed --------------------------------
        Dog max = new Dog("Max");
        update_obj(max);
        System.out.println("Dog's name is now: " + max.name);   //Changed

        Dog fido = new Dog("Fido");
        Dog fido_alias = fido;
        update_obj_v2(fido);
        System.out.println("Dog's name is now (v2): " + fido.name);     // Fido
        System.out.println("Fido object address has not changed (v2): " + String.valueOf(fido == fido_alias));  // True

        String[] fruits = {"Apple", "Orange"};
        update_array(fruits);
        System.out.println(Arrays.toString(fruits));    // [Changed, Orange]

        // ---------- Primitives, Immutable objects, NOT changed ------------------------------
        int i = 1;
        System.out.println("int before update: " + i); // 1
        update_int(i);
        System.out.println("int after update: " + i);  // 1

        Integer j = 1;
        System.out.println("Integer j before update: " + j); // 1
        update_Integer(j);
        System.out.println("Integer j after update: " + j);  // 1

        Integer k = 2;
        k++;
        System.out.println(k);      // 3

        String word = "SDSE";
        System.out.println("String before update: " + word);    //SDSE
        update_String_to_lower(word);
        System.out.println("String after update: " + word);     //SDSE
    }
}
 
PREVIOUS NEXT
Tagged: #java #pass #reference
ADD COMMENT
Topic
Name
2+9 =