- All
- Programming
- Java Cheat Sheet
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
variable | piece of data that can hold a value |
object | represents something in real world |
class | definition of an object (like a blueprint or recipe) |
attribute | variable, part of a class, also called: field, member- or instance variable |
method | set 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
Type | Example values | Common operators |
---|---|---|
int | 3, 400, -200, 0 | + - / * % |
boolean | true 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;
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;
statement;
method2
statement;
statement;
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();