Java While Loop || Java example

Java While Loop :

In java programming, we have different requirements based on the type of work we are doing for example we need to do a piece of work until certain condition is satisfied.

For example i want to print a piece of message or numbers from 0 to 9 incrementally or decrementally for this we can manually do like below…

System.out.println(1);
System.out.println(2);
.
.
.
.
System.out.println(9);

 

But what about a scenario where we want to print 1,000,000 numbers. Should we follow the above style of coding ???

Coding involves various methodologies out of which we need to assess the situation and follow them in this scenario where a similar task to be done multiple times we use looping concept.

 

Now what is a loop ?

Loop is executing a block of code until the condition is satisfied.When you don’t provide proper condition it may result in infinite loop too.

Here comes a smart code when you try to print 10 lakh numbers how many lines of code do you require of course more than 10 lakhs.

while(condition){
   // Block of code to be executed...
}

 

But what if we can use same number of lines top print for both 10 and 1,000,000. Cool right lets see how’s it possible.

Declare a variable i = 0;

public static int i = 0;
while(i < 10){

}

 

the most important thing here is incrementing the value of  ‘i’

    i++;

if you miss this then your loop turns to be a never ending loop or infinite loop.

 

Infinite Loop:

while(i < 10){

    System.out.println(i);
}

 

To make a proper loop we need to use incrementing condition

while(i < 10){

    System.out.println(i);
    i++;
}

 

Java While Loop

 

Now as we discussed above

Print 1,000,000:

Same code just change the number

while(i < 1000000){

    System.out.println(i);
    i++;
}

Java While Loop

If any query on Java While Loop let us know in the comment section below.

 

Show Buttons
Hide Buttons
Read previous post:
Java Conditional Statements || Java example

  Java Conditional Statements: We use few conditions in programming to make some operations possible like we need to test...

Close