Show Menu
Cheatography

Java Mastery - Fundamentals Cheat Sheet by

Fundamentals required to master Java programming

Primitive Data Types

int
32-bit
long
64-bit
short
6-bit
byte
8-bit
double
double­-pr­ecision 64-bit
float
single­-pr­ecision 32-bit
boolean
Boolean value (true or false)
char
16-bit Unicode character

Variab­les­/Id­ent­ifiers

Start with a letter (or_ or $)
Rest must be letters, _, $ or digits
Case sensitive
Start with a lower-case letter
Assignment statement replaces the previo­usly stored value
Use came­lCa­sing
thisIs­Cam­elC­asing

Operator Precen­dence and function

From high (16) to low (1)
Oper­ator
Desc­rip­tion
(16) [ ], . , ()
Access to array element, access to object member, parant­heses
(15) ++, --
Unary post-i­ncr­ement, unary post-d­ecr­ement
(14) ++, --, +, -, !, ~
unary pre-in­cre­ment, unary pre-de­cre­ment, unary plus, unary minus, unary logical NOT, unary bitwise NOT
(13) (), new
cast, object creation
(12)*, /, %
multiply, divide, modulus
(11)+-, +
additive, string concat­enation
(10<<, >>, >>>
shift
(9) <, <=, >, >=
relati­onal; greater than, less than (or equal to)
(8) ==, !=
equaly, not equal
(7) &
bitwise AND
(6) ^
bitwise XOR
(5) |
bitwise OR
(4) &&
logical AND
(3) ||
logical OR
(2) ?:
Ternary
(1) =, +=, -=, *=, =, /=, %=, &=
Assignment

Syntax

A specific set of rules, using a combin­ation of keywords and other things
Each keyword has a spoecific meaning, and sometimes need ot be used in specific orders.
Case-s­ens­itive. public, Public and PUBLIC are all different
Semi-colon defines the end of a statement
;
Must be at the end of every statement

class

Defines a class with the name after the keyword
Curly braces defines the class body
Anything in the curly braces is "­par­t" of this class
note, semi­-colon is not inserted after the class name
public class Hello {
}

Access Modifiers

These are java keywords
Allows defining the scope, how other parts of the code can access this code
Access Modifi­ers
Access Levels
public
Same Class, same package, other subclass, other package
protected
Same Class, same package, other subclass
no access modifier
Same Class, same package
private
Same Class
Access to members permitted by each modifier

Method

Collection of statements that perform an operation
main method
Entry point of any Java code
void
Java keyword
 
Indicates method returns nothing
( )
mand­atory method declar­ation
 
can include 1 or more parameters
{ }
Code block
 
Mandatory in a method declar­ation
 
Defines start and end of method
 
Place statements to perform tasks
Stat­ement
Complete command to be executed
 
Can include more than one expres­sions
public static void main(S­tring[] args) {
}

Variables

Way to store inform­ation
Accessed via name given
Can be changed
Must define the variables type of data
known as Data Types
Must initialise before use
Declar­ation Statement
Specify data type, then varaiable name
 
option­ally, add an expression to intialise a value
Data types do not form part of the expression
Example: int myNumber = 50
myN­umber = 50 is the expres­sion, not int

Literals

Boolean
true represents a true boolean value
 
false represents a false boolean value
String data
"s­tri­ng"
Sequence of characters (including Unicode)
Numeric
There are three main types: int, double, char
 
int
integer
Whole number­­(w­i­thout decimal points)
 
double
Floating point
decimal fractions / expone­ntial notation
 
char
character
Stores the 16-bit Unicode integer value of the character in question.

Operand

Describes any object manipu­lated by an operator
int myVar = 15 + 12;
+ is the operator
15 and 12 are the operands
 
Variables instead of literals are also operands

Expression

Combin­ation of variables, literals, method return values, and operators
Variable assignment without the data type declar­ation, or the string in " " being printed, and not the semi-colon
Exam­ples:
int myVar = 15 + 12;
15 + 12 is the expression
 
same if variables replace number literals
int myVari­able= 50;
myVar­iable= 50
Expression
Syste­m.o­ut.p­ri­ntl­n("R­andom string­");
"Random string­"
Expression
if(my­Var­iable > 50)
myVar­iable > 50
Expression
 

Expres­sions and Statements

A stat­ement is the entire code, from data type declar­ation, ending at the semi-c­olon,
int myVari­able= 50;
Statement
`Syste­m.o­ut.p­ri­ntl­n("r­andom string­");
Statement
myVar­iab­le++
Statement

Wrapper Class Limit

Can be experi­enced by all primitve data types
Overflow
Putting too large a number allocated by the computer for an integer
e.g.
Integ­­er.M­­AX­­_VALUE + 1 =
-2147­4­8­3648
Underflow:
Putting too small a number allocated by the computer for an integer
e.g
Integ­­er.M­­IN­­_VALUE - 1 =
21474­83647
Going past a limit on either side(m­ax/min) often results in cycling to opposite side. i.e. less than the min cycles to the max, and more than max cycles to the min

Integer (Wrapper Class)

Occupies 32 bits
has a width of 32
Integer
Gives ways to perform operations on an int
int numbers can be written with _ for readab­ility
e.g. 2_147_­483_647
(version 7 or higher)
 
Integ­er.M­AX­_VALUE
-21474­83648
 
Integ­er.M­AX­_VALUE
2147483647
A whole number
Doesn't handle the remainders
e.g.
int myInt = 5 / 2;
myInt = 2

Byte (Wrapper Class)

Occupies 8 bits
"byte has a width of 8"
byte
Mostly used as docume­ntation to show it is small
 
Smaller data type takes less space and provides quicker access
 
e.g. byte myMinB­yte­Value =
-128
 
byte myMaxB­yte­Value =
127
Not used as often, due to computers today having more space.

Short - Wrapper Class

Occupies 16 bits
"has a width of 16"
short
 
e.g. Short.MI­N_V­ALUE
-32768
 
e.g. Short.MA­X_V­ALUE
32767

Long (Wrapper Class)

Used for an integer larger than the amount an int can store
Has a width of 64
can store 2 to the power of 63
Long variables require an uppercase "­L" at the end of a number
 
e.g. myLon­gValue = 100L;
 
Otherwise, it is treated as an int

Single and Double Precision

Refers to format and space occupied by type.
Single Precis­ion
Has a width of 32
 
(Occupies 32 bits)
Double Precis­ion
Has a width of 64
 
(Occupies 64 bits)

Floating Point Numbers

float
float myFloa­tValue = 5.25f;
 
By default, Java assumes it's a double, requiring the f after the number
Unlike whole numbers
Has fractional parts expressed with a decimal point
 
e.g. 3.14159
Also known as "real number­s"
Used for more precise calcul­ations
Aren't recomm­ended to use much these days
A single precision number
Smaller and less precise than Double
Range: 1.4E to 3.4028­­23­5E+38
Requires less memory
32 bits / 4 bytes

Double

double
double myDoub­leValue = 5.25d;
A Double Precision Number
Requires more memory
64 bits / 8 bytes
Larger range and more precise than Single
Range: 4.9E-324 to 1.7976­­93­1­3­48­­623­­15­7­E+308

char

char
char myChar = 'D';
Stores only 1 character
>1 character prompts an error
Single ' used, not like that used for "­str­ing­s"
Occupies 16 bits
"­width of 15"
 
Not a single byte, as it allows to store Unicode characters
Used to store data in arrays
Using Unicode, \u must be before the specific code is used
char myUnic­odeChar = '\0044';
Displays "­D"

Unicode

Intern­ational encoding standard
Use with different languages & scripts
Each letter, digits, or symbol is assigned a unique numeric value
This value applies accross different platforms and programs
Allows repres­ent­ation of different languages
Can represent any one of 65535 different types of characters
via combin­ation of two bytes in memory
Full list of unicode charac­ters:

Boolean

Allows only two choices
true or false
Variable names commonly written as a question
boolean isJavaEasy = true;

String

A datatype that is NOT a primitive type
Actually a Class
A sequence of characters
Can contain a single character
 
String myString = "This is a string­";
Can use Unicode characters
String myString + "­\u00A9 2019";
Treats texts or digits typed as text only
No numerical calcul­ations are done.
String variables added with another variable append them only
String myNumber = "250";
String yourNumber = "­654­";
myNumber + yourNumber = 250654
Strings are immutable
Can't be changed after created

Code Blocks

Variables that exist outside the code block can be accessed inside the code block
But variables created within an if statement are deleted once the program leaves the code block
e.g.:
int score = 10
if(gameOver) {
  int finalScore = score + bonus;
}
int saveScore = finalS­core;
The final line of code would produce an error, because finalScore only exists within the if code block
The concept of variables inside a code block is called Scope
 

Arithmetic Operators

Name
Exam­ple
Addition
int result = 1 + 2;
result = 3
Subtra­ction
result = result - 1; // 3 - 1
result = 2
Multip­lic­ation
result = result 10; //2 10
result = 20
Division
result = result / 5; //20 / 5
result = 4
Modulus %
result = result % 3;
//remainder of (4 % 3)
result = 1
Modulu­s(aka remainder) retains the remainder of two operands

Operator Abbrev­iation

Original
Abbrev­iated
result = result + 1;
resul­t++;
result = result - 1;
resul­t--;
result = result + 2;
result += 2;
result = result * 10;
result *= 10;
result = result / 3;
result /= 3;
result = result - 2;
result -= 2;

if-then

Cond­itional Logic
Checks a condition, executing code based on whether the condit­ion(or expres­sion) is true or false
Executing a section only if a particular test evaluates to true
No ; after if parent­heses
boolean isAlien = false;
if (isAlien == false) {
System.ou­t.p­rin­tln­("It is not an alien!­");{
Use curly brackets if executing a code block
== tests if operands are identical
"Does isAlien equal or have the value false
The expression is isAlien false is true
 
it would return false if they are NOT equal
if keyword determines if the expression in the parent­hesis evaluates to true, only then executing the next line of code.

Logical AND

Symbol:
&&
Returns the boolean value true if both operands are true and returns false otherwise.
Exam­ple:
topScore = 80
secon­dTo­pScore = 60
if ((topScore > second­Top­Score) && (topScore < 100))
Brea­kdo­wn:
if ( (topScore is greater than second­Top­Score) AND (topScore is less than 100) )
if ( ( true ) AND ( true ) )
both operands are true, therefore the expression is true and will execute the next line
Truth Table:

p | q | p && q
T | T |     T
T | F |     F
F | T |     F
F | F |     F

Logical OR

Symbol:
| | ( two pipe charac­ters)
Either or both conditions must be true for the boolean value to return true
Exam­ple:
topScore = 80
secondTopScore = 60
if ((topScore > 90) || (secon­dTo­pScore <= 90))
Brea­kdo­wn:
if ( ( topScore is greater than 90) OR ( second­Top­Score <= 90) )
if ( ( false ) OR ( true ) )
One operand is true
boolean value returns true and will execute the next line.
True Table

p     q     p || q
T     T     T
T     F     F
F     T     T
F     F     T

Assignment and Equal to Operators

Assignment Operator
 
=
Assigns value to variable
e.g. int newValue = 50
In an if expres­sion, it will produce an error as the type required in the if condition is boolean
if (newValue = 50);
Incom­patible types.
Required bool­ean
Found: int
However, if a boolean is in the if condition, the boolean value can be reassi­gned. No error will be produced
 
Equal to operator
 
==
Compares operand values are equal to eachother
e.g. (50 == 50)
e.g. (newValue == oldValue)
boolean isCar = false;
if (isCar = true)
This turns isCar from false to true
Norm­al:
Equi­valent with NOT operator
Abbr­evi­ati­ons:
if (isCar == true)
if(isCar != false)
if (isCar)
if (isCar == false)
if(isCar != true)
if(!i­sCar)
  
Prevents mistakes and is more concise

Ternary Operator

A shortcut to assigning one of two values to a variable depending on a given condition
Like an if-t­hen­-else statement
Question mark comes after the condition
After the question mark, two values that can return are separated by a colon (:)
Takes 3 operands:
condition ?
operand1 :
operand2
 
Cond­ition we're testing against
First value to assign if first condition was true
Second value to assign if first condition was false
Example:
int age = 20
boolean isOver18 =
(age == 20) ?
true :
false
 
is age equal to 20?
if it is, isOver18= true
if false, isOver18 = false

EXAMPLE CODE

Example code using most concepts outlined in this cheatsheet
See comments for explan­ation
       

Support Cheatography!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Object-Oriented Design Principles Cheat Sheet