Reading:  

Quick introduction to Java Programming language - Part 1


Looping statements in Java

In some situation code need to be execute severaltimes to achieve this by using loop.

Looping Statements:

There are four types

  • for
  • while
  • do…while
  • for-each

 

For Loop:

This loop allows usto execute a block of code for a specific number of times.

Syntax:

for(initialization; condition; increment/decrement) {
       …
}

Various parts of above for loop are explained below

Initialization: This is beginning step allows us to declare and initialize loop control.It execute only once.

Condition: This step evaluates each time when iteration starts/at beginning of each iteration

Increment/Decrement: This step executes at the end of each and every iteration

public classForDemo
{
public static void main(String[] args)
{
int sum=0;
for(int i=1;i<=10;i++)
{
sum+=i;
}
System.out.println("Sum of numbers from 1 to 10 is: "+sum);
System.out.println("Program ends");
}


Output of above program is shown below

Nested For Loop:

In nested, where for within for loop.

Example

public class NestedForDemo
{
	public static void main(String[] args) 
		{
			for(int i=1;i<=3;i++)
			{
				for(int j=1;j<=3;j++)
				{
					System.out.println(i+" "+j);
				}
			}
			System.out.println("Program ends");
		}
   }

 Above Program will output

Break:

is a keyword used in “for” statements with if condition. Break is used to terminate the “for” loop iteration.

Syntax:

break;

Example: 

public class BreakDemo
{
	public static void main(String[] args) 
	{
		for(inti=1;i<=10;i++)
		{
			System.out.println("i is: " + i );
			if(i==3)
			   {
				break; // program will exit this loop when condition is true
			   }
		}
		System.out.println("Program ends");
	}
}

 

 Above program will output

Continue:

This is keyword used to skip the current iteration and execute the next iteration.

Syntax:

   continue;

Example: 

public class Account 
 {
	public static void main(String[] args) 
    {
		for(inti=0;i<=5;i++)
		{
			if(i==3)
			   {
				continue;
			   }
			System.out.println("i: "+i);
		} 
		System.out.println("Program ends");
    }
}

Output 

 

As you can see that value 3 was not printed because of continue; 

The return statement:

The return is a keyword to return the data from method and alsoto exit from the current method and jump back to the statement within the calling method that follows the original method call.

  • Statements exist after return statement i.e called unreachable.
  • If java has unreachable state, it will throw error.

Two types of return: One that returns a value and one that doesn't.

Syntax:

return variable;  or return;

public class ReturnDemo
{
	public static void main(String[] args) 
	{
		int totSum=0;
		for(int i=5;i<=10;i++)
		   {
			totSum+=sum(i);
		   }
		System.out.println(totSum);
	}
	static int sum(int a)
	{
		if(a%3==0)
		{
			return a;
		}
		else
		{
			return 0;
		}
	}
}

Output for above program will be 15 

 

While Loop:

This loop provides condition, to iteratespecific statements based on condition.

If condition fails/not met then statements will not execute inside the while loop.

Syntax:

while(condition) {
 //statements
}

Example:

public class WhileLoopDemo
{
	public static void main(String[] args) 
	{
		int i=1;
		while(i<=10)
		{
			System.out.println("i is: "+i);
			i++;
		}
		System.out.println("Program ends");
	}
}

Output of above program is shown below

Do…while:

This loop to iterate specific statements based on condition.But here

if condition is true/false,the statements will execute atleast once.

Syntax:

do 
{
 //statements
}
while(condition);

Example:

public class DoWhileDemo
 {
	public static void main(String[] args) 
	{
		int i=1;
		do
		{
			System.out.println("i is: "+i);
			i=i+2;
			System.out.println("After addition i value is: "+i);
		}
		while(i==1);
			System.out.println("Program ends");
	}
}

Output:

For each: (Advanced / Enhanced for)

For-each is used to iterate elements in a arrays/collections

  • It is added from java1.5/5.0 release
  • It works with array and collections

Syntax:

for(declaration: expression)   
{
 //Statements
}

Main method Example: 

public static void  main(String[] args)
 {
	int [] marks = {92, 80, 90, 88, 50};
	for(int i : marks )
	{
		System.out.print( i );
		System.out.print(",");
	}
	System.out.print("\n");
	String [] subjects ={"Maths", "Science", "English", "History"};
	for( String subName : subjects )
	{
		System.out.print( subName );
		System.out.print(",");
	}
}

Output is shown below 

 

 

Description

This tutorial is targetted for beginers seeking a quick get on with guide on Java programming language. 3 parts include 

  1. Java basics
  2. Object oriented programming
  3. Advance concepts

Each part is subdivided in multiple chapters.

Java basics has the following chapters

  1. Introduction
  2. Environment Setup
  3. Basic Syntax
  4. Objects and Classes
  5. Basic Data Types
  6. Variable Types
  7. Modifier Types
  8. Basic Operators
  9. Loops
  10. Decision Making
  11. Numbers Class
  12. Character and String Class
  13. Arrays
  14. Date and Time
  15. Regular Expression
  16. Methods
  17. Streams, Files and I/O
  18. Exceptions Handling

Thanks for reading and as always, your feedback is very important to us. Let us know how we can improve and if you found any issues with this write up, send us a correction.



Audience

Beginners or students seeking a refresher on Java language

Author: Subject Coach
Added on: 9th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!