Java Syntax: Writing Your First Java Program
Learn the basics of Java syntax by creating a Java file named Main.java
and using code to print "Hello World" to the screen. This introductory guide will help you understand the fundamental structure of Java code and get you started with programming in Java.
Java Syntax
Previously, we created a Java file called Main.java and used the following code to print "Hello World" to the screen:
Syntax
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Output
Hello World
Every line of code that runs in Java must be inside a class. In the above example, we named the class as Main. A class should always start with an uppercase first letter.
Note: Java is case-sensitive: "MyClass" and "myclass" have different meanings.
The name of the Java file must match the class name. Save it using the class name and add ".java" to the end of the filename.
To run the example above on your computer, ensure Java is properly installed. Refer to the "Get Started" chapter for installation instructions. The output should be "Hello World".
The main Method
The main()
method is required and appears in every Java program:
public static void main(String[] args)
Any code inside the main()
method will be executed. Don't worry about the keywords before and after main
. You will learn about them gradually.
For now, remember that every Java program has a class name that matches the filename, and every program must contain the main()
method.
System.out.println()
Inside the main()
method, we can use the println()
method to print a line of text to the screen:
public static void main(String[] args) {
System.out.println("Hello World");
}
Note: The curly braces {}
mark the beginning and the end of a block of code.
System
is a built-in Java class that contains useful members, such as out
, which is short for "output". The println()
method, short for "print line", is used to print a value to the screen (or a file).
Don't worry too much about System
, out
, and println()
. Just know that you need them together to print to the screen.
Also, each code statement must end with a semicolon ;
.