Sunday, December 25, 2011

JAVA Programming : For Loop

JAVA For Loop


For loop in java is one of the most common type of loop. There are two types of for loop:
  1. Basic For loop 
  2. For Each loop  (Introduced in Java 5)
Basic For loop:
For loop declaration has there parts : initialization, termination condition, iteration expression. These parts are separated by semicolons.

Syntax of for loop:-


   for(initialization; condition; iteration){ 
      //set of statements
   }



Initialization part: The initialization part of for loop is executed only for the first when the loop begins. It lets you declare and initialize one or more variables of the same types. One thing to note when the declaring a variable in for loop is the scope of variable. If the variable is declared in the for loop the variable's scope is limited to the for loop.

Condition part: The condition part must be an Boolean expression. In condition part there cannot be multiple test condition but we can use logical operators to make a logical expression that evaluates into a Boolean result. The body of the for loop is executed only if the condition is true else the loop is terminated.

Iteration part: After every iteration of  for loop's body, the iteration part is executed. This is the part where you can set the change in loop control variable. The given example will give a better understanding of working of for loop.

Example of for loop:- This is a very simple example of for loop which will take an integer input form user and print the table of that number.

import java.util.Scanner;
public class ForLoop {
  public static void main(String[] args) {
    System.out.println("Enter a number");
    Scanner scan = new Scanner(System.in);
    int userInput= scan.nextInt();
    int result=0;
    System.out.println("Table of "+userInput);
    System.out.println("--------------");
    for (int num = 1; num <= 10; num++) {
      result=userInput*num;
      System.out.println(userInput+" * "+num+" = "+result);
    }
  }
}

In this program, a Scanner class is used to take input from user. Next, is a for loop which is declare to run10 times. This for loop starts with initialization int num=1, and executes the body part  till the condition num<=10 becomes false, after executing the body of for loop for each and every time num value will be incremented by 1.

Output of Program:-


Different ways of using For Loop:- For Loop can be used in different ways and sometimes it can be very complex. We will discuses this in the examples below. In For loop there is one thing to notice that all three declaration part of for loop can be left blank.


    for ; ; ) {   
       //infinite loop
    }



The code above is will work as an infinite loop or endless loop and it will work same as while(true) loop.

As we now know that all three part of For loop are optional and can be left blank but it is very interesting to know that what kind of code you can write in these parts. The condition part is the only part of for loop declaration for which there is a rule defined that it must be an Boolean expression. In the remaining two, Initialization and Iteration part we can actually write any peace of code.


public class ForLoop {
  public static void main(String[] args) {
    int i = 0;
    for (System.out.println("Initializtion Part"); i<

     System.out.println("Iteration Part") ) {
     

       System.out.println("Body part");
       i++;
    

    }
  }
}



Output of Program:-

Use of comma and logical operators in For loop:- In For loop we can use multiple statements in initialization and iteration parts using comma. In initialization part we can define multiple variables by separating the variables with comma but the variables must be of same type.
As we know, condition part of the for loop must be an boolean expression therefor use of comma is not allowed but we can use logical operators to make a valid boolean  expression.


public class ForLoop {
  public static void main(String[] args) {
    for (int a=1, b=5, c=10; a<b || a<c ; a++,b--,c--) {
      System.out.println("a = "+a+" b = "+b+" c = "+c);
    }
  }
}



Output of the program:-

In the next post we will learn about For each loop or Enhanced For Loop.

Wednesday, November 23, 2011

JAVA Programming : Do While Loop

JAVA Do While Loop


