Saturday 19 March 2011

Java Classes, objects and methods

INTRODUCTION:
Java gives you the capability to do object-oriented programming. Object-oriented programming enables the programmer to group together data and the code that uses data into discrete units. Objects in java are defined using java classes. Anything we wish to represent in a java program must be encapsulated in a class that defines the state and behaviour of the basic program components known as object. Classes creates objects and objects use methods to communicate between them.
In java, the data items are called fields and the functions are called methods. calling a specific method in an object is described as sending a message to the object. A class provides a sort of template for an object and behaves like a basic data type such as int.

DEFINING A CLASS:
A class is a user defined data type used to implement an abstract object, giving you the capability to use object-oriented programming with java.
Once the class-type has been defined, we can create 'variables' of that type. These variables are termed as instances of class, which are actual objects.

The general form of a class definition is:
             Class name [extends superclassname]
             {
                   [variable declarations;]
                   [method declarations;]
             }
Everything written inside the square brackets is optional. Thus, the following would be a valid class definition.
             Class empty
             {
             }
Classname and Superclass name are any valid java identifiers. The keywords extends indicates that the properties of the superclassname class are extended to thr class classname. This concept is known as inheritance.

ADDING VARIABLES:
Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables because they are created whenever an object of the class is instantiated. Instance variables can be declared exactly the same way as we declare local variables.

Example:
     Class Movie
     {
          String title;
          int length;
          int cost;
          char type;
     }

The class movie contains four instance variables, out of which one is of type string, two are of type int and one is of type char. The two int variables can be declared in one line as
      int length, cost;

ADDING METHODS:
A class has no life without methods. The objects created by such class cannot respond to any message. Therefore it is necessary to add methods for manipulating the data contained in the class. Methods are declared inside the class immediately after the variable declaration.
The general form of method declaration is:
     type method-name (parameter-list)
     {
          method-body;
     }

Where, -methodname denotes the name of the method.
            -type denotes the type of value the method returns
            -parameter-list denotes the list of parameters to be passed into the method.

The parameter-list must always be enclosed in parantheses. The variables in the list are separated by commas. In the case where no input data is required , the declaration must retain the empty parantheses.

Let us consider Movie class again and add a method getData() to it.
    Class Movie
    {
       String title;
       int length;
       int cost;
       char type;
       void getData (String s,int x,int y, char z)
        {
           title = s;
           length = x;
           cost = y;
           type = z;
        }
       }
Nothe that the method has a return type void because it does not return any value. The getData method is basically added to provoide values to the instance variables.

CREATING OBJECTS:
In java, objects are essentially a block of memory that contains space to store all the instance variables. The other name of creating an object is instantiating an object.

To create an object a new keyword is used as an operator. This operator creates an object of the specified class and returns a reference to thst objects.

The syntax of creating an object is as follows:
Class-name object-name;         //declare
Object-name = new class-name () ;         //instantiate

Example:
      Movie mov1;
      mov1 = new Movie();

The first statement declares a variable to hold the object reference and the second actually assigns the object reference to the variable. Both statements can be combined into one as shown below:
      Movie mov1 = new Movie();
Where Movie is the class name , mov1 is the object created by the default empty constructor of the class. We can create any number of objects of a class. Each object has it's own copy of instance variables of its class. Thus, any changes to the variables of one object have no effect on the variables of the another. Two or more references can be created to the same object just by assigning one object reference variable to another.

Example:
     Movie mov2 = new Movie();
     Movie mov3 = mov2;
Here, Both mov3 and mov2 refer to the same object.

Java's two reference of same object


Saturday 12 March 2011

Decision making and looping

INTRODUCTION:
The iteration statements aloow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements. Java provides three kinds of loops:
  • While loop
  • do-while loop
  • for loop
All three constructs of java repeat a set of statements as long as a specified condition remains true. The specified condition is generally referred to as a loop control. For all three loop statements, a true condition is any nonzero value. A zero value indicates a false condition.

THE WHILE STATEMENT:
The most simple and general looping structure available in java is the while statement. The syntax of while loop is:
   while(condition)
   {
      // loop-body
    }
