Total Pageviews

Monday, April 23, 2012

EX 5 CATFISH SIMULATION

import java.util.*;
import java.lang.Object;
import java.util.Random;

/*
 *
 */

/**
 * Basic Catfish - simulates a catfish - can swim and consume
 * energy in the process.

 */
public class Catfish extends LivingBeing
 {

    /**
     * The catfish is born "alive".
     * Then it dies, becoming a corpse.
     */
    private String ALIVE = "alive";


    /**
     * The catfish is born "alive".
     * Then it dies, becoming a "dead" corpse.
     */
    private String DEAD = "dead";



    /**
     * Energy needed to swim in a block of time.
     */
    private int ENERGY_TO_SWIM = 2;
       
   
   
    /**
     * Row-wise location of the catfish
     */
    private int row;


    /**
     * Column-wise location of the catfish
     */
    private int column;


    /**
     * Image of the catfish - is really a filename
     */
    private String imageFileName;

   
    /**
     * Is the catfish dead or alive?
     */
    private String deadOrAlive;
   

    /**
     * Age expressed as blocks of time lived
     */
    private int age;
   
    private int energy;

    private Random aleatorio;

    /**
     * The simulation to which this catfish belongs.
     * This is needed so the catfish can send a message
     * to simulation.
     */
    private Simulation simulation;

   

    /**
     * Constructor. Initialize a catfish to start life at a specified
     * location with a specified energy. If location is out of bounds,
     * locate the catfish at the nearest edge.
     *
     * @param initialRow - the row at which the catfish is located
     * @param initialColumn - the column at which the catfish is located
     * @param initialSimulation - the simulation that the catfish belongs to
     */
    public Catfish(
        int initialRow,
        int initialColumn,
        Simulation initialSimulation) {

            simulation = initialSimulation;

            deadOrAlive = ALIVE;    

            age = 0;
            energy = 10;       
           
            imageFileName = "/Catfish-right.gif";   

            row = initialRow;
            column = initialColumn;
    }
   
    /**
     * Get the row at which the catfish is located
     *
     * @return - the row of the catfish's location.
     */       
    public int getRow() {
        return row;
    }

    /**
     * Get the column at which the catfish is located
     *
     * @return - the column of the catfish's location.
     */       
    public int getColumn() {
        return column;
    }


    /**
     * get filename of catfish image
     *
     * @return filename of Catfish image
     */
    public String getImage()
    {
        return imageFileName;
    }


    /**
     * Get the catfish's age
     *
     * @return the age of the catfish expressed in blocks of time
     */
    public int getAge() {
        return age;

        // Student:Please complete this method.
    }


    /**
     * Get the energy of the catfish
     *
     * @return current energy level of the catfish
     */
    public int getEnergy() {
        return energy;

        // Student:Please complete this method.
    }
   

    /**
     * Die: The Catfish dies.
     */
    public void die() {

        // Student:Please complete this method.   
        deadOrAlive = DEAD;

        // Set the deadOrAlive attribute to indicate that the catfish is dead.
    }



    /**
     * Is the catfish dead?
     *
     * @return <code>true</code> if dead. <code>false</code>, otherwise.
     */
    public boolean isDead() {


        if(deadOrAlive == DEAD)
            return true;
        else
            return false;
    }


   
    /**
     * Swim to a new location if possible.
     * Consumes some energy.
     */
    private void swimIfPossible() {


        // Student:Please complete this method.
        if (energy>=0){
            energy = energy - ENERGY_TO_SWIM;   
               
        aleatorio = simulation.getRand();
        row = aleatorio.nextInt(10);

        aleatorio = simulation.getRand();
        column = aleatorio.nextInt(10);

        }

   
        // Consume ENERGY_TO_SWIM units of energy to swim.


        // Check if there is any energy left after consumption.
        // Swim at random in one of four directions.
        // Assign a random row location for the Catfish as follows.
        //
        // (1) Send the "getRand" message to the "simulation" object to get a random number generator.
        // The "simulation" object is initialized in the constructor above.
        // (2) Send the "nextInt" message to the random number generator obtained above.
        //
        // The "nextInt" behavior returns an integer between 0(inclusive) and the integer specified as a parameter(exclusive).
        // Thus, specifiying a value of 10 to the "nextInt" behavior will return an integer between 0 and 9.
        //


        // Similarly, assign a random column location for the catfish
       
    }

   

    /**
     * Catfish lives its life. Dies if it has no energy left.
     */
    public void liveALittle() {

        // Student:Please complete this method.
       
        if (energy<=0)
        {
            die();
        }
        age=age + 1;

        // If there is no energy left, send a "die" message to this catfish
        swimIfPossible();
       

        // Increment the age of the Catfish by 1
       
        // Try to swim by sending a "swimIfPossible" message
       
    }
}

