Loops in Java & If-else conditional Statements
Loops in Java and IF-Else Conditional Statements
Shane Walsh - 08/12/22 - G00406694@atu.ie
Conditional Statements:
Java like many programming languages features what are known as conditional statements. An operator that allows you to run a selection of code if the set conditions are met. There are various types of if statements in Java.
The java if statement simply tests the condition and executes if the conditions are met, otherwise it skips over the next segment of code. A if-else statement will run the same however when the condition is not
met, you can set a particular new code block to be executed rather then skipping entirely. A If-else-if ladder is an evolvement of the previous, it allows you to perform a different condition if the original is not met. This can then go on and on continuously with new conditions. A nested if statement is similar to the previous mentioned, with the added specification of being placed within another if statement for added conditioning functionality in a case by case basis.
Loops in Java:
A loop in programming languages such as Java is a way of setting a group of code to run continually, over and over again until a condition is met or reached. These can be used to say run a certain process, like getting data from the user and adding it to a String. It'll run continuously until a condition is met or a counter has reached a desired number.
Note: Just like on conditional statements, loops can be nested inside another for added functionality.
Now lets dive into the different types of loops present in Java:
- While loops - Used to perform select code several times. If your number of loops required is not fixed, it's recommended using while loops in most cases.
- Do-while loops - Same as a while loop except it is guaranteed to run at least once. It'll "do" and then continue to loop "while" the conditions are met.
- For loop - This is used to perform select code a set amount of times before continuing with the rest of your code. For loops have the highest amount of usability, but are also the toughest to comprehend often.
Elements of a For Loop:
Initialization
The initial condition which is executed when the loop starts. We can initialize a variable, or use an existing one. This element is an optional condition within a for loop.
Condition
Tests the condition of the loop to keep it in play. Continues execution until the chosen condition is false. This is Boolean based so it must be a condition that can return a value of true or false. It is also optional.
Increment & Decrement
Increments or decrements a chosen variable, typically the one used in initialization, allowing you to step through arrays, Strings etc or other cases.
Statement
The statement is the block of code executed each time the for loop runs until the set conditions are no longer met.
References:
https://www.oracle.com
https://www.w3schools.com/java/default.asp
interesting post
ReplyDelete