10x Blogs Directory

Wednesday, April 1, 2009

Polymorphism

lPolymorphism in a Java program
-
  • The ability of a reference variable to change behavior according to what object instance it is holding.
  • This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to.

There are 3 forms of Polymorphism

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface
Example:

Given the parent class Person and the subclass Student of the previous examples, we add another subclass of Person which is Employee

lIn Java, we can create a reference that is of type super class to an object of its subclass. For example,
public static main( String[] args ) {
Student studentObject = new Student();
Employee employeeObject = new Employee();
Person ref = studentObject; // Person reference points              // to a Student object
   String name = ref.getName();
}
  • Now suppose we have a getName method in our super class Person, and we override this method in both Student and Employee subclass's
public class Student {
public String getName(){
System.out.println(“Student Name:” + name);
return name;
}
}
public class Employee {
public String getName(){
System.out.println(“Employee Name:” + name);
return name;
}
}

l
  • Going back to our main method, when we try to call the getName method of the reference Person ref, the getName method of the Student object will be called. 
l
  • Now, if we assign ref to an Employee object, the getName method of Employee will be called.

l
  • Another example that illustrates polymorphism is when we try to pass a reference to methods as a parameter
l
  • Suppose we have a static method printInformation that takes in a Person reference as parameter
public static printInformation( Person p ){
       // It will call getName() method of the
       // actual object instance that is passed
       p.getName();
}

  • We can actually pass a reference of type Employee and type Student to the printInformation method as long as it is a subclass of the Person class.

public static main( String[] args )
{
Student studentObject = new Student();
Employee employeeObject = new Employee();
printInformation( studentObject );
printInformation( employeeObject );
}
 

Thursday, March 12, 2009

Do-while-loop

Do-while-loop

-is similar to the while-loop
-statements inside a do-while loop are executed several times as long as the condition is satisfied -The main difference between a while and do-while loop:
The statements inside a do-while loop are executed at least once.

do-while loop has the form:
do
{
statement1;
statement2; . . .
}while( boolean_expression );

Example 1

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

Example 2

//infinite loop
do{
System.out.println(“hello”);
} while (true);

Example 3

//one loop
// statement is executed once
do
System.out.println(“hello”);
while (false);

Coding Guidelines

Common programming mistakes when using the do-while loop is forgetting to write the semi-colon after the while expression.
do{ ... }
while(boolean_expression)//WRONG->forgot semicolon;

Just like in while loops, make sure that your do-while loops will terminate at some point.

While-loop

While loop
-is a statement or block of statements that is repeated as long as some condition is satisfied.

while loop has the form:

while( boolean_expression )
{
statement1;
statement2; . . .
}

-The statements inside the while loop are executed as long as the boolean_expression evaluates to true.

Example 1
int x = 0;
while (x<10) { System.out.println(x); x++; }

Example 2
//infinite loop
while(true)
System.out.println(“hello”);

Example 3

//no loops
// statement is not even executed
while (false)
System.out.println(“hello”);

Monday, March 9, 2009

Switch Statements

  • switch
    -allows branching on multiple outcomes.
  • switch statement has the form:
switch( switch_expression )
{
case case_selector1: statement1;
// statement2;
//block 1 break;
case case_selector2: statement1;
// statement2;
//block 2 break;
default: statement1;
// statement2;
//block n
}
  • where,
    -switch_expression
    lis an integer or character expression
    -case_selector1, case_selector2 and so on,
    lare unique integer or character constants.
  • When a switch is encountered,
    -Java first evaluates the switch_expression, and jumps to the case whose selector matches the value of the expression.
    -The program executes the statements in order from that point on until a break statement is encountered, skipping then to the first statement after the end of the switch structure.
    -If none of the cases are satisfied, the default block is executed. Take note however, that the default part is optional.
  • NOTE:
    -Unlike with the if statement, the multiple statements are executed in the switch statement without needing the curly braces.
    -When a case in a switch statement has been matched, all the statements associated with that case are executed. Not only that, the statements associated with the succeeding cases are also executed.
    -To prevent the program from executing statements in the subsequent cases, we use a break statement as our last statement.

Coding Guidelines

  • Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use, based on readability and other factors.
  • An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or character value. Also, the value provided to each case statement must be unique.

Friday, March 6, 2009

if - Statements

  • if Statements are Decision control structures
    -Java statements that allows us to select and execute specific blocks of code while skipping other sections
  • Types:
    -if-statement
    -if-else-statement
    -If-else if-statement
  • if-statement
    -specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true.
  • if-statement has the form:if( boolean_expression )statement; or if( boolean_expression ){ statement1; statement2; }
    -where,
  • boolean_expression is either a boolean expression or boolean variable.
  • Eg -
  • int grade = 68;
  • if( grade > 60 )
  • System.out.println("Congratulations!");


Coding Guidelines

  • The boolean_expression part of a statement should evaluate to a boolean value. That means that the execution of the condition should either result to a value of true or a false.
  • Indent the statements inside the if-block.
    For example,
    if( boolean_expression )

{ //statement1;

//statement2;
}

if-else statement

  • if-else statement
    -used when we want to execute a certain statement if a condition is true, and a different statement if the condition is false.
  • if-else statement has the form:

if( boolean_expression )

{ statement1;

statement2; . . . }