Where the loop body may contain a single statement, a compound statement or an empty statement. The loop iterates while the condition evaluates to true. When the expression becomes false, the program control passes to the line after the loop body code.

//program for while loop

class whiletest
 {
    public static void main(String args[])
      {
         int n=10;
         while(n>0)
         {
           System.out.println("tick", +n);
           n--;
          }
       }
}

THE DO STATEMENT:
Unlike the while loop, the do-while is an exit-controlled loop i.e it evaluates its text-expression at the bottom of the loop after executing it's loop-body statements. This means that a do-while loop always executes at least once. The syntax of the do-while loop is:
    do
    {
         loop-body;
     }
while(condition);

Example: 
 Class doWhileCheck
  {
     Public static void main (String args[])
      {
         int n=10;
          do
            {
               System.out.println("tick" +n);
                n--;
            }
             while(n>0);
        }
   }
THE FOR STATEMENT:
The for loop is the easiest to understand of the java loops. All its loop-control elements are gathered in one place (on the top of the loop), while in the other loop construction of C++ , they( top-contol elements) are scattered about the program. The Syntax of the for loop statement is:

for( initialization expression(s); test condition; update expression)
{
   loop-body;
}

//program showing usage of for loop
class forTest
{
   public static void main(String args[])
 {
    int i;
    for( i=1; i<=10; i++)
     System.out.println(i);
 }
}

Following figure outlines the working of a for loop:

Execution of a for loop
 


Thursday 10 March 2011

Decision making and branching

Introduction:
Generally a program executes it's statements from beginning to end. But not many programs execute all their statements in strict order from beginning to end. Most programs decide what to do in response to changing circumstances.
In a program statements may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence,selection or iteration.
When a program breaks the sequential flow and jumps to another part of the code, it is called selection or branching.
When the branching is based on a particular condition, it is known as conditional branching.
If branching takes place without any condition, it is known as unconditional branching.

Java language supports two types of selections statements: if and switch. In addition, in certain circumstances '?' operator can be used as an alternative to if statements.

DECISION MAKING WITH IF STATEMENT:
An if statement tests a particular condition; if the condition evaluates to true , a course of action is followed i.e a statement or set of statements is executed . Otherwise (if the condition evaluates to false) ,the course-of-action is ignored.
The if statement may be implemented in different forms depending on the complexity of conditions to be tested.
  • Simple if statement
  • if....else statement
  • Nested if....else statement
  • else if ladder
SIMPLE IF STATEMENT:
The syntax of the if statement is shown below:
if(expression)
statements;

Where a statement may consist of a single statement , a compound statement, or nothing. The expression must be enclosed in parantheses. If the expression evaluates to true, the statement is executed, otherwise ignored.

Following figure illustrates the if construct of java:

Flow Chart of IF control
 Example:
if(a>10)
if(b<15)
c=(a-b)*(a+b);

If the value of a is greater than 10, then the following statement is executed which in turn is another if statement. This if statement tests b and if b is less than 15, then c is claculated.

THE IF....ELSE STATEMENT:
This form of if allows either-or condition by providing an else clause. The syntax of the if-else statement is the following:

if(expression)
  statement-1;
else
  statement-2;

If the expression evaluates to true i.e., a non-zero value, the statement-1 is executed, otherwise statement-2 is executed. The statement-1 and statement-2 can be a single statement, or a compound statement, or a null statement.

Following figure illustrates the if else construct of java:

Flow chart of if-else control
 Example:
int a,b;

if(a<=b)
   a=0;
else
   b=0;

NESTED IF....ELSE STATEMENT:
A Nested if is an if that has another if in it's 'if's' body or in it's else's body. The nested if can have one of the following three forms:

1.    if(expression1)
        {
          if(expression2)
           statement-1;
         else
           statement-2;
        }
      else
         body of else;

2.     if(expression1)
        body-of-if;
       else
       {
          if(expression2)
           statement-1;
         else
           statement-2;
        }

3.      if(expression1)
        {
          if(expression2)
           statement-1;
         else
           statement-2;
        }
      else
     {
       if(expression3)
           statement-3;
      else
         statement-4;
     }

