Java Syntax Basics

Essential Java syntax: variables, data types, operators, control flow, and basic structure.

Main Method

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

Variables & Types

// Primitive types
int age = 25;  # whole numbers
double price = 19.99;  # decimals
boolean isActive = true;  # true/false
char grade = A;  # single character

// String
String name = "John";  # text

// Constants
final int MAX = 100;  # cannot change

Operators

// Arithmetic
+ - * / %  # basic math

// Comparison
== != > < >= <=  # compare values

// Logical
&& || !  # and, or, not

// Increment
i++ ++i i-- --i  # add/subtract 1

If-Else

// Basic if
if (age >= 18) {
    System.out.println("Adult");
}

// If-else chain
if (score >= 90) {
    grade = A;  # excellent
} else if (score >= 80) {
    grade = B;  # good
} else {
    grade = C;  # average
}

Switch Statement

// Switch case
switch (day) {
    case 1:
        System.out.println("Monday");
        break;  # exit switch
    case 2:
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Other");  # if no match
}

For Loop

// Standard for loop
for (int i = 0; i < 10; i++) {
    System.out.println(i);  # prints 0 to 9
}

// Enhanced for loop
for (int num : numbers) {
    System.out.println(num);  # iterate array
}

While Loop

// While loop
int i = 0;
while (i < 10) {
    System.out.println(i);
    i++;  # increment
}

// Do-while loop
do {
    System.out.println(i);
    i++;
} while (i < 10);  # runs at least once

Arrays

// Declare and initialize
int[] numbers = {1, 2, 3, 4, 5};

// Create with size
String[] names = new String[10];  # 10 elements

// Access elements
int first = numbers[0];  # get first
numbers[1] = 10;  # set second