Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

while, do-while, for and for-each loop statements

Lets move ahead with my Java How to Program series to Iteration Statements. Generally, Iteration statements or looping statements are statements which are executed repeatedly based upon a boolean condition. Here boolean condition is also called as loop condition because it helps to determine when to terminate the loop. The code executed in each iteration is generally called as loop body. Basically a loop body may contain single statement or block of statement to execute.
Java programming language provides mainly three iteration statements such as :
  1. for statement
  2. while statement
  3. do-while statement
Generally all three iteration differ only in order in which they are executed. Mainly in, for statement and while statement loop condition is tested before executing loop body. In do-while loop condition is tested after executing loop body. Other than three basic iteration statement there is one enhanced for loop called as for-each loop. Generally the test condition should always be placed in such a way that loop terminated after a few iterations. If test conditions are placed wrongly the execution might enter into infinite loops. The overall looping process involves 3-4 steps. Let us examine each of them one-by-one :
  1. Initialization of counter variable to generate a counter for number of loops we want to follow.
  2. Having execution of the various statement in the loop.
  3. Testing the condition to proceed for the loop.
  4. At last incrementing the counter and following all steps above again.
Now we will discuss some of the widely used loop statements in Java :

The while loop 
The simplest loop is the while loop. The general format of the while loop is as follows:

initialization;

while ( test condition) {

  statements;

  increment;
}

while loop flow chart : 



The while loop working
The basic format is like initially initialization of a counter variable is done. This initialization helps to stop the iteration. After the initialization of counter variable test condition is evaluated. This evaluation of test condition is either true or false. Generally if test condition is true the loop body (statements) are executed. If not the while loop gets exit and next statement following it gets executed. Generally after statements are executed there comes optionally an incremental statement . The increment is necessary because it helps loop to get terminate. If this increment step is not present then while loop enters infinite loop. Generally we use counter variable in the test condition and even in the increment step. It is done so because each time loop executes test condition is tested with counter variable and we can make test condition true by using increment step at the bottom.



The do-while loop The do-while loop is a special looping statement. Generally significance of having this loop is to get atleast one time body statements to execute. Here looping follows some different pattern as compare to other loops. Lets look at the general format of the do-while loop :
initialization;
do{
  statements;
  increment;
}
while ( test condition); 
The do-while working The while loop makes a test condition first before execution of the statements in the body of loop. If the condition is true then only body in loop gets executed or else while loop gets executed. But in do-while loop body of loop gets executed and then test condition is evaluated for the next turn. That means body of the do-while loop will be executed once before any test condition is tested. So for having a loop which we think that it must execute body at least once we use do-while loop. The do keyword performs the execution and while keyword test the condition if test is true the control transfer to the do block again . If test condition is false the control exits do-while loop and next section of code gets executed.




The for loop The for loop is highly and most loved looping statement for the programmers. Lets look at the general format of the for loop :
for ( initialization; test condition; increment )
{
   statement;
} 
   
The for loop working 
The basic format of for loop is like initially initialization of a counter variable is done. This initialization helps to stop the iteration. After the initialization of counter variable test condition is evaluated. The counter variable is tested against the test condition. This evaluation of test condition is either true or false. Generally if test condition is true the loop body (statements) are executed. If not the for loop gets exit and next statement following it gets executed. Generally after statements are executed than there is an incremental statement . The increment statement increments or say decrements values of counter variable which helps loop to get terminate. If this increment step is not present then for loop enters infinite loop.




The for-each loop The for-each loop is an enhanced for loop that works similarly as for loop but it helps programmer in many ways. Generally it helps programmer when iterating on Collections. Typical example could be iterating over array elements without using array indexes. Lets look at the general format for the for each loop :
for( Type Identifier : Expression )
{
   statements;
} 
The for-each loop working Generally if we look at the general format of for each loop we see that it has type identifier and expression. Generally the type is the data type or the object which is been used. Identifier following it is name of the variable. Lastly, expression used must be a instance of array or instance of java.lang.Iterable interface. Suppose we want to loop over array, two things we can do : 1. Either iterate array by indexes using for loop. 2. Using for-each loop and just using expression of the for-each loop to be array variable name.

How to check the given number is even or odd using if-else statement in Java ?.

Introduction
Java beginners have many questions related to the use of if-else statement and other decision making statements. There one of the main question is to know how an if-else statement work ?. Today I am providing a simple source code to make you understand how if-else statement work in Java. To illustrate this , I am explaining if-else through a program. Let us begin our example by simple program to check whether a given number is even or odd by applying if-else statement. This program also teaches us basic of array definition as well as use of modulus operator. Before moving to the source code and explanation of the code. I will give you some idea about basic elements used in this program.

Syntax :

if(boolean-expression)
{
  if-code;
}
else
{
  else-code;
}

rest-of-code;


if-else statement flow chart



if-else statement working

If the boolean-expression is true if-code gets executed. If boolean-expression is false else-code gets executed. In this decision making statements generally either of the block gets executed whether its if-code or else-code, after either execution rest-code gets executed. Using if-else statement to check whether a given number is even or odd public class EvenOrOdd {    public static void main(String[ ] args) {       int[ ] numbers = new int[ ]{11,23,34,45,56,67,78,89,90,104};               for(int i=0; i < numbers.length; i++){         if(numbers[i]%2 == 0)            System.out.println(numbers[i] + " is even number.");         else            System.out.println(numbers[i] + " is odd number.");       }    } }
A Closer Look at the Sample Program Let us analyze the code step-by-step, after having known few basic functionalities of the elements used. Line 2 to 3 :- Line 2 begins with a main method. Generally its a starting point for every Java program. JVM upon execution of program first looks for this method. Line 3 begins with definition and initialization of an array variable. We define an array variable by statement say in our case as : int [ ] numbers, here we have defined an int array which can hold int values with a index. When we write new operator we are creating an object. Here we are creating an object of an int array holding values such as 11, 23 , 35, 45 etc. Line 5 to 9 :- Line 5 begins with a for loop. Generally, we need a for loop to loop through array variables one by one because we need to check for the each element stored in array that whether its even or not. To loop through all the elements of an array we can use length variable defined for array object. length variable gives us the total length of an array. After looping through the array by the test condition applied on length variable we come across if-else statement on line 6. IF-ELSE statement applies a boolean expression to have a decision making flow between even or odd. Here we check in if statement that number retrieved in each for loop execution is even or not. If boolean expression is true, if body gets executed and number gets print stating its even or if statement boolean expression comes out to be false else body gets executed stating that number is odd integer. Testing Boolean Condition :- Modulus Operator is used to test the boolean condition. Generally Modulus Operator % performs division between two operands and returns their remainder. Here let say in our case if number in for loop come as 45. So it will divide 45 by 2 and return remainder which is 1. Generally this 1 indicates that 45 is odd. If the number return with remainder as 0 , it indicates that number is even. Thus based on above logic if-else statement gets the decision making.

Variables and Data Types in Java

Introduction
Lets get started with my yet another hub on Java Tutorials. I am going to give a good tutorial on Variables and Data types used in Java programming language. The objective of this hub is to make you familiar with few questions i.e.
  1. What is a Variable ?.
  2. What is a Data Type ?.
  3. How to declare Variables ?.
  4. How to initialize a Variable ?.
  5. How to access a Variable ?.
  6. What are Constants ?.
  7. How is Automatic Conversions done ?.
  8. How Explicit Conversions work ?.
Lets begin with explanation of each of questions above.

What is a Variable ?.

Variables are the temporary elements in Java which are used to store information about a program. Variables are highly used in Java. It resides in memory and are temporary placeholder for information needed to use in a program. Since value of a variable exists in memory therefore as soon as program exits value is lost. Each variable in Java has a type and a value. Since Java is strongly typed language, therefore each variable used is associated with type. Generally few language out there in market are loosely typed i.e any information can be stored in variable, Whereas in Java data type provides user information that whether variable is integer, string or float etc. The value of variable can be changed anytime in a program, unless the variables are marked with a keyword final. Generally final variables are constants, once a value is assigned to them it does not change.

What is a Data Type ?.

Java is a strongly typed language. It means that for each variable defined there must be a data type associated with it. In Java data types provides developers an idea about the size of variables, a range of values that a variable can therefore store and also about operators that can be used with it. All data stored in a variables are Objects, having exception as primitive data types. Data types used in Java are platform independent, i.e a integer can store same size of data on different platforms such as windows, unix etc. There size to store data is platform independent. This has helped developers a lot, because they now don't need to convert one data type to other when switching the same code on different platforms.
Now let us look at some of the data types available to us in Java.
  • Integer Data Types
