Java Syntax & Structure
In this page:
Case Sensitivity
Java treats uppercase and lowercase letters as entirely different characters, so myVariable and MyVariable are two distinct identifiers -- this trips up beginners coming from case-insensitive languages.
Example: Case Sensitivity
public class Main {
public static void main(String[] args) {
int myVariable = 1;
int MyVariable = 2;
System.out.println(myVariable + " and " + MyVariable + " are different variables.");
}
}
Login to try C/C++/Java/PHP code in the editor
Curly Braces
Every class body, method body, loop, and conditional block is delimited by a matching pair of curly braces, and a missing or misplaced brace is one of the most common compiler errors you'll encounter.
Example: Curly Braces
public class Main {
public static void main(String[] args) {
if (true) {
System.out.println("Inside the if block");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Class Naming Conventions
Convention (enforced by tooling, not the compiler) says class names use PascalCase, capitalizing the first letter of each word, like BankAccount or HttpClient -- following it keeps your code readable to other Java developers.
Example: Class Naming Conventions
class BankAccount {
double balance;
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
System.out.println("Class named in PascalCase: BankAccount");
}
}
Login to try C/C++/Java/PHP code in the editor
Method Naming Conventions
Method names follow camelCase instead, starting lowercase, like calculateTotal() -- this visual distinction from PascalCase class names helps you tell at a glance whether an identifier is a type or a behavior.
Example: Method Naming Conventions
public class Main {
static int calculateTotal(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("Method named in camelCase: " + calculateTotal(2, 3));
}
}
Login to try C/C++/Java/PHP code in the editor
Indentation and Whitespace
The compiler doesn't care how you indent your code, but consistent indentation (typically 4 spaces per nesting level) is what makes deeply nested loops and conditionals actually readable to a human.
Example: Indentation and Whitespace
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
System.out.println("Consistently indented nested block: " + i);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: