This cheat sheet summarizes common parts of the syntax of the Java programming language. It also provides techniques for handling common procedures. This sheet is not a complete overview.

Basics

Common terms

variablepiece of data that can hold a value
objectrepresents something in real world
classdefinition of an object (like a blueprint or recipe)
attributevariable, part of a class, also called: field, member- or instance variable
methodset of statements (code), part of a class

Hello World

public class HelloWorld {

  public static void main(String[] args) {
    // Write line of text to console:
    System.out.println("Hello World!");
  }
}

Built-in types

TypeExample valuesCommon operators
int3, 400, -200, 0+ - / * %
booleantrue false&& || !
char'a' '3', '/', '%'
String"Hello" "world peace" "3.5"+

int, boolean, char are primitive types, String is a class.

Variables and Types

Declare

int x;

Declare & assign value

int x = 0;

Type is an object

String name = "Fjodor";

Class

Definition

public class Person {
}

Object

Declare an object p of type Person:

Person p;

Declare & initialize

Object p becomes a new Person:

Person p = new Person();

Object p is an instance of the class Person.

Method

Definition: class with two methods

public class Person {
  public int determineLength() {
    return 89;
  }
  public void save() {
  }
}

Inheritance

Definition

public class Animal {
}

public class Dog extends Animal {
}

Writing style

variable names start with a lowercase letter;
class names start with a capital letter;
indent-code blocks;

Comments

/*
Multiple lines of comments
*/
// single-line comment
/**
@author
@parameter
Java-doc style of comment
*/
More on Javadoc

Code structure

source file (.java)

class

method1
statement;
method2
statement;
statement;

What goes in a source file?

public class Dog {




} // class

What goes in a class?

public class Dog {
  void bark() {


  } // method
}

What goes in a method?

public class Dog {
  void bark() {
	statement1;
	statement1;
  }
}

Conditions

Booleans

boolean b = true;

Boolean expression

10 < 3
wave >= 100

If

if ( tv.isOn() )

Boolean as result of method

tv.isOn()

Boolean operators

&& || !

Loops

For

for (int x=0; x<10; x++) {
}

While

int x=0;
while (x<10) {
  x++;
}

Break (out of loop)

int x=0;
while (true) {
  if (x==123) break;
  x++;
}

Do-while

int x=0;
do {
  x++;
} while (x<10)

Expressions

Basic

x = x + 1

Operators

x = x + 1

Call (=use) methods

Call method save() of object context

context.save();

Method returns a value

int length = determineLength();

Add your own

More info

Learn more at:

Alternative cheatsheets

API

An API is a description of a library. A library is a set of classes (also called: package) to add to your program.

Import

Put import statements at the top of your code. Use class ArrayList from package java.util:

import java.util.ArrayList;

public class MyClass {
  ArrayList myList;
}