For loop in java with example

Previous
Next

There are several looping statements available in java. One of them is for loop in java.
For loop in java is used to execute some statements repeatedly until condition returns false.
There are three parts to for loop.

  • Initialization
  • Condition
  • Increment or decrement

Syntax for for loop in java:

Initialization: Initialization statement executes at beginning of loop only once.
condition:Condition gets evaluated in each iteration. For loop executes block of statements repeatedly unless condtion returns false.
Increment/Decrement: These statements get executed in each iteration.

Let’s take a very simple example:

Print number from 1 to 10 using for loop

Output:

1 2 3 4 5 6 7 8 9 10

If you are still confused with above concept, let’s understand it with the help of flow diagram.

For loop flow diagram

Let’s try to print only even numbers now.

Output:

2 4 6 8 10

Exercise:

If you are given array of integer, you need to find an element in that array.

Input:

{32,45,53,65,43,23}

You need to write a program to search an element in the array.If element is found in the array, return “PRESENT” else return “NOT PRESENT”

I would recommend you to try it yourself and then look at below code.

Program:

Output:

53 is present in the array
PRESENT

Infinite for loop in java:

You need to be careful with condition you provide in for loop otherwise you may end up creating infinite for loop.
For example:
Let’s say you want to print number from 10 to 1 and you use below code:

Output:

10 9 8 7 6 5 4 3 2 1

Now in above code, instead of i–, you have put i++. In this code,¬†loop¬† will go into infinite loop.

Another example of inifinite loop is below code:

Use two variables in for loop in java:

You can use multiple variables in for loop too.

For example:

Let’s say you want to check if String is palindrome or not. You can use two variables in for loop as below:

Output:

Enter a string : madam
String is Palindrome
Enter a string : adam
String is not Palindrome

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog