Conditionals And Loops
What are conditional statements in Java ?
When we want some statement(s) to execute on certain conditions and other statement(s) on different conditions, we use conditional statements.
The IF statement
The "if" statement lets us execute statement(s) depending upon the result of test condition.
The result of test condition is always a boolean value - true or false.
If the condition evaluates to true. Then the statement(s) inside "if" block will execute.
If the condition evaluates to false, then statements(s) will be skipped and the control will be send to the statement(s) after the "if" block.
The condition must be surrounded by parenthesis. Curly braces are optional if only one statement follows but mandatory if more than one statements are present.
FOR EXAMPLE :
The ELSE statement
When the "if" condition evaluates to false, only then statement(s) inside else block will get executed.
Nested IF statement
It allows one "if" statement to be written inside another "if" statement.
The IF-ELSE ladder
It is a sequence of if-else statements.
The SWITCH statement
It has the same functionality as the if-else ladder but it's more easier to work with.
Expression must have value of type byte, char, short or int. This value is compared against values of all the cases.
Values after the case keyword have to be constants.
The case that matches the value, statement(s) of that case will get executed.
If execution reaches the break statement, then switch statement will end.
When execution does not find break statement, the case that matches the value of expression and all the cases after it will get executed till it find the break statement.
What are Loops ?
When you need to perform a certain task repeatedly. You don't want to write code again and again, that's why LOOPS are made - to execute statements repeatedly.
LOOPS INVOLVES THREE STEPS :
- 1. Starting value (from what value to start).
- 2. Condition (if condition is true then keep executing code).
- 3. Increment / Decrement the value.
There are four LOOPS in Java
1. While loop
- condition is always checked first before executing code.
- we use it when we are not sure how many iterations should be performed
2. For loop
- condition is always checked first before executing the code.
- we use it when we know how many iterations are require to perform.
3. Do-while loop
- we use it when we want to the code to execute once, no matter whether condition is true or not.
- It check condition after executing the code once from then on it checks condition everytime before executing the code.
4. Enhanced for loop or For each loop
- It allows you to loop through each element of array as well as other collections of elements.
- It does not require any condition since it just iterate through each element till they are no more elements left.