EX 4 CATFISH

  /**
     *Author :  SHADOW
     */

public class Catfish {

    /**
     * Location of the catfish - which column.
     */
    private int column = 1;

    /**
     * Energy level of catfish
     */
    private int energyLevel = 10;

    /**
     * Location of catfish - the column
     *
     * @return - an integer representing the column location of catfish.
     */
    public int getColumn() {
       
        return column;
    // Student: return the column value

    }

    /**
     * Swim one cell to the right by incrementing the value stored in column by 1.
     */
    public void swimRight() {
       
        if(column<10){
            column = column + 1;
        }
        energyLevel = energyLevel - 1;
    // Student: Increment the value stored in column attribute by 1 and
    // decrement the value stored in energyLevel by 1 if the
    // new value of column is less than or equal to 10.

    }

    /**
     * get the image of catfish
     *
     * @return a String indicating the filename of catfish image
     */
    public String getImage() {
       
        if(energyLevel<5)
        {
            return "/CatFish-tired.gif";
        }
        else
        {
            return "/CatFish.gif";
        }
    / Student: return the image filename that represents the catfish
    // The image of a tired catfish (a catfish with energyLevel less than 5)
    // is "/CatFish-tired.gif".
    // The iamge of a catfish that is not tired is "/CatFish.gif".


    }
}

PRACTICAL QUIZ 5 SHIPPING LABEL SERVLET

/**
 *  Author:    SHADOW
 *  Date: 3 FEB 2012
 *  Description:create a servlet that processes two values ​​obtained from a
        Web page and displays a response based on those values.
 *
 */
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Label extends HttpServlet {
    public void doPost(HttpServletRequest request,
                        HttpServletResponse response)
                        throws ServletException, IOException {

        /**
         *  Indicate the content type (for example, text/html),
         *  being returned by the response
         */
            response.setContentType("text/html");

        /**
         *     Retrieve an output stream to use to send data to the client
         */
            PrintWriter out = response.getWriter();

        /**
         *    Get the user input from the form 
         */
            String SenderName1 = request.getParameter("SenderName");
            String SenderStrtAddr1 = request.getParameter("SenderStrtAddr");   
            String SenderCityZip1 = request.getParameter("SenderCityZip");   
            String ReceiverName1 = request.getParameter("ReceiverName");       
            String ReceiverStrtAddr1  = request.getParameter("ReceiverStrtAddr");           
            String ReceiverCityZip1   = request.getParameter("ReceiverCityZip");
            String Destination1 = request.getParameter("destination");   
                           
           
        /**
         *     Construct the HTML response : start with the header
         */
        out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>");
        out.println("<HTML>");
        out.println("<HEAD><TITLE>ShippingLabelForm</TITLE></HEAD>");
        out.println("<BODY bgcolor='#1E90FF'>");
        out.println("<TABLE>");
        out.println("<tr>");
        out.println("<td>");

        /**
         *     Add the sender information
         */
        out.println("<B>From:-</B>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td>");
        out.println("<p>"  + SenderName1 + "</p>");
        out.println("<p>"  + SenderStrtAddr1 + "</p>");
        out.println("<p>"  + SenderCityZip1 + "</p>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");


        /**
         *     Add the image
         */

        out.println("<TD align='right' valign='top'>");   
        out.println("<IMG SRC = '/" + Destination1 + "'" +  "alt='" + Destination1 + "'>");


        out.println("</td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td>");
        out.println("</td>");
        out.println("<td>");

        /**
         *     Add the receiver information
         */
        out.println("<BR><BR><B>To:-</B>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");
        out.println("<td>");
        out.println("<p>"  + ReceiverName1 + "</p>");
        out.println("<p>"  + ReceiverStrtAddr1 + "</p>");
        out.println("<p>"  + ReceiverCityZip1 + "</p>");
        out.println("</td>");
        out.println("<td>");
        out.println("</td>");
        out.println("</tr>");

        /**
         *    End with the footer
         */
        out.println("</table>");
        out.println("</body>");
        out.println("</html>");
    } // end-doPost

}

