You are on page 1of 49

JAVA Development

Flow control, Arrays,


Reference types
Control flow statements

- Regular execution flow is to execute all statements in a block in order,


from top to bottom

- Control flow statements allow to break up this flow, allowing conditional


execution of particular blocks of code

- Several types:
- decision-making: if-then, if-then-else, switch
- looping: for, while, do-while
- branching: break, continue, return
Decision-making - if

The if statement is used to test a condition.


- check a boolean condition (value: true or false)
- continue execution on different paths based on this check

There are various types of if statement in java:


● if statement
● if-else statement
● if-else-if ladder
● nested if statement
Decision-making - if-else

if (condition)
{  
//code if condition is true  
}
else
{  
//code if condition is false  
}

• The condition is a boolean expression, must use parenthesis


• The ‘else{..}’ part is optional, may be omitted (if not needed)
• The braces { } are optional if the block contains just a single
statement (but are recommended anyway, for clarity)
• Notice there is no ‘then’ after the if condition
if-else example

if (number % 2 == 0) {
System.out.println("even number");
} else {
System.out.println("odd number");
}

if (number % 2 == 0)
System.out.println("even number");
else
System.out.println("odd number");

if (number > 0){


System.out.println("positive number");
}
Decision-making - if-else-if

char grade = …

if (grade == 'A') {
System.out.println("Excellent");
} else if (grade == 'B' || grade == 'C'){
System.out.println("Well done!");
} else if (grade == 'D') {
System.out.println("You passed.");
} else if (grade == 'F') {
System.out.println("Try again!");
} else {
System.out.println("Invalid grade");
}
Decision-making - switch

switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
case 'C':
System.out.println("Well done");
break;
case 'D':
System.out.println("You passed");
break;
case 'F':
System.out.println("Try again");
break;
default:
System.out.println("Invalid grade");
}
Decision-making - switch

• The switch variable - must be of one of the supported types: byte, short, char, int, String, enum

• The switch cases: the value for each case must be of the same type as the switch variable,
and it must be a constant or a literal (no expressions allowed)

• Execution flow:
○ Jumps to the first case for which the value is equal to the switch variable, and it starts executing
the statements following that case, until a break statement is reached
○ When a ’break’ statement is reached, the whole switch terminates (execution jumps to the next
statement after the switch block)
○ Not every case needs to end with a ‘break’; if no break appears at the end of a case, the
execution will ”fall through” to subsequent cases until a break (or end of switch) is reached
■ Note: pay attention to this fall-through case! (make sure this is what you want/need)

• default: a special case, optional, which is selected when no other case matches the variable. It’s
recommended to be placed the last one (after all other cases); in this case it doesn’t need ‘break’ after it.
Loops

● Allow to execute a statement or group


of statements multiple times

● Number of repetitions is controlled by a


stop condition
• Make sure that you have a working stop
condition (if you don’t want an infinite loop)
Loops - for - general form

● FOR: repeats a group of statements for as long as a given condition remains true; it abbreviates the
code needed to manage the loop logic.
● Variant 1: the general form (with explicit control expressions):
for ( initialization ; termination ; increment ) {
//statements (loop body)…
}

○ Initialization expression: initializes the loop; executed once, as the loop begins; may declare local
variables, which can then be used in the termination and/or increment expressions.
○ Termination expression: evaluated before each iteration, loop ends when this becomes false
○ Increment expression: invoked after each iteration; it may update variables declared in initialization
expression (like increment/decrement a value)

for ( int i = 1; i <= 10; i++ ) {


System.out.println("count is: " + i);
}
Loops - for

Notes:
- all three expressions of the for loop are optional:
for ( ; ; ) { //=> infinite loop!
/*...*/
}

- the initialization (1st) and increment (3rd) expressions may contain


multiple parts, separated by “,” - for example to declare and increment
multiple variables on each step (but they are restricted to being of the same
type);
- note: the stop condition (2nd) does not support this (as it must evaluate to
a single boolean value)

for (int i = 0, j = 100 ; i < j ; i += 2, j -= 3){


System.out.println("i=" + i + ", j=" + j);
}
Loops - for - enhanced form

Variant 2: “enhanced form” (simplified form)


