0

I am unable a to understand a concept. double variable and double array are declared outside the function and a function which increments the value of both is made. Values from the functions are not returned still the value of the double array gets incremented where as it is not the same case with double variable. Why ? Same with Double class

    double x = 100.5;
    p.m1( x );
    System.out.println("" + x);
    double[] xa1 = {10,20,30,40};
    //p.m5( xa1 );
    for (int i=0;i<4;i++){
        System.out.println(xa1[i]);
    }

    public void m1(double a) {
      a += 100;
    }

    public void m5(double[] x) {

    for(int i=0; i < x.length; i++)
        x[i] += 100;      

   }

OUTPUT : 100.5

110.0 120.0 130.0 140.0

GeekyCoder
  • 27
  • 1
  • 6
  • 1
    This doesn't look like syntactically valid code. You have a `System.out.println()` and a `for` loop not contained in a block. Please post your real code. – Asaph Feb 10 '16 at 18:14

1 Answers1

0

Arrays in Java are objects so functions receive reference to it

  • But java passes only by value ? – GeekyCoder Feb 10 '16 at 18:15
  • Not exactly. In java, all arguments are passed by value, including Objects. And it's true that arrays are Objects in java. An Object's *reference* is passed by value. – Asaph Feb 10 '16 at 18:16
  • @TipuSultan: [Java is ***always*** pass by value.](http://stackoverflow.com/a/40523/1079354) – Makoto Feb 10 '16 at 18:17
  • @TipuSultan Not exactly. An Object *references* are passed by value. The distinction is subtle but significant. – Asaph Feb 10 '16 at 18:18
  • Is the same case with Double wrapper class object ? because in Double object is created instead of a variable in stack – GeekyCoder Feb 10 '16 at 18:19