Java Cheatsheet

View saved

This sheet is a compact map of beginner-to-intermediate Java. Use it to recall syntax while you code; use the course for guided practice.

Every entry includes a definition and a small example you can paste into a .java file or REPL-like scratch class.

Program structure

main method

Entry point for a standalone program. The JVM looks for public static void main(String[] args).

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

package

Groups related classes and maps to a folder path. Declare package at the top of the file.

package com.example.demo;

public class Greeter { }

import

Brings another type into scope so you can use its short name.

import java.util.ArrayList;
import java.util.List;

List<String> names = new ArrayList<>();

System.out.println

Prints a line to standard output. Use print for no newline, printf for formatted text.

System.out.println("score=" + 95);
System.out.printf("pi≈%.2f%n", 3.14159);

Comments

// for one line, /* */ for blocks, /** */ for Javadoc on types and members.

// temporary note
/* multi-line */
/** Describes a method. */

Types & variables

Primitives

byte, short, int, long, float, double, char, and boolean. They are not objects and have default values in fields.

int count = 3;
double price = 9.99;
boolean ok = true;
char grade = 'A';

String

Immutable sequence of characters. Prefer equals() for content comparison, not ==.

String name = "Ada";
System.out.println(name.length());
System.out.println(name.equals("Ada"));

var (local type inference)

From Java 10, var lets the compiler infer a local variable's type from the initializer.

var message = "hi";      // String
var nums = new int[3];   // int[]

Casting

Narrowing conversions need an explicit cast. Widening (int→long) is implicit.

double d = 9.7;
int n = (int) d;  // 9
long big = n;

final

A final variable can be assigned only once. Final fields are often set in constructors.

final int MAX = 100;
// MAX = 200; // compile error

Control flow

if / else

Branch on a boolean condition. Braces are optional for one statement but recommended.

int score = 85;
if (score >= 90) {
  System.out.println("A");
} else if (score >= 80) {
  System.out.println("B");
} else {
  System.out.println("C");
}

switch

Select among discrete values. Modern Java supports switch expressions with yield/arrow forms.

int day = 2;
switch (day) {
  case 1 -> System.out.println("Mon");
  case 2 -> System.out.println("Tue");
  default -> System.out.println("Other");
}

for loops

Classic indexed for, enhanced for-each over arrays/iterables.

for (int i = 0; i < 3; i++) {
  System.out.println(i);
}
for (char c : "hi".toCharArray()) {
  System.out.println(c);
}

while / do-while

while checks first; do-while always runs the body once before checking.

int n = 3;
while (n > 0) {
  System.out.println(n);
  n--;
}

break / continue

break leaves the loop; continue skips to the next iteration.

for (int i = 0; i < 10; i++) {
  if (i % 2 != 0) continue;
  if (i > 6) break;
  System.out.println(i);
}

Methods & arrays

Method signature

Modifiers, return type, name, and parameter list. static methods belong to the class, not an instance.

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

Overloading

Same method name with different parameter lists. Return type alone is not enough to overload.

static int max(int a, int b) { return a > b ? a : b; }
static double max(double a, double b) { return a > b ? a : b; }

Arrays

Fixed-length, zero-based. Length is a field, not a method.

int[] nums = {3, 1, 4};
System.out.println(nums.length);
nums[1] = 2;

ArrayList

Resizable list from java.util. Stores objects (use Integer for ints via autoboxing).

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
names.add("Lee");
System.out.println(names.get(0));

Enhanced for + arrays

Read each element without managing an index. You cannot safely remove while iterating this way.

String[] tags = {"java", "jvm"};
for (String tag : tags) {
  System.out.println(tag);
}

Classes

class & fields

A class bundles state (fields) and behavior (methods). Instances are created with new.

public class Point {
  int x;
  int y;
}

Point p = new Point();
p.x = 3;

Constructors

Special methods named after the class. Initialize fields when an object is created.

public class Point {
  int x, y;
  public Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

Encapsulation

Keep fields private and expose controlled access with getters/setters or other methods.

public class Account {
  private double balance;
  public double getBalance() { return balance; }
  public void deposit(double amount) { balance += amount; }
}

Inheritance

extends reuses and specializes another class. A class may extend only one superclass.

class Animal {
  void speak() { System.out.println("..."); }
}
class Dog extends Animal {
  @Override
  void speak() { System.out.println("woof"); }
}

Exceptions

try/catch handles recoverable errors. Checked exceptions must be caught or declared with throws.

try {
  int n = Integer.parseInt("x");
} catch (NumberFormatException e) {
  System.out.println("bad number");
}

Common tools

javac / java

Compile .java to .class with javac, then run the class (or module) with java.

javac App.java
java App

classpath

Tells the JVM where to find user classes and JARs. Separate entries with : on Unix and ; on Windows.

javac -cp lib/*:. App.java
java -cp lib/*:. App

jar basics

Package classes into a JAR. A Main-Class manifest entry lets you run with java -jar.

jar cfe app.jar App App.class
java -jar app.jar

equals / hashCode reminder

Override both when instances are compared by value in sets or as map keys.

// If two objects are equal, their hashCodes must match.
// IDEs can generate equals/hashCode from fields.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.