JAVA N WEB TECH SYLLABUS

Thursday, November 18, 2010

Exception Handling In Java

Hi
In Java Exception Handling is managed by 5 key word,they are

  1. try
  2. catch
  3. finally
  4. throw
  5. throws  
Here i am posting a typical example code which will make use of these five keywords,in this example we are writing code for preparing Tea.
For preparing the tea we require the following Ingredients
  • TeaPowder
  • Milk
  • Sugar
If these things are not available at the preparation time we are throw Exception objects created from our Exception classes like
  • SugarException
  • TeaPowderException
  • MilkException. 
As we know to create our own exception classes we have to extend it from the Base Class Exception.
The code for this is shown below
import java.io.DataInputStream;
import java.io.IOException;
/*
 * MakeTea.java
 *
 * Created on November 16, 2010, 9:11 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author NVAEEN S MIRAJKAR
 */

class SugarException extends Exception
{
    int errorCode;
    String info;
    public SugarException()
    {
        this.errorCode=100;
        this.info="No Sugar Exception";
    }
    public String getDetails()
    {
        return("Error Code="+this.errorCode+"\t"+this.info);
    }
}

class MilkException extends Exception
{
    int errorCode;
    String info;
    public MilkException()
    {
        this.errorCode=101;
        this.info="No Milk Exception";
    }
    public String getDetails()
    {
        return("Error Code="+this.errorCode+"\t"+this.info);
    }
}

class TeaPowderException extends Exception
{
    int errorCode;
    String info;
    public TeaPowderException()
    {
        this.errorCode=102;
        this.info="No Tea Powder Exception";
    }
    public String getDetails()
    {
        return("Error Code="+this.errorCode+"\t"+this.info);
    }
}
public class MakeTea {
    
    /** Creates a new instance of MakeTea */
    int milk;
    int teaPowder;
    int sugar;
    
    public MakeTea(int sugar,int teaPowder,int milk) throws SugarException,MilkException,TeaPowderException
    {
        if(milk==0)
        {
            MilkException mke=new MilkException();
            throw mke;
        }
        if(sugar==0)
        {
            
            throw new SugarException();
        }
        if(teaPowder==0)
        {
            TeaPowderException tpe=new TeaPowderException();
            throw tpe;
        }
        this.milk=milk;
        this.teaPowder=teaPowder;
        this.sugar=sugar;
        
    }
    public static void printScreen(String msg)
    {
        System.out.println(msg);
    }
    public static void main(String args[])
    {
        int sugar = 0;
        int milk = 0;
        int tpowder = 0;
        
        MakeTea.printScreen("To Prepare Tea First on the gas an lite the stove");
        try 
        {
            
            DataInputStream din=new DataInputStream(System.in);
            
            MakeTea.printScreen("Enter the quantity of Sugar");
            sugar=Integer.parseInt(din.readLine());
            
            MakeTea.printScreen("Enter the quantity of Tea Powder");
            tpowder=Integer.parseInt(din.readLine());
            
            MakeTea.printScreen("Enter the quantity of Milk");
            milk=Integer.parseInt(din.readLine());

            MakeTea.printScreen("The Quantities entered are \n"+
                    "Sugar="+sugar+
                    "\nTeapowder="+tpowder+
                    "\nMilk="+milk);
        
            
        } 
        catch (IOException ex) 
        {
           MakeTea.printScreen("Cannot read values from key board");
        }
        
        try 
        {
            
            MakeTea mkt=new MakeTea(sugar,tpowder,milk);
            MakeTea.printScreen("We have Sucessfullt prepared the Tea now enjoy......!");
        } 
        catch (SugarException ex) 
        {
            MakeTea.printScreen(ex.getDetails());
        } 
        catch (MilkException ex) 
        {
            MakeTea.printScreen(ex.getDetails());
        } 
        catch (TeaPowderException ex) 
        {
            MakeTea.printScreen(ex.getDetails());
        }
        finally
        {
            MakeTea.printScreen("Wether u are able to make tea or not OFF the Stove n GAS");
            MakeTea.printScreen("Gas n Stove Turned OFF");
        }
        
        
    }
    
}

Tuesday, November 9, 2010

Java Code for getting the current date and time

Here in this code we are making use of the classes
java.util.Calendar;
java.util.GregorianCalendar;

these classes are present inside the Util package

