Running a Java Program

When you click the run button, Java starts execution in the main method as shown in the code below (public static void main(String[] args)). The body of the main method is all the code between the first { and the last }. Every class in Java can have a main method.

The following is the main method for the Person class. It shows two variables (p1 and p2) of type Person being created and each of the variables refers to a new Person object. Each new Person object’s name and phone number are set to the passed values (new Person("Deja", "555 132-3253")). Then each object’s toString method is called to output information about the object. The toStringmethod is called when you try to print the value of an object using System.out.println(object);

The main method must be declared as public static void main(String[] args). The only part of this that you can change is the args. You can use a different name instead if you wish. The public keyword is necessary since this method needs to be executed from outside the current class. The static keyword means that you can execute this method on the class (not on an object), which is important since no objects of this class have been created yet when the main method starts. The void keyword says that this method doesn’t return anything. The (String[] args) says that this method can take some information when you execute it which will be passed to the method as an array of strings called args. An array is like a list and you will learn more about arrays in a later chapter.

See the example below of running a Java program.