Tino APCS

Main Method

A program is a set of instructions that tells the computer what to do.

In Java, a program consists of one or more classes, where each class can perform different tasks and can tell other classes to perform tasks as well.

Methods

The tasks that a class can perform are defined as methods in the class.

The methods are instructions that accomplish the task, possibly by telling other classes to perform subtasks.

The entry point of every Java application is the main() method.

  • When you run a Java program, the Java Virtual Machine begins by running the code in the main() method of the class you have chosen.
  • Every Java application needs at least one main() method. Even large projects with many different parts and files need an entry point - and that entry point is the main() method.
  • You need to memorize the syntax shown below. Please don't copy and paste the syntax. Type it out by hand - always!
  • Over time, you will learn the concepts needed to understand meaning of each part of the main() method. An explanation follows below; don't memorize this.
public static void main(String[] args)  

Dissecting main()

Note: You don't have to understand this yet!

public

  • 'public' is an access specifier, which determines who is allowed to access and run this method. 'public', in particular, means that any other class is allowed to run this method, hence the name.

static

  • This means that this method can be used without creating an object. Unlike standard instance methods, static methods do not use any instance variables or depend in any way on the object’s state and therefore can be called via its class rather than from an object.
  • (e.g. in order to callMath.random(), you don't need to make a new Math-type object. You can simply call it from the Math class itself.)

void

  • 'void' means this method does not return any value to its caller.

main

  • This is the name of the method.
  • 'main' is special - it will always be the entry point of a program in Java. If you change this name, then it is no longer the entry point for your program, and Java will complain with the message "main method not found."
  • This is not apparent in BlueJ because BlueJ allows you to dynamically run any static method rather than always starting in an official main() method. Most Java editors are not as forgiving as BlueJ.

String[] args

  • This is the parameter. String[] defines the parameter type, and args is the name of the parameter. args, being a name, can technically be named anything you want. Try it!
  • When you run a Java program, it is possible to pass in parameters via the command line. If parameters are passed in, they are stored in this array as Strings and it's your job to parse the Strings and interpret the meaning of each parameter.

Dark Mode

Outline