A Java program is a file that contains one or more classes, and a class is simply a container for methods. The smallest program that does anything is three lines long. Understanding why those three lines have that shape is the difference between copying a tutorial and being able to write the next program on your own.
The previous lesson in this module covered "How Do You Install the JDK on Windows and Verify It?", and the next lesson in this module is about "How Do You Compile and Run Java Without an IDE?", which shows you how to drive the compiler and the runtime from a terminal.
What does the smallest complete program look like?
Here is a program that prints one line. Save it as Greeting.java. The name of the file matters, and the next section explains exactly why.
public class Greeting {
public static void main(String[] args) {
System.out.println("Hello from Java");
}
}
Four parts of that file carry all of the weight. The line public class Greeting declares a class and gives it a name. The line public static void main is the entry point that the launcher looks for. The part String[] args is where command line arguments arrive. And System.out.println(...) writes a line of text to the standard output, which is the place your text appears in the terminal.
Now compile it and then run it, and you will see the line that you printed.
javac Greeting.java
java Greeting
Hello from Java
The first command produces a file called Greeting.class, and that file holds the bytecode. The second command starts the runtime, which loads the class file, finds the main method inside it, and calls it. There are two separate steps here and two separate results. The source code becomes bytecode, and then the bytecode runs.
Why must the file name match the class name?
Java finds a public class by looking for a file with the same name, and the capital letters have to match as well. If you put public class Greeting inside a file that is called greeting.java, then the compiler tells you about it.
Greeting.java:1: error: class Greeting is public, should be declared in a file named Greeting.java
This rule exists so that a reader, and the compiler, can always find the source code of a class by its name alone, without having to look through every file in a folder. One file may hold several classes, but only one of them may be public, and that one class decides the name of the file.
What does the main signature actually say?
Read the signature one word at a time, and every word earns its place.
public static void main(String[] args) {
// public : the runtime is allowed to call this from outside the class
// static : the method belongs to the class itself, not to an object
// void : the method does not give a value back
// args : an array that holds the command line arguments
int width = 20;
String banner = "--------------------";
System.out.println(banner);
System.out.println("value: " + width);
}
The word static matters because the launcher has no object to call the method on. It only has the class. The word void matters because the runtime does not wait for a result. Your program ends when main returns. The args array is the hand-off point for input, and it is worth using early so that arguments feel like a normal part of the language instead of a mystery.
# pass two arguments to the program
java Greeting 42 hello
Inside main, args[0] is the first argument and args[1] is the second one. The length args.length tells you how many arguments arrived. Arguments always arrive as text, so any number that you pass stays a String until you convert it yourself.
How do you print more than one thing?
System.out.println accepts a single value, and the + operator glues values together into a string. The print version leaves out the newline, which is what you want when you are building one line piece by piece.
public class Report {
public static void main(String[] args) {
String product = "Notebook";
int quantity = 3;
double price = 4.50;
System.out.println("Item: " + product);
System.out.println("Total: " + (quantity * price));
System.out.print("Loading");
System.out.print(".");
System.out.println(" done");
}
}
Notice the parentheses around quantity * price. Without them, the + would glue the number to the text first, and the arithmetic would never happen. This is a small trap that catches everybody once, because the program still compiles and still runs.
What do the first errors look like?
Two mistakes come up again and again. A missing semicolon gives you a message that points at the next line, because the compiler only knows that a statement has finished when it finds the semicolon. A misspelled class name gives you a "cannot find symbol" error, and the message lists the symbol that it was looking for.
Greeting.java:4: error: ';' expected
System.out.println("Hello from Java")
^
Read the error from the bottom upwards. The little caret marks the exact position of the problem. The line number tells you where to look. The file name tells you which file to open. The message text at the top is the least useful part, so do not start there.
What are the other parts of a class?
A class is more than a name and a method. There are three more pieces that you will use constantly. The fields hold the state that a class carries. The constructors explain how an object is created. The methods are the actions that operate on that state.
A program that models something real tends to have all three of them, and keeping them in that familiar order makes the code easy to read.
public class Rectangle {
private final double width;
private final double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double area() {
return width * height;
}
public double perimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Rectangle sheet = new Rectangle(21.0, 29.7);
System.out.printf("Area: %.2f%n", sheet.area());
System.out.printf("Perimeter: %.2f%n", sheet.perimeter());
}
}
The shape of this class is the shape of most Java that you will write. The state is in the fields. The construction happens in the constructor. The behaviour is in the methods. And a small main method shows the rest of it working.
Notice that width and height are declared as private final. The class owns its own data, and it does not let callers change it behind its back. That is not ceremony. It is what makes the object trustworthy to the rest of the program.
Which names are worth arguing about?
Java has naming conventions, and following them saves every reader a little decoding. Class names are written in PascalCase, which means that every word starts with a capital letter. Method names, parameter names and variable names are written in camelCase, which means that the first word starts with a small letter and the other words start with capital letters. Constant names are written in UPPER_SNAKE_CASE.
A class that represents one record is usually given a noun, and its methods are given verbs. The class Rectangle has an area() method and not computeArea(), because the name of the class already says what is being calculated.
These are conventions and not rules, and the compiler will not complain about anything else. But code that follows them reads as if its author already knew what the code was going to do, and that impression is worth a lot when you come back to the file six months later.
Quick reference
- The file name must match the name of the public class, and the capital letters have to match as well.
- javac File.java compiles your code into bytecode, and java ClassName runs it.
- The signature is public static void main(String[] args). The launcher calls it without having any object.
- Command line arguments arrive as strings inside args.
- Put parentheses around arithmetic that sits inside string concatenation.
- Read compiler errors from the caret outwards, and not from the top of the message.
Try it yourself: write a class called Profile that prints a name, a role and the year that the person joined, one on each line. Compile it and run it. Then change the name of the class to profile while leaving the file name alone, compile again, and read the error carefully enough to explain why the compiler cares about the difference between the two names.