JAVA BASICS
Java syntax
Java syntax is the set of rules for writing Java code. Let us examine a simple program line by line and see why it needs a class, a file name and the method main.
Example of a simple Java program
This program outputs the text “Labas, Java!” to the console:
public class Main {
public static void main(String[] args) {
System.out.println("Labas, Java!");
}
}Labas, Java!
The class and its name
Executable Java code is written inside a class. The first line in the example creates a class named Main. By the usual Java naming convention, a class name starts with an uppercase letter.
The class body is enclosed in braces { and }. They mark where the class begins and ends. All methods and other members belonging to the class are written between these braces.
MyClass and myclass would be two different names.
The file name must match
If a public class is named Main, its code must be saved in the file Main.java. The file name consists of the exact class name and the .java extension. For example, the class Car would be stored in the file Car.java.
If the public class name and file name do not match, the Java compiler reports an error. This makes it easy to link a public class to its source file in a Java project.
The main() method
A simple Java program starts executing in the method main. The Java Virtual Machine looks for this entry point and starts running the statements inside it.
public static void main(String[] args) For now, you do not need to understand every detail of the keywords public, static and void. They will be explained in later topics. At this stage, remember that main() is the program’s starting point, and the statements inside its braces run in order.
Outputting text
The statement System.out.println("Labas, Java!"); outputs text to the console and then moves the cursor to a new line. The text is enclosed in double quotes, and the statement ends with a semicolon.
In Java, a semicolon marks the end of many statements. If you omit it, the compiler will usually be unable to interpret the statement correctly and will report a syntax error.
What should you remember?
- Java code is written inside classes.
- A class name usually starts with an uppercase letter.
- The public class name and the
.javafile name must match. - The program starts executing in the method
main(). - Java is case-sensitive.
- Many Java statements end with a semicolon.