0

why is the output 0.0 if I write the following code? It seems to me like it wouldn't read the variable x inside my class Car.

public class Car {

double x = 2; 
double y;
double v = x * y; 

public Car(double y) {
this.y = y; 
}

public static void main(String[] args) {
Car car = new Car(100);
System.out.println(car.v);
}

}//end of class
Michael
  • 43
  • 6
  • 2
    I think you have a misunderstanding about what that double v = x * y line is doing. It's not like a math equation where you are setting a function and it updates when x or y update. When you put that line it it grabbing the value of x * y at that exact time and saving that value into v. – Anthony DiGiovanna Oct 18 '22 at 16:29
  • The value of v is zero because is calculated before you pass the value of y. Try moving you v calculation into the constructor and it will works – Heterocigoto Oct 18 '22 at 16:59

3 Answers3

5

The v is being calculated before the y is set in the constructor, so it will always equal 2*0, so 0.

You can do the v calculation inside the constructor instead.

public class Car {

    double x = 2; 
    double y;
    double v;

    public Car(double y) {
       this.y = y; 
       v = x * y; 
    }
}
Luke B
  • 2,075
  • 2
  • 18
  • 26
2

your double v = x * y line is being done on instantiation of a car object, when x is 2 and y is unititialized (0). You need to move that line into the constructor if you want it to update with the proper value.

0

I have included some System.out inside the constructor to get the flow of the execution.

Here, the value of v is already assigned with value of x and y where x = 2 and y = 0.0.

So,you can modify your code as below:

Code:

Car.java

public class Car {
  double x = 2;
  double y;
  double v;

  public Car(double y) {
    System.out.println("Inside constructor");
    System.out.println("value of v here:" + v);
    this.y = y;
    v = x * y;
    System.out.println("value of v now:" + v);
  }
}

Test.java

public class Test {
      public static void main(String[] args) {
        Car car = new Car(100);
        System.out.println(car.v);
      }
}

Output:

Inside constructor
value of v here:0.0
value of v now:200.0
200.0
GD07
  • 1,117
  • 1
  • 7
  • 9