Do Loop is very similar to the while loop. The only difference between while and do while loop is that the while loop first checks the condition and executes the body of while loop only if the conditions results as true but in while loop the condition is evaluated after the loops body is executed once, so even if the condition is false at the first time the body of loop will be executed at least once.


  do{
     //set of statement
  while(condition);



Example of Do While loop:- The examples below will explain the working of do while loop.

In the examples below the while loop and do while will work exactly same i.e. will give the same output.

public class DoWhileLoop {
  public static void main(String[] args) {
  int i=1;
    do {
      System.out.println("enter into loop");
      i++;
    while (i<=10);
  }
}

public class DoWhileLoop {
  public static void main(String[] args) {
    int i = 1;
    while (i <= 10) {
      System.out.println("enter into loop");
      i++;
    }
  }
}

In the examples below the while loop and do while will not give the same output. 

public class DoWhileLoop {
  public static void main(String[] args) {
  int i=11;
    do {
      System.out.println("enter into loop");
      i++;
    while (i<=10);
  }
}

public class DoWhileLoop {
  public static void main(String[] args) {
    int i = 11;
    while (i <= 10) {
      System.out.println("enter into loop");
      i++;
    }
  }
}



In these examples the condition will be false at the first time so the body of while loop will never get processed but the body of do while will be processed once.

JAVA Programming : While Loop

JAVA While Loop


Loops in java are the control flow statements that are used to repeat a block of code multiple times according to a given condition.  There are three types of loops: For , Do , While. The while loop is very simple but very effective when we have to execute a block of code until a particular expression(condition) is true. The condition will evaluate into a boolean result.

Syntax of while loop:-


    while(condition){
      //set of statements    
    }


Example of while loop:- To understand the functionality of while loop lets see the example. While loop first checks the given condition, if the condition results into true then the statement written inside the while loop block will be executed and then the condition is checked again. This process goes until the given condition is false.

import java.util.Scanner;
public class While {
  public static void main(String[] args) {
    int i=1;
    System.out.println("Enter any number to print table");
    Scanner scan = new Scanner(System.in);
    int num = scan.nextInt();

    while (i<=10) {
      System.out.println(num+" * "+i+" = "+num*i);
      i++;
    }  
  }
}

Output of Program:- 

Tuesday, July 19, 2011

JAVA Programming : Switch Statement

JAVA Switch Statement


Switch Statement is also a control flow statement like If statement. But Switch statement is a bit different from If statement, because an If statement can only choose one course of action form multiple choices but switch statement can have multiple outcomes. We will explain it below. A switch statement works only for convertible int values (like byte, int, short, char) and enum constants.

Syntax of Switch Statement:


 switch(expression){
      case constantOne:
        //set of statement   
      case constantTwo:
        //set of statement
      case constantThree:
        //set of statement
      default:
        //set of statement
 }



Now lets see the functionality of Switch statement: In a switch statement the flow of execution starts from top to down i.e. the first case will be evaluated and the second case and so on and wherever it finds the matching case it will execute the associated code block and the remaining code block till the end of switch. Let’s understand with an example:


public class SwitchStatement {
  public static void main(String args[]){   
    int a=2;
    switch (a){
    case 1:
      System.out.println("one");
    case 2:
      System.out.println("two");
    case 3:
      System.out.println("three");
    case 4:
      System.out.println("four");
    }  
  }
}



The output of this program is :
     two
     three
     four

Here we can see that after finding the matching case, the associated code block and all the code blocks after that will get executed till the end of switch statement. This kind of situation is called fall through. To overcome this problem we can use break statement.

Break: Whenever the program finds a break statement, the execution of program jumps out of switch. Break statement is also used in loops like for and while. We discusses about it later.


public class SwitchStatement {
  public static void main(String args[]){   
    int a=2;
    switch (a){
    case 1:
      System.out.println("one");
      break;
    case 2:
      System.out.println("two");
      break;
    case 3:
      System.out.println("three");
      break;
    case 4:
      System.out.println("four");
      break;
    }  
  }
}



This is same example as above but with a slight change. We have used the break statement in all cases. So, the output of this program will be:

    two

This is because when it executes the case 2 block it will encounters a break statement and the execution of program will move out of switch immediately without executing remaining cases. This way it avoids the fall through situation. 

Default: Default works same as Else in If-Else statement. In switch statement if there is no matching case the default case will get executed. Here is an example: 


import java.util.*;
public class SwitchStatement {
  public static void main(String args[]){
    int option=0;
    String week="";
    Scanner scn = new Scanner(System.in);
 
    System.out.println("Enter a Weekday")
    option=scn.nextInt();
    
    switch (option){
    case 1:
      System.out.println("Sunday");
      break;
    case 2:
      System.out.println("Monday");
      break;  
    case 3:
      System.out.println("Tuesday");
      break;
    case 4:
      System.out.println("Wednesday");
      break;
    case 5:
      System.out.println("Thursday");
      break;
    case 6:
      System.out.println("Friday");
      break;
    case 7:
      System.out.println("Saturday");
      break;
    default:
      System.out.println("Wrong option");
      break;
    }  
  }
}



Output of Program: When there is a matching switch case.

When there is no matching case the default code block will execute.

Monday, June 20, 2011

JAVA Programming : If Statement

JAVA If Statement


The If statement may be defined as a decision making statement, a control flow statement or a selection statement. In a simple program the execution of code starts form first line and ends at the last line but what if we want to execute a block of code only under a certain circumstances. The if statement is the simplest decision making statement. An If statement evaluates a Boolean expression (true or false) and determine whether to run a particular set of statement or not. The syntax of an if statement is:


if (booleanExpression) {  
      //set of statement 
}



Example of If Statement: Using If statement to find out whether a number is divisible of 5 or not.

public class IfStatement{
  public static void main(String args[]){
    int x=15;
    if(x%5==0){
      System.out.println("x is divisble by 5");   
    }
  }   
}



If-Else Statement:- An If statement runs a block of code if the testing condition is true. By using If-else statement we can give another another block of code that will run when the If condition is not true. In other words in If-Else statement code in If block will run when condition is true and code in Else block will run when condition is false. Below is the syntax of If-Else statement. 


if(booleanExperssion){   
  //set of statement
}
else{
  //set of statement
}



Example of If-Else Statement: In this example we will find weather a number is odd or even using If-Else Statement. As we know if a number is divisible by 2 then it is an even number else it is an odd number. 


public class IfElseStatement{
  public static void main(String args[]){
    int x=5;
    if(x%2==0){
      System.out.println("x is an even number");   
    }else{
      System.out.println("x is an odd number");
    }
  }   
}



If Else If Statement: If-Else-If Statement is used when we have to choose form multiple course of action or we can say If-Else-If Statement is used when we have to check multiple conditions and there is different course of action for every condition. Let’s understand it with an example where we have to set student’s grade on the basis of marks.


public class IfElseIf{
  public static void main(String args[]){    
    int 
marks=85;
    char grade = ' ';
    if(marks >= 90){
      grade = 'A';
    }
    else if (marks >= 80){
      grade = 'B';
    }
    else if (marks >= 70){
      grade = 'C';
    }
    else if (marks >= 60){
      grade = 'D';
    }
    else{
      grade = 'E';
    }
  }   
}


In If-Else-If statements once a condition is found true that particular block of statement are executed and rest of the condition will not be checked. For example when first If condition is found true, it will not check the rest of the Else If or else statements otherwise it will check the second Else If and so on.
In this example, marks are 85 therefore it satisfies more than one given conditions which is greater than equal to 60, greater than equal to 70 and grater than equal to 80. But when the first else if which is greater that equal to 80 found true it will not check the remaining conditions and the grade will be set to B which is the correct grade. But here you can notice a wrongly formatted code can lead to an error. Lets take a look at the code below:


public class IfElseIf{
  public static void main(String args[]){    
    int 
marks=85;
    char grade = ' ';
    if(marks >= 60){
      grade = 'D';
    }
    else if (marks >= 70){
      grade = 'C';
    }
    else if (marks >= 80){
      grade = 'B';
    }
    else if (marks >= 
90){
      grade = 'A';
    }
    else{
      grade = 'E';
    }
  }   
}


In this program as the first if condition is true the grade will be set to D and rest of conditions will be ignored. But the correct grade should be B as the marks scored are more than 80. So now we can see if the program is not correctly formatted it can lead to errors. This problem can be solved using multiple condition in one If block using logical operators like || and &&. 


public class IfElseIf{
  public static void main(String args[]){
    int marks=85;
    char grade = ' ';
    if(marks >= 60 && marks < 70){
      grade = 'D';
    }
    else if (marks >= 70 && marks < 80){     
      grade = 'C';
    }
    else if (marks >= 80 && marks < 90){
      grade = 'B';
    }
    else if (marks >= 90){
      grade = 'A';
    }
    else{
      grade = 'E';
    }
  }   
}



Here by giving multiple conditions using logical operators we can make sure that the code will result in correct output even if the code is not correctly formatted. 


Friday, April 22, 2011

JAVA Programming : Operators

JAVA Operators 

A Operator in Java is a Symbol that manipulates one or more primitive data types (arguments) to produce a result. Operators are very important part of Java programming. Below is the list of Operators available in Java.

OPERATORS
Assignment Operators
=








Arithmetic Operators
-
+
*
/
%
++
--








Relational Operators
> 
< 
>=
<=
==
!=









Logical Operators
&&
||
!












Bit wise Operator
&
|
^
>> 
>>> 










Compound Assignment Operators
+=

-=
*=
/=
%=










Conditional Operator
?:







Assignment Operator: It is the most common and simple operator that is used to assign value on its right to the operand on its left.

Arithmetic Operators: As the name suggest these are the operators that are used for performing arithmetic operations. Java provide seven arithmetic operators add, subtract, multiply, divide, mode (returns remainder), unary increment and unary decrement.

Bit Wise Operators: Bit operator in Java are use to manipulate variables at bit level. It is not recommended to use bit wise operatically in normal application programming because in makes code hard to understand. So, we are not going to discusses bit wise operators in details. In code below we shown how to use these operators.

Compound Operators:- Compound operators provide a short way or syntax to write Arithmetic and Bitwise operators. There are eleven compound operators in Java. 

Below is the Java Code that shows how to use Assignment, Arithmetic, Bit wise and Compound Operator in a program. This Class doesn't actually do anything  in terms of producing result, but it shows you the syntax to use these operators. 


public class Operators {
    public static void main(String arg[]) {

      vv//Assignment Operator
      vvint a = 1;     // a has value 1
        int b = 2;    // b has value 2
        int c = a;    // c gets the value of a i.e 1


        //Arithmetic Operators
        a = b + c;    //Addition
        a = b - c;    //subtraction
        a = b * c;    //Multiply
        a = b / c;    //Division
        a = b % c;    //Mode


        a++;      //Increment a by 1
        a--;      //Decrement a by 1

        //Bit Wise Operators
        a = a << 3;   //Left Shift 
        a = a >> 3;    //Right Shift
        a = a >>> 3;  //Unsigned Right Shift

        a = b & c;     //AND
        a = b | c;    //OR
        a = b ^ c;    //XOR

        a = a + b;  //this is normal + operation
        a += b;    //this is compound operation of above 

        //compound Operators
        a -= b;
        a *= b;
        a /= b;
        a %= b;

        a >>= 3;
        a <<= 3;
        a >>>= 3;

        a &= b;
        a |= b;
        a ^= b;
    }
}


Relational Operator:
Relational Operator in Java are binary operators i.e. they are used to compare two operands. There are six relational operators as shown above. Relational operator in java compare to numaric objects and results in a boolean value.


public class Relational{
   public static void main(String args[]){

     int a = 20, b = 10;

     System.out.println("a > b results in : "+(a > b));
     System.out.println("a < b results in : "+(a < b));
     System.out.println("a >= b 
results in :  "+(a >= b));
     System.out.println("a <= b results in :  "+(a <= b));
     System.out.println("a == b results in :  "+(a == b));
     System.out.println("a != b results in :  "+(a != b));

   }
 }



Logical Operator:
Logical operator evaluates two Java boolean values and gives results in boolean value. There are three logical operator in Java. Below is the code that shows the basics of logical operators.


public class Logical{
   public static void main(String args[]){
     boolean a = true;
     boolean b = false;

     System.out.println("a && b 
results in : (a && b));
     System.out.println("a || b results in : (a || b));
     System.out.println("!a results in : " (!a));
   }
}



Truth table for and or and not operations: Here P and Q are Boolean expressions and T stands for true and F stands for false.
Conditional Operator:
Conditional Operator is a ternary operator in Java which evaluates a expression and returns option1 if result is true else returns option2. Take a Look at the figure below.

public class Conditional {
   public static void main(String args[]){   
     int a=5;
     int b=10;
     int max;

     max= a > b ? a : b ; 
     System.out.println("Max = "+max);
   }
}