Oop Java
Oop Java
Oop Java
- Several types:
- decision-making: if-then, if-then-else, switch
- looping: for, while, do-while
- branching: break, continue, return
Decision-making - if
if (condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
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");
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
● 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)
Notes:
- all three expressions of the for loop are optional:
for ( ; ; ) { //=> infinite loop!
/*...*/
}
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
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
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
Examples: Example:
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:
- 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
- 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:
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
Examples:
double[] arrayOfDoubles;
int[] arrayOfInts;
String[] arrayOfStrings;
Arrays - creation
Examples:
double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123};
arrayVar[index]
Examples:
double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123};
arrayVar[index] = value;
Examples:
double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123};
arrayVar.length
Example:
int len = myList.length; //is 10
Array - literals
Elements of an array can also be arrays -> multidimensional arrays (array of arrays)
Examples:
● 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
- 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)
- Memory usage: memory is not allocated when declaring an array, but only
later when creating the actual instance (with new() or literal)
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);
- 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
//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 :)
Need a break?...
Further study :)
Ternary operator…
not so bad, after all :)
Further study :)
Arrays...