else

{ statement3;

statement4; . . .}

  • Example:

int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");
else
System.out.println("Sorry you failed");

Coding Guidelines

  • To avoid confusion, always place the statement or statements of an if or if-else block inside brackets {}.
  • You can have nested if-else blocks. This means that you can have other if-else blocks inside another if-else block.
  • For example,
    if( boolean_expression ){

if( boolean_expression )

{ //some statements here }
}
else{ //some statements here
}


if-else-else if statement

  • The statement in the else-clause of an if-else block can be another if-else structures.
  • This cascading of structures allows us to make more complex selections.
  • The statement has the form:

if( boolean_expression1 )

statement1;

else if( boolean_expression2 )

statement2;

else statement3;

  • Example


int grade = 68;
if( grade > 90 ){
System.out.println("Very good!");
}
else if( grade > 60 ){
System.out.println("Very good!");
}
else{
System.out.println("Sorry you failed");
}

Common Errors

  • The condition inside the if-statement does not evaluate to a boolean value. For example,

//WRONG

int number = 0;

if( number )

{ //some statements here }

The variable number does not hold a boolean value

  • Writing elseif instead of else if.

    Using = instead of == for comparison.

For example,

//WRONG

int number = 0;

if( number = 0 )

{ //some statements here }

This should be written as,

//CORRECT

int number = 0;

if( number == 0 )

{ //some statements here}

Thursday, March 5, 2009

Introduction to Arrays

  • Suppose we have here three variables of type int with different identifiers for each variable.
int number1;
int number2;
int number3;

number1 = 1;
number2 = 2;
number3 = 3;

As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose.
  • In Java and other programming languages, there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of variable is called an array.
  • An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.

Declaration ofan Array

  • To declare an array, write the data type, followed by a set of square brackets[], followed by the identifier name.
  • For example,
int []ages;
or
int ages[];


Instantiation of an Array

  • After declaring, we must create the array and specify its length with a constructor statement.
  • Definitions:
    -Instantiation
  • In Java, this means creation
    -Constructor
  • In order to instantiate an object, we need to use a constructor for this. A constructor is a method that is called to create a certain object.
  • We will cover more about instantiating objects and constructors later.
  • To instantiate (or create) an array, write the new keyword, followed by the square brackets containing the number of elements you want the array to have.
  • For example,

//declaration int ages[];

instantiate objectages = new int[100];

or, can also be written as,

//declare and instantiate object

int ages[] = new int[100];

  • You can also instantiate an array by directly initializing it with data.
  • For example,int arr[] = {1, 2, 3, 4, 5};This statement declares and instantiates an array of integers with five elements (initialized to the values 1, 2, 3, 4, and 5).


Accessing Array Element

  • To access an array element, or a part of the array, you use a number called an index or a subscript.
  • Index number or Subscript
    -assigned to each member of the array, to allow the program to access an individual member of the array.
    -begins with zero and progress sequentially by whole numbers to the end of the array.
    -NOTE: Elements inside your array are from 0 to (sizeOfArray-1).
  • For example, given the array we declared a while ago, we have

//assigns 10 to the first element in the array ages[0] = 10;

//prints the last element in the array System.out.print(ages[99]);

  • NOTE:
    -once an array is declared and constructed, the stored value of each member of the array will be initialized to zero for number data.
    -for reference data types such as Strings, they are NOT initialized to blanks or an empty string “”. Therefore, you must populate the String arrays explicitly.


Coding Guidelines

  • It is usually better to initialize or instantiate the array right away after you declare it. For example, the declaration,

int []arr = new int[100]; is preferred over,

  • It is usually better to initialize or instantiate the array right away after you declare it. For example, the declaration,

int []arr = new int[100]; is preferred over,

int []arr; arr = new int[100];

int []arr; arr = new int[100];


Array Length
  • In order to get the number of elements in an array, you can use the length field of an array.
  • The length field of an array returns the size of the array. It can be used by writing,
    arrayName.length


Coding Guidelines

  • When creating for loops to process the elements of an array, use the array object's length field in the condition statement of the for loop. This will allow the loop to adjust automatically for different-sized arrays.
  • Declare the sizes of arrays in a Java program using named constants to make them easy to change. For example, final int ARRAY_SIZE = 1000; //declare a constant . . . int[] ages = new int[ARRAY_SIZE];


Multi-Dimensional Array

  • Multidimensional arrays are implemented as arrays of arrays.
  • Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name.
  • To access an element in a multidimensional array is just the same as accessing the elements in a one dimensional array.
  • For example, to access the first element in the first row of the array dogs, we write, System.out.print( dogs[0][0] );
  • This will print the String "terry" on the screen.



Command-line Arguments

l
  • A Java application can accept any number of arguments from the command-line. 
  • Command-line arguments allow the user to affect the operation of an application. 
  • The user enters command-line arguments when invoking the application and specifies them after the name of the class to run.  
  • In Java, when you invoke an application, the runtime system passes the command-line arguments to the application's main method via an array of Strings.

    public static void main( String[] args )


    Each String in the array contains one of the command-line arguments

    Example:

    1public class CommandLineSample
    2{
    3 public static void main( String[] args ){
    4
    5 for(int i=0; i
    6 System.out.println( args[i] );
    7 }
    8
    9 }
    10}