Loop and Array
Loop and Array
if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Loops are handy because they save time, reduce errors, and they make
code more readable.
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"
Java While Loop
The while loop loops through a block of code as long as a specified condition is true:
Statement 3 is executed (every time) after the code block has been executed.
The "inner loop" will be executed one time for each iteration of the "outer loop":
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
(int i = 0; i < 5;
){
System.out.println(
);
}
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, you
can place the values in a comma-separated list, inside curly braces:
Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo