-1
public class SubiectLicentaTrei {
    public static void main(String args[]) {
        double d = 12.34;
        ScadeUnitate su = new ScadeUnitate();
        su.scadeUnitate(d);
        System.out.println(d);
    }
}

class ScadeUnitate {
    public void scadeUnitate(double d) {
        d = d - 1.0;
    }
}

Outputs 12.34 when I expect 11.34.

George Irimiciuc
  • 4,573
  • 8
  • 44
  • 88

3 Answers3

3

Java is pass by value

so when you pass the here

ksu.scadeUnitate(d);

d will be a pass-by-value and when you deduct it here

d = d - 1.0;

d wont reference the value 11.34. but will get destroyed when out-of-scope

solution:

put a return value of the scadeUnitate method

public double scadeUnitate(double d)

get the return value to reference from the returned value.

d = su.scadeUnitate(d);
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
0

Cause d is primitive local variable and keeps new state only in scadeUnitate function. You should rework your function to return new value and reassign d with new value in main function.

Viacheslav
  • 5,443
  • 1
  • 29
  • 36
0

In Java references to Objects, and primitives are passed by value.

 public class SubiectLicentaTrei {
        public static void main(String args[]) {
            double d = 12.34; // local variable `d`'s value is 12.34                 
            ScadeUnitate su = new ScadeUnitate();
            su.scadeUnitate(d);  // passing 12.34 to constructor.
            System.out.println(d);
        }
    }

    class ScadeUnitate {
        public void scadeUnitate(double d) {  // another local variable `d` (different from original one). Also `d` is of a primitive type (`double`)
            d = d - 1.0;       // the second local variable d being changed. The first d is untouched.
        }
    }
TheLostMind
  • 35,966
  • 12
  • 68
  • 104