Thursday, August 29, 2013

Loops in Java with examples



In java or any other programming language use three types of looping methods
1.    While loop
2.    Do while loop
3.    For loop

While loop

  • This loop is used for iteration purposes in programming.
  • First there should be initialization and then check the condition, if condition is true it can go inside the while loop and execute.
  • When condition is false it skips the loop.
   Initialization;
   While (condition)
   {
       Body of loop
   }

Try these example for understand about while loops.


public class Mango{ 
     public static void main(String args[]){
         
          int x =1;
          while(x<6){
              System.out.println(x);
              ++x;
          }
     }
}



Illegal while conditions


There should be a condition in while loop

          Ex: while (x==5), while (false), while (x!=3)…etc.


int x=1;
While (x)
{
      Body of loop
}


int x;
While (x=10)
{
Body of loop
}



Legal while conditions


int x;
While (x==10)
{
     Body of loop
}


int x=10;
While (true)
{
     Body of loop
}



Do while loop

  • This is like a while loop, but different is this is execute at least one time, and then check the condition.


Initialization;
    do{
         Body of loop
    } While (condition);




Try these example for understand about while loops.

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

          int x =1;         
          do{
              System.out.println(x);
              ++x;
          }while(x<6);
     }
}


public class Apple{
     public static void main(String args[]){
       int x=1;
    
       while(x<15){

          int y=1;
          while(y<12){
             
            int res = x*y;
            System.out.println(x+ " * " +y+" = "+ res);
            y++;
          }  
          System.out.println("------------------------");
          ++x;
    
     }
  }
}


For loop


for (initialization; test condition; increment)
    {
          Body of the loop
    }

  • This is the structure of for loop, but same thing can be done in several ways. (Look at the examples)
  • First you have to declare the variable that you are going to use. This should be the initial state of variable.
  • Then semicolon is compulsory.
  • After this, condition is there, if condition is true, the body of the loop is executed.
  • Then it go to increment process and same thing happen until condition false.
Try this codes to understand about for loop.


public class Apple{

     public static void main(String args[]){
    
          for(int  x=0; x<5; x++){
    
              for(int y=0; y<=x; y++){
                   System.out.print("*");
              }
              System.out.print("\n");
          }
     }
}



public class Apple{

     public static void main(String args[]){

          int mark[] = {10,20,30,40,50,60,};//array in java

          for(int x=0; x<mark.length; x++){
              System.out.println(mark[x]);
          }
     }
}



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

           for(;;){
                System.out.println("This is endless for loop");
           }
     }
}



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

          int x= 10;
          for(;x<15;){
              System.out.println("This is a valid for loop");
              x++;
          }
     }
}



Continue and break

  • Break keyword is used to stop entire loop.
  • Continue means it skips the current iteration and execute the program.


public class Apple{

     public static void main(String args[]){
    
          for(int  x=0; x<=20; x++){
         
              if(x==5){
                   continue;//this is used to skip a part
              }
         
              if(x==15){
                   break;//this is used to break the loop
              }
          System.out.println(x);
             
          }   
     }
}



Labeled for loop

  • You can label for loops as you want.
  • If there are nested loops it is better way to identify each loop separately.
  • Before “for” keyword you can type the name of loop and add colon after it.

In this example I have labeled outer and inner loops.


public class Apple{ 
     public static void main(String args[]){
         
          outer:
          for(int x=0; x<10; x++){
         
              System.out.println(x);
             
              inner:
              for(int y=0; y<10; y++){
                   System.out.println(y);
             
                   if(y==5){
                        continue outer;
                   }        
              }   
          }
     }
}




Enhanced for loop

  • This is available after java 5.
  • Syntax is there, first you have to use array to declare data.
          int x[] = {elements};
          for (declaration : expression);
    
Try these codes to understand about enhanced for loop.


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

          int x[] = {1,2,3,4,5,6};
         
          //this is normal for loop
          for(int i=0; i<x.length; i++){
            System.out.println("Normal for loop: " + x[i]);
          }
         
          //this is enhanced for loop
          for(int j :x){
            System.out.println("Enhanced for loop: " + j);
          }   
     }
}





Wednesday, August 28, 2013

Switch statement


This is used to test equality of values of set of values. We used 'case' as a name of each values. This is the syntax of switch statement.


Switch (expression)
{
     case value1:
       block 1;
       break;
    
     case value1:
        block 1;
        break;

     case value1:
        block 1;
        break;

     default:
        default block;
        break;
}


  • If you are working with java 7, you can use byte, short, int, enum and also strings for switch case. We are going to learn about enum in next lessons.
  • Look at the following example

public class SwitchDemo {

 public static void main(String args[]) {

  int key = 3;

  switch (key) {
  case 1:
   System.out.println("Key is 0");
   break;

  case 2:
   System.out.println("Key is 1");
   break;

  case 3:
   System.out.println("Key is 2");
   break;

  case 4:
   System.out.println("Key is 3");
   break;

  default:
   System.out.println("Key is not there");
   break;
  }
 }
}
  • You can also try without using "break" keyword. This keyword is used to break the running process when it found the correct value.
  • Default is another keyword which is used to give a default message.
  • If there is no matching case according to your key, this default case will be executed.


Switch with enum


enum Day {
 Sunday, Monday, Friday
}

public class SwitchEnumDemo {

 public static void main(String args[]) {
  Day d = Day.Monday;
  switch (d) {
  case Sunday:
   System.out.println("Today is Sunday");
   break;
  case Monday:
   System.out.println("Today is Monday");
   break;
  case Friday:
   System.out.println("Today is Friday");
   break;
  default:
   System.out.println("Invalid input");
  }
 }
}

Illegal switch statements



public class SwitchDemo {

 public static void main(String args[]) {

  final int x = 1;
  int y;
  y = 2;
  int z = 0;

  switch (z) {

  case x: // OK
  case y: // compile time error
  //Case values must be final variables.
  }
 }
}




public class SwitchDemo {

 public static void main(String args[]) {

  byte x = 2;

  switch (x) {
  case 23:
  case 128: // compile time error
  // Range of byte is -128 to 127
   
  }
 }
}



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

         int num = 20;
        
         switch(num) {
         case 10:
             System.out.println("10");
         case 10:
             System.out.println("10"); //compile time error
             //Same value cases are not allowed.
         case 15:
             System.out.println("15");
         default:
             System.out.println("Other");
         }
    }

}


Simple calculator example using switch

  • You need to have Java 1.7 to use Strings as the case.


public class SimpleCalculator {

 public static void main(String args[]) {

  Scanner scn = new Scanner(System.in);

  System.out.print("Enter number one: ");
  double num1 = scn.nextDouble();

  System.out.print("Enter number two: ");
  double num2 = scn.nextDouble();

  System.out.println("Enter your operator: ");
  String op = scn.next();

  switch (op) {

  case "+":
   System.out.println("Sum: " + (num1 + num2));
   break;

  case "-":
   System.out.println("Substraction: " + (num1 - num2));
   break;

  case "*":
   System.out.println("Multiplication: " + (num1 * num2));
   break;

  case "/":
   System.out.println("Devision : " + (num1 / num2));
   break;

  default:
   System.out.println("Invalid input");
   break;
  }
 }
}






Friday, August 23, 2013

If statement


This is used to get a decision in programming language. There are four basic types of "If statements". First we look at the structures of them and then try programs.

Structure 01


if ( condition )
{
   //statement executes when boolean condition is true
}


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

  int x = 12;

  if (x == 10) {
   System.out.print("X: " + x);
  }
 }
}


Structure 02


if ( condition )
{
     //statement executes when boolean condition is true
}
else
{
     //statement executes when boolean condition is false
}



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

  int x = 12;

  if (x == 10) {
   System.out.print("X: " + x);
  } else {
   System.out.print("X is invalid ");
  }
 }
}




Structure 03


if ( condition one )
{
     //statement executes when boolean condition one is true
}
else if(condition two )
{
     //statement executes when boolean condition two is true
}
else if(condition three )
{
     //statement executes when boolean condition three is true
}
else
{
     //statement executes when all boolean conditions are false
}



public class Apple {

 public static void main(String args[]) {

  int x = 85;

  if (x < 35) {
   System.out.println("Grade is F");
  }

  else if (x < 55) {
   System.out.println("Grade is C");
  }

  else if (x < 65) {
   System.out.println("Grade is B");
  }

  else if (x < 75) {
   System.out.println("Grade is A");
  }

  else {
   System.out.println("Grade is A+");
  }

 }
}



Structure 04


if( condition X )
{
     if(condition Y)
{
     //statement executes when boolean condition Y is true
}
else
{
//statement executes when boolean condition Y is false
}
}
else
{
     //statement executes when boolean condition X is false
}



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

  int x = 10;

  if (x == 10) {
   if (x < 5) {
    System.out.print("x < 5");
   } else {
    System.out.print("x > 5");
   }
  } else {
   System.out.print("X is invalid ");
  }
 }
}



You can use if-else without curly brackets.


public class Apple {

 public static void main(String args[]) {

  int x = 20;

  if (x != 10)
   System.out.println("X is not equal to 10");

  /*
   * if you don't add "{}" it will automatically add the brackets and
   * close the bracket after the first execution line
   */

 }
}



public class Apple {

 public static void main(String args[]) {

  int x = 20;

  if (x != 10)
   System.out.println("X is not equal to 10");
  /*
   * if you don't add "{}" it will automatically add the brackets and
   * close the bracket after the first execution line
   */
 }
}



public class Apple {

 public static void main(String args[]) {

  int x = 20;

  if (x != 10)
   ;
  else
   ;
  System.out.println("x == 10");

  /* This is legal but you can't add any other line between if and else */
 }
}






Tuesday, August 20, 2013

Operators in java





Operators in java

There is a list of all operators used in java.

Operator
Description

Rank
.
Member selection
1
( )
Function

[ ]
Array element reference

-
Unary minus
2
++
Increment

--
Decrement

!
Logical negation

~
Once compliment

*
Multiplication
3
/
Division

%
Modulus

+
Addition
4
-
Subtraction

<< 
Left shift

>> 
Right shift

>>> 
Right shift with zero fill

< 
Less than
6
<=
Less than or equal to

> 
Greater than

>=
Greater than or equal to

Instance of
Type comparison

==
Equality
7
!=
Inequality

&
Bitwise AND
8
^
Bitwise XOR
9
|
Bitwise OR
10
&&
Logical AND
11
| |
Logical OR
12
? :
Conditional operator
13
=
Assignment operator
14
Op =
Shorthand assignment


You can practice these operators using below simple programs.


Arithmetic operators


public class Operators1 {

     public static void main(String[] args) {
         
          float a = 523f;
          float b = 10f;
         
          System.out.println("a = " + a );
          System.out.println("b = " + b );
          System.out.println("a + b = " + (a+b));
          System.out.println("a - b = " + (a-b));
          System.out.println("a / b = " + (a/b));
          System.out.println("a * b = " + (a*b));
          System.out.println("a % b = " + (a%b));
         
     }
}


Compound assignment operator


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

     double x= 5,y= 100;

     x+=y;     //x=x+y
     System.out.println(x);

     x-=y;     //x=x-y
     System.out.println(x);

     x*=y;     //x=x*y
     System.out.println(x);

     x/=y;     //x=x/y
     System.out.println(x);

     x%=y;     //x=x%y
     System.out.println(x);
     //in this situation the value of x is changing line by line.

}
}

Increment and decrement operators


public class Operators2 {

     public static void main(String[] args) {
         
          int a = 5;
         
          System.out.println("a = " + a );
          System.out.println("++a = " + ++a);
          System.out.println("a++ = " + a++);
          System.out.println("a = " + a );
     }
}


Relational operators


public class RelationalOperatorDemo {

 public static void main(String[] args) {

  int a = 10;
  int b = 5;

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

 }
}


Logical operators


public class LogicalOperatorDemo {

 public static void main(String[] args) {

  int a = 10;
  int b = 5;
  int c = 1;

  System.out.println("a : " + a);
  System.out.println("b : " + b);
  System.out.println("c : " + c);
  System.out.println(a > b && c > a);
  System.out.println(a > b && !(c > a));
  System.out.println(a > b || c > a);

 }
}


Conditional operator


public class Operators5 {

     public static void main(String[] args) {
         
          int a = 10;
          int b = 5;
         
          System.out.println("a : " + a );
          System.out.println("b : " + b );
          System.out.println("a > b : " + ((a>b)? true :false ));
     }
}


This operator is like if else statement. You can do this one as follows example also.


public class Operators5 {

     public static void main(String[] args) {
         
          int a = 10;
          int b = 5;
         
          System.out.println("a : " + a );
          System.out.println("b : " + b );
         
          if(a>b){
              System.out.println(true);
          }
          else{
              System.out.println(false);
          }   
     }
}

Bitwise compliment


class Apple{
    
     public static void  main(String args[]){
    
          int x = 10;
          int y = ~x;
    
          System.out.println(y);
     }
}



Try these examples to get an experience of operators.


class Apple{

     public static void main(String args[]){
         
     System.out.println( 10+20+ " Add" );
     System.out.println( "Add " + 10+20 );
     System.out.println( "Add " + (10+20) );

     }
}

/*In the second print line 10+20 is got as a string*/