What are the different loops available in java? - Java

What are the different loops available in java? How do we choose the right loop for a specific job?

A loop is a set of statements that is supposed to repeat one or more times. Java supports 3 loops.

1. while loop – The block of statements will be repeated as long as the condition returns true. The condition should return false for exiting the loop. The ‘while’ loop can be used when the number of iterations are not certain.

2. do … while – Similar to the while loop. But the difference is – the iteration takes place at least for once. This is due to the condition that is placed at the end of body of the loop. The ‘do….while’ is apt when the loop certainly to execute at least for one time. For example, to display a menu with several options to select. When the user does not want to repeat, he should be given a provision soon after entering into the loop.

3. for loop – Use for loop when the number of the iterations are known before entering into the body of the loop. It has flexibility to assign variables before entering into the body of the loop and perform updation at the end of the loop.

4. for… each - Similar to for loop : perfectly apt for dealing with arrays. When each successive element is to be accessed, use this loop. The length or the indexes can not be used with this loop. Also useful to access a set of collections such as List, Set etc.
Primitive type - Java
The key word ‘new’ is used for creation of objects. Primitive types are to use constants but not objects. Hence, new key word is not used for primitive variables...
What is finalize()? Is finalize() similar to a destructor? - Java
The finalize() method of java is invoked by JVM to reclaim the inaccessible memory location, When the ‘orphan’ object (without reference) is to be released, JVM invokes the finalize() method...
Why does String define the equals( ) method? - Java
The equals() method is defined in String class in order to test whether two strings values are same sequence of characters...
Post your comment