PRACTICAL QUIZ 4 MOVE CATFISH RIGHT

public class Catfish {

    /** Location of the catfish - which column. */
     */
    private int column = 1;

    /**
     * Location of catfish - the column
     *
     * @return - an integer representing the column location of catfish.
     */
    public int getColumn() {
    return column;
    // Student: return the column value

    }

    /**
     * Swim one cell to the right by incrementing the value stored in column by 1.
     */
    public void swimRight() {
    column = column + 1;
    // Student: Increment the value stored in column attribute by 1.

    }
}

Wednesday, April 11, 2012

http://www.javabeginner.com/learn-java/java-constructors

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.


Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).


public class Cube1 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube1() {
  length = 10;
  breadth = 10;
  height = 10;
 }
 Cube1(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
 }
 public static void main(String[] args) {
  Cube1 cubeObj1, cubeObj2;
  cubeObj1 = new Cube1();
  cubeObj2 = new Cube1(10, 20, 30);
  System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
 }
}
 
 
 
 
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.



Below is an example showing the creation of Cube objects by using the new operator.
public class Cube {

 int length = 10;
 int breadth = 10;
 int height = 10;
 public int getVolume() {
  return (length * breadth * height);
 }
 public static void main(String[] args) {
  Cube cubeObj; // Creates a Cube Reference
  cubeObj = new Cube(); // Creates an Object of Cube
  System.out.println("Volume of Cube is : " + cubeObj.getVolume());
 }
}
 
 
 
 
 

Method Overloading

Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call
Below is an example of a class demonstrating Method Overloading


public class MethodOverloadDemo {

 void sumOfParams() { // First Version
  System.out.println("No parameters");
 }
 void sumOfParams(int a) { // Second Version
  System.out.println("One parameter: " + a);
 }
 int sumOfParams(int a, int b) { // Third Version
  System.out.println("Two parameters: " + a + " , " + b);
  return a + b;
 }
 double sumOfParams(double a, double b) { // Fourth Version
  System.out.println("Two double parameters: " + a + " , " + b);
  return a + b;
 }
 public static void main(String args[]) {
  MethodOverloadDemo moDemo = new MethodOverloadDemo();
  int intResult;
  double doubleResult;
  moDemo.sumOfParams();
  System.out.println();
  moDemo.sumOfParams(2);
  System.out.println();
  intResult = moDemo.sumOfParams(10, 20);
  System.out.println("Sum is  " + intResult);
  System.out.println();
  doubleResult = moDemo.sumOfParams(1.1, 2.2);
  System.out.println("Sum is  " + doubleResult);
  System.out.println();
 }
} 



JAVA INHERITANCE

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.


class Box {

 double width;
 double height;
 double depth;
 Box() {
 }
 Box(double w, double h, double d) {
  width = w;
  height = h;
  depth = d;
 }
 void getVolume() {
  System.out.println("Volume is : " + width * height * depth);
 }
}

public class MatchBox extends Box {

 double weight;
 MatchBox() {
 }
 MatchBox(double w, double h, double d, double m) {
  super(w, h, d);
  weight = m;
 }
 public static void main(String args[]) {
  MatchBox mb1 = new MatchBox(10, 10, 10, 10);
  mb1.getVolume();
  System.out.println("width of MatchBox 1 is " + mb1.width);
  System.out.println("height of MatchBox 1 is " + mb1.height);
  System.out.println("depth of MatchBox 1 is " + mb1.depth);
  System.out.println("weight of MatchBox 1 is " + mb1.weight);
 }
}
 
 
OUTPUT
 
Volume is :   1000.0

width of MatchBox 1 is 10.0

height of MatchBox 1 is 10.0

depth   of MatchBox 1 is 10.0

weight of MatchBox 1 is 10.0
 
 
==================================================================================
 

this and super keywords

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.


class Counter {

 int i = 0;
 Counter increment() {
  i++;
  return this;
 }
 void print() {
  System.out.println("i = " + i);
 }
}

public class CounterDemo extends Counter {

 public static void main(String[] args) {
  Counter x = new Counter();
  x.increment().increment().increment().print();
 }
}
 
 
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0


=========================================================================

Abstract Class in java

Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.
Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.

Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.
A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful.


abstract class Vehicle {

 int numofGears;
 String color;
 abstract boolean hasDiskBrake();
 abstract int getNoofGears();
}


Example of a shape class as an abstract class
 
 
abstract class Shape {