THE ELSE-IF LADDER:
A common programming construct in the java is the if-else-if ladder , which is often also called the if-else-if staircase because of it's appearence.

It takes the following general form:
if(expression1) statement1;
  else
      if(expression2) statement2;
  else
      if(expression3) statement3;
   :
   else statement n;

The expressions are evaluated from top downward. As soon as expression evaluates to true , the statement associated with it is executed and the rest of the ladder is bypassed. If none of the expression are true, the final else gets executed. If the final else is missing , no action takes place if all other conditions are false.

Although it is technically correct to have indentation in the if-else-if ladder as shown above. however, it generally leads to overly deep indentation . For this reason, the if-else-if ladder is generally indented like this:

if(expression1)
  statement 1;
elseif(expression2)
  statement 2;
elseif(expression3)
  statement 3;
    :
else
  statement n;

THE SWITCH STATEMENT:
Java provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed.
The general form of switch is:
switch(expression)
{
case value1:
   Codesegment 1
case value2:
   Codesegment 2
   ...
case valuen:
   Codesegment n
default:
   default Codesegment
}

A switch statement is used for multiple way selection that will branch to different code segments based on the value of a variable or an expression . The optional default label is used to specify the code segment to be executed when the value of the variable or expression does not match with any of the case values. if there is no break statement as the last statement in the code segment for a certain case, the execution will continue on into the code segment for the next case clause without checking the case value.

NESTED SWITCH:
You can use switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines in its own block, no conflicts arise between the case statements in the inner switch and those in the outer switch.

