Java Syntax - Complete Guide
Basic Syntax Rules
Java syntax is influenced by C and C++, but it enforces strict rules to reduce errors and improve readability.
Important rules include:
• **Case Sensitivity**: Java is case-sensitive. For example, `MyClass` and `myclass` are different identifiers.
• **Class Names**: Should begin with an uppercase letter and use CamelCase convention.
• **Method Names**: Should begin with a lowercase letter and use camelCase convention.
• **Source File Name**: Must match the public class name exactly, with a `.java` extension.
• **Main Method**: The entry point must be `public static void main(String[] args)`.
Java Statements and Blocks
Statements are instructions that tell the program what to do. A block is a group of statements enclosed in curly braces `{}`.
Every statement must end with a semicolon (`;`).
// Single statement
int x = 10;
// Block of statements
{
int y = 20;
int sum = x + y;
System.out.println(sum);
}
Comments in Java
Comments are ignored by the compiler and serve to make code easier to understand. Java supports three styles of comments:
// Single-line comment
/*
* Multi-line comment
* Spans multiple lines
*/
/**
* Documentation comment
* Used by Javadoc to generate docs
* @param name the name to greet
*/
public void greet(String name) {
System.out.println("Hello, " + name);
}
Identifiers and Keywords
Identifiers are names for variables, methods, classes, and more. Rules for identifiers:
• May contain letters, digits, underscores, and dollar signs.
• Must start with a letter, underscore, or dollar sign (not a digit).
• Cannot be a Java keyword (e.g., `class`, `public`, `static`).
Keywords are reserved words with special meaning and cannot be used as identifiers.
Packages and Imports
Packages group related classes and help avoid name conflicts. The `import` statement lets you use classes from other packages without writing their fully qualified names.
// Package declaration (must be the first line)
package com.example.myapp;
// Import specific classes
import java.util.ArrayList;
import java.util.Scanner;
// Import all classes from a package
import java.util.*;
public class MyClass {
// Class implementation here
}
Common Syntax Pitfalls
- ❌ Missing semicolons at the end of statements
- ❌ Mismatched or missing curly braces `{}`
- ❌ Wrong case for class or method names
- ❌ File name not matching the public class name
- ❌ Main method missing or using wrong signature
- ❌ Forgetting to import required classes
Best Practices
- ✅ Follow Java naming conventions consistently
- ✅ Use proper indentation (commonly 4 spaces)
- ✅ Write comments for complex or important logic
- ✅ Keep classes and methods focused on one task
- ✅ Organize your code into packages logically
- ✅ Use appropriate access modifiers to limit scope