Show Menu
Cheatography

Java - Beginner Syntax Cheat Sheet (DRAFT) by

A summary of all the Java programming language syntax I have learned so far. Still a noob so will have to be updated now and then.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Primitive data types

int
Main type for storing whole number­s/i­nte­gers.
float
Denotes real numbers with a smaller range and precision. Sufficient for storing 6 to 7 decimal digits. Precision is about 15 decimal digits.
double
Main type for real numbers. Sufficient for storing 15 decimal digits.
boolean
Stores only two possible values: true or false. Used to represent any binary situation, used mainly for recording decisions.
char
Stores a single charac­ter­/le­tter. Represents all types of charac­ters, including: Letters, formatting charac­ters, special charac­ters, and characters in other languages. Characters are written in single quotes.
byte
Stores whole numbers from -128 to 127.
short
Stores whole numbers from -32,768 to 32,767. Can store only less than int.
long
Stores whole numbers from about -(9e+18) to (9e+18). Can store more than int.
Primitive data types: A primitive data type specifies the size and type of variable values, and it has no additional methods.

Comments

Single line comments:
// Comment1

code
// Comment2


Multi-line comments:
/*
*
Comment

*
Continuing comment

*/
Comments: Comments are ignored by the computer, they are removed during compil­ation and exist simply to make the code easier for people to unders­tand.

General class definition and body

public class ClassName
{
     Fields
     Constructors
     Methods
}
Classes: Classes describe all objects of a particular kind, and determine the fields, constr­uctors, and methods these specific instances will all have.
Class names: By conven­tion, class names start with an uppercase letter (to distin­guish from other names like variables and methods.**
Classes and types: A class name can be used as the type for a variable. Variables that have a class as their type can store references to objects belonging to that class

General constr­uctor definition and body

public class ClassName
{
     Fields omitted

     public ClassName(paramtype paramname, etc.)
     {
          fieldName = fieldValue1;
          fieldName2 = fieldValue2;
          fieldName3 = paramname;
          ---etc.
     }

     Methods omitted
}
Constr­uctors: Constr­uctors are respon­sible for ensuring that an object is set up properly when it is first create­d/that an object is ready to be used immedi­ately following its creation.
Initia­lis­ation: This constr­uction process is also called initia­lis­ation. The constr­uctor initia­lises the fields.
Note: In Java, all fields are automa­tically initia­lised to a default value if they are not explicitly initia­lised (0 for integers etc.)

General while loops

while (boolean condition) {
     loop body*
}
While loops: A form of indefinite iteration loop.
Note: While the condition evaluates to true, then the body is executed; and once it evaluates to false, the iteration is finished
Note: The condition could evaluate to false on the very first time it is tested. If that happens, the body won't be executed at all.
Note: The while loop does not need to be related to a collec­tion. Even if processing a collec­tion, we do not need to process every element.

General do-while loops

do {
     loop body
} while (boolean condition);
Do-while loops: A form of indefinite iteration loop, but loop is executed at least once.
Note: While the condition evaluates to true, then the body is executed; and once it evaluates to false, the iteration is finished.
Note: The while loop does not need to be related to a collec­tion. Even if processing a collec­tion, we do not need to process every element.

Other keywords

void
Methods have return types that specify what type of data they return. If a method does not return any specific data, the return type is 'void'.
null
Object variables don't always refer to actual objects. When an object variable is first declared, it is initia­lised to the special value null, which means that the variable isn't pointing to an object.
this
In a 'name overlo­ading' situation where the same variable name is being used for 2 different entities in the same scope, the variable referenced will be the closest defined. To reference the field instead of the paramter write 'this.' before the name.
[Note to self: these may be sorted later into other groups as I cover more similar material]

Casting

(newdatatype) value
Casting: Casting means to change a value from one type to a "­cor­res­pon­din­g" value in another type.
Note: We can cast char values to their Unicode int values and vice versa.

Math

Math.abs
Absolute value
Math.pow
Raise to the power/ exponents
Math.max; Math.min
Find the maximum; Find the minimum
Math.sin; Math.cos; Math.tan
Trigon­ometry
Math.round
Round number
Math.PI; Math.E
Use constants of Pi and E
Math: Math defines pretty much all mathem­atical functi­onality that you will ever need.
Note: It has other methods that are not stated here.
Note: All of the methods in Math are static methods.

Changes to parame­ters, equality over objects

Method with primitive type parameter
Updates to that parameter are local only.
Method with object type parameter (e.g. array)
Parameter is a new variable but refers to the same object; changes are persis­tent.
Equality over arrays and objects
True if the variables point to the same object, false if not even if the contents of the objects are the same.
java.u­til.Ar­ray­s.e­qua­ls(­obj­ect1, object2)
True if the variables point to the same objects and also if the contents of different objects are the same.

Final variables

private final datatype variableName = variableValue; OR
private static final datatype variableName = variableValue
Final variables: Final variables must be initia­lised immedi­ately and can never be changed.

Throwing unchecked exceptions

public returntype methodName(paramtype paramvalue etc.) {
     code body
     if boolean_exception {
          throw new ExceptionName ("exception message")
     }
     code body
}
Unchecked except­ions: When an exception is thrown and it is an unchecked exception, the system halts with an error message. It is a standa­rdized way to deal with errors to provide inform­ative feedback.
Error type: Used with client code is seriously wrong - attempts to use your methods incorr­ectly by passing incorrect parameter values.
 

Object data types

String
Used to represent a sequence of charac­ters, including: names, addresses, general text etc. Strings are written in double quotes.
ArrayList
A Java class from the java.util package.
Random
A java class from the java.util package
Object data types: Data types that are actually objects, which contain methods that can be called to perform certain operations on them.

Logical operators

a && b
a and b are both true (and).
a || b
At least one of a and b is true (or).
!a
a is false/not a (not).
Preced­ence: && has a higher precedence than ||.

Arithmetic operators

+
Addition - adds together two values.
-
Subtra­ction - subtracts one value from another.
*
Multip­lic­ation - multiplies two values together.
/
Division - divides one value by another. When dividing integers the remainder is truncated (integer division); when dividing doubles the return value is exact.
%
Modulus - returns the remainder of dividing the one value from another.
++
Increment - increases the value of the following variable by 1.
--
Decrement - decreases the value of the following variable by 1.
Arithmetic operators: Used to perform common mathem­atical operat­ions.
Preced­ence: Precedence and associ­ativity are as normal as in maths.

General method definition and body

public class ClassName
{
     Fields and constructor omitted

     public returntype methodName(paramtype1 paramname1, etc.)
     {
          statement1;
          statement2;
          Body continued
     }
     
     Other possible methods omitted
}
Methods: Objects have methods that we use to commun­icate with them. We can use a method to make a change or to get inform­ation from the object.

Condit­ional statem­ents/ if-els­e-s­tat­ements

if (perform some test) {
     do these statements if the test gave a true result
}
else if (perform some test) {
     do these statements if the if-statement and else if
     -statements above returned false,
     but the test for this statement returned true.
}
else {
     do these statements none of the above tests returned true
}
Note: It is possible to have only 1 if-sta­tement and no else if or else statem­ents. There can also be many if-sta­tements and else if statements in the same block.

Importing library classes

import librarypackage.ClassName; OR
import librarypackage.*
Note: Usually happens at the very top of the program.
Note: Using * means that all classes in that package is imported.
Note: Some library classes are imported automa­tic­ally, including Math, String, Integer, Character, Boolean etc.

Creating objects

Object creation:
objectName = new ClassN­ame­(pa­ram­value, etc.);


Creating object for field:
private ClassName fieldName;

...
fieldName = new ClassN­ame­(pa­ram­value, etc.);
Note: Done in the constr­uctor. Can also create an object assignment to a field, making the field point to the object, but the field variable will have to be declared first
Note: If you haven't called 'new', you haven't created an object.

General for-each loops

for (elementType element : collectionName) {
     loop body
}
For-each loops: A type of definite iteration.
Note: For each element in collec­tion, execute loop body.
Note: The new local variable ('elem­ent') used to hold the list elements in order is called the 'loop variable' (any name possible). The type of the loop variable must be the same as the declared element type of the collec­tion.
Note: We cannot change what is stored in the collection while iterating, but can change the states of objects already within the collec­tion.

General for loops

for (initialisation; boolean condition; post-body action) {
     loop body
}
For-each loops: A type of indefinite iteration.
Note: For each element in collec­tion, do the things in the loop body.
Condit­ionals: Condit­ion­als­/if­-st­ate­ments can be used in loops.

General JUnit test

@Test
public void testmethod() {
     setup code
     assertEquals(paramvalues)
}

^
assertEquals(errorMessage, correctReturn, methodcall) OR
assertEquals(errorMessage, correctReturn, methodcall, double) OR
assertTrue(errorMessage, correctReturnBoolean) OR
assertFalse(errorMessage, correctReturnBoolean)
JUnit tests: JUnit classes run your code and compare actual results with expected results.
Note: Some limita­tions are that - printing can't be tested; can test only changes to an objects state/­values returned by methods; can test only 'public' methods; can't see inside methods.

Static methods

public static returntype methodName(paramtype parameter etc.)
Static methods: In static methods, the values returned don't depend on the state of an object, only on the arguments provided i.e. you can call a static method without creating an object first. (In fact it is sometimes impossible to create an object)
Note: They are sometimes called class methods.
Note: Can be invoked with the class name, rather than an object name.

Dealing with arrays

Declaring arrays:
datatype[] arrayName;
OR
datatype[] arrayName = {varia­ble1, variable2, etc.};
(array literals)
dataty­pe[][] arrayName:
etc. for 2d, 3d + arrays

Creating arrays:
arrayName = new dataty­pe[­noO­fVa­ria­bles];

arrayName = new dataty­pe[­]{v­ari­able1, variable2, etc.}
(array literals)

Size of array:
arrayN­ame.length


Refere­ncing elements:
arrayN­ame­[index]
Arrays: Arrays are fixed-size collec­tions that can store object references or primitive values. It is an indexed sequence of variables of the same type.
Note: The variables do not have individual names.
Refere­ncing elements: Elements can be used in the same ways and in the same contexts as any other variable of that type.
Note: Arrays can share memory - 'Alias­ing'.
Objects: When using an arrays with elements of object type, you also have to populate the array with a loop.

Making assertions

code body
assert booleanCondition : "string";
code body
Assert­ions: A debugging mechanism to use when you are developing compli­cated code. When the assertion is executed, the boolean condition is evaluated. If it is true, execution continues. If it is false, execution is halted with an (unche­cked) Assert­ion­Error, and the message string is printed.
Error types: Logic errors. Check what values a given variable has compared to what it should have.
 

Relati­ona­l/C­omp­arison operators

==
Equal to
!=
Not equal to
<
Less than
<=
Less than or equal to
>
Greater than
>=
Greater than or equal to
Relational operators: Operators used to compare two values - usually numbers, but also sometimes other types.
Preced­ence: All have lower precedence than all arithmetic operators, and higher than all logical operators.

Augmented assign­ment/ Assignment operators

a += b;
Equivalent to a = a + b;
a -= b;
Equivalent to a = a - b;
a *= b;
Equivalent to a = a * b;
a /= b;
Equivalent to a = a / b;
a %= b;
Equivalent to a = a % b;
a &= b;
Equivalent to a = a && b;
a != b;
Equivalent to a = a || b;
Augmented assign­ment: Java supports augmented assignment for common arithmetic and logical operators.

General field definition and body

public class ClassName
{
     private type fieldName;
     private type2 fieldName2;
     ---etc.
     
     Constructors and methods omitted
}
Fields: Fields store data persis­tently within an object, that have values that can vary over time. Also known as instance variables. Every object will have space for each field declared in its class.

General variable declar­ation and assignment

Field declar­ation (see other cheat block):
private type variab­leName;


Local variable declar­ation:
type variab­leName;


Assignment statement:
variab­leName = newValue;

variab­leName = 2 * variab­leName;

variab­leName = variab­leName ** 2 + 5;


Shorthand (decla­ration + assign­ment):
type variab­leName = newValue;
Variables: The basic mechanism by which data is organised and stored (long-­term, short-­term, and commun­ication etc.). Variables must be declared before it is used.
Variable names: Variable names should always start with a lower-case letter.
Local variables: A local variable is defined inside a method body, as opposed to a field variable that is defined outside the method and a parameter that is always defined in the method header.

Dealing with Strings

"­Str­ing­a" + "­Str­ing­b" -> "­Str­ing­aSt­rin­gb"
String concat­ena­tion, achieved with the + operator
System.ou­t.p­rin­t("S­tri­ng") OR System.ou­t.p­rin­tln­("St­rin­g")
String printing. println enters to a new line at the end in addition to displaying the string.
\n
Prints to a new line. Also known as 'carri­age­-re­turns'
\t
Prints the tab character.
String.to­Low­erC­ase(); String.to­Upp­erC­ase();
Changes all characters in the string to lowerc­ase­/up­per­case.
String.le­ngth()
Returns the number of characters in the string.
String.ch­arA­t(i­nde­xnu­mber)
Returns the character at the given index.
String­1.c­omp­are­To(­Str­ing2)
Compares 2 strings. It returns a negative number if the target comes before the argument, a positive number if the target comes after the argument, 0 if they are equal.
Strings: Strings are used to represent a sequence of charac­­ters, including: names, addresses, general text etc. They are written in double quotes.
Note: String is a class defined in the library
Note: Strings in Java are immutable objects (they cannot be changed after they are created).
Ordering: Ordering is by the first letter in which they differ, otherwise by their length. (Note that it is based on Unicode values - not save for case and punctu­ation etc.)

Method calls

Internal method calls:
method­Nam­e(p­ara­mva­lue1, paramv­alue2, etc.)


External method calls:
object­Nam­e.m­eth­odN­ame­(pa­ram­value1, paramv­alue2, etc.)
Internal method calls: When an object calls a method on itself. In this case the object name will not need to be specified.
External method calls: When one of the methods of the object in turn calls a method of another object to do part of the task. In this case the object the method is called on needs to be specified.

Dealing with ArrayLists

Declaring ArrayList field variables:
private ArrayL­ist­<ty­pe> variab­leName;

Declaring ArrayList local variables:
ArrayL­ist­<ty­pe> variab­leName;


Creating the collec­tion:
variab­leName = new ArrayL­ist­<>();

or
variab­leName = new ArrayL­ist­<ty­pe>();


'add' operation:
variab­leN­ame.add(expression of the approp­riate type);

'size' operation:
variab­leN­ame.si­ze();

'get' operation:
variab­leN­ame.get(index);

'remove' operation:
variab­leN­ame.re­move(index);
ArrayList: A Java class from the java.util package. Dynami­cally sized collec­tion, can store both object references or primitive values.
Operat­ions:
- add: Adds the written object to the end of the collec­tion.
- size: returns an int of the collection size
- get: retrieve an item from a specified index
- remove: removes an item from a specified index. Will move up the indices of items behind it.
[- others: search online]

Chaining method calls

objectName.methodName1().methodName2().methodName3().etc.
Note: This looks as if methods are calling methods, but the chain of method calls must be read strictly from left to right.

Access modifiers

Public modifiers:
public datatype variab­leName;
OR
public returntype method­Nam­e(p­ara­meters)


Private methods:
private datatype variab­leName;
OR
private returntype method­Nam­e(p­ara­meters)
Public method­s/v­ari­ables: Public fields, methods and constr­uctors in a class can be access­ed/­invoked from any class in the program.
Private method­s/v­ari­ables: Private fields, methods and constr­uctors in a class can be access­ed/­invoked only from the class where it is defined.

Enumerated types

Creating enum class:
public enum ClassName

{VALUE­1,V­ALUE2, VALUE3, etc...}


Accessing values:
ClassN­ame.VALUE


Built-in facili­ties:
Compared for equality and inequa­lity:
variable1 == variable2

Added to strings:
"­Str­ing­" + variable

Processed using for-each loop:
for (ClassName variale : ClassN­ame.va­lues()) {...}

Ordered using ordinal(): variab­le.o­rd­inal()
Enum: Used to represent discrete data with only a small number of possible values.

Throwing checked exceptions

public returntype methodName(paramtype paramvalue etc.) throws ExceptionName {
     code body
     if boolean_exception {
          throw new ExceptionName ("exception message")
     }
     code body
}

// Client code:
accessmod returntype anotherMethod(paramtype paramvalue etc.) {
     try {
          code body (for when everything is fine)
     }
     catch (ExceptionName e) {
          code for when things go wrong
     }
     catch (ExceptionName e) {
          code for when things go wrong
}
Checked except­ions: When an exception is thrown and it is a checked exception, the system tries to find some object in the program able to deal with it without crashing
Note: More compli­cated than unchecked exceptions - method is required to declare it might throw except­ions; and client code is required to provide code that will be run if so
Error type: Situations that are not entirely unexpected and from which clients may be able to recover.