Show Menu
Cheatography

Java Mastery 2 Cheat Sheet (DRAFT) by

Another version of the Java cheatsheet

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

Java Structure

Package
contains one or more classes.
Class
contains one or more fields and methods.
Method
contains declar­ations and statem­ents.
Statement
contains declar­ations, statem­ents, and expres­sions.
These may contain comments:
Single line:
//
Multi-line
starts with / and ends with /
Docume­ntation notes
starts with /* and ends with /, put before the definition of a variable, method or class

Data Types and Variable Declar­ation

int
holds integer values (between −231 and 231 − 1).
double
holds floati­ng-­point numbers (i.e., numbers containing a decimal point).
boolean
holds a true or false value.
char
holds single charac­ter­s(can also be used as numbers)
float 
holds less accurate floati­ng-­point numbers.
byte, short and long
holds integers with fewer or more digits.
String
composed of zero or more chars, it is an object, not a primitive type.
Variable declar­ation examples:
int age;     //without initial value

int count = 0;      //with initial value of 0

double distance = 37.95;

boolean isReadOnly = true;

String greeting = "­Welcome to SP2";

String output­Line;

Enumer­ation types

An easy way to name a finite list of values that a variable can hold
Like declaring a new type, with a list of possible values
Can have any number of values, but you must include them all in the enum declar­ation
Can declare variables of the enumer­ation type:
Can use the comparison operator with them:
Example:

Claring a new type with a list of possible values:
public enum Filing­Status { 

SINGLE, MARRIED, MARRIE­D_F­ILI­NG_­SEP­ARATELY }


Enumer­ation type variable declar­ation:
Filing­Status status = Filing­Sta­tus.SI­NGLE;


With comparison operator:
if (status == Filing­Sta­tus.SI­NGLE)

Reading input

Structure
Import Scanner class:
import java.u­til.Sc­anner;
Create a scanner, assign it to a variable:
Scanner scanner = new Scanne­r(S­yst­em.in);
 
new Scanne­r(..)
creates a new one
 
System.in says scanner is to take input from the keyboard
Request user to input number
System.ou­t.p­rin­t("P­lease input data: ");
Read in the number:
myNumber = scanne­r.n­ext­Int();
Read in String:
String myString = scanne­r.n­ext­Line();
Read in double:
String myDouble = scanne­r.n­ext­Dou­ble();
Read in char:
char myChar = scanne­r.n­ext­().c­ha­rAt(0);

Printing

Print and end line
System.ou­t.p­rin­tln­(so­met­hing);
Print and doesn't end the line
System.ou­t.p­rin­t(s­ome­thing);

Assignment statements

alues can be assigned to variables by assignment statem­ents.
Syntax:
variable = expression
The expression must be of the same type as the variable.
The expression may be a simple value or it may involve comput­ation
When a variable is assigned a value, the old value is discarded and totally forgotten.
 

Methods

This is a named group of declar­ations and statements
They are called or invoked by naming it in a statement
Every method definition must specify a return type
Return type void:
used if nothing is to be returned
 
plain
return
can be used
If not
void
, return statements that specify the value to be returned must be supplied
Method call:
Request to an object to do something, or compute value
When calling a method, parameter types are not specified
Parameters of the type specified in the definition must be supplied
Method calls can be used as a statement
Methods that return a value may be used as part of an expression

Arithmetic expres­sions

number literals (e.g., 42) and variables (e.g., x);
+
indicate addition;
-
subtra­ction
*
multip­lic­ation
/
division
%
modulo­(in­dicates remainder of an integer only division)
( )
indicate the order in which to do things.
An operation involving two ints results in an int.
When dividing one int by another, the fractional part of the result is thrown away, e.g., 14 / 5 gives 2 (and 14 % 5 gives 4).
Any operation involving a double results in a double, e.g., 3.7 + 1 gives 4.7 (int values are automa­tically converted to double where needed

Boolean expres­sions

<
less than
<=
less than or equals
==
equals
>
greater than
>=
>=
!=
not equals
&&
"­and­" true if and only if both operands are true
||
"­or" true if and only if at least one operand is true
!
"­not­" reverses the truth value of its one operand
Example:
(x > 0) && !(x > 99)

“x is greater than zero and is not greater than 99”

Condit­ional expres­sions

condition ? expr1 : expr2
Becomes expr1 if condition is true, otherwise expr2.
Example:
x < 0 ? -1 : 1

“if x is less than zero, then -1, otherwise 1”

String concat­enation

You can concat­enate (join together) Strings with the + operator
fullName = firstName + " " + lastName;
ou can concat­enate any value with a String and that value will automa­tically be turned into a String.
System.ou­t.p­rin­tln­("There are " + count + " apples.");

If statements

An if statement lets you choose whether or not to execute one statement, based on a boolean condition.
Condition must be boolean.
Syntax:
if (boole­an_­con­dition) statement;
Example:
if (x < 100) x = x + 1;
// adds 1 to x, but only if x is less than 100
An if statement may have an optional else part, to be executed if the boolean condition is false.
Syntax:
if (boole­an_­con­dition) statement else statement
Example
if (x >= 0 && x < limit) y = x / limit; else System.ou­t.p­rin­tln­("x is out of range: " + x);

Compound statements

Group multiple statements into a single statement by surrou­nding them with braces,
{ }
.
there is no semicolon after a compound statement
Braces can also be used around a single statement, or no statements at all (to form an “empty” statem­ent).
It is good style to always use braces in the if part and else part of an if statement, even if they surround only a single statement.
Example:
 if (score > 100) {

 score = 100;

 System.ou­t.p­rin­tln­("score has been adjust­ed");

}
 

While Loops

A while loop will execute the enclosed statement as long as a boolean condition remains true.
Syntax:
while (boole­an_­con­dition) statemen
he condition must be boolean.
If the condition never becomes false, the loop never exits, and the program never stops.
Example:

n = 1;
while (n < 4) {
System.ou­t.p­rin­tln(n + " squared is " + (n * n));
n = n + 1;
}

Result:
1 squared is 1
2 squared is 4
3 squared is 9

for loop

The for loop looks compli­cated, but is very handy.
Syntax:
for (initi­alise ; test ; increment) statement
There is no semicolon after the increment.
The initialise part is done first and only once
Then, the test is performed, and, as long as it is true,
the statement is executed, and
the increment is executed
Initia­lise:
define the loop variable with an assignment statement, or with a declar­ation and initia­lis­ation.
Test, or condition:
A boolean condition.
Example:

Print the numbers 1 through 10 and their squares:
for (int i = 1; i < 11; i++) {
System.ou­t.p­rin­tln(i + " " + (i * i));
}

Print the squares of the first 100 integers, ten per line:
for (int i = 1; i < 101; i++) {
System.ou­t.p­rin­t(" " + (i * i));
if (i % 10 == 0)
System.ou­t.p­rin­tln();
}

When do you use each loop

for loop
if you know ahead of time how many times you want to go through the loop.
while loop
in almost all other cases.
do-while loop
if you must go through the loop at least once before it makes sense to do the test.

break statement

Inside any loop, the break statement will immedi­ately get you out of the loop.
If you are in nested loops, break gets you out of the innermost loop
It doesn’t make any sense to break out of a loop uncond­iti­onally; you should do it only as the result of an if test
break should not be the normal way to leave a loop
Use it when necessary, but don’t overuse it.
Example:

for (int i = 1; i <= 12; i++) {
if (badEg­g(i))
break;
}

continue statemen

Inside any loop, the continue statement will jump right before the end of the loop body.
In a while or do-while loop, the continue statement will bring you to the test.
In a for loop, the continue statement will bring you to the increment, then to the test

Multiway decisions

The if-else statement chooses one of two statem­ents, based on the value of a boolean expression
The switch statement chooses one of several statem­ents, based on the value

switch statement

works with the byte, short, char, and int primitive data types
works with enumer­ation types, the String class, and a few special classes that wrap certain primitive types: Byte, Short, Character, and Integer.
Notice that colons ( : ) are used as well as semico­lons.
The last statement in every case should be a break;
The default: case handles every value not otherwise handled.
public static void printS­tat­us(­Fil­ing­Status status) {
switch (status) {
case SINGLE: // SINGLE rather than Filing­Sta­tus.SINGLE
System.ou­t.p­rin­t("S­ingle filing­");
break;
case MARRIED:
System.ou­t.p­rin­t("M­arried joint filing­");
break;
case MARRIE­D_F­ILI­NG_­SEP­ARA­TELY:
System.ou­t.p­rin­t("M­arried separate filing­");
break;
default:
System.ou­t.p­rin­t("U­nex­pected case");/ / better: throw an exception if code. needs to be updated to handle new case
}
}