Instance Variables and Main Method in Car Loan Payment Calculator


I’ve just completed the Car Loan Payment Calculator project, but I had to watch the developer video to do so. Why are the instance variables created in the main method scope instead of just after the class has been declared? We haven’t seen any examples of this prior to this project and I don’t understand.

//Calculates monthly car payment
public class CarLoan {
//Why aren't the variables created here rather than in the main method?
  public static void main(String[] args) {
    int carLoan = 10000;
    int loanLength = 3;
    int interestRate = 5;
    int downPayment = 2000;
    if (loanLength <=0 || interestRate <=0) {
      System.out.println("Error! You must take out a valid car loan.");
  } else if (downPayment >= carLoan) {
      System.out.println("The car can be paid in full.");
  } else {
      int remainingBalance = carLoan - downPayment;
      int months = loanLength * 12;
      int monthlyBalance = remainingBalance / months;
      int interest = (monthlyBalance * interestRate) / 100;
      int monthlyPayment = monthlyBalance + interest;

I posted this question on stackexchange and received an answer there. They are local variables, not instance variables, and therefore they belong to the invocation of the method, not an instance of the object.

1 Like