26 August 2012


Java Tutorial #5

  Friends today we start our discussion from Decision making processes & concept of looping , where we
 will see numerous ways by which we can repeat a process or take decision in java & in the end we will
 program few examples in decision making process, looping.
 Decision making statements 
          if statement    
    if satement is mainly used to execute a block of code when a given condition inside the if block is correct.
  We can also add many conditions inside one if loop by applying && or || logical operator discussed in the  
  previous tutorial  







          The basic structure of if block will look somewhat like this:-
               if(test expression)
            {
                 statement block that need to be executed
               }
               statement X;
   The if...else statement 

    if else statement is mainly used to execute both the aspect of a given expression , if a given expression is correct than, block of if part will gets execute & if the given expression doesn't satisfy the above condition than else part of the block will gets executed
                  The proper diagramatic explanation of the if...else statement is shown above.
    The basic structure of if...else block will look somewhat like this:-
                   if(test expression)
             {
                       True block statement
                   }
                   else
                   {
                       False block statement
                   }
                   Statement X;
        
    The else if ladder
 it mainly used to check more than one condition at a time when there is no link between various condition. It
 starts checking the condition start from the first if block & if any of the condition matches it executes that
 block & gets exited from all the remaining blocks if if or else if statement & if none of the if statement
  matches the conditio it simply executes the last else block(if present)
                   The proper diagramatic explanation of the else if ladder is shown above







  The basic structure of else if block will look somewhat like this:-
               if(test expression1)
         {
                   statment-1;
               }
               else if(test expression2)
               {
                   statement-2;
               }
               else if(test expression3)
               {
                   statement-3;
               }
               -----------
               else if(test expressionn)
               {
                   statement-n;
               }
               else
                  default statment; 
                                   
               Statement X;
    
    The switch statement
    It is also somewhat like elseif ladder in which if the case of a given expression matches with the listed case then that case's statement blocks gets executed.
    NOTE:-Friends keep in mind that if we dont use break statement after each case's block ending the block of the case that satisfy the geiven condition & remaining ll the blocks after that case will also gets executed.
  The proper diagramatic explanation of the switch case is shown above



 The basic structure of switch statement will look somewhat like this:-
               switch(expression1)
       {
                         case value-1;
                             block-1
                                break;

                         case value-2;
                             block-2
                                break;
                           -------
                           -------
                          default;                                       
                             default-block
                                break;
                         }          
                  Statement X;
    
   Now lets practice one program that can use all the above explained concepts;

    ___________________________________________________________________
  public class DecisionMaking{
 public static void main(String args[])
 {
  int a=325,b=457,c=478;
  System.out.println("largest value among the following is:");
  if(a>b)
  {
   if(a>c)
   {
    System.out.println(a);
   }
   else
    System.out.println(c);
  }
  else{
   if(c>b)
    System.out.println(c);
   else System.out.println(b);
  }
 }
 }
_________________________________________________________________________________

 Looping in Java
    for loop


 This is one of the most used type of looping that mainly used if we know the number of times you need to
 execute the loop
 The basic structure of the for loop is given below:-

          for(initilization; test condition; increment)
                {
                  body of the loop;
                }
                Statment X;        
    The while statement
    this is also among the famous looping construct that is being mainly used if we dont know the end of the loop or number of times the loop is going to execute
                  The comparison between for & while loop is shown in below drawn figure;-
    The basic structure of the while loop is given below:-
              IntiAlization:
              for(test condition)
                    {
                      body of the loop;
                    }
                    Statment X;        
    The do-while statement


           Till now all the looping conditions we learn use to check condition before executing its block, but
  do-while statement allows us to execute its block once before applying the conditions.
           It is almost same as use once for seeing genuinity of the product before paying to the shopkeeper
  The basic structure of the do-while loop is given below:-

          initilization;
                do
                {
                  body of the loop;
                }
                while(test condition);
                Statment X;
        
 Now lets see an example on looping
  Here we are finding the Computing power of 2;
    _________________________________________________________________________
    class Power{
     public static void main(String args[])
        {
         long p;
            int n;
            double q;
            p=1;
            for(n=0;n<10;++n)  
            {
             if (n==0)
                 p=1;
                 else
                  p*=2;
                 q=1.0/(double)p;
                 Syatem.out.println(" "+q+" "+" "+p);
                  
            }
           }
          }
_____________________________________________________________________________ 

21 August 2012

Java Tutorial #4

Operator and expressions
    Arithmetic operator (+,-,*,/,%)
    These can operate on any build in numeric data-type of java except on boolean type ('true' , 'false') . All the arithmetic operators work in the same way as they use to do in C or C++
    Modulo operator
    Modulo operator mainly gives the remainder of two numbers division.
             Always keep in mind that sign of the result in modulo arithmetic is always the sign of first operand (or dividend)
    e.g=> -14%3=-2
               -14%-3=-2
                14%-3=2
    Unlike C,C++ modulo operator % can be applied to the floating point data as well
    The floating point modulus operator returns the floating point equivalent of an integer division.
                     It simply means that ,the division is carried out with both the floating point operand, but the resulting divisor is treated as integer & resulting in floating remainder will acts as the output of the modulo division of floting point numbers
    When arithmetic operation is performed on two different types of data values,the resultant will always be converted into higher precision value
Logical operator
    &&
    Logical and
    can be true only when both the values across && operator should be true
    ||
    Logical or
    can be true only when atleast any one the values across || operator should be true
    !
    Logical not
    false if expression is anything other than 0
