Thursday, 19 November 2009

Command line arguments

It is a way of passing to program some information

through command line

example

class test

{

public static void main ( String args [ ] )
{
       //  for loop to access all command line arguments
for (int i = 0 ; i < args.length ; i ++)
{
System.out.println ("Argument " + (i +1) + " : " + args [i]) ;
} // for loop ends
} // main function ends

} // class ends

Run this class as following

java test one two three

  • Whatever comes after the name of class (seperated by space) , goes into the parameter args which is a String array
  • for loop runs as long as there are elements in the array args which depends on how many we pass

Output:  Argument 1 : one

              Argument 2 : two
              Argument 3 : three

args [ 0 ] holds one
args [ 1 ] holds two
args [ 2 ] holds three

Wednesday, 18 November 2009

Use of final

final


final can be used in multiple places

final variable

final method

final class


final variable

  • Value of a variable whose declaration is preceded by keyword final , cannot be changed during program execution
  • If any part of code tries doing that , it results in error
  • They must be given some value at the time of decaration, compiler does not give them default value as it does for non final variables
example

                          final int number = 5 ;

final method

  • When we want that a method should not be overridden by a subclass , precede it's declaration with final
  • If a subclass tries to override a method declared as final , it results in error
example

final void sample ()

{
// code
}

final class

  • When we want that a class should not be extended by a subclass , precede it's declaration with final
  • If a subclass tries to extend a class declared as final , it results in error
example

final class test

{
// methods and properties
}

Use of static

static can be used in multiple places


static block

static methods

static variables


static block

  • static blocks are run first when a class executes.
  • If a class contains main method , they will be executed before call to main method
  • There can be any number in a class , run in the order of appearance in source file
  • Can access only static methods and static variables
General form

static
{
// code to execute
}

example

class test
{

public static void main ( String args [ ] )
{
System.out.println ("In main") ;
} // main function ends

// static block
static
{
System.out.println ("In static") ;
}
} // class ends

Output : In static
              In main

static methods

There may be some processing which is not linked to any one object ,
but is general or applies to all objects in a common manner

  • Their declaration is preceded by keyword static
  • They can access only static methods and static variables
  • They can be accessed by class name also
                              classname.methodName 

example

static double getPi ()
{
double value = 3.1415 ;
return value ;
}

Regardless of object , value of PI remains same so we declare a function returning
value of PI as static

static variables

  • There may be property of a class which is not linked to any one object ,
          it is a class property . Such properties are declared static.

  • Their declaration is preceded by keyword static
  • They can be accessed by class name also
                                 classname.propertyName ;

  • Some practical examples are serial number , colour codes
  • There is only one copy of static variables and all objects share it
exmple

class test
{
static int serial = 0 ;

public static void main ( String args [ ] )
{

test t1 = new test () ;
test t2 = new test () ;
test t3 = new test () ;

System.out.println (t1.increment()) ; // 1
System.out.println (t2.increment()) ; // 2
System.out.println (t3.increment()) ; // 3

} // main function ends

static int increment ()
{
serial ++ ;
return serial ;
}    // function ends

} // class ends

Output:  1
             2
             3

As there is single copy of serial , we get incremental output

Difference from non static

Check what's the output when serial is instance variable and increment is non
static method

Access Control

It is a mechanism for managing visibility of

  • class members (properties , methods , constructors)
  • classes defined in a package

Visibility simply means access.It can be set to different levels
by using these keywords

When applied to class members

public :

They are accessible everywhere

private :

Can be accessed only by the code in defining class

protected :

  • Within the package : accessible everywhere
  • Outside the package , only subclasses can access

default : When nothing is specified

Accessible only within the package

When applied to class

public :

Visible inside as well as outside the package in which it is defined

default : When nothing is specified

Visible only inside the package in which it is defined

Monday, 16 November 2009

Use of this Keyword

this has muliple uses
First use
It refers to the current object
example
class test
{
private int number = 20 ;
void show ( int number )
{
System.out.println ("Local variable " + number ) ; // prints 10
System.out.println ("Object property " + this.number ) ; // prints 20
} // function ends
public static void main ( String args [ ] )
{
test one = new test ( ) ;
one.show (10) ;
} // main function ends
} // class ends

  • In the function show , when we use number it refers to the local variable,
    hiding object property number
  • If we want to access the object property number , we have to use this

    Second use
    It can be used to call an overloaded constructor
    example
    class Student
    {
    String name ;
    int age ;
    Student ( )
    {
    }
    Student ( String input1 )
    {
    name = input1 ;
    }
    Student ( String input1 , int input2 )
    {
    this ( input1 ) ; // call second constructor to initialize name of student
    age = input2 ;
    }
    public static void main ( String args [ ] )
    {
    Student one = new Student ( "Harry" , 20 ) ;
    System.out.println ("Name : " + one.name + " , age : " + one.age ) ;
    } // main function ends
    } // class ends
    Output: Name : Harry , age : 20
    Third constructor calls the second one using this and passes the input1 value which is set to name inside second constructor
    Advantage is that each constructor does not need to initialize all
    the properties itself. It calls the appropriate overloaded form by
    passing the needed values.

