In this lesson, we’ll cover the basic syntax of Java through an example program and explain each part of it in detail.
Example Program: Print “Greetings, Universe” to the Screen
Create a Java file named Greeting.java
with the following code to print “Greetings, Universe” to the screen:
public class Greeting { public static void main(String[] args) { System.out.println("Greetings, Universe"); } }
Example Explained
- Class Definition
public class Greeting {
Every piece of code that runs in Java must be enclosed within a class. The class name should always start with an uppercase letter. In this example, the class name is Greeting
.
Note: Java is case-sensitive, meaning that Greeting
and greeting
are considered different.
- File Naming
The name of the Java file must match the class name. Therefore, the file should be saved asGreeting.java
. - Main Method
public static void main(String[] args)
The main()
method is required in every Java program. Any code within the main()
method will be executed. The keywords before and after the main()
method will be explained in future lessons.
- Print Statement
System.out.println("Greetings, Universe");
Inside the main()
method, we use the println()
method to print a line of text to the screen. Here, it prints “Greetings, Universe”.
Note: Curly braces {}
are used to denote the beginning and end of a code block.
Explanation:
System
is a built-in Java class that contains useful members, such asout
, which is short for “output”.- The
println()
method (short for “print line”) prints the specified value to the screen (or a file). Tip: Each statement in Java must end with a semicolon (;
).
Additional Information
- Case Sensitivity: In Java,
MyVariable
andmyVariable
are different identifiers. Always be mindful of the case when naming classes, methods, and variables. - Comments: You can add comments to your code using
//
for single-line comments or/* */
for multi-line comments. Comments are ignored by the compiler and are used to describe the code for better understanding.