switch(count)
{
   case 1:
   switch(target)
   {
       case 0:
       System.out.println("target is zero");
       break;
       case 1:
       System.out.println("target is one");
       break;
   }
break;
    case2: //. . .

Here the case 1: statement is inner switch does not conflict with the case 1: statement in the outer switch. The count variable is only compared with the list of cases at the outer level. if the count is 1 , then target is compared with the inner list cases.

No two case constants in the same switch can have individual values. A switch statement enclosed by an outer switch can have case constants in common.

THE ?: OPERATOR:
Java has an operator that can be used as an alternative to if statement. You are familier with this operator, the conditional operator ?: This operator can be used to relace if-else statements of the general form:

     if (expression 1)
        expression 2;
     else
         expression 3;

The above form of if can be alternativlely written using ?: as follows:

       expression 1? expression 2: expression 3;

Wednesday 9 March 2011

Java Tokens

A Java program is a collection of tokens, comments and white spaces. There are five types of tokens included in java language. They are:
  • Reserved keywords
  • Identifiers
  • Literals
  • Operators
  • Seperators
Java Character Set:
Characters used to write java tokens are the smallest units of java language. These characters are defined by the unicode character set, an emerging standard that tries to create characters for a large number of scripts world wide. The unicode is a 16  bit character coding system.

Keywords:
Keywords implement specific features of the language. There are 60 reserved keywords defined in the java language. These keywords combined with the syntax of the operators and separators, from the definition of the java language. These keywords cannot be used as names for a variable, class or method.

Java Reserved Keywords
 Identifiers:
Identifiers are used for class names, method names, and variable names. An identifier may beb any sequence of uppercase and lowercase letters,numbers, or the underscore and dollar-sign characters. They must not begin with a number.
Again java is case sensitive , so First is different from first. Some examples of valid identifiers are:
avg            temp              b5                count              ptest              this_is_fine

Invalid variable names include:
2count            high-temp            Not/fine

Literals:
A constant value in java is created by using a literal representation of it. Literals can be digits, letters, and other characters. Major five types of literals in java are:
  • Integer literals
  • Floating-point literals
  • Character literals
  • String literals
  • Boolean literals
Each of them has a type associated with it. The type describes how the values behave and how they are stored. Example of some literals are given below:
10098.6          'Y'             "This is an answer"

A literal can be used anywhere a value of it's type is allowed.

Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce a result.

Separators:
In java, there are a few characters that are used as seperators . Semicolon(;) is the most commonly used seperator in java. It is used to terminate statements. The seperators are shown below:


Java Seperators


Tuesday 8 March 2011

Structure of java program

A Java program may contain many classes of which main() is defined in only one class. Classes contain data members and methods that operate on the data members of the class. Methods may contain datatype declarations and executable statements. To write a java program, we first define classes and then put them together. The different sections of a java program are shown in the below figure:


                                           Structure of java program

Document Section:
This section comprises a set of comment lines giving the name of the program, the author and the other details which the programmer would like to refer to at a larger stage. Comments must explain why and what of classes and how of algorithms. This would greatly help in maintaining the program.

Package Statement:
Package statement is the first statement aloowed in java. This statement declares the package name and informs the compiler that the classes defined here belong to this package.

Example:
package course;

The package statement is optional i.e., our classes may or may not be a part of package.

Import Statements:
After a package statement and before any class definition , may appear a number of import statements.

Example:
import course.selection;

This statement instructs the interpreter to load the selection class combined in package course. We can access classses that that are part of other named package susing import statements.

Interface Statements:
An interface is like a class but includes a group of method declarations. This is also an optional section and is used only when we wish to implement multiple inheritance features in the program.

Class Definitions:
A Java program may contain single or multiple class definitions. They are the primary and essential elements of java program. These classes are used to map the objects of real-world problems. The number of classes used depends on the complexity of the program.

Main Method Class:
This class is essential part of a java program since every java stand-alone program requires a main method as its starting point. The main method creates objects of various classes and establishes communication between them. The program terminates on reaching the end of main, and the control passes back to the operating system.




Monday 7 March 2011

Overview of java programming

Java is general purpose, object-oriented programming language. Two types of java programs canbe developed.
  • Stand-alone applications
  • Web Applets
Stand-alone applications are programs written in java to carry out certain tasks on a stand-alone local computer. A stand-alone java program can be executed in two steps:
  1. Compiling source code into byte code using javac compiler.
  2. Executing the byte code program using java interpreter.
Web Applets are small java programs developed for internet applications.They are developed for doing everything like creating simple animated graphics, complex games, utilities etc.

SIMPLE JAVA PROGRAM:

//A Simple java program
Class Simple
{
public static void main (String args[])
    {
     System.Out.Println ("A Simple Java Program");
     }
}

We will explain the above program step by step.

Comment
The First line is a single line comment which will be ignored during compilation. Comments make you understand what your program does. Use /*-----*/ for multiple line comments.

Class Declaration
In java, everything must be declared in a class, which is declared by the keyword Class. Public is a keyword which makes the class available and accessible to any one.
(Simple) one is a java identifier that specifies the name of the class to be defined.

Opening Brace
In java, every class definition begins with an opening brace "{" and ends with a closing brace "}". Pair of "{}" braces define the scope of any method or class.

The Main Line
public static void main (String args[])
This linbe begins the main() method. This is the line at which program will begin executing. All java applications begin execution by calling main(). The main() must be declared as Public, since it must be called by code outside of it's class when the program is started.
The keyword void simply tells the compiler that the main() does not return a value. The keyword static allows main() to be called without having to instantiate a particular instance of the class.

The Output Line
System.Out.Println ("A Simple Java Program");
This line outputs the string followed by a new line on the screen. Output is accomplished by the built-in  println() method. System is a predefined class that provides access to the system, and out is the output stream that is connected to the console.

All statements in java ends with a semicolon(;).

Benefits of OOPS

There are several benefits of OOP to both program designer and the user. Object orientation solves many problems which are associated with the development and quality of software products. New technology gives greater programmer productivity, good quality of software and low maintanance cost. The main advantages are:
  • We can eliminate redundant code and extend the use of existing classes.
  • Programs can be build from the standard working modules that communicate with one another and to start writing the code from scratch. This shows to saving of development time and higher productivity.
  • The data hiding rules helps the programmer to make secure programs that cannot be invaded by code in other parts of the program.
  • It has multiple objects to coexist without any interference.
  • It has map objects in the problem domain to those objects in the program.
  • partition of work is easy in a project based on objects.
  • The data-centered design approach capture more details of a model in an implementable form.
  • Object oriented systems can be easily upgraded from small to large systems.
  • It is possible to easily manage software complexity.