Java Syntax
Syntax means the rules of writing code. Java has strict rules, and the compiler tells you when you break one. Here are the most important ones.
A Java program
public class Main { // class
public static void main(String[] args) { // method
int age = 20; // statement
System.out.println("Age: " + age); // statement
}
}
Output
Age: 20
The rules
- All code is inside a class. (Java 25 compact files are an exception for small programs.)
- A statement ends with a semicolon
;. - Blocks use curly braces
{ }. A block groups many statements, like the body of a method or a loop. - Java is case sensitive.
name,NameandNAMEare three different names. - The file name must match the public class name, and the file ends with
.java. - Spaces and new lines do not matter, but good formatting makes the code easy to read.
Identifiers
An identifier is a name you give to a variable, method or class. The rules:
- It can have letters, digits,
_and$. - It cannot start with a digit.
- It cannot be a keyword like
class,intorfor. - It has no spaces.
public class Names {
public static void main(String[] args) {
int 2nd = 5;
}
}
Output
Names.java:3: error: not a statement
int 2nd = 5;
^
Names.java:3: error: ';' expected
int 2nd = 5;
^
2 errors
error: compilation failed
Naming conventions
| What | Style | Example |
|---|---|---|
| Class, interface, record, enum | PascalCase | StudentRecord |
| Method, variable | camelCase | totalMarks, getName() |
| Constant | UPPER_SNAKE_CASE | MAX_SIZE |
| Package | all small letters | com.example.shop |
Statements and blocks
public class Blocks {
public static void main(String[] args) {
int marks = 72;
if (marks >= 40) { // a block starts
System.out.println("Pass");
System.out.println("Well done");
} // a block ends
}
}
Output
Pass
Well done
Keywords
Java has about 50 reserved words, such as class, public, static, if, else, for, while, return, new, try and catch. You cannot use them as names. You will learn them step by step in this tutorial.
Note:
Follow the naming conventions from the start. All Java code in the world uses them, so your code will look familiar to every other developer. Next: Java Comments.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |