if then else
if
statement identifies the statement/code block to run based on the expressions value(the specific condition) |
Code block is defined by curly braces |
{can contain 1 or more statements} |
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 duplication |
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 automatically creates variables with the appropriate data type for us |
Defining a new method:
public static void methodName(boolean boolParam, int intParam)
{ } |
void
means to "return nothing" |
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. |
methodName(variable1, variable2);
|
In the example, two arguments expected |
datatype need not be specified |
A variable can be assigned a method result |
e.g. int highScore = calculateScore(gameOver, score, level, bonus);
|
When the variable highScore is printed, the result of the calculations is sent back from the calculateScore method and assigned ot the variable |
Return variable from method to main:
public static int methodName(boolean 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: |
|
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(String[] args) { boolean isThisHelpful = true; int points = 15; methodName(isThisHelpful, points); }
|
public static int methodName(boolean isThisHelpful, int points) {
if (isThisHelpful) {
int finalScore = points + 5
System.out.println("Your final score is: " + finalScore);
return finalScore;
}
return -1;
// -1 indicates invalid value/not found
Method Overloading
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 implementations |
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 overloading, as there are 10 methods of the same name |
It improves code readability and re-usability |
Easier to remember one method name isntead of many |
Achieves naming consistency |
Gives flexibility to call a similar method with different types of data, based on defined arguments/parameters |
Switch
Similar to the if-then-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 comparision. Without it, results will be unpredictable. |
The final switch statement is default, same as else |
Switch statement |
if-then-else equivalent |
|
|
|
Setting the variable to be changed |
|
|
System.out.println("Value was 1");
|
System.out.println("Value was 1");
|
|
|
|
System.out.println("Value was 2");
|
System.out.println("Value was 2");
|
|
|
|
System.out.println("Was not 1 or 2");
|
System.out.println("Was not 1 or 2");
|
|
|
|
Case tests can also be on one line, e.g.: |
|
|
|
Common Methods
variable.toLowerCase() |
Turns the string variable to all lower case |
variable.toUpperCase() |
Turns the string variable to all UPPERCASE |
Math.round(variable) |
Rounds decimal numbers to the nearest value |
String.format("%.2f", variable) |
Converts and outputs the variable number with just two decimale points |
Math.sqrt(variable); |
Variable must be long. If not, add (long) before the expression |
variable1.equals(variable2) |
Tests if one String variable is equal to another |
For Loop/Statement
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; termination; increment) |
init: |
Code initialised once at the start of the loop |
termination: |
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 |
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 incremented, 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(condition { //statements } |
while(true) { if(i == 5) { break;
} count++; |
Do-While |
It will always execute once or more depending on defined expressions |
do { //statements } while(condition); |
Remember, semi-colon after while condition |
count = 1; do { count++; } while(count != 6);
|
Object-Oriented Programming
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 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, constructors or blocks Instance variables: variables withina class but outside any method. Initialised when the class in instantiated. 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 application |
Example
public static void printSum(int a, int b) {
System.out.println("sum = " + (a + B));
}
|
|
Instance Methods
Belongs to an instance of a class |
To use, we must instantiate 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.out.println("woof"); } } |
public class Main { public static void main(String [] args) {
Dog rex = new Dog(); //create instance `rex.bark(); //call instance method
` } } |
Static or Instance Method?
Should a method be static?
|
V
Doies it use any fields(instance variables) or Instance methods?
YES? It should probably be an instance method
NO? It should probably be a static method
|
Created By
Metadata
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by Bayan.A