Web Analytics

Java Syntax Basics

Beginner ~20 min read

Understanding Java syntax is essential for writing correct, readable code. In this lesson, you'll learn about statements, code blocks, semicolons, whitespace handling, comments, and Java naming conventions. These fundamental rules form the foundation of all Java programming.

Statements

A statement is a complete instruction that performs an action. In Java, statements must end with a semicolon (;).

Output
Click Run to execute your code
Statement Types:
  • Declaration statements: Declare variables (e.g., int x;)
  • Expression statements: Assignments or method calls (e.g., x = 5;)
  • Control statements: Control flow (if, for, while, etc.)

Semicolons

In Java, almost every statement must end with a semicolon. The semicolon tells the compiler where one statement ends and the next begins.

Output
Click Run to execute your code
Important: Missing semicolons cause compilation errors. The compiler will report an error like ';' expected. However, class and method declarations don't need semicolons after their closing braces.

Code Blocks

A block is a group of statements enclosed in curly braces {}. Blocks define scope and group related statements together.

Output
Click Run to execute your code

Block Rules

  • Blocks start with { and end with }
  • Variables declared inside a block are only accessible within that block (scope)
  • Blocks can be nested (a block inside another block)
  • Opening brace can be on the same line or next line (style preference)
Brace Style: Two common styles:
  • Same-line: if (condition) { (K&R style)
  • Next-line: if (condition)\n{ (Allman style)
Choose one style and be consistent throughout your code.

Whitespace

Java is generally whitespace-insensitive - extra spaces, tabs, and blank lines are mostly ignored by the compiler. However, whitespace is important for code readability.

Output
Click Run to execute your code
Whitespace Type Usage Example
Spaces Separate tokens, improve readability int x = 5; vs int x=5; (both valid, first is clearer)
Tabs Indentation (typically converted to spaces) Used for code indentation
Newlines Separate statements, improve readability One statement per line is standard practice
Blank lines Separate logical sections Improve code organization
Best Practice: Use consistent indentation (typically 4 spaces or 1 tab). Most IDEs can automatically format your code according to your preferences.

Comments

Comments are notes in your code that the compiler ignores. They help document your code for yourself and other programmers. Java supports three types of comments:

Output
Click Run to execute your code

Comment Types

Type Syntax Use Case Example
Single-line // Short notes, inline explanations // This is a comment
Multi-line /* */ Block of comments, longer explanations /* This is a\nmulti-line comment */
JavaDoc /** */ Documentation comments (generates API docs) /** This is JavaDoc */

JavaDoc Comments

JavaDoc comments start with /** and are used to generate HTML documentation. They can include special tags like @param, @return, @author, etc.

Output
Click Run to execute your code
When to Comment:
  • Explain why you're doing something (not what - code should be self-explanatory)
  • Document complex algorithms or business logic
  • Provide usage examples for methods
  • Note temporary workarounds or known issues
Don't Over-Comment: Avoid comments that just repeat what the code does. int x = 5; // Set x to 5 is a bad comment - it's obvious from the code.

Naming Conventions

Java has established naming conventions that make code more readable and maintainable. While not enforced by the compiler, following these conventions is essential for professional Java development.

Output
Click Run to execute your code

Java Naming Rules

Element Convention Example Notes
Class names PascalCase HelloWorld, BankAccount Each word capitalized, no underscores
Method names camelCase calculateTotal(), getUserName() First word lowercase, subsequent words capitalized
Variable names camelCase userName, totalAmount Same as method names
Constants UPPER_SNAKE_CASE MAX_SIZE, DEFAULT_VALUE All uppercase, words separated by underscores
Package names lowercase com.example.util All lowercase, dots separate words

Identifier Rules

Identifiers (names for classes, methods, variables) must follow these rules:

  • Must start with a letter (a-z, A-Z), underscore (_), or dollar sign ($)
  • Can contain letters, digits (0-9), underscores, and dollar signs
  • Cannot be Java keywords (like class, int, void)
  • Case-sensitive (myVar and MyVar are different)
  • No length limit, but keep them reasonable and meaningful
Output
Click Run to execute your code
Good Naming:
  • Use descriptive names: calculateTotal() instead of calc()
  • Use verbs for methods: getUser(), setName(), calculatePrice()
  • Use nouns for variables: userName, totalPrice, isValid
  • Avoid abbreviations unless well-known: calculateTotal() not calcTot()

Common Mistakes

1. Missing semicolons

// Wrong
int x = 5
System.out.println(x)

// Correct
int x = 5;
System.out.println(x);

2. Mismatched braces

// Wrong - missing closing brace
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello");
    // Missing }

// Correct
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

3. Using keywords as identifiers

// Wrong - 'class' is a keyword
int class = 5;  // Error!

// Wrong - 'void' is a keyword
String void = "test";  // Error!

// Correct - use descriptive names
int studentClass = 5;
String returnValue = "test";

4. Starting identifiers with numbers

// Wrong
int 2value = 5;  // Error!

// Correct
int value2 = 5;
int secondValue = 5;

5. Inconsistent naming

// Wrong - mixing conventions
int UserName = "John";  // Should be camelCase
int user_name = "John";  // Should be camelCase, not snake_case

// Correct
int userName = "John";

Exercise: Fix the Code

Task: Fix all syntax errors and follow Java naming conventions!

Requirements:

  • Fix missing semicolons
  • Fix mismatched braces
  • Use proper naming conventions
  • Add appropriate comments
  • Make the code compile and run
Output
Click Run to execute your code
💡 Hint

Check for: missing semicolons, proper class name matching filename, correct brace placement, and camelCase for variables.

Summary

  • Statements must end with a semicolon (;)
  • Code blocks are enclosed in curly braces {}
  • Java is whitespace-insensitive but use whitespace for readability
  • Three comment types: // (single-line), /* */ (multi-line), /** */ (JavaDoc)
  • Class names: PascalCase (e.g., HelloWorld)
  • Methods and variables: camelCase (e.g., userName)
  • Constants: UPPER_SNAKE_CASE (e.g., MAX_SIZE)
  • Identifiers must start with a letter, underscore, or dollar sign
  • Cannot use Java keywords as identifiers
  • Java is case-sensitive

What's Next?

Great! You now understand the fundamental syntax rules of Java. In the next module, you'll learn about variables and data types - the building blocks for storing and manipulating data in your Java programs.