Constructors

We have seen earlier that constructor is used to create a new object
Student one = new Student ( ) ;
new gives a call to the constructor of class
But , we did not define any constructor so how was one found ?
Java compiler automatically adds an empty , no argument constructor
if none is provided by the programmer.

It's access level is same as that of the defining class

Defining constructors
Their declaration is similar to that of methods
General form
access level name ( parameter list )
{
// body of constructor
}
access level : public , protected , private
If none is specified , default access is used
name : It must be same as class name
parameter list : It is the list of type-identifier pairs seperated by , . These identifiers receive the value of arguments passed in a constructor call
body : here you can initialize the object or call other constructors

Diferences from methods

  • Methods can have any valid identifier as name but constructor name must be same as class name
  • Methods must specify return type whereas constructors only return the class type which is not specified.
  • No return statement is required , constructors themselves return class type
Like methods , they can also be parameterized and overloaded

example ( parametrized constructor)
Working on the earlier used Student example
Student one = new Student ( ) ;
This calls the no argument constructor provided by Java compiler
We can define our own constructors also
Student ( String input1 , int input2 )
{
name = input1 ;
age = input2 ;
}
This constructor defines two parameters
Student one = new Student ( "Harry" , 20) ;
As can be seen , object properties get initialized inside the constructor

Advantage of this approach is that for each Student object we create ,
we don't have to write these two statements
one.name = "studentname" ;
one.age = 25 ; // or any valid value

for each object we create .

It's better to write it once inside the constructor , and reuse it for all the objects created by passing the values for name and age .

example (constructor overloading)

  • Just as methods can be overloaded , same way constructors can be
    overloaded by changing the signature of different constructors
  • Appropriate constructor gets called by matching the arguments
    passed and the parameters of constructor.

    Student ( ) // no parameter
    {
    }
    Student ( String input1 ) // one parameter
    {
    name = input1 ;
    }
    Student ( String input1 , int input2 ) // two parameters
    {
    name = input1 ;
    age = input2 ;
    }
    new Student ( ) ; // calls the first constructor
    new Student ( "Harry" , 20) ; // calls the third constructor

    Why overloading is required ?
    Sometimes , we don't have values for all properties of an Object at the
    time we are creating that object
    Say , we have a student whose age is not known initially
    Student one = new Student ( "Mike" ) ; // calls the second constructor
    This student has name Mike but no age
    When age is known , we can set age
    one.age = 25 ;
    This brings flexibility in initializing objects

More on Methods

As we discussed earlier , methods contain code to do some process or task
General form of a method is :
return type name (parameter-list)
{
// code to do some process ( body of method)
}
return type : A method can return some value like a number or String or any valid data type including class types
name : name is any valid identifier
parameter-list : it is the list of type-identifier pairs seperated by , . These identifiers receive the value of arguments passed in a method call

  • In Java , every method must have a return type and it must return a value compatible with it's return type
  • If a method does not return a value , it's return type must be void

    example 1
    int getNumber ()
    {
    int number = 10 ;
    return number ;
    }
    example 2
    String getNumber ()
    {
    int number = 10 ;
    return number ;
    }
    method in example 2 would cause compile time error , as returned value and return type are not compatible
    example 3
    void call (int input1 , int input2)
    {
    // code
    }
    call (5 , 10) ; // ok input1 will get value 5 and input2 will get value 10
    call (5) ; // error as passed values (arguments) do not match the number of parameters
    call (5 , "abc") ; // error as second argument is String
  • Number , type and sequence of passed values must match that in the parameter list
  • Passed value can be a variable like x,y or it can be a literal value like 5, 10 , "abc"

    Method overloading

    In a class , you can not have two methods with same name and signature
    link: Method Signature It consists of name of method and it's parameter list
    example
    void method1 (int a , int b)
    {
    // code
    }
    You cannot have another method with same name and same parameter list in same class
    But you can have same method name but different signature. This is called method overloading

Signature can be changed by changing

  • the number of parameters
  • same number but changing the types
    Lets see how overloading works and how it helps
    void method1 (int a , int b) // two int parameters
    void method1 (int a , float b) // two parameters: one int and another float
    void method1 (int a , int b , String c) // different number of parameters
    void method1 (int c , int d) // invalid : signature same as first one


First three forms are overloaded as they have different signatures
Fourth form is invalid , because for method call
method1 (5,10) ;
It is not possible to determine which
version to call , first or fourth

  • When a method call is there , Java looks for a match between the signature in method call
    and the method definition.
  • It must match to one method whose signature matches the method call exactly

    Advantage of Overloading
    It allows us to have multiple methods having similar processing with the same name ,
    which can be easier to handle then having method names like method1 , method2 ,
    method3 , method4 , method5 and so on

    Argument passing
    We now know , that we can pass variables or literals in a method call
    which are recieved by the corresponding parameters in method
    definition
    There are two ways of argument passing
    By value
    : for primitive data types like int , float , boolean
    By reference : for objects

example ( By value )
void one ( int a , int b)
{
a = a + 5 ;
b = b + 5 ;
System.out.println ( "Function one " ) ;
System.out.println ( "a = " + a + " b = " + b ) ;
}
void two ( )
{
int a = 5 ;
int b = 10 ;
one ( a , b) ;
System.out.println ( "Function two " ) ;
System.out.println ( "a = " + a + " b = " + b ) ;
}
Output :
Function one
a = 10 b = 15
Function two
a = 5 b = 10

  • The value of a and b in function two does not get changed.
  • Reason being value of these variables was copied into
    parameters of function one.
  • There is no relation after this between passed arguments
    and in the recieving parameters

    example ( By reference )
    Using the Student class defined earlier
    void one ( Student input)
    {
    input.name = "James" ;
    input.age = 30 ;
    System.out.println ( "Function one " ) ;
    System.out.println ("Name : " + input.name + " , age " + input.age ) ;
    }
    void two ( )
    {
    Student newStudent = new Student () ;
    newStudent.name = "Harry" ;
    newStudent.age = 20 ;
    one ( newStudent ) ; // pass this object as argument
    System.out.println ( "Function two " ) ;
    System.out.println ("Name : " + newStudent.name + " , age " + newStudent.age ) ;
    }
    Output:
    Function one
    Name : James , age 30
    Function two
    Name : James , age 30
  • Memory address stored in newStudent is copied into parameter input
  • Any changes we make on input object , they will reflect on newStudent object
  • Object is same , only it is being referred by two different variables

    To summarize
  • Primitive types ( byte , int etc.) are passed by value and Objects are passed by reference
  • In by value , value of argument is copied into the parameter. Any changes to the receiving
    parameter won't affect the original value
  • In by reference , memory address of of argument is copied into the parameter. Any changes to the receiving parameter would affect the original value as it refers to the same Object (same memory location)

Sunday, 15 November 2009

Classes & Objects

  • Class is the basis for object oriented programming in Java.
  • A class defines a structure , a template which the objects
    of that type have.
  • It defines a new data type.
  • Object is an instance of a class. It follows the template
  • Object is concrete and it occupies memory
    Any Java code must be contained within a class
    Lets take a simple example to understand the idea
    of class and object
    example

class Student
{
private String name ;
private int age ;
}

  • This class defines structure for a student.
  • Any object of Student type will have two
    properties : name and age
  • Though each Student object will follow the
    same template as defined by class Student,
    each will have it's own data for name and age.


Let us declare some Student objects
Student one = new Student () ;

// assign values to student properties
one.name = "Harry" ;

one.age = 20 ;
Student two = new Student () ;
two.name = "Tom" ;
two.age = 25 ;
name,age are the attributes of Student which define it

Class usually also has associated methods

class Student
{
private String name ;
private int age ;
public String getName ()
{
return name ;
}
public void setName (String input)
{
name = input ;
}
}

Student one = new Student () ;
one.setName ("Harry") ;
Instead of directly assigning a value as above,
we called a function.
Same way, to access the attribute value, we call getName function
System.out.println ( one.getName () ) ; // prints Harry


The above concept can be extended to more complex classes
having number of attributes and functions.
General structure of a class is
class classname
{
type property1 ;
type property2 ;
type method1 (list of parameters)
{
// processing code
}
type method2 (list of parameters)
{
// processing code
}
}
N number of properties and methods can be there
properties: They define the data of object and are also known as instance variables. Each object has it's own data

methods: They contain code to do processing.Each object can access
these methods to initiate some action or do a process
setName method was called to assign name to student
getName method was called to get the name of student

methods can be used for handling basic tasks like above
to complex processes.They can interact with each other
to accomplish a task together
Declaring objects
In the above example, we declared Student object
Student one = new Student () ;

  • Student is the name of class
  • one is a variable of type Student (remember every class defines a new data type)
  • new is an operator which dynamically allocates memory by calling
    the constructor for class
    new Student () ;
    Three things happen
  • Constructor of Student class is called,
  • memory is allocated to newly
    defined object
  • memory address is returned which is assigned
    to variable one

Once an object is created and it's reference stored, we can access it's
properties and invoke class methods on this reference


one.name ; // returns name of student
one.age ; // returns age of student
one.setName () ; // calls method setName

Obtaining a new object of class can be divided in two steps
Step 1

Student one ;
It declares a variable of type Student. one does not refer
to an actual object at this point.
System.out.println (one) ; // prints null
When a variable of Object type does not point to an actual object,
it holds null.
Step 2
one = new Student ( ) ;
Now, object is actually created and it's reference (or memory address)
is assigned to variable one
General form of creating objects

classtype1 var-name = new classtype2 () ;

  • classtype1 : It is the type of the holding variable
  • var-name : name of variable which will hold reference to object
  • classtype2 : type of object being created
  • In the above example classtype1 and classtype2 are both same (Student).
    They can be different when classes are part of hierarchy.

    How object reference variables work
    It's easy to understand but very important concept.

Taking again the Student class example
Student one = new Student () ;
one.name = "Harry" ;
one.age = 20 ;
Student two = new Student () ;
two.name = "Tom" ;
two.age = 25 ;

System.out.println (one.name) ; // prints Harry
System.out.println (two.name) ; // prints Tom
two = one ; // assign address of one to two
System.out.println (one.name) ; // prints Harry
System.out.println (two.name) ; // prints Harry
Now two also refers to object referred by one
one = null ; // assign null explicitly
System.out.println (one.name) ; // will cause exception, as one does not refer to any object
System.out.println (two.name) ; // prints Harry

  • one does not refer to any object now but two continues
    to refer to an object
  • It's important to see which variable is referring to which
    object at any time

Jump Statements

As the name suggests , these are used to transfer control during program execution

Different Jump statements
1 break
2 continue
3 return

Lets look at each starting with break

break has 3 different uses

a To exit a switch block
As we have seen earlier, switch case block has different cases.
If we want that after execution of a particular case , following
cases should be skipped, use break before the closing brace

example
int i = 1 ;
switch (i)
{
case 1 : { System.out.println ("case 1") ; break ; }
case 2 : { System.out.println ("case 2") ; }
case 3 : { System.out.println ("case 3") ; }
}

Here, output would be case 1.
Because of use of break in case 1 , following two cases are skipped
and control comes out of switch block.

b To exit a loop
We have discussed different loops: for , while , do while
break can be used to exit any of these loops depending on
a condition or as such

int numbers [ ] = { 1,3,9,5,4,7,15} ;
for (int i = 0 ; i < numbers.length ; i ++)
{
if (numbers [i] % 2 == 0)
{
System.out.println ("Even number found .. exiting ") ;
break ; // skip rest of iterations
}
System.out.println ( numbers [i] ) ;
}
  • for loop moves through the array and checks if a number at any index is even (divisibility check) .
  • When the expression evaluates to true loop is exited using the break statement.
Similarly, it can be used with while and do while loops
c exiting a loop marked by a label
label can be any descriptive text other than language reserved keywords

outer : for ( int i = 0 ; i < 5 ; i ++)
{
inner : for ( int j = 0 ; j < 10 ; j ++)
{
// break ;
break outer ;
} // inner loop ends
} // outer loop ends

  • By default break exits from the innermost enclosing loop, in this case loop labelled inner.
  • But, if we want to exit outer loop (any block other then the enclosing), what we should do ? We can mark that block with a label and then use that label along with break.
break outer ;
Here, outer loop labelled outer is exited instead of the inner one and control comes to line following the end of this loop.
Remember : This form can be used to exit any block (not just loops) which encloses the break statement.
2 using continue
Sometimes, we need to just skip the current iteration of a loop instead of all the remaining as in break.
example
int numbers [ ] = { 1,3,9,5,4,7,15} ;
for (int i = 0 ; i < numbers.length ; i ++)
{
if (numbers [i] % 2 == 0)
{
System.out.println ("Even number found") ;
continue ; // skip current iteration
} // if block ends
System.out.println ( numbers [i] ) ;
} // for loop ends

Here, when an even number is found
continue ;
causes rest of the code (outside the if block) to be skipped, though for loop will continue to execute .
Same way it can be used with while and do while loops
3 returning from a function
  • function is a piece of reusable code
  • Sometimes whole of the code in a function need not be executed.
  • To get back from a function early, we use
return ;

example
public void choice ( int number)
{
if (number > 10)

{
return ; // skip rest of the code
} // if block ends
// do something if number is less then or equal to 10
} // function ends

If a condition is not satisfied , all the code need not be executed
which would avoid unnecessary processing and errors.

Wednesday, 4 November 2009

Jump Statements: break,continue,return

As the name suggests , these are used to transfer control during program execution

Different Jump statements
1 break
2 continue
3 return

Lets look at each starting with break

break has 3 different uses
a To exit a switch block

As we have seen earlier, switch case block has different cases.
If we want that after execution of a particular case , following
cases should be skipped, use break before the closing brace

example
int i = 1 ;
switch (i)
{
case 1 : { System.out.println ("case 1") ; break ; }
case 2 : { System.out.println ("case 2") ; }
case 3 : { System.out.println ("case 3") ; }
}
Here, output would be case 1
Because of use of break in case 1 , following two cases are skipped
and control comes out of switch block.
b To exit a loop
We have discussed different loops: for , while , do while
break can be used to exit any of these loops depending on
a condition or as such

example
int numbers [ ] = { 1,3,9,5,4,7,15} ;
for (int i = 0 ; i <>

{

if (numbers [i] % 2 == 0)

{

System.out.println ("Even number found .. exiting ") ;

break ; // skip rest of iterations

}

System.out.println ( numbers [i] ) ;

}

  • for loop moves through the array and checks if a number at any index is even (divisibility check) .
  • When the expression evaluates to true loop is exited using the break statement.

Similarly, it can be used with while and do while loops

c exiting a loop marked by a label

label can be any descriptive text other than language reserved keywords

example

outer : for ( int i = 0 ; i <>

{ inner : for ( int j = 0 ; j <>

{

// break ;

break outer ;

} // inner loop ends

} // outer loop ends

  • By default break exits from the innermost enclosing loop, in this case loop labelled inner. But, if we want to exit outer loop (any block other then the enclosing), what we should do ?
  • We can mark that block with a label and then use that label along with break.

break outer ; // exits outer loop

Here, outer loop labelled outer is exited instead of the inner one and control comes to line following the end of this loop.

Remember : This form can be used to exit any block (not just loops) which encloses the break statement.

2 using continue

Sometimes, we need to just skip the current iteration of a loop instead of all the remaining as in break.

example

int numbers [ ] = { 1,3,9,5,4,7,15} ;

for (int i = 0 ; i <>

{

if (numbers [i] % 2 == 0)

{

System.out.println ("Even number found") ;

continue ; // skip current iteration

}

System.out.println ( numbers [i] ) ;

}

Here, when an even number is found

continue ; // current iteration is skipped

  • It causes rest of the code (outside the if block) to be skipped .
  • for loop will continue to execute .
  • Same way it can be used with while and do while loops

3 returning from a function

  • function is a piece of reusable code
  • Sometimes whole of the code in a function need not be executed. To get back from a function early, we use

return ;

example

public void choice ( int number)

{

if (number > 10)
{
return ; // skip rest of the code
}
// do something if number is less then or equal to 10
}
If a condition is not satisfied , all the code need not be executed
which would avoid unnecessary processing and errors.

Sunday, 9 August 2009

Control Statements 2

Iteration statements
There are three iteration statements
1 while
2 do-while
3 for

All three create loops. Hence, they can be used where
some task is to be repeated number of times

Let us discuss all of them one by one

While

It continues execution until the expression on which it
depends evaluates to true. As soon as, value of
expression changes to false, loop will be terminated.

General syntax of while

while (someexpression)

{
// statements
}

Here, someexpression must evaluate to boolean value

As long as it is true statements inside block continue to get executed. When it changes to false, loop terminates and control passes to next line of code following the while block closing brace

do-while
It is similar in function to while block but with one important difference

General syntax of do-while

do

{
// statements
} while (someexpression)

The difference as you might have noticed is that when
the controlling expression is evaluated.

In while, it is evaluated before execution begins. Hence,
loop might not execute even once.

In do-while check is performed at the end.Hence, it is
guranteed that the loop would execute atleast once.

Examples

int i = 5 ;

while ( i < 5 )
{
System.out.println ( "Never printed" ) ;
}
Here, i < 5 results in false hence loop is not entered

do { System.out.println ( "Printed once" ) ; }
while ( i < 5 )
Here, loop is executed once as the expression i < 5 is checked after the loop body executes once.

To summarize, whenever you have a situation where loop body needs to be executed at least once, use do-while otherwise use while

for loop

It is a very powerful and flexible control block It has number of variations

General syntax of for

for ( initialization expression ; control expression ; update expression )

{
// statements to be executed
}

initialization expression : variables can be declared and initialized here
i = 5 // single variable
i = 5 , j = 6 // two variables seperated by comma
control expression : It must evaluate to a boolean. It's value determines whether the loop will execute and till when it will execute
update expression : variables forming the control expression can be updated here

Each of the above part is optional

Let us go through some examples to see the different variations
example 1

Standard form

for ( int i = 0 ; i < 5 ; i ++)
{
System.out.println ( "Value of i is : " + i ) ;
}

Steps in execution
a variable i is declared and initialized
b value of i is checked in control expression i < 5 . As it evaluates to true , loop body is executed printing Value of i is 0
c update expression is evaluated changing the value of i to 1
d Step b and c are repeated till update expression evaluates to false e when i = 5 , loop gets terminated

example 2

Initialization expression moved outside the loop

int i = 0 ;
for ( ; i < 5 ; i ++)
{
System.out.println ( "Value of i is : " + i ) ;
}
example 3

  • Initialization expression moved outside the loop
  • control expression moved inside the loop body

int i = 0 ;

for ( ; ; i ++)

{

  • if ( i >= 5 )
    {
    break ;
    } // if block ends

    System.out.println ( "Value of i is : " + i ) ;

    } // for loop ends


    Here, the loop control logic is made with the help of if block and break statement.
    As soon as value of i reaches 5 , if block is entered and break causes the loop
    to terminate

    example 4
  • Initialization expression moved outside the loop
  • control expression moved inside the loop body
  • update expression moved inside the loop body

    int i = 0 ;

    for ( ; ; )

    {

    if ( i >= 5 )

    {
    break ;
    } // if block ends
    System.out.println ( "Value of i is : " + i ) ;
    i ++ ;
    } // for loop ends

As you can see, you have the option to keep as many expressions
inside the loop () and as many outside it.

Output is same in all the cases, only implementation way has changed

Using comma operator in for loop

Sometimes for loop depends on more then one variable. We can
initialize and update multiple variables seperated by comma as shown

int i , j ;

for ( i = 3 , j = 5 ; i < 10 ; i ++ , j ++)

{
// loop body
}

Note: Control expression must be a single expression

Nested loops

Java allows you to nest one loop inside the other. You will occassionaly
need nested loops to do some tasks

Following example shows the use of nested for loop's

// Print tables from 1 to 10 upto multiple of 10

for (int i = 1 ; i < 11 ; i ++)

{
System.out.println ("Table of " + i + "\n") ;
for (int j = 1 ; j < 11 ; j ++ )
{
System.out.println (i + " x " + j + " = " + (i*j) ) ;
} // inner for loop ends
System.out.println ("\n \n") ;
System.out.println ("------------------------------------------") ;
System.out.println ("\n \n") ;

} // outer for loop ends

For each iteration of the outer loop, inner loop executes 10 times.
After it's termination, statements following it are executed and then
the outer loop executes again till the control condition is true

Any of the loop can be nested inside another

Control Statements 1

One of the benefit of programs is that they are flexible.That means,
there will be different outcomes in different situations.
This is achieved with the help of control statements which
alter the flow of program depending on the result of a
expression or state of variable

Lets go through them one by one

Selection statements

if block

General syntax is

if (expression)

{
// statements
}
expression must evaluate to a boolean value (true or false)
It's simple: if outcome is true, statements inside block are
executed otherwise they are skipped.

if else

General syntax is

if (expression)
{
// statements 1
}
else
{
// statements 2
}

Here, if expression evaluates to true if block
is entered and statements 1 are executed.
Otherwise else block is entered and
statements 2 get executed.

You can nest an if block inside another if block

if (cond1) // outer if

{
// processing code

if (cond2) // inner if

{
// processing code
}

}

You can extend the concept of if else to if else if else if .... ladder

if (cond1)
{
}
else if (cond2)
{
}
else if (cond3)
{
}
else
{
}

Expression can use relational operators (> , < ), equality operators (== , !=),
boolean operators (or,and,!) or have a call to function.
Only thing is that output should be boolean

Switch block

When the number of conditions is large, Switch block comes in handy

General syntax is

switch (expression)

{

case 1 :
case 2:
.
.
.
case n :
default :
}
Here expression should evaluate to byte , short , int or char type
Depending on the value of expression, matching case would be executed
If there is no exact match, code in the default block (optional) would be executed

Lets work out a simple example

int weekDay = 3 ;

switch (weekDay )
{
case 1 : { System.out.prinln ("It's Monday") ; break ; }
case 2 : { System.out.prinln ("It's Tuesday") ; break ; }
case 3 : { System.out.prinln ("It's Wednesday") ; break ; }
case 4 : { System.out.prinln ("It's Thursday") ; break ; }
case 5 : { System.out.prinln ("It's Friday") ; break ; }
case 6 : { System.out.prinln ("It's Saturday") ; break ; }
case 7 : { System.out.prinln ("It's Sunday") ; break ; }
default : {System.out.prinln ("Check input") ;} ;
}
When switch block is entered, it checks the value of weekDay which is 3.
It searches for a case with this value and executes it.
If weekDay had value say 10, there would'nt be any matching case so default would
have got executed.
It is always good to enclose the statements under each case and default in curly { }
break is used to exit switch block after a case gets executed.If you omit it, all the following
cases would get executed
Like if block you can have nested switch also

int outer = 1;
int inner = 2 ;
switch (outer)

{
case 1 :
{
switch (inner)
{
case 1 : { // do something }
case 2 : { // do something }

} // inner switch ends

} // case 1 of outer switch ends

case 2

} // outer switch ends

In the outer switch block, value of outer variable is matched with the
cases. Inside case 1 , inner switch block is entered where value of
inner is matched with the cases and case 2 gets executed.

Difference between if - else - if and switch

1 Switch is usually more performance oriented as compared to if else if ladder
2 Switch looks for exact match, whereas in if block we can have any kind of expression
which evaluates to a boolean

Friday, 10 July 2009

Operator precedence

Operator precedence

postfix
expr++ expr--
unary
++expr --expr +expr -expr ~ !
multiplicative
* / %
additive
+ -
shift
<< >> >>>
relational
< > <= >= instanceof
equality
== !=
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR

logical AND
&&
logical OR
ternary
? :
assignment
= += -= *= /= %= &= ^= = <<= >>= >>>=

To avoid confusion, it is recommended to use parenthesis ()
in expressions to avoid unexpected results

Boolean Logical Operators

Boolean Logical Operators
These operators operate on boolean operands and result
is also boolean. Like relational and equality, they are also
used frequently in if blocks and different loop for decision
making.
Operator Description
& Logical AND : evaluates to true if both operands evaluate to true
Logical OR : evaluates to true if both operands evaluate to true
^ Logical XOR : evaluates to true if odd no of operands are true
Short circuit OR
&& Short circuit AND
! Unary NOT
?: Ternary

Difference between & and &&

& : It evaluates both the operands
&& : It won't evaluate the second operand if the first operand evaluates to false
Example
Case 1
boolean flag = false ;
int count = 5 ;
if (flag & count ++ < 6)
{
// something
}
System.out.println (i) ; // count is 6 here

Case 2
boolean flag = false ;
int count = 5 ;
if (flag && count ++ < 6)
{
// something
}
System.out.println (i) ; // count is 5 here
In the second case, short circuit AND is used.When flag
evaluates to false, it does not go to the second part of
expression. Hence count ++ is not executed
Difference between and
: It evaluates both the operands
: It won't evaluate the second operand if the first operand evaluates to true
You can work it out on the lines of above example

Unary NOT
  • It simply returns toggled value of it's operand.
  • Operand remains unaffected.
    boolean flag = false ;
    if (! flag)
    {
    System.out.println ("flag still false " + flag) ;
    }
    Here, if block would be executed as NOT operator returns true but
    flag still holds false

    Ternary operator
    General syntax is
    exp ? statement 1 : statement 2
    exp: expression evaluating to a boolean
    If exp evaluates to true statement 1 is executed
    otherwise statement 2
    It can be thought of of as a shorthand for if else block

Relational Operators

Relational Operators
  • These operators are used to compare two values for equality or comparison.
  • Result of each comparision is boolean (true or false)


Operator Description
== Equal to Returns true if compared values are equal
!= Not Equal to Returns true if compared values are not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

boolean flag = 10 > 5 ; // flag set to true

  • These are mostly used with if block , different kind of loops (for,while,do while)
    to alter the program flow based on boolean output
    int num1 = 10 ;
    int num2 = 20 ;
    if (num1 == num2)
    {
    // do something
    }
    Remember, == operator is for equality check whereas = operator is assignment operator
  • Only Numeric types (int,float) and character type can be compared with relational operators
  • == and != can be used for any type

Use of == operator with String type and Objects
When you compare primitive types (int,float) using ==
you will get desired result but with Strings and other
Objects, you will get surprising results.

Case 1
String str1 = new String ("abc") ;
String str2 = new String ("abc") ;
if (str1 == str2)
{

// statement1
}
else
{
// statement2
}
Which statement would get executed ?
Apparently statement1 but actually statement2 would get executed
== compares the memory address for Objects (Strings are objects in Java)
As str1 and str2 have different memory addresses, comparison evaluates to
false and else block is executed.
Case 2
String str1 = "abc" ;
String str2 = "abc" ;
if (str1 == str2)
{

// statement1
}
else
{
// statement2
}
Now which statement would be executed ?
This time statement1
When Strings are initialized as literals , same value Strings
will have only one copy.Hence str1 and str2 point to same
location in memory

Operators

Java language provides number of operators. Many of these are similar to as in
other languages. All operators can be grouped into 4 categories
1 Arithmetic
2 Bitwise
3 Relational
4 Boolean Logical

Arithmetic operators
  • addition +
  • subtraction -
  • division /
  • Multiplication *
  • Modulus %
Modulus returns the remainder of division
10 % 3 will return 1
Each of the above has shorthand notation also
a = a + b ;
a += b ;
Both are equivalent

Increment and decrement operators

++ Single unit increment operator
-- Single unit decrement operator
Above two have two flavours : Post fix and Pre fix
Lets see what's the diference between two by working on a simple example
int a = 5 ;
int b ;
Post fix
b = a ++ ; // b will be set to 5
System.out.println ("b = " + b + " a = " + a ) // b will be 5 and a will be 6
Here, the value of a is used first (assigned to b) and then it is incremented
Pre fix
b = ++a ; // b will be set to 6
System.out.println ("b = " + b + " a = " + a ) // b will be 6 and a will be 6
Here the value of a is first incremented and then used (assigned to b)
In both cases, a will finally be 6 but value of b is different in both cases.
Decrement ( -- ) operators work in the same way, they decrease the value by 1

Thursday, 9 July 2009

Arrays

  • Arrays are a collection of like typed variables referenced by a common name.
  • Each element in an Array is referenced by a index.
  • Index starts from 0 , that is first element is stored at index 0
  • Arrays can be multi dimensional
Declaration
It is declared like other data types but with [] .
int arr1 [] ; // single dimension array
int arr2 [][] // two dimension array
int arr3 [][][] // three dimension array
Here int (could be any valid data type) specifies that this array can hold int values
Initialization
There are different ways to initialize an array
Using new operator
float arr1 [] = new float [5] ;
new operator dynamically allocates memory at runtime
Here 5 is the size of array, number of elements it can hold
Now each element can be accessed by it's index and assigned a value
Note: Compiler provides default value (depending on data type) to each
element.
arr1 [0] = 10 ;
arr1 [3] = 20 ;
and so on
Don't go beyond index 4, because that is the last index.
It will result in ArrayIndexOutOfBoundsException

Curley braces style
float arr1 [] = {5.0 , 3 , 4 } ;
Values are given as comma seperated list enclosed in { }
here, size need not be specified as it is same as the number of
values given in the list

Multi dimensional arrays
Two Dimensional
You can think of it as a row column matrix
double twoDim [] [] = new double [dim1] [dim2] ;
dim1 : rows in the matrix
dim2 : columns in the matrix
int a [] [] = new int [3] [3]
a00 a01 a02
a10 a11 a12
a20 a21 a22
Remember, both the indexes start at 0
int a [] [] same as int [] a [] same as int [] [] a

Tuesday, 26 May 2009

Variables

Here we would be talking about variables

Every programming language has variables. A variable can be defined

as a named storage location whose value can change during the

execution of program .

General declaration syntax is :

data type variable name = [initialization value]

eg int number ; // declaration without initialization

int number = 10 ; // declaration with initialization

  • Initialization is optional
  • Once declared other parts of program (code) can refer to it by it's name

Scope and Lifetime of a variable

Scope means which part of program can access a previously defined variable.

Normally, scope is defined by curly braces. We will explain scope rules with the help

of following examples.

Consider a for loop and a function

for ( int count = 0 ; count <>{

int i = 5 ;

System.out.println ("Value of i is : " + i ) ; // prints on console

}

void other ( )

{

System.out.println ("Value of i is : " + i ) ; // results in compile time error

}

As variable i is defined inside the for loop, enclosed in the braces it can be used

only there.Trying to use it anywhere else would result in compile time error

Variables declared inside ( ) can also be accessed within the following braces.

In the for loop above, variable count has been declared inside the ( ) and can be

accessed only inside the for loop .

Nested scopes



It is possible to embed another block defined by { } inside another block

Lets look at an example on how scope rule works when there are nested scopes

for ( int i = 0 ; i <>

{ // start outer

// j is not visible (accessible here)

for ( int j = 0 ; j <>

{ // start inner

// i is accessible here

} // end inner

} // end outer

Lifetime : As soon as a variable goes out of scope, it's value is destroyed because it can not

be used after it goes out of scope

for ( int i = 0 ; i <>

{

int x = 10 ;

x = x * 5 ;

System.out.println (" Value of x is : " + x) ;

}

Output is :

Value of x is : 50

Value of x is : 50

Value of x is : 50

This is because every time, next iteration of for loop occurs x goes

out of scope ( as code execution moves out of { } ) . So it's value gets destroyed.

It again gets initialized to 10 when the loop is entered .

Next we will be discussing about Arrays

Data Types

Data Types
Every language has some data types so does Java
Data type defines the behaviour of variable on which it is applied
Different data types defined in Java language are
Integer types (4)
Name width (bits) Range
byte 8 -128 to 127
short 16 -32,768 to 32,767
int 32 -2,147,483,648 to 2,147,483,7
long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807


  • All these types can hold non fraction values only
  • Range is the valid number which can be assigned to them

If a byte is assigned 150 , compile time error would be there

Floating types (2)

Name width (bits)

float 32

double 64

  • These are used to hold values with fractional part
  • Any fractional value is treated as double type by default by compiler

Character type

char : It is a 16 bit type used to hold single character enclosed in single literals ' '

boolean : This type holds either true or false only.

  • These are primitive types,corresponding to these are wrapper types which

will be discussed later

  • String data type is used to hold sequence of characters like world enclosed in double quotes " "
  • Moreover, In Java each class represents a data type

Let's move on to variables




Explanation of first program

Here is a brief explanation of the first sample program
Code
class first
{
public static void main ( String args [] )
{
System.out.println ("First Java program") ;
} // main function ends
} // class ends

class : It is one of the Java keywords.It specifies the beginning of
a new class which contains the code to execute.
main : It is a function.It is the entry point for a Java desktop application,
execution will begin with this function
public : It is one of the access specifiers in Java, a keyword
void : It is return type of function.Every function in Java must

have a valid return type.

String : It is one of the data types

args : It is a argument which stores value passed to a function

We will be giving details of all the above elements later on.





Monday, 25 May 2009

Running a simple program

Here you would learn how to write and run a simple Java program .
First of all, you have to set your environment. It includes
1 Setting the path variable
Go into the directory where you have installed Java
eg C:\Program Files\Java\jdk1.6.0_07\bin
Copy the corresponding path on your machine
This gives the location of java compiler
Now right click on My computer > Properties > Advanced > Environment variables
Click New in System Variables
Enter path in variable name field
Paste the directory path in Variable value field and click on Ok
Close it
2 Setting classpath

Create a folder which will contain your programs

Copy it's path

Create a new System variable with name as classpath and

value as the path of your new directory

Click Ok and close

3 Sample code

class first

{

public static void main ( String args [] )

{

System.out.println ("First Java program") ;

} // main function ends

} // class ends

You can copy this code in a notepad file with name first and extension .java

and save it in the

folder created above

4 Running the program

Click on Start > Run or Press Windows key and then R

Type cmd and press enter

Type cd path

where path is the location of your folder for programs (same as classpath)

Type javac first.java and press enter

A class file should appear in the directory

Now type java first and press enter

First Java program should get printed on the screen

See Details for explanation of code

Wednesday, 11 March 2009

Jave Code

Java Code Home
Fundamentals of Java Language

Here we present few Key features of Java platform which have made it so popular around the world
  • Java is a simple language to learn as it uses familiar syntax of C/C++
  • It implements certain things in a cleaner way (Memory management) and leaves out some confusing aspects of it's predecessors (eg. Multiple inheritence,Pointers)
  • It is completely Object oriented, everything in Java is inside classes
  • Programs written in Java are robust
  • Java supports multi threaded programming which enables programs to do multiple tasks simultaneously in an elegant manner
  • Java programs are platform independent.You can write a Java program once and be sure that it would run on any platform

Don't worry if certain things seem to be new ! We would get into details during the course of this tutorial.