Java With Us
Home   |   Tutorial   |   Programs  

Java Tutorial

Introduction to Java
Hello World Program
Variables and Data types
More about data types
Displaying text using print and println
Displaying text using printf
Java Comments
Naming conventions for Identifiers
Mathematical operations in Java
Taking input from the user

Classes and Objects
Introduction to object oriented programming
The constituents of a Class
Creating objects and calling methods
Get and Set Methods
Default constructor provided by the compiler
Access Specfiers
Scope and lifetime of Variables
Call by value and Call by Reference

A few more topics
Class as a reference data type
Constants or literals
Final variables
Increment and decrement operators
Manipulating Strings
Overloading constructors and methods
Static methods and variables
The Java API
The Math class
this keyword
Wrapper classes

Control Structures
Control Statements
Repetition statements
Nested loops
Formulating algorithms
Branching Statements

Arrays introduction
Processing arrays using 1oops
Searching and sorting arrays
Array of objects
Multi dimensional arrays
Taking input as command line arguments
Using ellipsis to accept variable number of arguments

Inheritance introduction
Relation between a super class and sub class
Final classes and methods
The protected access specifier
Class Object

Abstract classes and methods

Exception handling
Exception handling introduction
Exception hierarchy
Nested try catch blocks
Throwing exceptions

Repetition Statements

Java provides three repetitions structures: while, do while and for. These statements are also known as loops. We shall look into the syntaxes of these structures first and also learn how we can formulate algorithms using these loops.

The while loop

Following is the syntax of the while loop. The statements in the while block are executed as long as the condition evaluates to true.

while ( condition ) {
    // code

For this loop to end, the condition should at some point of time become false. This is achieved using counters. Counters are simple variables which are incremented (or changed) every time the body of the loop is executed. They are used to keep track of the number of times the loop is executed. The value of counter is used in the conditional expression to determine the end of the loop. Consider the following code snippet which is used to print the statement "Hi" thrice on the screen.

int ctr = 0;
while (ctr < 3 ) {

The value of the integer variable ctr is first set to zero. When control enter the while statement, the condition ctr<3 is evaluated. Since 0<3 is true, the body of the loop is executed. The statement "Hi" is printed and ctr is incremented to 1. The condition is evaluated again. ctr < 3 is still true. The body of the loop is again executed. In this way, the while loop executes thrice after which ctr becomes 3. Now, since the condition 3< 3 evaluates to false, control moves out of the while loop. In the above program, we can eliminate the ctr++; statement and include it in the while condition itself by using increment operator. But be careful while deciding whether pre increment or post increment should be used.

int ctr = 0;
while (ctr++ < 3 )  {

We also quite often use the value of the counter as a part of our code. For example, the following code is used to add the numbers from 1 to 100.

int ctr = 1; sum =0;
while (ctr<=100) {
    sum = sum + ctr;

Always use integers (byte, short, int or long) variables as counters. Never use floating point numbers to control loops since floating point numbers are not accurate values. For example, the floating point constants 3.4 is not exactly the value 3.4 but is an approximation of some other closer value like 3.39999999999.....

Following program shows how the output produces will be incorrect when using floating point constants. The actual purpose of the program was to print the floating point numbers 0.1, 0.2, 0.3 ....1.0 on the screen but the result produced was different.

double ctr = 0.1;
while (ctr <= 1) {
    ctr = ctr + 0.1;



As you can see, instead of displaying 0.3, 0.30000000000000004 was displayed and similar is the case with the last three numbers. Similar would have been the case if we used ctr to print some statement a predefined number of times.

While loop is an entry control loop which means that the condition is checked before entering the body of the loop. Therefore, it might be possible that the body of the loop is not executed even once. For example, if we set the condition in the above examples to str<0, the loop is not executed even once. In contrast, we have the exit control loops in which the condition is checked after executing the body of the loop because of which the loop is executed atleast once. Following is the syntax of the do while loop:

do {
    // code
} while ( condition );

Note that there is a semicolon after the while statement. Following code uses the do while loop to print "Hi" thrice on the screen.

int ctr = 0;
do {
} while (ctr < 3);

The last of the repetition statements is the for loop which provides a more convenient way to handle counters in loops. Following is the syntax of a for loop:

for ( initialization; condition; increment/ decrement ) {
    // body

The for header has three parts namely initialisation, condition and increment/ decrement. The initialisation part is used to declare and initialise loop control variables or any other necessary variables before entering into the loop. The condition is checked before executing the loop and the increment/ decrement part is executed after each time the body of the for loop is executed. The third part of the for header can also contain statements other than increment and decrement operations. The above for loop is equivalent to the following while loop.

while ( condition ) {
    // body
    increment / decrement;

However, there is major difference between these two loops. Variables that are declared in the for header have a scope and lifetime that is limited to the body of the for loop. These variables are not accessible once we come out of the for loop. This is one reason why for loops are preferred over while loops.

Following code prints the numbers from 1 to 10 using a for loop.

for ( int i=1; i<=10; i++) {

We generally use the identifiers I, j, k for loop control variables. We may also, declare these variables outside the for loop if the value of this counter if required after control moves out of the for loop.

int i;
for (i=1; i<=10; i++) {
    System.out.println("The value of i was "+i +"when the loop condition evaluated to false");

The above code will display the statement "The value of i was 11 when the loop condition evaluated to false" in addition to printing the numbers from 1 to 10. If the variable i was declared in the for header itself, the above print statement would have produced a compilation error.

We may declare more than a single variable in the initialisation part of the header. However, each of these variables should have the same data type and they should have not been declared earlier. The following for header declares and initialises two variables i and j.

for ( int i= 0, j=10; // code; // code )

Here are the various formats of the initialisation part that are allowed:

< variable name > = <value >
< data type > < variable name > = < value >
< data type > < variable name 1 > = < value (optional) > , < variable name 2 > = < value ( optional ) >, ...... <variable name n > = < value ( optional ).....

The increment decrement part can contain more than one statement. These are separated by a comma and not by a semicolon. Generally, we use this part only to increment or decrement variables, though other statements are also allowed.

for ( // code; // code; i++, j++, k+=5 ) {

It is not necessary that all the three parts of the for header have to be present. One or all of them may be skipped. Following shows a for header in which only the condition part is specified. The other two parts are left empty.

for( ; i<=10; ) {
    // code

In all the above three decision making statements, if the condition is left empty, it is taken as true. Such a loop keeps executing for ever and is known as an infinite loop.

while ( ) {
    // code

Infinite loops may also result even after specifying the condition as in the following example:

for ( int i=1; i <= 10 ;i--) {

Infinite loops are considered to be logical errors. There would be no reason as to why a programmer wishes to run a loop for ever. This would eventually cause the system to crash. Infinite loops result from trivial mistakes. For example, in the just preceding example, i++ was replaced with i-- which caused the loop to run continuously. Loops that do not have a body are known as empty loops. For example, the following while loop is an empty loop:

while ( ctr++<10 ) {

We may also write this loop in the following way:

while ( ctr++ < 10 ) ;

The above statement is equivalent to the following which contains an empty statement. As stated already, whitespaces do not matter in a program.

while ( ctr++< 10 )

Control statements may be nested within one another. An if else structure may be written inside a for loop, a for loop can contain another for loop which in turn can contain one more for loop and so on....

Privacy Policy