Java Double Math

So I, have this code to trace and I had the results of 2.25 and 2.75. But when I compile it, I get 1.5 and 2.0. Why is that? Do the parentheses have anything to do with that?

public class TraceClass {
    private double valBefore;
    private double valAfter;

    public TraceClass(double valIn) {
        this.valBefore = valIn;
        this.valAfter = 0.0;
    }

    public void doIt(boolean which){
        if (which == true) {
            this.valAfter = ((int) this.valBefore) + .5;
        }
        else {
            this.valAfter = (int) (this.valBefore + .5);
        }
    }

    public double getValAfter(){
        return this.valAfter;
    }
}
public class MainClass {
    public static void main(String[] args) {

        TraceClass traceObj = new TraceClass(1.75);

        traceObj.doIt(true);
        double temp = traceObj.getValAfter();
        System.out.println("Result is " + temp);

        traceObj.doIt(false);
        temp = traceObj.getValAfter();
        System.out.println("Result is " + temp);
    }
}

edit: this is code that my teacher gave out ask practice for stack tracing. i got 2.25 because I added 1.75+.5= 2.25. But then I accidentally added .5 to 2.25 to get 2.75 edit2: typo

Answer

Both the parentheses and the casts to int affect the result, and the order matters.

For the true case, valBefore is casted to int first, yielding the integer value 1 (it is truncated). Then .5 is added, a double value, so 1 is widened to 1.0 and 1.5 results.

For the false case, valBefore is added to 0.5 first, and 1.5 + .5 is 2.0. Then that result is cased to int which yields 2. The assignment back to the double variable valAfter widens it back to double2.0.

Leave a Reply

Your email address will not be published. Required fields are marked *