Show Menu
Cheatography

Java Mastery - Part 2 Cheat Sheet by

Part 2 of the Java Mastery cheatsheet series. Please read "Java Mastery - Fundamentals" for a better understanding of the content here.

if then else

if
statement identifies the statem­ent­/code block to run based on the expres­sions value(the specific condition)
Code block is defined by curly braces
{can contain 1 or more statem­ents}
else
comes after the if, executed when the condition is
false
else if 
can test multiple conditions
Example

int score = 6000;

if (score >= 5000) {

  do something;
} else if (score <1000 && score >= 500) {

  do something else;
] else [ 

  do this if all previous conditions are false
}

Method

Prevent code duplic­ation
Same as 'function' in other languages
Set the name of the method, then the data type and name of parameters it will access from the
main
method
Java automa­tically creates variables with the approp­riate data type for us

Defining a new method:

public static void method­Nam­e(b­oolean boolParam, int intParam)
{
}
void
means to "­return nothin­g"

Calling a Method

When the method is called, all the code in curly braces { } in the method is executed
Execute by calling the method (in
main
) with the required arguments in the brackets
Arguments can be the variable name or the actual values we want to send, as long as it matches the parameters
otherwise an error.
method­Nam­e(v­ari­able1, variab­le2);
In the example, two arguments expected
datatype need not be specified
A variable can be assigned a method result
e.g.
int highScore = calcul­ate­Sco­re(­gam­eOver, score, level, bonus);
When the variable highScore is printed, the result of the calcul­ations is sent back from the calcul­ate­Score method and assigned ot the variable

Return variable from method to main:

public static int method­Nam­e(b­oolean boolParam, int intParam)
{
}
Changing
void
to
int
means we are returning an
int
data type to the Main Method
The method must explicitly return he variable:
return newValue;
An
int
variable is expected, whether or not the statements in the method execute
(i.e. when an if statement is either true or false, something must be returned)
All the program variations must be accounted for
Full example:
public static void main(S­tring[] args) { 

 
 boolean isThis­Helpful = true;

 
int points = 15;

 
method­Nam­e(i­sTh­isH­elpful, points);

}
public static int method­Nam­e(b­oolean isThis­Hel­pful, int points) {


 
if (isThi­sHe­lpful) {

   
int finalScore = points + 5

   
System.ou­t.p­rin­tln­("Your final score is: " + finalS­core);

   
return finalS­core;

   
 }

return -1; 

// -1 indicates invalid value/not found

Method Overlo­ading

Allows us to create multiple methods with the same name with different parameters
Changing the data type of the method will not make it a unique signature. The number of paramaters make it unique.
The methods can have the same name but different implem­ent­ations
sum(int a, int b);

sum(int a, int b, int c);

sum(int a, int b, int c, int d);
public static int sum(int a, int b) {

return a + b;

 }
public static int sum(int a, int b, int c) {

return a + b + c; 
}
public static int sum(int a, int b, int c, int d) {

return a + b + c + d; 
}
pintln methid is an example of method overlo­ading, as there are 10 methods of the same name
It improves code readab­ility and re-usa­bility
Easier to remember one method name isntead of many
Achieves naming consis­tency
Gives flexib­ility to call a similar method with different types of data, based on defined argume­nts­/pa­ram­eters

Switch

Similar to the if-the­n-else statement
Good for testing values of the same variable
The variable that will be changed goes inside the brackets
the conditions tested will be the case numbers
break; are essential to close off your case compar­ision. Without it, results will be unpred­ict­able.
The final switch statement is default, same as else
Switch statement
if-the­n-else equivalent
int value = 1;
int value = 1;
switch­(value) {
Setting the variable to be changed
case 1:
if (value == 1) {
System.ou­t.p­rin­tln­("Value was 1");
System.ou­t.p­rin­tln­("Value was 1");
break;
case 2:
} else if (value == 2) {
System.ou­t.p­rin­tln­("Value was 2");
System.ou­t.p­rin­tln­("Value was 2");
break;
default:
  } else {
System.ou­t.p­rin­tln­("Was not 1 or 2");
System.ou­t.p­rin­tln­("Was not 1 or 2");
break;
}
}
Case tests can also be on one line, e.g.:
case 3:case 4:case 5:
 

Common Methods

variable.toLowe­rCase()
Turns the string variable to all lower case
variable.toUppe­rCase()
Turns the string variable to all UPPERCASE
Math.round(variable)
Rounds decimal numbers to the nearest value
String.fo­rma­t("%.2f­", variable)
Converts and outputs the variable number with just two decimale points
Math.sqrt(varia­ble);
Variable must be long. If not, add (long) before the expression
variab­le1.eq­ual­s(v­ari­able2)
Tests if one String variable is equal to another

For Loop/S­tat­ement

Processes a part of a code block until a condition is satisfied
Variable created in the for statement only exists in that code block
Structure:
for(init; termin­ation; increment)
init:
Code initia­lised once at the start of the loop
termin­ation:
Determines at what point it exits the for loop
 
Once it evaluates to false, it will exit the loop and proceed to the next line
increment
An expression invoked after each iteration
Example:
for(int i = 0; i < 5; i++)
int i = 0
initialise i to zero,
i < 5
test if i is less than 5 and keeps processing until i is greater than 5
i++
add 1 to the value of i
Looping forwards or backwards depends on the conditions and ranges

For Statement

while/­do-­while

Similar to the for loop
instead of looping a certian number of times(as seen in
for
), `while() allows you to loop until the expression is true or false
the count must be increm­ented, otherwise you will enter an infinite loop
for version
while version
for(int i = 0; i != 5; i++) {

//do something }
int i = 1

while(i != 6)
{
//do something }
while
while(­con­dition {
//stat­ements
}
while(­true) {

if(i == 5) { 

break; 

}
count++;
Do-While
It will always execute once or more depending on defined expres­sions
do {
//stat­ements
} while(­con­dit­ion);
Remember, semi-colon after while condition
count = 1; 
do {
count++;
} while(­count != 6);

Object­-Or­iented Progra­mming

Object
A value of a class type
 
Has states and behaviours
 
State is stored in fields
 
e.g. a dogs name, breed, colour
 
Behaviour is shown via methods
 
e.g. a dogs behaviour: barking, wagging tail, running
Class
Describes set of objects with the same behaviour
 
Can have any number of methods to access the value of different methods
Updating a variable using a method instead of directly
Why?
If the variables access modifier is set to
private
for security reasons, we don't want users to directly change the variable by making it 'public'
Use
this.
before the class to refer to a particular field
this.model = model;
this means to update the field model with the contents of the parameter
model
that was passed through.
Classes can have:
Local variables: Defined in methods, constr­uctors or blocks
Instance variables: variables withina class but outside any method. Initia­lised when the class in instan­tiated.
Class variables: Variables declared within a class, outside any method, with the static keyword

Static Variables

Declared using the keyword
static
Also known as static member variables
Every class instance shares the same static variable
Changes made to that variable will be seen in other instances
Accessible by static methods directly
Reading user input with Scanner,
scanner
is declared as a static variable
e.g.
private static String name;
not a good idea

Instance variables

They don't use the static keyword
Known as fields or member variables
Belong to an instance of a class
Represents the state of an isntance
Every instance:
-Has it's own copy of an instance variable
-Can have a different value(­state)

Static Method

Declared using a static modifier
Can't access instance methods and instance variables directly
Cannot use the
this
keyword
Usually used for operations that don't require data from an instance of the class (from
this
)
When a method does not use instance variables, that method should be declared as a static method
e.g. main is a static method and is called by JVM when it starts an applic­ation
Example

public static void printS­um(int a, int b) {

 
System.ou­t.p­rin­tln­("sum = " + (a + B));

}
 

Instance Methods

Belongs to an instance of a class
To use, we must instan­tiate the class first by using the new keyword
Can access instance methods and variables directly
Can access static methods and static variables directly
Example:
class Dog {

 
public void bark() {
 
 
System.ou­t.p­rin­tln­("wo­of");

  }
}
public class Main { 

 
public static void main(S­tring [] args) {
   
Dog rex = new Dog();
//create instance

   
`rex.b­ark(); //call instance method
`
  }
}

Static or Instance Method?

Should a method be static?
  |
  V
Doies it use any fields­(in­stance variables) or Instance methods?

YES? It should probably be an instance method

NO? It should probably be a static method
       
 

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

          Eclipse Cheat Sheet
          Selenium WebDriver Cheat Sheet Cheat Sheet

          More Cheat Sheets by Bayan.A

          Networks - Physical Layer Cheat Sheet
          Java Mastery - Fundamentals Cheat Sheet
          CompTIA ITF Cheat Sheet