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
Moviemust live inMovie.java: same spelling, same letter case. - A file can hold several classes, but only one can be public.
- Compiling
Movie.javaproduces one.classfile 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!");
}
}
| 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]);
}
}
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.