Wednesday, 18 June 2014

Java Classes And Objects

In object-oriented programming technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.

Object in Java:

Object is the real world entity that has state and behavior.
e.g. laptop, bike, dog , pen, table, car etc. It can be physical or logical.

 Car is an object. Its name is Honda City, color is Blue etc. known as its state. 
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.

Introduction to Java Classes:

A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors.
A class can contain fields and methods to describe the behavior of an object.
Methods are nothing but members of a class that provide a service for an object or perform some business logic. 
Java fields and member functions names are case sensitive.
Current states of a class’s corresponding object are stored in the object’s instance variables.
Methods define the operations that can be performed in java programming.

A class has the following general syntax:

class ClassName
{
         //class body
}

Example of class

public class Rectangle
{
     int length;
     int breadth;
     int area;

     public int getArea()
     {
       area=length*breadth;
       return area;
     }
}

A class in java can contain:

data member
method
constructor
block
class and interface

How do you reference a data member/method ?
This is done by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object.

For Example:
RectangleObject.length=20;
RectangleObject.breadth=10;
RectangleObject.getArea();

Class Variables(Static Variables)
We use class variables also know as Static variables when we want to share characteristics across all objects within a class. 
When you declare a variable as static only single copy is created among all the objects.
Hence when one object changes the value of a class variable, it affects all objects of the class. 
We can access a class variable by using the name of the class.
Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.

Class Methods(Static Methods)
Class methods, similar to Class variables can be invoked without having an instance of the class.
You cannot call non-static methods from inside a static method.

Instance Variables
Each Object would have its own copy of the variable. 
When you change the value of the instance variables , it does not affects the other objects.

Top level class modifier
The modifier applicable to top level class are:
1. public
2. <default>
3. abstract
4. final

How to create Object of a class ?
By new key word we can create object of a class.New keyword occupy memory for the objects.
public class Area
{
   int length;
   int breadth;
   int area;
   public int area()
   {
      area=length*breadth;
      return area;
   }
   public static void main(String[] args)
   {
        Area a=new Area(); //object creation
        a.length=20;
        a.breadth=10;
        System.out.println("Area = " + a.area());
   }
}
OUTPUT
Area = 200



Friday, 30 May 2014

for Loop in C

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A For loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a For loop statement :

Synatax:

for(initial expression; test expression; update expression) 
{ 
body of loop; 
}

Lets take an Simple Example:
#include<stdio.h>
int main()
{
        int i;
        for(i=0;i<=5;i++)
              printf("Hello World");
         return 0;
}

Output:
it will print five times Hello World
Explanation of For Loop :

1.Firstly the for loop executes the initialize statement in which the subscript variable will be initialized
with the initial value.

2.After the initialize statement the condition part of the loop will be executed if the condition becomes true then body of the loop will be executed otherwise the loop will be terminated

3.If the loop condition becomes true then body of the loop will be executed. After the execution of the for loop body the control goes to the third part of the loop statement i.e Expression Updation

4.After updating subscript variable control again goes to execute condition statement.



for more understanding the flow of loop plz go here....


Different ways of using For loop :

In order to do certain actions multiple times , we use loop control statements. For loop can be implemented in different verities of using for loop -

1. Single Statement inside For Loop
2. Multiple Statements inside For Loop
3.  No Statement inside For Loop
4.  Semicolon at the end of For Loop
5.  Multiple Initialization Statement  inside For Loop
6.  Missing Initialization in For Loop
7.  Missing Increment /Decrement  Statement
8.  Infinite For Loop
9.  Condition with no Conditional Operator.

Way 1 : Single Statement inside For Loop

for(i=0;i<5;i++)
     printf("Hello");
1. Above code snippet will print Hello word 5 times.
2. We have single statement inside for loop body.
3. No need to wrap printf inside opening and closing curly block.
4. Curly Block is Optional.

Way 2 : Multiple Statements inside For Loop
for(i=0;i<5;i++) 
{ 
        printf("Statement 1"); 
        printf("Statement 2"); 
        printf("Statement 3"); 
        if(condition)     
        {     
              --------     
              --------     
          } 
  }
If we have block of code that is to be executed multiple times then we can use curly braces to wrap multiple statement in for loop.

Way 3 : No Statement inside For Loop
for(i=0;i<5;i++) 
{   }
1.This is bodyless for loop. It is used to increment value of “i”.
2.This verity of for loop is not used generally.
3.At the end of above for loop value of i will be 5


Way 4 : Semicolon at the end of For Loop

for(i=0;i<5;i++);
1. Generally beginners thought that , we will get compile error if we write semicolon at the end of for loop.
2. This is perfectly legal statement in C Programming.
 3. This statement is similar to bodyless for loop. (Way 3)

Way 5 : Multiple Initialization Statement inside For
for(i=0,j=0;i<5;i++) 
{ 
       statement1; 
       statement2;  
       statement3; 

}
Multiple initialization statements must be seperated by Comma in for loop.


Way 6 : Missing Increment/Decrement Statement
for(i=0;i<5;) 
{ 
        statement1; 
        statement2; 
        statement3; 
         i++; 
}
however we have to explicitly alter the value i in the loop body.

Way 7 : Missing Initialization in For Loop
i = 0;
for(;i<5;i++) 
{ 
       statement1; 
       statement2;
       statement3;
 }
we have to set value of ‘i’ before entering in the loop otherwise it will take garbage value of ‘i’.

Way 8 : Infinite For Loop
i = 0;
for(;;) 
{ 
       statement1; 
       statement2; 
       statement3; 
       if(breaking condition)    
              break; 
        i++; 
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause overflow of stack.


Understanding of For loop

#include<stdio.h>
int main()
{
        int i;
        for(i=0;i<=5;i++)
              printf("Hello World");
         return 0;
}
Lets start with step by step and what will happen when condition is true:
Seq.No        Statement Flow                Explanation
01    Flow No 1 will be executed            i = 0
02    Flow No 2 will be executed            Condition Checking
03    Flow No 3 will be executed        True Condition and print Hello World
04    Flow No 4 will be executed              -
05    Flow No 5 will be executed            i = 1
06    Flow No 3 will be executed        True Condition and print Hello World
07    Flow No 4 will be executed              -
08    Flow No 5 will be executed            i = 2
09    Flow No 3 will be executed        True Condition and print Hello World
10    Flow No 4 will be executed              -
11    Flow No 5 will be executed            i = 3
12    Flow No 3 will be executed        True Condition and print Hello World
13    Flow No 4 will be executed              -
14    Flow No 5 will be executed            i = 4
15    Flow No 3 will be executed        True Condition and print Hello World
16    Flow No 4 will be executed              -
17    Flow No 5 will be executed            i = 5
18    Flow No 3 will be executed            False Condition

Therefore it gives five times Hello World . Ok Guys i think u will understand of whole scenario.

Return Statement In Java

Return statement

The return statement is used to explicitly return from a method.That is it transfer the control to the caller of method.
And most important , return statement is always be the last statement of the current block.

Simple Program for Return statement:

package org.modi;
public class Test
{
    public static void main(String[] args)
    {
       System.out.println("Main method begin");
       if(true)
       {
          return; //it is last statement of current (if) block
       }
       System.out.println("Main method end");
    }
}
OUTPUT
Main method begin
From this program we can see that , when return statement encountered the execution of method terminated.







Continue Statement In Java

Continue Statement

The continue statement is used to continue the execution of loop.
In while and do-while loops , a continue statement transfer control to the conditional expression that controls the loop.
In for loop , first control goes to the increment/decrements portion and the goes to the expression.

Simple Program for Continue Statement

package org.modi;
public class Test
{
   public static void main(String[] args) 
   {
      for(int i=0;i<10;i++)
      {
         System.out.print( i+" " );
         if(i%2==0)
            continue;
         System.out.println("");
      }
  }
}
OUTPUT
0 1 
2 3 
4 5 
6 7 
8 9 
From program we can see that when continue statement encountered then first the control goes to the increment/decrements and then goes to expression.

Break Statement in Java

Break Statement

In java , the break statement has three uses.
1. It terminates a statements sequence in switch statement.
2. It can be used to exit a loop.
3. It can be used as a "civilized" form of goto.

And last two uses are explained here.

2. Using the break to exit loop:

By break  , you can force to terminates the loop.When a break statement is encountered inside a loop , 
the loop is terminated and program control reeches to the next statement to the loop.The break statement can be used with any of the loop.

Simple program of Break statement:

package org.modi;
public class Test
{
  public static void main(String[] args)
  {
 int i=1;
 while(i<100)
 {
  if(i==5)
  {
   break; //terminates the loop while i become 5
  }
  System.out.println("i : "+i);
  i++;
 }
 System.out.println("After while loop");
 }
}
OUTPUT
i : 1
i : 2
i : 3
i : 4
After while loop
You can see in above program the while loop designed  to iterate from 1 to 99 ,
But the break statement terminate the loop while i reach to 5
When break statement  used inside a set of nested loops , it will only break out the innermost loop.

3. Using break as a goto form:

Java does not have a goto statement,so where goto is required java defines the expanded form of the break statement.
By using this form of the break statement you can break out one or more blocks of code.
This form of the break works with a label.

The general form of the labeled break statement is :

break label;
Here,label is the name of a label that identifies the block of the code.When this form of the break executes , control transferred 
to the named block.
To name a block , put label at the start of it.A label is valid java identifier followed by a colon (:) .

Simple program of break statement in from of goto:

package org.modi;
public class Test
{
   public static void main(String[] args)
   {
       one:
       {
          two:
         {
             three:
            {
              System.out.println("Block Three begin");
              if(true)
                  break two;  //control goes out of block two
              System.out.println("Block Three End");
           }
           System.out.println("Block Two");
        }
        System.out.println("Block one");
      }
   }
 
}
OUTPUT
Block Three begin
Block one

Do-While In Java

Do-While Loop

The do-while loop always executes its body at least once,because its conditional expression is at the bottom of the loop.It repeats the statement or block of code while its controlling expression is true.It can execute the statements at least one  or more times.

Syntax of the while loop:

do
{
   //statements
}while(condition);
Each iteration of the do-while loop first execute the body of the loop and then evaluates the conditional expression.If this expression is true, then loop will repeat otherwise the loop terminates.

Flow Chart Of do-while loop:

Simple program of the while loop:

package org.modi;
public class Test
{
    public static void main(String[] args)
    {
 int i=5;
 do
 {
  System.out.println("Count " + i );
  i--;
 }while(i>0)
   }
}
OUTPUT
Count 5
Count 4
Count 3
Count 2 
Count 1


While in Java

While Loop

The while loop is Java's most fundamental loop statement.It repeats the statement or block of code while its controlling expression is true.In while loop, condition is given before the statement.  It can execute the statements 0 or more times.

Syntax of the while loop:

while(condition)
{
   //statements
}

The condition can be any boolean expression.The body of the loop will be executed as long as the conditional expression is true.
When condition becomes false , control passes to the next line of code immediately following the loop.
If loop have only one statement then , curly braces are not necessary.

Flow Chart of the while loop:

Simple program of the while loop:

public class Test { public static void main(String[] args) { int i=5; while(i>0) { System.out.println("Count " + i ); i--; } } }
OUTPUT
Count 5 Count 4 Count 3 Count 2 Count 1

Some important points about while loop:


1.Since the while loop evaluates its conditional expression at the beginning the loop , the body of the loop        will not execute if condition is false at the beginning.
public class Test
{
 public static void main(String[] args)
 {
  int i=5 , j=10;
  while(i>j)
  {
   System.out.println("While loop body");
  }
  System.out.println("Out of While loop");
 }
}
OUTPUT
Out of While loop
2. The body of the while loop can be empty.This is because a null statement is syntactically valid in java.

public class Test
{
 public static void main(String[] args)
 {
  int i=5 , j=10;
  while(++i<--j)
  System.out.println(i);
 }
}
OUTPUT
8
3.If condition will always true then it will become infinite loop.
while(true) //infinite loop


Thursday, 29 May 2014

Break And Continue in C

Break:
The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. When the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop. The break statement can be used with all three of C's loops for, while and do...while loops.
Syntax:
break;

The figure below explains the working of break statement in all three type of loops.


Here's an example of a use for the break statement:
#include
int main()
{
 int t ;
 for ( ; ; ) 
 {
  scanf("Enter any no.\n%d" , &t) ;
  if ( t==10 ) 
                break ;
 }
 printf("End of an infinite loop...\n");
 return 0;
 }
Output:
Enter any no.
2
3
10
End of an infinite loop...
In above example, it takes no. until user enter 10 because t=10 then it will break.

Continue:
The continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process. In the case of the for loop, the increment part of the loop continues. One good use of continue is to restart a statement sequence when an error occurs.

Syntax:
continue; 

Here's an example of a use for the break statement:

#include
int main()
{
 int x ;
 for ( x=0 ; x<=100 ; x++) 
 {
  if (x%2) continue;
  printf("%d\n" , x);
 }
}

Goto Statement in C

10:53 Posted by Hindustan News , , No comments
In C programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
.............
label: 
statement;
}
 When, the control of program reaches to goto statement, the control of the program will jump to the label: and executes the code below it.


#include
#include
void main(){
    int a;
    goto label;
    a = 10;
    printf(“%d”, a);
    label:
    a = 20;
    printf(“%d”, a);
}
Output:
20

When goto label in C is encountered, control goes to the statement next to the label. Here, label is not the keyword. We can use any name for the label. It’s user defined.
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced as much as possible in a program.

Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto statement makes the logic of the program complex and tangled. In modern programming, goto statement is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue statements. In fact, any program in C programming can be perfectly written without the use of goto statement. All programmer should try to avoid goto statement as possible as they can.