Skip to content

Comments, files and the main method

โ˜• Java 17 ยท Your First Java Class ยท 2/3

You can now write a class with fields and methods. Three more things turn it into a real, runnable program.

Comments: notes for humans

The compiler ignores comments completely. Java has three kinds:

// Single-line comment: everything after // on this line is ignored

/*
 * Multi-line comment: everything between the markers is ignored.
 */

/**
 * Javadoc comment: read by tools to generate HTML documentation.
 * @author Mounir
 */
public class StreamingPlatform {
    String name;   // store the platform name
}
Comment Starts / ends Use it for
Single-line // to the end of the line short notes
Multi-line /* โ€ฆ */ longer explanations
Javadoc /** โ€ฆ */ documenting classes and methods

One public class per file

Java ties classes to files with strict rules:

// File: Movie.java

public class Movie {      // the public class: same name as the file
    String title;
}

class Helper {            // allowed: a second class, but not public
}
  • A public class named Movie must live in Movie.java: same spelling, same letter case.
  • A file can hold several classes, but only one can be public.
  • Compiling Movie.java produces one .class file per class (Movie.class, Helper.class).

In practice, you'll put each class in its own file.

The main method: where a program starts

The JVM starts every program in a method with this exact signature:

public class StreamingPlatform {

    public static void main(String[] args) {
        System.out.println("Welcome to ADC Flix!");
    }
}
$ javac StreamingPlatform.java
$ java StreamingPlatform
Welcome to ADC Flix!
Keyword Why it's there
public the JVM must be able to call it from outside
static it belongs to the class: the JVM calls it without creating an object
void main returns nothing to the JVM
String[] args the words typed after the class name on the command line

System.out.println(...) prints a line to the console.

Command-line arguments

args is an array of String. Its first element is args[0]:

public class Greeting {
    public static void main(String[] args) {
        System.out.println("Hello, " + args[0]);
    }
}
$ java Greeting Mounir
Hello, Mounir

Run it without any argument and args[0] doesn't exist: the program stops with an ArrayIndexOutOfBoundsException.

You now have every piece of a complete class. Let's assemble them in the lab.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

โ† Fields and methods ยท Next: the lab โ†’