-2

I have referred to the various explanations around here on SO about pass by value and pass by reference in Java. So far the notion is that incase of primitive datatypes it goes pass by value and incase of reference and user defined datatypes it is pass by reference. I also read that arrays are always pass by reference. However, when I try to execute the following program why the outputs are different in both these methods? The location of the object is called the reference. So if I am passing by value to demoByValue_ it should return 90 or 91? What am I missing here? Also, will it help to start fiddling with first pointers from C/C++ in order to get an abstract picture of this idea or what could be a real life analogy to grasp thi concept for a beginner? I did look into the analogy of house addresses and if the person wants to go to a specific house it needs the address etc. But, I want to know here that why I am failing to understand this concept? How to access the reference to the value of a primitve data type to see whats going on?

public class Misc {

    public static void main(String[] args) {

        int a = 91;
        System.out.println(a); //prints 91
        demoByValue(a);
        System.out.println(a); //prints 91
        a = demoByValue_(a);
        System.out.println(a); //prints 90 -- Why??
    }
    public static void demoByValue(int a){
        a = 90;
    }
    public static int demoByValue_(int a){
        a = 90;
        return a;
    }
}
  • a = demoByValue_(a); you assign a = value of demoByValue_ method, it's 90, so your value was received is 90 – ThanhLD Apr 18 '18 at 03:57
  • @ThanhLD does it still make it pass by value? – javanewbie Apr 18 '18 at 03:58
  • yes. Java is always pass-by-value – ThanhLD Apr 18 '18 at 04:14
  • The first few sentences of this question show a mistaken assumption. Java is ALWAYS pass by value. NEVER by reference. Having said that, object variables, including array variables, store references rather than values, so it sometimes SEEMS a bit like you're passing an object by reference. The bottom line is that if you want a method to have its own local copy of an object, you need to copy it yourself. – Dawood ibn Kareem Apr 18 '18 at 04:20

1 Answers1

0

This is pretty normal till this program flow:

    int a = 91;
    System.out.println(a); //prints 91
    demoByValue(a);
    System.out.println(a); //prints 91

91 is printed because the value can change and

  public static void demoByValue(int a){
    a = 90;
}

This function demoByValue is not overwriting the value just assigning to the local variable in the parameter and done But this

 public static int demoByValue_(int a){
    a = 90;
    return a;
}

overwrite here: a = demoByValue_(a);

Daouda
  • 101
  • 8