- for easy iteration over arrays, collections
- useful in cases when you don’t need to know/use the indexes of the elements, but just go
over all the elements of that collection

for (declaration : expression) {


//statements…
}

Example:
- int[] numbers = {1,2,3,4,5,6,7,8}; //an array (a group of multiple int values)
- for (int item : numbers) { //declare a variable i, which takes all values from the array
- System.out.println("count is: " + item);
}
Loops - while

• WHILE: repeats a group of statements while a given


condition remains true.
• The condition is checked before each execution of the loop
body. Due to this, the body may not be executed at all !
(if the condition is false from the start)
• Syntax:
while (condition) {
//statements…
}

Example:
int x = 1; //initialization (outside the loop)
while (x <= 10) { //check condition (before each loop)
System.out.println("value of x: " + x);
x++; //increment logic (manual, inside the loop)
}
Loops – do while

● DO-WHILE: like while, except that the condition is checked


after each execution of the loop body (instead of before)
● Due to this, the body is always executed at least once! (even
when condition is false from the start)
● Syntax:
do {
//statements…
} while (condition);

Example:
int x = 1; //initialization (outside the loop)
do {
System.out.println("value of x: " + x);
x++; //increment logic (manual, inside the loop)
} while (x <= 10); //check condition (after each loop)
Loops – common mistakes

- the braces are optional, if body contains only 1 statement - but they are highly recommended
(add clarity about what exactly is included in the loop):
int sum = 0;
int i = 0;
while (i < 10) //note lack of {} here
i++; //so this is the single statement of the loop!
sum += i; //outside/after the loop (despite formatting)
System.out.println("sum=" + sum); //prints “0”

- also the body can be empty (resulting in an useless loop); so watch out for this:
String s = "";
for (int i = 1; i <= 10; i++) ; //note: lack of {}, the extra ';'
s += "~"; //so this is actually outside/after the loop
System.out.println(s); //prints just one “~”, not 10!
or:
int j = 0;
while (j++ < 10) ; //note the ‘;’ -> empty body loop
System.out.println("j=" + j); //outside the loop, runs only once, prints “11”
Loops – infinite

There is no guarantee/requirement that a loop Note:


should eventually stop: if you use a condition which Such loops which lack a proper stop condition can still
is never false, it will result in an infinite loop! be stopped/controlled by using the break statement.
- Make sure this is what you want/need! (it can be
valid/useful in some few cases, but many times is
unintentional)

Examples: Example:

while (true) { while (true) {


//code running forever //statements…
} if (someCondition) break; //ends loop
}
for (int i = 1; true; i++) {
//code running forever
}

for (int i = 1; i != 10; i += 2) {


//code expected to stop? does it?
}
Branching - break, continue

break continue
- Terminates (breaks out of) a loop or - Skips the remaining code in current iteration
switch statement, the execution flow of a loop, so the execution flow continues with
continues with the statement immediately the next loop iteration (after evaluating the stop
following the loop/switch. condition..)

Example: Example:

int[] numbers = {10,20,30,40,50}; int[] numbers = {10,20,30,40,50};


//prints: 10 20 //prints: 10 20 40 50
for (int x : numbers) { for (int x : numbers) {
if (x == 30) { if (x == 30) {
break; continue;
} }
System.out.println(x); System.out.println(x);
} }
Loops – example

int[][] array = {{8, 1, 3, 10}, {0, 3, 6}, {7, 9, 10}};


int i = 0;
for (int[] row : array) {
for (int number : row) {
if (number % 2 == 0) {
System.out.println("number: " + number + ", i: " + i);
break; // this only exits the inner for, not the outer
}
}
i += 1;
}

What will this code print out?...


Branching - return

- return statement: normally used to return a value as the end result of a method
- so not really needed/used for methods declared to return void

- it can also be used for branching:


- when return is called, even when it’s not the last statement in body, the
method will immediately end !
- may need to also specify a value to return, if method is not declared to return void
- this allows a method to have multiple exit points, including breaking from
loops or if/switch statements.

- Note: while sometimes useful (like placing all validations upfront), it’s recommended to
keep the number of exit points to minimum, for readability
Branching - return examples

Examples:

