Androidberry logo Androidberry text logo
AndroidBerry Home
  • Learn Java
  • Java Programs
  • Interview Questions
  • Androidberry Facebook connect
  • Androidberry twitter connect
  • Androidberry Google Plus connect

Java Tutorials


Basic Introduction

What is Java?
Java Features
Java vs Other Languages
Java on Internet
Java Components
Java First Program
Java Commandline argument
Java Constants
Java Variables
Java Types of Variables
Java Datatypes
Java Getting Input from User
Java Typecasting
Java Operators
Java Math Functions

Decision Making

Java if statement
Java if-else statement
Java nested if-else
Java else-if ladder
Java Switch case statement
Java Nested Switch Case
Java Ternary/Conditional operator

Looping

Java while loop
Java do-while loop
Java for loop
Java Enhanced loop/for each loop
Java Labelled for loop
Java Nesting of loops
Java Break and Continue

Classes and Objects

Java Class
Java Object
Java Object Array
Java Nesting of Classes
Java Methods
Java Method Overloading
Java Constructor
Java Constructor Overloading
Java This Keyword
Java Garbage Collection
Java Static Keyword
Java Arrays
Java String
Java StringBuffer
Java String vs StringBuffer
Java Vector Class
Java Vector vs Array
Java Wrapper Classes

Inheritance

Interfaces

Packages

Exception Handling

Multithreading

Java Applets

Graphics Programming

More on Java

Java Programs
Java Keywords Dictionary
Java Interview Questions

Java Looping | While Loop


While Loop

Looping

“The process of repeatedly executing a block of statements is known as looping.”

If a loop continues forever, it is called as infinite loop. Just like the sun arises on the earth every day.

In looping, statements block of statement is executed until some conditions for the termination of the loop occurred.

How looping works?

  1. Setting and initialization of a counter
  2. Execution of the statements in the loop
  3. Test for a specified condition for execution of the loop
  4. Incrementing the counter

Different types of loops?

  1. while loop
  2. do while loop
  3. for loop

while loop

While loop is the simplest looping structure. While loop is entry controlled loop statement. That means the condition is given at the beginning of loop. If the given condition does not satisfy , the loop statements never get executed.

Syntax

while (test-condition)
{
	// body of while loop
	//increment/decrement counter
}

Flowchart

While Loop Flowchart

Working of while loop

  • First the test condition is evaluated before entering into the while loop. (counter should be initialized outside the loop).
  • If the test condition returns true result, then body of the loop is executed and again condition is checked.
  • Counter increments every time untill the test condition is having true result.
  • Different ways of incrementing the loop.
    • count++ or ++count
    • count = count + 1
    • count += 1
  • As soon the test condition becomes false then loop is terminated.

Example - Printing 1 to 10 numbers using while loop

class WhileLoopEx
{
   public static void  main(String args[])
   {
      int start = 1;
      int end = 10;

      while ( start <= end)
      {
        System.out.println(start);
	  start ++;
      }
   }
}

Output

1
2
3
4
5
6
7
8
9
10

Program Explanation

  • First of all start variable is initialized to 1 and end to 10 (for the first time in a life of while loop).
  • Before entering into the loop, while first checks the condition 1 <= 10 which is true, then control enters into the loop.
  • Print start variable which is holding 1, and then increments start variable by 1, now start stores the new value 2.
  • Now again condition is checked as 2 <= 10 which is true. then follow step 2,3 until 10 <=10 becomes false.
  • Exit from loop.

Iterations on Example

Before entering into the loop, the value of start = 1 and value of end = 10

Iteration Condition while (start <= end) Result start
Iteration 1 while (1 <= 10) true 2
Iteration 2 while (2 <= 10) true 3
Iteration 3 while (3 <= 10) true 4
Iteration 4 while (4 <= 10) true 5
Iteration 5 while (5 <= 10) true 6
Iteration 6 while (6 <= 10) true 7
Iteration 7 while (7 <= 10) true 8
Iteration 8 while (8 <= 10) true 9
Iteration 9 while (9 <= 10) true 10
Iteration 10 while (10 <= 10) true 11
Iteration 11 while (11 <= 10) false 11

Different ways to write while loop


1. while loop without braces

If we have only single statement in the body of loop,then we can write it without using curly braces.

Example

class WhileLoopEx
{
   public static void  main(String args[])
   {
      int i=1,add=0;

      while(i<=5)
      add += i++;
        
      System.out.println("add = "+add);
   }
}                             

Output

add = 15

2. Increment|Decrement and condition at same line

Below program shows the numbers between 1 to 5

class WhileLoopEx
{
   public static void  main(String args[])
   {
      int a=0;
      while(a++ < 5)
      {
         System.out.println("a : "+a);
      }
   }
}

Output

a : 1
a : 2
a : 3
a : 4
a : 5

3. We can also check float,double etc.

Below program checks the float condition and adds float value by 1.0

class WhileLoopEx
{
   public static void  main(String args[])
   {
      float a = 1.0f;
      double add = 0;
      while(a<=5.5)
      {
         add = add +a ;
	   a=a+0.5f;
      }
      System.out.println("addition : "+add);
   }
}

Output

addition : 32.5

4. Running Indefinite loop

Below program doesn't give any output at all. due to ; after while. Compiler will keep rotating eternally.

class WhileLoopEx
{
   public static void  main(String args[])
   {
      int a=0;
      while(a < 10);
      {
        a++;
	  System.out.println("a : "+a);
      }
      System.out.println("final a : "+a);
   }
}

Output

No output will be displayed.


5. Running infinite loop

Below program will start incrementing the value from 1 to infinite.

class WhileLoopEx
{
   public static void  main(String args[])
   {
      int a=1;
      while(a > 0)
      {
        a++;
	  System.out.println("a : "+a);
      }
   }
}

Output

1
2
.
.
23455
.
.

Best Examples for Practice
  • Check number is Prime or Not program
  • Check number is Palidrome or Not program
  • Check character is Vowel or Consonent program
  • Find Factorial of Number program
  • Find nth Power of any Number program
  • Print Multiplication table of Any Number program
  • Count total Number of Digits in the given Number program
  • Print Any Number in Reverse Order program
  • Convert given Decimal Number into Binary Number
  • Convert given Number into Words form
<< Previous Next >>

See Also

All Java Programs
Java Keywords
Java Interview Questions

AndroidBerry Support

About us
Contact us
Suggest us
Questions?

Follow us

Androidberry FacebookFacebook
Androidberry TwitterTwitter
Androidberry GooglePlusGoogle+
Back to top
Androidberry Name Logo