Classes and methods

Pulling together the code fragments from the previous section, the class definition looks like this:

  class NewLine {

    public static void newLine() {

    public static void threeLine() {
      newLine(); newLine(); newLine();

    public static void main(String[] args) {
      System.out.println("First line.");
      System.out.println("Second line.");

The first line indicates that this is the class definition for a new class called NewLine. A class is a collection of related methods. In this case, the class named NewLine contains three methods, named newLine, threeLine, and main.

The other class we've seen is the Math class. It contains methods named sqrt, sin, and others. When we invoke a mathematical method, we have to specify the name of the class (Math) and the name of the method. That's why the syntax is slightly different for Java methods and the methods we write:

  Math.pow(2.0, 10.0);

The first statement invokes the pow method in the Math class (which raises the first argument to the power of the second argument). The second statement invokes the newLine method, which Java assumes is in the class we are writing (i.e., NewLine).

If you try to invoke a method from the wrong class, the compiler will generate an error. For example, if you type:

  pow(2.0, 10.0);

The compiler will say something like, “Can't find a method named pow in class NewLine." If you have seen this message, you might have wondered why it was looking for pow in your class definition. Now you know.