Search code examples
javamethodsinstance-variablesmain-method

Why Are the Instance Variables Declared in the Main Method?


I'm learning Java on Codecademy and recently completed a project that calculates monthly payments for a car loan. The problem is that I don't understand the solution, and no one has responded to my question about it on the Codecademy forum.

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.

Here is the code:

//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;
      System.out.println(monthlyPayment);
    }
  }
}

Solution

  • Variables defined within a method are local variables, they belong to an invocation of the method, not to an instance of an object.

    The intent seems to be to provide an example that is understandable to beginners who haven't been introduced to constructors, instance variables, and methods. They want to teach local variable declaration, some simple calculating and if-statements, and printing to the console before getting into that other stuff.

    As an exercise it would be fine for you to change the CarLoan class to give it instance variables, just to see another way to do it. Keep the variable values hard-coded, make an instance method that calculates the monthly payment, and have the main method print the result to the console.