Java Syntax

Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Line one");
        System.out.println("Line two");
    }
}

The rules

  • Every statement ends with a semicolon.
  • Blocks are wrapped in { }.
  • Java is case-sensitive: myVar and myvar differ.
  • Class names use PascalCase; methods and variables use camelCase; constants use UPPER_SNAKE_CASE.
Java
System.out.print("no newline");
System.out.println("with newline");
System.out.printf("Name: %s, Age: %d, Price: %.2f%n", "Sita", 21, 1250.5);

Common format specifiers: %s string, %d integer, %f float, %.2f two decimal places, %n newline, %% a literal percent.

Comments

Java
// single line

/* multi
   line */

/**
 * Javadoc comment — used to generate API documentation.
 * @param name the person's name
 * @return a greeting
 */

Reading input

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = sc.nextLine();

        System.out.print("Enter your age: ");
        int age = sc.nextInt();

        System.out.println("Hello " + name + ", age " + age);
        sc.close();
    }
}

Watch out: nextInt() leaves the newline in the buffer, so a following nextLine() returns an empty string. The usual fix is an extra sc.nextLine() after reading a number.

Knowledge Check

4 questions — test your understanding

1

What is the difference between an ArrayList and a LinkedList?

2

What does `Collections.unmodifiableList()` return?

3

What is the difference between HashMap and TreeMap?

4

What does the enhanced for loop `for (String s : list)` do?