Tino Intro To Java

Last modified: January 07, 2024

Running a Java Program

Once you have written and compiled a class, you need a main method to serve as the starting point for running your program.

When you run a Java program, Java always looks for a main method to begin execution. In BlueJ you will explicitly call the main method to run your program, but in most other Java development environments, you will simply run the class containing the main method and it will only work if the main method is declared exactly as shown below.

In this course, you are encouraged to put your main method in a separate file called a "driver" which drives the overall program logic. This allows you to potentially use each of your other classes in different programs because the class definitions are independent of the programs that use them. Here is a skeleton driver class with a main method:

public class Driver {
    public static void main(String[] args) {
        ... code goes here
    }
}

Don't worry about understanding everything yet. Here's all you need at this point:

  • A "driver" class needs a main method
  • A "main method" is what Java looks for when you run a program
  • The main method is where you create objects and tell them to do things.

Here's a driver for our Person class. It creates two Person objects and uses the methods we created.

public class Driver {

    public static void main(String[] args) {

        // Declare a Person object named joe
        Person joe;

        // Instantiate (create) the Person object using
        // the default constructor
        joe = new Person();

        // Tell joe to do things
        joe.printInfo();
        joe.increaseAge(5);
        joe.printInfo();

        // Declare and initialize a Person object named bob in one line
        // using a parameterized constructor
        Person bob = new Person(18, 1.72, true, "Bob");

        // Tell bob to do things
        String answer = bob.getName();
        System.out.println( "Hi, I'm " + answer );
        System.out.println( "My height in inches is " + bob.heightToInches() );

    }
}

Things to notice:

  • Creating an object takes two steps.
    1. Declare the object's type and variable name
      Person joe;
    2. Instantiate (create) the object using the new keyword + constructor.
      joe = new Person();
  • To instruct an object to do things, use the dot operator . followed by the method name.
    joe.printInfo();
  • Some methods require parameters to do their job
    joe.increaseAge(5);
  • Some methods return values back to the caller, so you should store the answer in a variable of the appropriate type. String answer = bob.getName();

Dark Mode

Outline