Java chapters

Chapter 16 of 17

Java Syntax Cheatsheet

Try this in our Java Compiler →

Everything in one place

Use this chapter as a quick reference once you've worked through the rest of the course. It collects every core construct of Java into runnable, copy-pasteable snippets you can scan whenever you forget the exact syntax.

Hello world & variables

```java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

int age = 25; String name = "Aman"; boolean isStudent = true; System.out.println(name + " " + age); ```

Data types & operators

```java
int n = 42;
double d = 3.14;
char c = 'A';
boolean b = true;
String s = "hello";
int[] arr = {1, 2, 3};

int a = 10, b = 3; System.out.println(a + b); System.out.println(a % b); System.out.println(a > b && b < 5); ```

Conditionals & loops

```java
int score = 72;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

for (int i = 0; i < 5; i++) { System.out.println(i); }

int n = 0; while (n < 3) n++; ```

Functions & arrays

```java
static int add(int a, int b) {
    return a + b;
}

public static void main(String[] args) { System.out.println(add(2, 3)); }

int[] nums = {10, 20, 30}; for (int n : nums) System.out.println(n);

import java.util.ArrayList; ArrayList list = new ArrayList<>(); list.add(40); ```

Strings & objects

```java
String name = "PlayLearn";
System.out.println(name.length());
System.out.println(name.toUpperCase());
System.out.println(name.contains("Learn"));

class User { String name; int age; User(String n, int a) { name = n; age = a; } String greet() { return "Hi " + name; } }

User u = new User("Aman", 20); System.out.println(u.greet()); ```

Errors, modules & I/O

```java
try {
    int n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
    System.out.println("Bad input: " + e.getMessage());
}

// File: util/Math.java package util; public class Math { public static int add(int a, int b) { return a + b; } }

// File: Main.java import util.Math; System.out.println(Math.add(2, 3));

import java.util.Scanner; Scanner sc = new Scanner(System.in); String name = sc.nextLine(); System.out.println("Hello, " + name); ```

How to use this page

Bookmark it. When you start a new project, open this cheatsheet alongside your editor and use it as a syntax lookup. Once a construct becomes second nature you'll stop needing the reference for it — and that's exactly when you know you've mastered that part of Java.

Try it yourself

Java Compiler
Output
Code runs on the Play with Coding execution engine — your code is saved locally for next time.