Special operators
    Instanceof opertaor
    It is an object reference operator and returns "true" if the object on LHS is an instance of the class on the RHS
    This opertor mainly help us to determine whether an object belongs to a particular class or not
              e.g=> person instanceof student
                         will be true if person belongs to the class of student otherwise it will return false
    Dot operator
    is mainly used to access the instance variable & method of class objects
     e.g=>person.age ;                    //refernce to variable age
          person.salary();                //refrence to the method salary
    
    Remember java doesnot have any operator for exponentiaion (or power), in place it have a method function in math class called pow(a,b) that will implement the same work as being done by the operator, if it would have been.(i.e=>a^b or, a to the power b);
    y=(int)(a+b)
    here the result is being converted into int value
    y=(int)a+b
    here a is convered into int value & then being added with b , so the resultant may not be an int value.

Generic typecasting
Typecasting is an unsafe operation because the compiler cannot check the wrong typcast. The compiler throws an exception if typecast fails at runtime
When using generics, the compiler insert typecast at appropriate places to implement type casting. So typecast become implicit in palce of explicit. Generics also detremine the typecast error at compile time rather than runtime
syntax
            Class SampleGenerics
            {
             sample code;
            }
            
e.g=>Illustration of use of generic type in collections
______________________________________________________________________________
______________________________________________________________________________
Following example illustrate how we can print array of different type using a single Generic method:

public class GenericMethodTest
{
   // generic method printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements              
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    } 
}
_______________________________________________________________________________
_______________________________________________________________________________


    Selected important math function
    Math functions are the part of java.lang Package
    atan2(x,y) =>returns an angle whose tangent is x/y (i.e=> it is tan-inverse
                                                                                                   function)
    exp(x)=>returns e raised to x
    rint(x)=>returns truncated value of x
    abs(a)=>returns absolute value of a
    Syntax
    Math.function_name();
    eg=>Math.sqrt(x);

20 August 2012

Tutorial 3

Java Tutorial #3

Java Programming Structure

Document section (suggested)
Package statement (optional)
Import statement (optional)
Interface statement (optional)
Class definition (optional)
Package statement (optional)
Main method class
{
Main method definition
}

 1.1 Document section- comprises of set of comment lines giving the name of program ,author, & other
  details which programmer would like to refer to at later stages

 1.2Package statement declares a package name & inform the compiler that the classes defined here
 belongs to this package
 e.g=> package author

 1.3Import statment we can have access to the classes that are not part of our package

 1.4Interface statement we can have access to the classes that are not part of our package

 1.5Main method  is same as in C++ from where the program execurtion starts and end with theend of
 main method
 Friends,always keep in mind that java is case sensitive ,so int radius & int RAdius are two different  
 variable (or identifier) not the same one
 The character used in java are defined by the unicode charecter set, which is a 16bit character coding 
 system. So char in java takes 2byte space unlike 1byte space in C or C++

 Keywords java language has 50 reserved keywords that are never been used as identifier. all keywords are
  given in lower case letter .
                     For more information about keywords Click here
 
Secret of java platform Independence
     Different language compilers translates source code into machine code for a specific computer. On the
 other hand, java compiler produces an inermediary code known as bytecode for a machine called
 java-virtual machine, that exists inside the computer memory and simulates computer within computer that
 converts bytecode into machine specific code. As bytecode of all the system are same and hence java is
 platform independent.


 Command line argument
Command line argument is one of the nice way of passing the data at runtime at the time of compilation.
Public static void main(String srgs[])
Here args is declared as an array of strings (known as string object).Any argument provided in command line (at time of execution) are passed to the array args as its element that can be used in the program



  Use of Command line argument

 
               /*
         * This program uses command line argument as input
                */
                Class static void main(String args[])
                {
                 int count , i=0;
                    String string;
                    count =args.length ; //inbuilt function to count the 
                                                //number of argument passed by the
                                                // user at run time
                    System.out.println("Number of arguments ="+count);
                    while(i < count)
                    {
                     string = args[i];
                        i+=1;
                         System.out.println(i+":"+"Java is"+string+"!");         
                    }
                }
 
 Data-type supported in java


  Integer type
  java doesnot support the concept of unsigned type,so java integer value are either positive or negative

 Floating point
 is treated as double precision quantities(double). To force them to be in single precision mode we must
 append f or F to the number

 NOTEAll mathematical function such as sin,cos,sqrt return or take double type value Floating point data
 type support a special value known as Not-a-Number(NaN), that is used to represent the result of
 opertation such as divie by zero where actual number is not produced

 Character type is same as in C or C++ or any standard procedural or object oriented language

 Boolean type  is denoted by the keyword boolean and uses only 1 bit of storage that can take only two
  values "true" or "false"

 NOTEIt should be remembered that wider data type requires more time for manipulation and therefore it is
  advisable to use smaller data type whenever possible
 one of the great advantage of java is that if a variable is not initialzed it is autometically set to zero(or the
  standard default value of that primitive data type)
Typecasting
  converts one primitive data-type to another primitive data-type
    Automatic conversion
    is possible only if the destination type has enough precision to store the source value
    eg=> byte b=75;
    int a=b; s valid statement
    Note that we need to explicitely cast if we are to convert a more precised value to the less precised one
    Syntax
    type variable1=(type) variable2;