By Barry Burd

To do something useful with code that you write in Java, you need a main method. You can put the main method in a separate file. First, let’s start with a “traditional” example. This program processes simple purchase data.

import java.util.Scanner;
class ProcessData {
 public static void main(String args[]) {
  Scanner keyboard = new Scanner(System.in);
  double amount;
  boolean taxable;
  double total;
  System.out.print("Amount: ");
  amount = keyboard.nextDouble();
  System.out.print("Taxable? (true/false) ");
  taxable = keyboard.nextBoolean();
  if (taxable) {
   total = amount * 1.05;
  } else {
   total = amount;
  }
  System.out.print("Total: ");
  System.out.println(total);
  keyboard.close();
 }
}

Now add the main method

import java.util.Scanner;
class ProcessPurchase {
 public static void main(String args[]) {
  Scanner keyboard = new Scanner(System.in);
  Purchase onePurchase = new Purchase();
  System.out.print("Amount: ");
  onePurchase.amount = keyboard.nextDouble();
  System.out.print("Taxable? (true/false) ");
  onePurchase.taxable = keyboard.nextBoolean();
  if (onePurchase.taxable) {
   onePurchase.total = onePurchase.amount * 1.05;
  } else {
   onePurchase.total = onePurchase.amount;
  }
  System.out.print("Total: ");
  System.out.println(onePurchase.total);
  keyboard.close();
 }
}

The best way to understand this code is to compare it, line by line, with the code before it. In fact, there’s a mechanical formula for turning the first code into the second code.

First code Second code
double amount;boolean taxable;double
total;
Purchase onePurchase = new
Purchase();
amount onePurchase.amount
taxable onePurchase.taxable
total onePurchase.total

The two programs do essentially the same thing, but one uses primitive variables, and the other leans on the Purchase code.