Integer Data Types has capability to store integer values. Generally there are 5 types of Integer data types available in Java. Let look and classify them.

 

  • Floating Point Data Types
Floating Point Data Types has capability to store integer and floating point values. Generally there are 2 types of floating point data types available in Java. Lets look and classify them.



  • Boolean Data Types
Boolean Data Types has capability to store true and false values. Lets look and classify them.


How to Declare a Variable ?

Now that we know something about variables and data types, we can easily understand how to declare a variable. Generally by word declare we mean the creation of a variable. Creation of variable can be done any point of time in a code. Lets look at few examples below :-

// Declaring a variable follows below simple syntax.
// [data type][space][identifier][;]
// Few Examples :

int i ; // int -> data type and i -> identifier
float j ; // float -> data type and j -> identifier
long salary ;  // long -> data type and salary -> identifier


How to initialize a Variable ?.

After declaration of a variable, we usually assign it a value. Thus by the term initialize we mean that providing a value to a variable at the time of declaration. By default a local variable gets a value which is left over in memory. Here local variable means that a variable is been declared in a method or a block of code. Generally initialization of a variable is done by assignment operator called as ' = '. Lets look at few examples :-

// Initialization of a variable follows below simple syntax.
// [data type][space][identifier][=][value][;]
// Few Examples :

int i=0 ; // int -> data type,i -> identifier and 0 -> value
float j=3.2f ; // float -> data type , j -> identifier and 3.2f -> value
long salary=1000L ; // long -> data type salary -> identifier and 1000L -> value


How to access a variable ?.

After having some basic knowledge about the variables such declaring and initialization. We can move ahead to look for how to access a variables value. By accessing we mean how can we get out of variable value stored in it. Before accessing a value of a variable, it should be initialized. If you try to access value compiler will throw an error at compile time. Generally in order to access a variable we just use identifier name that's it. One thing should be in mind that variable accessed should not be coded in double quotes "". As double quotes are by deault String literals. Instead of printing the value , it will print the identifier name. Below example code shows how to access a variable.

/* This is Simple Java program call it as Welcome.java.
   It prints some text on the console.*/

public class Welcome 
{
   // main method begins execution of Java application
   public static void main( String[ ] args )
   {
      int hubscore = 50; // declaring and initializing a variable

      System.out.println( "Welcome Java Programs to Hubpages! with hubscore : "+hubscore ); // hubscore in quotes is String and outside quotes its name of variable which will print value in it.
   } // end method main
} // end class Welcome


// Output of the program

Welcome Java Programs to Hubpages! with hubscore : 50


What are Constants ?. Constants are the variable whose value we do not want to get change after it has been assigned a value. Generally to achieve this feature we have to use keyword called as final. A final keyword will make the variable constant. Any attempt to change value of final variable after its initialization would throw a compile time error. As a best practice we generally use capital letters in giving a name to an identifier. Let see how syntax looks like: // Syntax for declaring and initializing a constant // [final][data type][identifier][=][value][;] final int constants = 10 ;  How is Automatic Conversions done ?. When creating a Java application or code we usually have to convert one data type to another. This is somewhat quite hectic task. Java has an excellent feature of automatic conversion. In Java basically there are two types of conversion : 1. Upcasting 2. Downcasting. Upcasting is done automatically and called as Automatic conversion. While downcasting is done explicitly and called as Explicit conversion, which we will see later. In Automatic conversion also upcasting, Java let us do the upcasting. Here below image shows that small data types can be assigned to large data types without any much headache. Java does it for us.
// Automatic Conversion in Java // int data type automatically gets assigned to float data type int age = 10; float oldAge = age; // Everything is handled by Java just size matters // small data type ---upcasted-- > large data types How Explicit Conversions work ?. Explicit conversions basically downcasting is been handled by the programmer itself. If we want to convert large data type to small data type then we have to write some extra code for that. Generally we have to use a special operator for that. The special operator is named as Cast Operator. Cast operator looks like ( data type ) . Here data type in brackets is the data type to which we want to convert. Let see example code :- // We want to convert double (larger data type) to float // (smaller data type) final double PI = 3.14; float newPi = (float)PI; // Cast operator (float) converts double to float and // assign it to newPi
 
© 2021 Learn Java by Examples Template by Hubberspot