Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java wrong output class variable

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The v is being calculated before the y is set in the constructor, so it will always equal 0*2, 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; 
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading