JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Checkout for Promo Codes

Java For Loop


The for statement or for loop provides a way to iterate over a range or list of values. Using for loop you can repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; condition for terminating loop;increment) {
       statement(s)
}

In the above statement, initialization expression initializes the loop; it is executed only once, as the loop begins.

When the termination condition returns false, then the loop terminates.

The increment expression is invoked after each iteration through the loop. Here you can either increment or decrement a value.

Here is a simple for loop example to display numbers from 1 to 10.

package com.java2novice.loops;

public class SimpleForLoop {

	public static void main(String a[]){
		//simple for loop to print from 1 to 10
		/**
		 * here int i=1; means at the beginning of the
		 * loop, we are creating and initializing the variable 
		 * to value 1.
		 * 
		 * 1<=10; means when i value reaches or above 10, the 
		 * control should come out of the loop.
		 * 
		 * i++ means on each iteration, we are incrementing 
		 * i value by step 1.
		 */
		for(int i=1;i<=10;i++){
			System.out.print(i+" ");
		}
		System.out.println();
		/**
		 * another example to increment by 2 steps
		 */
		for(int i=1;i<=10;i=i+2){
			System.out.print(i+" ");
		}
		System.out.println();
		/**
		 * Below loop prints the numbers in reverse order
		 */
		for(int i=10;i>0;i--){
			System.out.print(i+" ");
		}
		System.out.println();
	}
}

Output:
1 2 3 4 5 6 7 8 9 10 
1 3 5 7 9 
10 9 8 7 6 5 4 3 2 1 
<< Previous Program | Next Program >>

Java Loop Examples

  1. Java While Loop
  2. Java Do-While Loop
  3. Java For Loop
  4. Java For each Loop
  5. break statement in java
  6. continue statement in java
Knowledge Centre
What is servlet context?
The servlet context is an interface which helps to communicate with other servlets. It contains information about the Web application and container. It is kind of application environment. Using the context, a servlet can obtain URL references to resources, and store attributes that other servlets in the context can use.
Famous Quotations
Before you go and criticize the younger generation, just remember who raised them.
-- Unknown Author

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2020 by Nataraja Gootooru. All Rights Reserved.