void printSquareRoot(double x) { static String gradeLabel(char grade) {


if (x < 0) { //validate first if (grade == 'A') {
System.out.println("Invalid value!"); return "Excellent!";
return; //exit (no return value) }
} if (grade == 'B' || grade == 'C') {
//then work with valid x value… return "Well done";
} }
if (grade == 'D') {
int findIndexOf(int x, int[] numbers) { return "You passed";
for (int i = 0; i < numbers.length; i++) { }
if (numbers[i] == x) { return "Try again";
return i; //exit loop and method }
}
}
return -1; //default value (if not found)
}
Arrays

What is an array?
● Reference type
● Sequence of elements
● All elements of same type (e.g. int, double, String, Object)
● Fixed length (must be specified from the start)
● Elements can be accessed (for read/write) using an index, e.g:
○ read the 3rd element
○ update the 5th element
Arrays - declaration

Declaring array variables:

dataType[] arrayRefVar; //preferred way


dataType arrayRefVar[]; //also works, but not recommended

Examples:

double[] arrayOfDoubles;
int[] arrayOfInts;
String[] arrayOfStrings;
Arrays - creation

Creating arrays - several ways:

● Allocating a new, uninitialized array (must specify size):


dataType[] arrayRefVar = new dataType[arraySize];

● Using new with an initializer:


dataType[] arrayRefVar = new dataType[] {e1, e2, e3, e4};

● Using a literal (shorter version):


dataType[] arrayRefVar = {element1, element2, element2};
Arrays - creation

Examples:

● Allocating a new, uninitialized array:


String[] names = new String[3];

● Using new with an initializer:


String[] names = new String[]{"Alice", "Bob", "Eve"};

● Using just a literal:


String[] names = {"Alice", "Bob", "Eve"};
Arrays - reading elements

double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123};

Reading the value of an element is done


using its index:

arrayVar[index]

● indices are 0-based (they start from 0)


● they go up to (arrayLength - 1)

Examples:

myList[0] -> returns 5.6


myList[8] -> returns 99.993
myList[10] -> causes an error, as max index is 9
Arrays - updating elements

double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123};

Updating the value of an element is also done


using its index:

arrayVar[index] = value;

Examples:

double a = myList[0]; //read 1st, is 5.6


myList[0] = 8.1; //update it
double b = myList[0]; //read again, is now 8.1
Arrays - length

double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123};

Getting the length of an array:

arrayVar.length

Note: you cannot change an array’s length


once it has been declared (only read it)

Example:
int len = myList.length; //is 10
Array - literals

- Special syntax to specify array’s values directly in the code:


String[] response = {"Yes", "No"};
//is equivalent to:
String[] response = new String[2];
response[0] = "Yes";
response[1] = "No";

- Can contain literal values, but also expressions:


double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0};
byte b = 2; short s = 32000;
double[] myList2 = { 2+3, b*s };

- Important: literals can only be used when assigning to a variable directly!


Arrays of arrays

Elements of an array can also be arrays -> multidimensional arrays (array of arrays)

Examples:

int[][] products; //declare a 2-dimensional array (of unknown sizes)


int[][] myArray1 = new int[4][5]; //create instance (with default values)
int[][] myArray2 = { {0, 0, 0, 0, 0},
{0, 1, 2, 3, 4},
{0, 2, 4, 6, 8},
{0, 3, 6, 9, 12} };
Arrays of arrays

//array of 2 rows, with 5 elements each


int[][] myArray = { {0, 0, 0, 0, 0}, //1st line (index=0)
{0, 1, 2, 3, 4} }; //2st line (index=1)

Reading an element requires two indexes:


int three = myArray[1][3]; //2nd line, 4th elem

Using a single index returns a subarray:


int[] zeroToFour = myArray[1]; //2nd line, as 1-dimensional array

Note: sub-arrays don’t need to have all the same size:


int[][] jaggedArray = { {0},
{1, 2},
{3, 4, 5} };
Arrays utility methods

java.util.Arrays - has useful methods for some common array operations:


- Arrays.toString(array) - returns a string representation of the array (values separated by “,”)
- Arrays.equals(array1, array2) - returns true if the 2 arrays have exactly same elements

- Arrays.copyOf(array, lengthToCopy) - copies some/all the elements of an array (starting


from first one) and returns them in a new array
- Arrays.copyOfRange(array, fromIndex, toIndex) - copies the elements of the array from a
specified index range (from is inclusive, to is exclusive) and returns then in new array
- Arrays.fill(array, elem) - fills a given array with a given value (replace all elements, in-place)

- Arrays.sort(array) - sorts the elements of the array (in-place, returns void)


- Arrays.binarySearch(array, elem) - searches for elem in array using the binary search
algorithm, and returns its index, or a negative value if not found; note: the array MUST be
already sorted, or else the search may work incorrectly!
Primitives vs references

● In Java, everything is an Object!


○ ...except Primitives

● Objects are composed of primitives and/or other objects

● A Reference variable is just an address to an Object in memory


○ Can be null, since they many not point to any address

● Primitive variables are not addresses, but hold the value itself
○ Cannot be null, since the memory always contains something
(so each primitive type has a default value, like: 0, false..)
Primitives - memory usage

Primitives only take up memory space


to store the value itself:

● char takes: 2 bytes


● byte: 1 byte
● short: 2 byes
● int: 4 bytes
● long: 8 bytes
● float: 4 bytes
● double: 8 bytes
● boolean: 1? byte
Arrays - memory usage

- Arrays are stored in a contiguous memory area, holding a sequences of values of their type
- Note: some memory is also used for the array variable (holding the start address of the array)

Array of 5 ints (including variable): Array of 5 longs (including variable):


Why does it matter

- Memory usage: memory is not allocated when declaring an array, but only
later when creating the actual instance (with new() or literal)

- It determines the performance of array operations:


○ Iterating over an array’s elements (accessing them by index) is quite fast
○ Resizing an array (deleting elements from it, or making room for more
elements) requires making a new copy of the whole array, which is slow
Strings - arrays, but immutable

A string can be seen as an array of chars:


String s = new String(new char[] { 'a', 'b', 'c' });

But unlike regular arrays, the string makes its own copy, so you cannot update it:
char[] chars = new char[] { 'a', 'b', 'c' };
String s = new String(chars);
chars[2] = 'z';
System.out.println(s);

This still prints ‘abc’.

The String type is immutable: once created, no modifications are possible!


(operations which seem to change String values actually create new copies)
Methods - var args (as arrays)

- Methods can be declared only with a clearly defined (fixed) number of parameters
- It is possible to declare a method with “var-args” - having a variable number of values for one of
the parameters - by adding “...” after that param’s type:
returnType methodName(SomeType... paramName)
- Usage:
- Inside method body, the param with multiple values is accessible/equivalent to an array of
values (of the declared param type)
- When method is called from outside, we can simply pass multiple param values as usual
(no need to pass them as a single value of type array)
- Combined with fixed params:
- the method can also have a list of regular (single value) params, of different types,
combined with a single param with multiple values;
- in this case, the param with multiple values must always be the last one in list!
Methods - var args examples

Example: //Other method using an array param instead;


//Var-args method, with a multi-value param(last) //similar to var-args, but not the same!
static void print(String label, static void printArr(String label,
int... numbers) { int[] numbers) {
System.out.print(label); //access fixed param System.out.print(label);

//multi-value param accessed like an array //2nd param accessed the same way (as array)
for (int n : numbers) {System.out.print(n+" ");} for (int n : numbers) {System.out.print(n+" ");}
System.out.println(); System.out.println();
} }

… …
//Using the var-args method: //BUT calling it is DIFFERENT:
//May specify multiple values (after 1st)
print("Some numbers:", 1, 2, 3); //Calling it like this is NOT allowed:
//OR: may specify 2nd param as an array //printArr("Numbers:", 1, 2, 3); //-> error: wrong params!
print("Other numbers:", new int[]{1, 2, 3});
//Can be called only like this, with an actual array
//May also specify NO values for 2nd param printArr("Numbers:", new int[]{1, 2, 3});
//(will be seen as an empty array in body)
print("No numbers:" );
Extra reading

- http://tutorials.jenkov.com/java/operations.html
- http://tutorials.jenkov.com/java/arrays.html

- https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html
- https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

- https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
Further study :)

Naming stuff...
Further study :)

While or do-while ?..


Further study :)

Need a break?...
Further study :)

Ternary operator…
not so bad, after all :)
Further study :)

Arrays...

You might also like