AP Computer Science Exam Question
Consider the following class definition representing a car:
public class Car {
private String make;
private String model;
private int year;
private double mileage;
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
this.mileage = 0;
}
public void drive(double miles) {
mileage += miles;
}
public void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Mileage: " + mileage);
}
}
Write a program that creates an instance of the Car
class, sets the make to "Toyota", the model to "Camry", and the year to 2019. Then, call the drive()
method on the car object to simulate driving 1000 miles. Finally, call the displayInfo()
method to display the car's information.
What is the output of the program?
Answer: The output of the program will be:
Make: Toyota
Model: Camry
Year: 2019
Mileage: 1000.0
Explanation:
The program creates an instance of the Car
class with the make set to "Toyota", model set to "Camry", year set to 2019, and mileage set to 0. Then, the drive()
method is called with an argument of 1000, which increments the mileage
variable by 1000. Finally, the displayInfo()
method is called, which prints the make, model, year, and mileage of the car.
The output confirms that the make is "Toyota", the model is "Camry", the year is 2019, and the mileage is 1000.0.