Skip to content

Instantly share code, notes, and snippets.

@aerphanas
Created February 11, 2023 07:14
Show Gist options
  • Select an option

  • Save aerphanas/963d90d6a7fa332093ae02f2d94891ac to your computer and use it in GitHub Desktop.

Select an option

Save aerphanas/963d90d6a7fa332093ae02f2d94891ac to your computer and use it in GitHub Desktop.
Java pass by reference

pass by reference example 1

public class PassbyRefOne {
    int a = 10;
    void addTen(PassbyRefOne num){
        num.a = num.a + 10;
    }
    public static void main(String[] args) {
        PassbyRefOne x = new PassbyRefOne();
        System.out.println("Value of x is " + x.a);
        x.addTen(x);
        System.out.println("Value of x is " + x.a);
    }
}

pass by reference example 2

public class PassbyRefTwo {
    public int a;
    public PassbyRefTwo(){
        a = 10;
    }
    public static void main(String[] args) {
        PassbyRefTwo x = new PassbyRefTwo();
        System.out.println("Value of x is " + x.a);
        addTen(x);
        System.out.println("Value of x is " + x.a);
    }

    public static void addTen(PassbyRefTwo num) {
        num.a = num.a + 10;
    }
}

pass by reference example 3

public class PassbyRefThree {
    public static void main(String[] args) {
        int a[] = {10};
        System.out.println("Value of x is " + a[0]);
        addTen(a);
        System.out.println("Value of x is " + a[0]);
    }
    private static void addTen(int a[]) {
        a[0] = a[0] + 10;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment