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.