 public String color;
 public Shape() {
 }
 public void setColor(String c) {
  color = c;
 }
 public String getColor() {
  return color;
 }
 abstract public double area();
}
 
 
====================================================================================
  
Java Method Overriding 
 
Method Overriding is achieved when a subclass overrides non-static methods defined in the superclass, following which the new method implementation in the subclass that is executed.
The new method definition must have the same method signature (i.e., method name and parameters) and return type. Only parameter types and return type are chosen as criteria for matching method signature. So if a subclass has its method parameters as final it doesn’t really matter for method overriding scenarios as it still holds true. The new method definition cannot narrow the accessibility of the method, but it can widen it. The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class
A program to explain the different concepts of Java Method Overridding


class CustomException extends Exception {

}

class SuperClassWithDifferentMethods {

 protected int field1 = 10;
 protected static int field2 = 20;
 public void method1() {
  System.out.println("SuperClassWithDifferentMethods.method1()");
 }
 public final void method2() {
  System.out.println("SuperClassWithDifferentMethods.method2()");
 }
 private void method3() {
  System.out.println("SuperClassWithDifferentMethods.method3()");
 }
 private final void method4() {
  System.out.println("SuperClassWithDifferentMethods.method4()");
 }
 public static void method5() {
  System.out.println("SuperClassWithDifferentMethods.method5()");
 }
 public void method6() throws Exception {
  System.out.println("SuperClassWithDifferentMethods.method6()");
 }
 private void method7() {
  System.out.println("SuperClassWithDifferentMethods.method7()");
 }
 private void method8(int x) {
  System.out.println("SuperClassWithDifferentMethods.method8()");
 }
 public static void method9() {
  System.out.println("SuperClassWithDifferentMethods.method9()");
 }
}

class OverridingClass extends SuperClassWithDifferentMethods {

 public int field1 = 30;
 public static int field2 = 40;
 public void method1() {
  System.out.println("OverridingClass.method1()");
 }
 //We can't override a public final method
 /*   public final void method2(){  

  System.out.println("OverridingClass.method2()");

  }*/
 private void method3() {
  System.out.println("OverridingClass.method3()");
 }
 private final void method4() {
  System.out.println("OverridingClass.method4()");
 }
 public static void method5() {
  System.out.println("OverridingClass.method5()");
 }
 public void method6() throws CustomException {
  System.out.println("OverridingClass.method6()");
 }
 public void method7() {
  System.out.println("OverridingClass.method7()");
 }
 public void method8(final int x) {
  System.out.println("OverridingClass.method8()");
 }
 //A static method cannot be overridden to be non-static instance method
 /*public void method9() {

  System.out.println("OverridingClass.method9()");

  }*/
}

public class MethodOverridingDemo {

 public static void main(String[] args) {
  OverridingClass oc1 = new OverridingClass();
  SuperClassWithDifferentMethods sc3 = new OverridingClass();
  oc1.method1();
  oc1.method2();
  //     Since its private, the below 2 methods are not visible
  /*     oc1.method3();

   oc1.method4();*/
  oc1.method5();
  try {
   oc1.method6();
  } catch (CustomException e) {
   e.printStackTrace();
  }
  oc1.method7();
  oc1.method8(100);
  System.out.println("oc1.field1 : " + oc1.field1);
  System.out.println("oc1.field2 : " + oc1.field2);
  System.out.println("sc3.field1 : " + sc3.field1);
  System.out.println("sc3.field2 : " + sc3.field2);
  sc3.method5();
  OverridingClass overClass = new OverridingClass();
 SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass;
  supClass.method5();
  supClass.method1();
 }
}
 
 
OUTPUT
 
OverridingClass.method1()

SuperClassWithDifferentMethods.method2()

OverridingClass.method5()

OverridingClass.method6()

OverridingClass.method7()

OverridingClass.method8()

oc1.field1   : 30

oc1.field2 : 40

sc3.field1 : 10

sc3.field2 :   20

SuperClassWithDifferentMethods.method5()

SuperClassWithDifferentMethods.method5()

OverridingClass.method1() 

Tuesday, April 10, 2012

overloading and overriding functions JAVA

class Base
{
void show()
{
System.out.println("Base class show function");
}
}
class Derive extends Base
{
void show()
{
super.show();  ------------------------------------------  IT CALLS THE BASE CLASS
System.out.println("Derive class show function");
}
}
class Example
{
public static void main(String args[])
{
Derive d=new Derive();
d.show();
Base b=new Base();
b.show();
}
}