A Loop meaning in programming is to run a block of code multiple times again and again till some occurred condition or infinitely.
Types of loops in Java
Why to Use Loops Example:
Let me make you understand more clearly, why loops are important in programming by showing a simple before and after scenario.
Suppose you want to print numbers from 1 to 5, then you can write a program like below.
public class Display {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
}
}
This program will print number from 1 to 5.
But suppose, you’ve to print number from 1 to 1000. Would you love to write System.out.println 1000 times in your program?; – Of course not.
So, the better solution will be using a loop like below. It’ll print 1 to 1000 elements in a few lines of code.
public class Display {
public static void main(String[] args) {
for( int i =1; i<= 1000; ++i){
System.out.println(i);
}
}
}
Hope you understand well why to use loops in java programming!
loops uses example scenarios,
At this stage learning stage, you may not understand the below uses, but as you go and understand related topics line list, file handling etc, it’ll be easier for you get them.
For now, these scenarios for using loop will give you an idea. Just keep them in mind.
- You may want to print numbers from 1 to 1000, then loop can be used.
- If want to get the items from a list one by one
- You may want to read a line from a text file and process each of them
- Or, you may want to continuously monitor some events, if that events occur, then act etc.