Java Syntax
In the earlier section, we created a simple Java file and displayed output
on the screen. Let’s now
understand the basic syntax rules that every Java
program follows.
Basic Java Example
Below is a simple Java program that prints a message to the
console.
File Name: Welcome.java
public class Welcome {
public static void main(String[] args) {
System.out.println("Java syntax made
simple");
}
}
Output
Java syntax made simple
How the Example Works
1. Java Classes
All executable Java code must be written inside a class.
A class name:
- Must begin with an uppercase letter by convention
- Acts as a container for your program logic
In this example, the class name is Welcome.
Important: Java is case-sensitive.
Welcome, welcome, and WELCOME are treated as different identifiers.
2. File Name Rule
The Java source file must have the same name as the class, followed by
the .java extension.
Example:
- Class name → Welcome
- File name → Welcome.java
If the file name and class name do not match, the Java compiler will
report an error and the program will not execute.
3. Entry Point of a Java Program
Every Java application starts running from the main
method:
public static void main(String[] args)
This method acts as the starting point of execution.
Any statements written inside this method are executed when the
program runs.
For now, you don’t need to fully understand the keywords public,
static, or void. Just remember:
Without the main() method, a Java program cannot run.
Printing Output in Java
Inside the main() method, Java provides a way to display text using
the println() method.
Example
public static void main(String[] args) {
System.out.println("Learning Java step by
step");
}
Explanation
- { } define the beginning and end of a block of code
- System is a built-in Java class
- out represents the output stream
- println() prints the text and moves the cursor to a new line
You can think of System.out.println() as a single instruction
that means:
“Display this message on the screen.”
Semicolon Rule
Every executable Java statement must end with a semicolon
(;).
It tells the compiler that the instruction is complete.