Lesson 5: Basic Java Syntax, Comments, and Naming Conventions
Consistency and readability are crucial in programming.
1. Essential Syntax Rules
- Case Sensitivity: Java is case-sensitive.
myVariableis different frommyvariable. - Statements: Every statement in Java must end with a semicolon (
;). - Code Blocks: Curly braces (
{}) define a block of code (e.g., inside a class, method, or loop). - Whitespace: Java largely ignores extra whitespace (spaces, tabs, newlines) outside of string literals, but use it to format code clearly.
2. Comments
Comments are non-executable text used to explain code.
| Type | Syntax | Use Case |
|---|---|---|
| Single-line | // This is a comment | Explaining a specific line or variable. |
| Multi-line | /* ... */ | Commenting out large blocks of code. |
| Documentation (Javadoc) | /** ... */ | Generating external documentation. |
java /**
-
This class represents a Student object. */ public class Student { // This is a single-line comment private int age;
/*
- This is a multi-line comment
- describing the constructor. */ public Student(int age) { this.age = age; } }
3. Naming Conventions (Crucial for Readability)
Java follows strict conventions (CamelCase is primary):
| Item | Convention | Example |
|---|---|---|
| Classes | PascalCase (Start capitalized) | CarEngine, UserManager |
| Methods | camelCase (Start lowercase) | calculateTotal(), printDetails() |
| Variables | camelCase | firstName, currentSpeed |
| Constants | SCREAMING_SNAKE_CASE (All caps, underscores) | MAX_VALUE, PI_CONSTANT |
| Packages | all lowercase | com.mycompany.utils |