public class GregorianCalendar
extends Calendar
GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar used by most of the world.
The standard (Gregorian) calendar has 2 eras, BC and AD.
This implementation handles a single discontinuity, which corresponds by default to the date the Gregorian calendar was instituted (October 15, 1582 in some countries, later in others). The cutover date may be changed by the caller by calling setGregorianChange().
Historically, in those countries which adopted the Gregorian calendar first, October 4, 1582 was thus followed by October 15, 1582. This calendar models this correctly. Before the Gregorian cutover, GregorianCalendar implements the Julian calendar. The only difference between the Gregorian and the Julian calendar is the leap year rule. The Julian calendar specifies leap years every four years, whereas the Gregorian calendar omits century years which are not divisible by 400.
GregorianCalendar implements proleptic Gregorian and Julian calendars. That is, dates are computed by extrapolating the current rules indefinitely far backward and forward in time. As a result, GregorianCalendar may be used for all years to generate meaningful and consistent results. However, dates obtained using GregorianCalendar are historically accurate only from March 1, 4 AD onward, when modern Julian calendar rules were adopted. Before this date, leap year rules were applied irregularly, and before 45 BC the Julian calendar did not even exist.
Prior to the institution of the Gregorian calendar, New Year's Day was March 25. To avoid confusion, this calendar always uses January 1. A manual adjustment may be made if desired for dates that are prior to the Gregorian changeover and which fall between January 1 and March 24.
Values calculated for the WEEK_OF_YEAR field range from 1 to 53. Week 1 for a year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek(), getFirstDayOfWeek(), and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 or 53 (as needed).
For example, January 1, 1998 was a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (these are the values reflecting ISO 8601 and many national standards), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997.
Values calculated for the WEEK_OF_MONTH field range from 0 to 6. Week 1 of a month (the days with WEEK_OF_MONTH = 1) is the earliest set of at least getMinimalDaysInFirstWeek() contiguous days in that month, ending on the day before getFirstDayOfWeek(). Unlike week 1 of a year, week 1 of a month may be shorter than 7 days, need not start on getFirstDayOfWeek(), and will not include days of the previous month. Days of a month before week 1 have a WEEK_OF_MONTH of 0.
For example, if getFirstDayOfWeek() is SUNDAY and getMinimalDaysInFirstWeek() is 4, then the first week of January 1998 is Sunday, January 4 through Saturday, January 10. These days have a WEEK_OF_MONTH of 1. Thursday, January 1 through Saturday, January 3 have a WEEK_OF_MONTH of 0. If getMinimalDaysInFirstWeek() is changed to 3, then January 1 through January 3 have a WEEK_OF_MONTH of 1.
Example:

import java.util.Calendar;
import java.util.GregorianCalendar;

public class DateAndTime {

          public static void main(String args[]) {
                      GregorianCalendar today = new GregorianCalendar();

                          int todayMonth = today.get(Calendar.MONTH);

                              int todayDayOfMonth = today.get(Calendar.DAY_OF_MONTH);

                                  int todayYear = today.get(Calendar.YEAR);

                                      int todayDayOfYear = today.get(Calendar.DAY_OF_YEAR);
 
                                      int hour=today.get(Calendar.HOUR);
 
                                      int minutes=today.get(Calendar.MINUTE);
 
                                      int seconds=today.get(Calendar.SECOND);
                                      System.out.println(todayDayOfMonth+"-"+todayMonth+"-"+todayYear+" "+hour+":"+minutes+":"+seconds);
          }
}
                      
                                                                                                                                   
            
 

Tuesday, November 2, 2010

Java Inheritance

Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance the most commonly used key words would beextends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how theextends keyword is used to achieve inheritance.
public class Animal{
}

public class Mammal extends Animal{
}

public class Reptile extends Animal{
}

public class Dog extends Mammal{
}
Now based on the above example, In Object Oriented terms following are true:
  • Animal is the superclass of Mammal class.
  • Animal is the superclass of Reptile class.
  • Mammal and Reptile are sub classes of Animal class.
  • Dog is the subclass of both Mammal and Animal classes.
Now if we consider the IS-A relationship we can say:
  • Mammal IS-A Animal
  • Reptile IS-A Animal
  • Dog IS-A Mammal
  • Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.

Example:

public class Dog extends Mammal{
   public static void main(String args[]){

      Animal a = new Animal();
      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}
This would produce following result:
true
true
true
Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended.

Example:

public interface Animal {}

public class Mammal implements Animal{
}

public class Dog extends Mammal{
}

The instanceof Keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal
interface Animal{}

class Mammal implements Animal{}

class Dog extends Mammal{
   public static void main(String args[]){

      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
} 
This would produce following result:
true
true
true