The main comparison operators include
the shortcut for adding or subtracting 1 from a variable:
The place of the operator (either before of after the variable) can affect the result. Putting the operator before the variable means "first increment and then use the new value" (++x).
For example:
int x = 0;
int z = ++x;
System.out.println("x = "+x + ", z = " + z);
will output x = 1, z = 1, but
int x = 0;
int z = x++;
System.out.println("x = "+x + ", z = " + z);
will output
x = 1, z = 0! z gets the value of x and then x is changed.
Conditional branching uses comparison operators to compare values. Saying "If there is a dog, run away" would be conditional branching since you will only run away if a dog is present. Conditional branching includes if statements and loops:
int age = 16;
if(age < 21){
System.out.println("You are too young to own a dog!");
} else{
System.out.println("Wow you sure are old!");
}
output:
You are too young to own a dog!
If we increase the age to 22 then we get the output "Wow you sure are old!"
There are three main loop constructs: while, do-while, and for. They are helpful when repeating statements!
As long as the condition is true execute the statements inside the block (blocks are encapsulated by curly braces).
int x = 0; // assign 0 to x
while (x < 3) {
// loop will run since 0 < 3
System.out.println(x); // print current value of x
x = x + 1; // add 1 to x to avoid being here infinitely
}
output:
0
1
2
Do-while loops are similar to while loops but evaluate the expression after executing the block at least once. The block inside the do{} block will always execute at least once:
int x = 1;
do {
System.out.println(x);
x++;
} while (x < 1);
A for loop is used when you want to loop a certain number of times:
for (int x = 0; x < 4; x++) {
System.out.println(x);
}
output:
0
1
2
3
Steps:
Enhanced for loops are used to easily iterate through elements in a collection (such as arrays).
int[] arr = {0, 6, 3, 2, 1};
for (int a : arr) {
System.out.println(a);
}
output:
0
6
3
2
1
You will learn about arrays when we look into variables.