Every programming language possesses grammatical syntax rules governing how source code is constructed. In Java, syntax is heavily derived from C/C++, but enforces strict object-oriented structure and type safety.
A standard Java file follows a precise structural hierarchy organized into three primary sections:
// 1. Package Declaration (optional, must be first non-comment line)
package com.veewom.tutorial;
// 2. Import Statements (pulls in standard or external libraries)
import java.util.Scanner;
import java.time.LocalDate;
// 3. Class Declaration (encompasses variables and methods)
public class BankAccount {
// Instance variables (State)
private double balance;
// Methods (Behavior)
public void deposit(double amount) {
this.balance += amount;
}
// Main Method (Entry Point)
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(500.0);
System.out.println("Balance: " + acc.balance);
}
}
myVariable, MyVariable, and MYVARIABLE represent three distinct identifiers.public class, the filename must exactly match the class name with the .java extension (e.g. BankAccount.java). A single .java file can contain only one top-level public class.;). Missing semicolons cause immediate compiler syntax errors.{ ... }.Writing professional, maintainable code requires adhering to standard Java conventions:
| Element | Convention | Real-World Examples |
|---|---|---|
| Classes & Records | PascalCase (UpperCamelCase), noun | StudentRecord, OrderProcessingService, ArrayList |
| Interfaces | PascalCase, adjective or noun | Serializable, Comparable, PaymentGateway |
| Methods | camelCase (lowerCamelCase), verb | calculateTotal(), getUserById(), isEmpty() |
| Variables | camelCase, descriptive noun | accountNumber, studentAge, totalPrice |
| Constants | ALL_UPPERCASE with underscores | MAX_CAPACITY, DEFAULT_TIMEOUT_MS, PI |
| Packages | all_lowercase (reversed domain) | com.veewom.java, org.apache.commons |
Exam Question: "Can a Java program compile without a main method? Can it run without a main method?"
Answer: Yes, it compiles! A class without a main method compiles into .class bytecode without any error (this is how library helper classes are created). However, if you attempt to launch it using java ClassName, the JVM will fail at runtime with Main method not found in class.
Now let us explore how data is stored in memory using local, instance, and static variables. Proceed to: Java Variables & Scope →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Local, instance, and static variables.
Primitives, sizes, and memory models.
Parameters, return types, and overloading.
Single, multi-line, and Javadoc.