Your first Java program
A basic Java program starts in a method named main and can print text to the console.
How it works
Start from the outside. public class Main defines the class. Inside it, main is the conventional entry point for this program. String[] args can hold startup arguments. System.out.println sends a value to standard output and then starts a new line.
The sample shows Hello and then 7. Read the expression in the second call first so you can see why the console shows its answer instead of the characters 3 + 4.
Walk through an example
In a file named Main.java, the class Main contains the main method. The method’s first statement calls System.out.println to display a message.
What to watch for
Java distinguishes uppercase and lowercase letters. The public class name and the file name should match, and a statement like println ends with a semicolon.
Code example
public class Main {
public static void main(String[] args) {
System.out.println("Hello");
System.out.println(3 + 4);
}
}Check your understanding
What appears in the console?
See the example and explanation
- Worked example
- Given
System.out.println(3 + 4); - Answer
7
Java evaluates the addition and passes the resulting integer to println.