Java Syntax
java syntax semicolon curly braces identifiers keywords comments naming conventions camelCase PascalCase main method case sensitive
Introduction
Every programming language has a set of rules that define how code should be written. These rules are called syntax.
Think of syntax as the grammar of a programming language.
Just as English sentences must follow grammatical rules to make sense, Java programs must follow Java syntax rules to compile and run successfully.
Even a small mistake—such as a missing semicolon or incorrect capitalization—can cause compilation errors.
Understanding Java syntax is the first step toward writing clean, readable, and professional Java code.
In this lesson, you'll learn:
- Basic Java program structure
- Java statements
- Blocks
- Comments
- Case sensitivity
- Identifiers
- Keywords
- Whitespace
- Semicolons
- Curly braces
- Code formatting
- Naming conventions
- Real-world examples
- Best practices
- Common mistakes
- Hands-on exercises
- Professional interview questions
By the end of this lesson, you'll be able to read and write basic Java programs confidently.
Your First Java Program
Let's begin with a simple Java program.
public class Main {public static void main(String[] args) {System.out.println("Hello, Java!");}}
Output:
Hello, Java!
Although this program is small, it contains several important syntax elements.
Let's understand each one.
Understanding the Program
Class Declaration
public class Main
Every Java application is built using classes.
Here:
publicis an access modifier.classis a Java keyword.Mainis the class name.
A class acts as a blueprint for creating objects.
Main Method
public static void main(String[] args)
This is the entry point of every Java application.
When you run a Java program, the JVM starts execution from the main() method.
We'll study methods in detail later in this course.
Printing Output
System.out.println("Hello, Java!");
This statement prints text to the console.
Systemis a predefined Java class.outrepresents the standard output stream.println()prints text and moves to the next line.
Java Statements
A statement is a complete instruction.
Example:
int age = 25;
Another example:
System.out.println(age);
Each statement tells the compiler to perform a specific task.
Semicolons (`;`)
Almost every Java statement ends with a semicolon.
Example:
int salary = 50000;
Incorrect:
int salary = 50000
Output:
Compilation Error
The semicolon tells the compiler where one statement ends and the next begins.
Curly Braces (``)
Curly braces define a block of code.
Example:
if (true) {System.out.println("Welcome");}
Braces group related statements together.
You'll use them in:
- Classes
- Methods
- Loops
- Conditional statements
Java is Case-Sensitive
Java treats uppercase and lowercase letters as different characters.
Example:
int age = 25;
This is different from:
int Age = 25;
And different from:
int AGE = 25;
All three are separate variables.
Keywords
Keywords are reserved words that have predefined meanings in Java.
Examples include:
classpublicprivatestaticvoidifelseforwhilereturnnew
You cannot use keywords as variable or class names.
Incorrect:
int class = 10;
This causes a compilation error.
Identifiers
Identifiers are names given to:
- Variables
- Methods
- Classes
- Objects
- Packages
Example:
String studentName;
Here, studentName is an identifier.
Rules for Identifiers
Identifiers:
- Can contain letters, digits,
_, and$. - Cannot begin with a digit.
- Cannot contain spaces.
- Cannot be Java keywords.
Valid:
studentNameemployeeIdtotalAmount
Invalid:
2nameemployee nameclass
Whitespace
Java ignores extra spaces, tabs, and blank lines.
Example:
int age = 25;
and
int age = 25;
Both compile successfully.
However, proper formatting greatly improves readability.
Comments
Comments help explain code.
The compiler ignores comments.
Single-Line Comment
// This is a comment
Multi-Line Comment
/*Thisisamulti-linecomment.*/
Documentation Comment
/*** Calculates employee salary.*/
Documentation comments are used by tools that generate API documentation.
Java Naming Conventions
Professional developers follow naming conventions to improve readability.
Class Names
Use PascalCase.
Good:
EmployeeStudentManagerBankAccount
Variable Names
Use camelCase.
Good:
firstNametotalPricestudentAge
Method Names
Also use camelCase.
Examples:
calculateSalary()sendEmail()printInvoice()
Constant Names
Use uppercase with underscores.
Example:
MAX_USERSDEFAULT_TIMEOUT
Code Formatting
Readable code is easier to understand and maintain.
Good:
if (marks >= 35) {System.out.println("Pass");}
Poor:
if(marks>=35){System.out.println("Pass");}
Although both work, the first version is much easier to read.
Real-World Example
Imagine you're working with a team of 50 developers.
Everyone follows the same naming conventions and formatting style.
Benefits include:
- Easier code reviews
- Faster debugging
- Better collaboration
- Reduced misunderstandings
Clean code is just as important as working code.
Common Compilation Errors
Missing Semicolon
int age = 20
Incorrect Capitalization
system.out.println("Hello");
Correct:
System.out.println("Hello");
Missing Curly Brace
public class Main {public static void main(String[] args) {System.out.println("Hello");
The compiler reports an error because the closing braces are missing.
Invalid Identifier
int 2salary = 1000;
Variable names cannot begin with numbers.
Best Practices
Use Meaningful Names
Instead of:
int x;
Use:
int employeeSalary;
Descriptive names make the code self-explanatory.
Keep Formatting Consistent
Indent your code properly.
Most IDEs can automatically format Java code.
Write Comments Wisely
Comment why something is done rather than repeating what the code already says.
Good comments explain intent.
Keep Methods Small
As you begin writing methods, aim for small, focused methods that perform one task well.
Let the IDE Help You
Modern IDEs highlight syntax errors as you type and can suggest fixes.
Use these features to learn and write cleaner code.
Common Mistakes
Forgetting Semicolons
One of the most common beginner errors.
Using Reserved Keywords as Identifiers
Keywords such as class or return cannot be used as variable names.
Ignoring Case Sensitivity
main, Main, and MAIN are different identifiers.
Poor Naming
Avoid names like:
axtemp
Prefer descriptive names.
Inconsistent Formatting
Poor formatting makes code harder to understand and maintain.
Hands-on Exercise
Complete the following tasks:
- Write a Java program that prints your name.
- Create a class named
Student. - Declare three variables using proper naming conventions.
- Add single-line, multi-line, and documentation comments.
- Intentionally remove a semicolon and observe the compiler error.
- Try using a Java keyword as a variable name and see the resulting error.
- Format your code using your IDE's auto-format feature.
These exercises will help you become comfortable with Java syntax and compiler feedback.
Summary
Java syntax provides the rules that every Java program must follow.
Understanding statements, semicolons, braces, comments, identifiers, keywords, and naming conventions is essential for writing clean, readable, and error-free code.
Strong syntax skills form the foundation for learning variables, control statements, object-oriented programming, and advanced Java concepts.
Key Takeaways
- Java is a case-sensitive programming language.
- Every Java program starts execution from the
main()method. - Most statements end with a semicolon.
- Curly braces define blocks of code.
- Identifiers must follow Java naming rules.
- Keywords are reserved and cannot be used as identifiers.
- Comments improve code readability and documentation.
- Consistent formatting and naming conventions lead to professional-quality code.
Professional Interview Questions
1Why is Java case-sensitive?
Professional Answer
Java treats uppercase and lowercase letters as different characters. This allows identifiers such as age, Age, and AGE to represent different variables or methods. Case sensitivity helps avoid ambiguity and ensures consistent program behavior.
Follow-up Questions
- Is Main the same as main?
- Why is System written with an uppercase S?
Interview Tip: Use simple examples like age and Age to explain the concept clearly.
2What is the purpose of the main() method?
Professional Answer
The main() method is the entry point of a Java application. When the JVM starts a Java program, it looks for the public static void main(String[] args) method and begins execution from there.
Follow-up Questions
- Why is main() declared as static?
- Can a Java program have multiple methods named main()?
Interview Tip: Remember the exact signature of the standard main() method, as interviewers often ask for it.
3What are identifiers in Java?
Professional Answer
Identifiers are user-defined names assigned to classes, methods, variables, packages, and objects. They must follow Java naming rules, such as not starting with a digit and not using reserved keywords.
Follow-up Questions
- Can an identifier contain underscores?
- Can an identifier start with $?
Interview Tip: Mention both the naming rules and recommended naming conventions to show a professional understanding.