Thursday, May 28, 2009

Setting the CLASSPATH System Variable  

0 comments

To display the current CLASSPATH variable, use these commands in Windows and Unix (Bourne shell): 
In Windows: C:\> set CLASSPATH

In Unix: % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use these commands: 

In Windows: C:\> set CLASSPATH=
In Unix: % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable, use these commands (for example): 

In Windows: C:\> set CLASSPATH=C:\users\george\java\classes
In Unix: % CLASSPATH=/home/george/java/classes; export CLASSPATH

Monday, April 6, 2009

inheritance diagrametically  

0 comments

Diagram 1 :-


                                           In this diagram PERSON is the base class, and OLD_PERSON, YOUNG_PERSON both are the child classes to PERSON and YOUNG_PERSON have the three more childs.

                                           Here the YOUNG_PERSON class and OLD_PERSON class both are having the qualities (here data members and member function) of PERSON class, But all PERSON's are not having both qualities.

                                           So we can call PERSON class data members and member function from YOUNG_PERSON and OLD_PERSON classes.

Diagram 2 :-

Diagram 3 :-



                                                  Here CheckingAccount and SavingAccount both are have the parent class is BankAccount. Here every BankAccount have the function of to use both CheckingAccount and SavingAccount classes. But Bank Account are not having the fuctions of all function on Checking Account or SavingAccount.

                                                 The BankAccount, Client and Bank all are the child classes of Object calss,So Object class is the base class of these three classes

Monday, March 9, 2009

Managing Source and Class Files  

0 comments

            Many implementations of the Java platform rely on hierarchical file systems to manage source and class files, although The Java Language Specification does not require this. The strategy is as follows. 

Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java. For example: 
              // in the Rectangle.java file 
              package graphics;
              public class Rectangle() {
               . . . 
              }

Then, put the source file in a directory whose name reflects the name of the package to which the type belongs:               .....\graphics\Rectangle.java

The qualified name of the package member and the path name to the file are parallel, assuming the Microsoft Windows file name separator backslash (for Unix, use the forward slash). class name graphics.Rectangle
pathname to file              graphics\Rectangle.java


As you should recall, by convention a company uses its reversed Internet domain name for its package names. The Example company, whose Internet domain name is example.com, would precede all its package names with com.example. Each component of the package name corresponds to a subdirectory. So, if the Example company had a com.example.graphics package that contained a Rectangle.java source file, it would be contained in a series of subdirectories like this:       ....\com\example\graphics\Rectangle.java

When you compile a source file, the compiler creates a different output file for each type defined in it. The base name of the output file is the name of the type, and its extension is .class. For example, if the source file is like this 
                   // in the Rectangle.java file
                   package com.example.graphics;
                   public class Rectangle{
                    . . . 
                   }

                  class Helper{
                   . . . 
                  }

then the compiled files will be located at: 
\com\example\graphics\Rectangle.class
\com\example\graphics\Helper.class

Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as: 
\sources\com\example\graphics\Rectangle.java

\classes\com\example\graphics\Rectangle.class
By doing this, you can give the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses. 

The full path to the classes directory, \classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path. For example, if 
\classes
is your class path, and the package name is 
com.example.graphics,

then the compiler and JVM look for .class files in 

\classes\com\example\graphics.

A class path may include several paths, separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in your class path.

Setting the CLASSPATH System Variable


To display the current CLASSPATH variable, use these commands in Windows and Unix (Bourne shell): 
In Windows: C:\> set CLASSPATH
In Unix: % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use these commands: 
In Windows: C:\> set CLASSPATH=
In Unix: % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable, use these commands (for example): 
In Windows: C:\> set CLASSPATH=C:\users\george\java\classes
In Unix: % CLASSPATH=/home/george/java/classes; export CLASSPATH

Using Package Members  

0 comments

To use a public package member from outside its package, you must do one of the following: 

  • Refer to the member by its fully qualified name 
  • Import the package member 
  • Import the member's entire package 

Each is appropriate for different situations, as explained in the sections that follow.

So far, most of the examples in this tutorial have referred to types by their simple names, such as Rectangle and StackOfInts. You can use a package member's simple name if the code you are writing is in the same package as that member or if that member has been imported. 

However, if you are trying to use a member from a different package and that package has not been imported, you must use the member's fully qualified name, which includes the package name. Here is the fully qualified name for the Rectangle class declared in the graphics package in the previous example. 


                              graphics.Rectangle

Importing a Package Member

Here's how you would import the Rectangle class from the graphics package created in the previous section.

                 import graphics.Rectangle;

Importing an Entire Package

To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character. 

                              import graphics.*;






Creating a Package  

0 comments

             To create a package, you choose a name for the package (naming conventions are discussed in the next section) and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package. 

The package statement (for example, package graphics;) must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

// only comment can be here
package world;  // package creation

public class HelloWorld {
  public static void main(String[] args) {
  System.out.println("Hello World");
  }
}

                   If you do not use a package statement, your type ends up in an unnamed package. Generally speaking, an unnamed package is only for small or temporary applications or when you are just beginning the development process. Otherwise, classes and interfaces belong in named packages.

Type Erasure  

0 comments

                     When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

public class MyClass {
  public static void myMethod(Object item) {
  if (item instanceof E) { //Compiler error
  ...
  }
  E item2 = new E(); //Compiler error
  E[] iArray = new E[10]; //Compiler error
  E obj = (E)new Object(); //Unchecked cast warning
  }
}
--------------------------------------------------

public class WarningDemo {
  public static void main(String[] args){
  Box bi;
  bi = createBox();
  }

  static Box createBox(){
  return new Box();
  }
}
Recompiling with -Xlint:unchecked reveals the following additional information: 
WarningDemo.java:4: warning: [unchecked] unchecked conversion
found : Box
required: Box
  bi = createBox();
  ^
1 warning

Wildcards  

0 comments

               

               In generics, an unknown type is represented by the wildcard character "?".

                           Cage someCage = ...;
                       Read "? extends Animal" as "an unknown type that is a subtype of Animal, possibly Animal itself", which boils down to "some kind of animal". This is an example of a bounded wildcard, where Animal forms the upper bound of the expected type. If you're asked for a cage that simply holds some kind of animal, you're free to provide a lion cage or a butterfly cage.

                        It's also possible to specify a lower bound by using the super keyword instead of extends. The code , therefore, would be read as "an unknown type that is a supertype of Animal, possibly Animal itself". You can also specify an unknown type with an unbounded wilcard, which simply looks like . An unbounded wildcard is essentially the same as saying .

                        you could house your animals in their individual cages, as shown earlier, and invoke this method first for the lions and then for the butterflies: 
 feedAnimals(lionCage);
 feedAnimals(butterflyCage);
Or, you could choose to combine your animals in the all-animal cage instead: 
 feedAnimals(animalCage);

Subtyping  

0 comments

you can assign an Integer to an Object, since Object is one of Integer's supertypes: 
  Object someObject = new Object();
  Integer someInteger = new Integer(10);
  someObject = someInteger; // OK
In object-oriented terminology, this is called an "is a" relationship. Since an Integer is a kind of Object, the assignment is allowed. But Integer is also a kind of Number, so the following code is valid as well: 
  public void someMethod(Number n){
  // method body omitted 
  }

  someMethod(new Integer(10)); // OK
  someMethod(new Double(10.1)); // OK

Bounded Type Parameters  

0 comments

There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. 

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). 

/**
 * This version introduces a bounded type parameter.
 */
public class Box {

  private T t;  

  public void add(T t) {
  this.t = t;
  }

  public T get() {
  return t;
  }

  public void inspect(U u){
  System.out.println("T: " + t.getClass().getName());
  System.out.println("U: " + u.getClass().getName());
  }

  public static void main(String[] args) {
  Box integerBox = new Box();
  integerBox.add(new Integer(10));
  integerBox.inspect("some text"); // error: this is still String! 
  }
}
By modifying our generic method to include this bounded type parameter, compilation will now fail, since our invocation of inspect still includes a String: 
Box.java:21: inspect(U) in Box cannot
  be applied to (java.lang.String)
  integerBox.inspect("10");
  ^
1 error

To specify additional interfaces that must be implemented, use the & character, as in: 

Generic Methods and Constructors  

0 comments

                

Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared. 

/**
 * This version introduces a generic method.
 */
public class Box {

  private T t;  

  public void add(T t) {
  this.t = t;
  }

  public T get() {
  return t;
  }

  public void inspect(U u){
  System.out.println("T: " + t.getClass().getName());
  System.out.println("U: " + u.getClass().getName());
  }

  public static void main(String[] args) {
  Box integerBox = new Box();
  integerBox.add(new Integer(10));
  integerBox.inspect("some text");
  }
}
Here we've added one generic method, named inspect, that defines one type parameter, named U. This method accepts an object and prints its type to standard output. For comparison, it also prints out the type of T. For convenience, this class now also has a main method so that it can be run as an application. 

The output from this program is: 
T: java.lang.Integer
U: java.lang.String
         

Type Parameter Naming Conventions  

0 comments

By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name. 

The most commonly used type parameter names are: 
E - Element (used extensively by the Java Collections Framework) 
K - Key 
N - Number 
T - Type 
V - Value 
S,U,V etc. - 2nd, 3rd, 4th types 
You'll see these names used throughout the Java SE API and the rest of this tutorial.

Generic Types  

0 comments

Generic Types:                 

    Just we update our Box class to use generics. We'll first create a generic type declaration by changing the code "public class Box" to "public class Box"; this introduces one type variable, named T, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There's nothing particularly complex about this concept. In fact, it's quite similar to what you already know about variables in general. Just think of T as a special kind of variable, whose "value" will be whatever type you pass in; this can be any class type, any interface type, or even another type variable. It just can't be any of the primitive data types. In this context, we also say that T is a formal type parameter of the Box class. 

/**
 * Generic version of the Box class. 
 */
public class Box {

  private T t; // T stands for "Type"  

  public void add(T t) {
  this.t = t;
  }

  public T get() {
  return t;
  }
}

As you can see, we've replaced all occurrences of Object with T. To reference this generic class from within your own code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:

generics introduction  

0 comments

Generics:                   

   Generics add stability to your code by making more of your bugs detectable at compile time. Some programmers choose to learn generics by studying the Java Collections Framework; after all, generics are heavily used by those classes. However, since we haven't yet covered collections, this chapter will focus primarily on simple "collections-like" examples that we'll design from scratch. This hands-on approach will teach you the necessary syntax and terminology while demonstrating the various kinds of problems that generics were designed to solve. 

A Simple Class

                       Box class need only provide two methods: add, which adds an object to the box, and get, which retrieves it:

 public class Box {

  private Object object;

  public void add(Object object) {
  this.object = object;
  }

  public Object get() {
  return object;
  }
  }

 

public class BoxDemo1 {

  public static void main(String[] args) {

  // ONLY place Integer objects into this box!
  Box integerBox = new Box();

  integerBox.add(new Integer(10));
  Integer someInteger = (Integer)integerBox.get();
  System.out.println(someInteger);
  }
}
The BoxDemo1 program creates an Integer object, passes it to add, then assigns that same object to someInteger by the return value of get. It then prints the object's value (10) to standard output. We know that the cast from Object to Integer is correct because we've honored the "contract" specified in the comment. But remember, the compiler knows nothing about this — it just trusts that our cast is correct. Furthermore, it will do nothing to prevent a careless programmer from passing in an object of the wrong type, such as String: 

public class BoxDemo2 {

  public static void main(String[] args) {

  // ONLY place Integer objects into this box!
  Box integerBox = new Box();

  // Imagine this is one part of a large application
  // modified by one programmer. 
  integerBox.add("10"); // note how the type is now String

  // ... and this is another, perhaps written
  // by a different programmer
  Integer someInteger = (Integer)integerBox.get();
  System.out.println(someInteger);
  }
}

Saturday, February 14, 2009

What is the difference between structures and enumeration?  

0 comments

                    Unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly contains the data of the struct, whereas a variable of a class type contains a reference to the data. They are derived from System.ValueType class.


Enum->An enum type is a distinct type that declares a set of named constants.They� are strongly typed constants. They are unique types that allow to declare symbolic names to integral values. Enums are value types, which means they contain their own value, can’t inherit or be inherited from and assignment copies the value of one enum to another.

public enum Grade

What are Vector, Hashtable, LinkedList and Enumeration?  

0 comments

Vector : The Vector class provides the capability to implement a growable array of objects.Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash codes are integer values that identify objects.


LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations.


Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.

What is an enumeration ?  

0 comments

                                       An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

Friday, January 30, 2009

Abstract Methods and Classes  

0 comments

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. 

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: 
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in: 
public abstract class GraphicObject {
  // declare fields
  // declare non-abstract methods
  abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.


Abstract Classes versus Interfaces:


Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead. 


Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example. 

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

When an Abstract Class Implements an Interface:


In the section on Interfaces , it was noted that a class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface methods, provided that the class is declared to be abstract. For example, 
abstract class X implements Y {
  // implements all but one method of Y
}

class XX extends X {
  // implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y. 

Class Members:


An abstract class may have static fields and static methods. You can use these static members with a class reference—for example, AbstractClass.staticMethod()—as you would with any other class.


Writing Final Classes and Methods  

0 comments

You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final. 

You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final: 
class ChessAlgorithm {
  enum ChessPlayer { WHITE, BLACK }
  ...
  final ChessPlayer getFirstPlayer() {
  return ChessPlayer.WHITE;
  }
  ...
}
Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. 

Note that you can also declare an entire class final — this prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class.

Object as a Superclass  

0 comments

The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the instance methods of Object. You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class. The methods inherited from Object that are discussed in this section are: 
protected Object clone() throws CloneNotSupportedException
  Creates and returns a copy of this object. 
public boolean equals(Object obj)
  Indicates whether some other object is "equal to" this one. 
protected void finalize() throws Throwable
  Called by the garbage collector on an object when garbage
  collection determines that there are no more references to the object 
public final Class getClass()
  Returns the runtime class of an object. 
public int hashCode()
  Returns a hash code value for the object. 
public String toString()
  Returns a string representation of the object. 


The notify, notifyAll, and wait methods of Object all play a part in synchronizing the activities of independently running threads in a program, which is discussed in a later lesson and won't be covered here. There are five of these methods: 
public final void notify() 
public final void notifyAll() 
public final void wait() 
public final void wait(long timeout) 

public final void wait(long timeout, int nanos)

Note: There are some subtle aspects to a number of these methods, especially the clone method. You can get information on the correct usage of these methods in the book Effective Java by Josh Bloch.

Keyword super  

0 comments

Accessing Superclass Members
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass: 
public class Superclass {

  public void printMethod() {
  System.out.println("Printed in Superclass.");
  }
}
Here is a subclass, called Subclass, that overrides printMethod(): 
public class Subclass extends Superclass {

  public void printMethod() { //overrides printMethod in Superclass
  super.printMethod();
  System.out.println("Printed in Subclass");
  }
  public static void main(String[] args) {
   
  Subclass s = new Subclass();
  s.printMethod(); 
  }

}
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following: 
Printed in Superclass.
Printed in Subclass
Subclass Constructors
The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example that MountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own: 
  public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {
  super(startCadence, startSpeed, startGear);
  seatHeight = startHeight;
  } 
Invocation of a superclass constructor must be the first line in the subclass constructor. 

The syntax for calling a superclass constructor is 
super();  
--or--
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.


Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

c and Hiding Methods  

0 comments

Instance Methods


An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method. 

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type. 

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information on @Override, see Annotations. 

Class Methods


If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. 

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. Let's look at an example that contains two classes. The first is Animal, which contains one instance method and one class method: 
public class Animal {
  public static void testClassMethod() {
  System.out.println("The class method in Animal.");
  }
  public void testInstanceMethod() {
  System.out.println("The instance method in Animal.");
  }
}
The second class, a subclass of Animal, is called Cat: 
public class Cat extends Animal {
  public static void testClassMethod() {
  System.out.println("The class method in Cat.");
  }
  public void testInstanceMethod() {
  System.out.println("The instance method in Cat.");
  }

  public static void main(String[] args) {
  Cat myCat = new Cat();
  Animal myAnimal = myCat;
  Animal.testClassMethod();
  myAnimal.testInstanceMethod();
  }
}
The Cat class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Cat and calls testClassMethod() on the class and testInstanceMethod() on the instance. 

The output from this program is as follows: 
The class method in Animal.
The instance method in Cat.
As promised, the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.

Inheritance  

0 comments

Definitions: 


 

A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). 

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object. 

Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.

Summary of Interfaces  

0 comments

An interface defines a protocol of communication between two objects. 

An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions. 

A class that implements an interface must implement all the methods declared in the interface. 

An interface name can be used anywhere a type can be used.

Rewriting Interfaces  

0 comments

Consider an interface that you have developed called DoIt: 
public interface DoIt {
  void doSomething(int i, double x);
  int doSomethingElse(String s);
}
Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: 
public interface DoIt {

  void doSomething(int i, double x);
  int doSomethingElse(String s);
  boolean didItWork(int i, double x, String s);
   
}
If you make this change, all classes that implement the old DoIt interface will break because they don't implement the interface anymore. Programmers relying on this interface will protest loudly. 

Try to anticipate all uses for your interface and to specify it completely from the beginning. Given that this is often impossible, you may need to create more interfaces later. For example, you could create a DoItPlus interface that extends DoIt: 
public interface DoItPlus extends DoIt {

  boolean didItWork(int i, double x, String s);
   
}
Now users of your code can choose to continue to use the old interface or to upgrade to the new interface

Implementing an Interface  

0 comments

A Sample Interface, Relatable


Consider an interface that defines how to compare the size of objects. 

public interface Relatable {
 
  // this (object calling isLargerThan) and
  // other must be instances of the same class
  // returns 1, 0, -1 if this is greater

  // than, equal to, or less than other

  public int isLargerThan(Relatable other);

   

Implementing the Relatable Interface
Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable. 
public class RectanglePlus implements Relatable {
  public int width = 0;
  public int height = 0;
  public Point origin;

  // four constructors
  public RectanglePlus() {
 origin = new Point(0, 0);
  }
  public RectanglePlus(Point p) {
 origin = p;
  }
  public RectanglePlus(int w, int h) {
 origin = new Point(0, 0);
 width = w;
 height = h;
  }
  public RectanglePlus(Point p, int w, int h) {
 origin = p;
 width = w;
 height = h;
  }

  // a method for moving the rectangle
  public void move(int x, int y) {
 origin.x = x;
 origin.y = y;
  }

  // a method for computing the area of the rectangle
  public int getArea() {
 return width * height;
  }
   
  // a method to implement Relatable
  public int isLargerThan(Relatable other) {
  RectanglePlus otherRect = (RectanglePlus)other;
  if (this.getArea() < otherRect.getArea())
  return -1;
  else if (this.getArea() > otherRect.getArea())
  return 1;
  else
  return 0;  
  }
}
Because RectanglePlus implements Relatable, the size of any two RectanglePlus objects can be compared.

defining an interface  

0 comments

An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body. For example: 
public interface GroupedInterface extends Interface1,
  Interface2, Interface3 {

  // constant declarations
  double E = 2.718282; // base of natural logarithms

  // method signatures
  void doSomething (int i, double x);
  int doSomethingElse(String s);

}
The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface. 

An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.

what is interface?  

0 comments

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts. 

For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning Satellite) position data and wireless transmission of traffic conditions and use that information to drive the car. 

The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces

0 comments

The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.

An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnDelims flag having the value true or false:
If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters.
If the flag is true, delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.

A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed.

A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

The following is one example of the use of the tokenizer. The code:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}


prints the following output:
this
is
a
test


StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

The following example illustrates how the String.split method can be used to break up a string into its basic tokens:
String[] result = "this is a test".split("\\s");
for (int x=0; x System.out.println(result[x]);


prints the following output:
this
is
a
test

this is available Since: JDK1.0

Wednesday, January 28, 2009

IO system writer class  

0 comments

IO system reader class  

0 comments

IO system output class  

0 comments

IO system input class  

0 comments


Wrapper Classes -- methods with examples  

0 comments

There are some of the methods of the Wrapper class which are used to manipulate the data. Few of them are given below:

1. add(int, Object): Learn to insert an element at the specified position.

2. add(Object): Learn to insert an object at the end of a list.

3. addAll(ArrayList): Learn to insert an array list of objects to another list.

4. get(): Learn to retrieve the elements contained with in an ArrayList object.

5. Integer.toBinaryString(): Learn to convert the Integer type object to a String object.

6. size(): Learn to get the dynamic capacity of a list.

7. remove(): Learn to remove an element from a particular position specified by a index value. 

8. set(int, Object): Learn to replace an element at the position specified by a index value.

Wrapper Classes  

0 comments

Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper 
classes, because they "wrap" the primitive data type into an object of that class. So, there is an 
Integer class that holds an int variable, there is a Double class that holds a double 
variable, and so on. The wrapper classes are part of the java.lang package, which is imported 
by default into all Java programs. The following discussion focuses on the Integer wrapper 
class, but applies in a general sense to all eight wrapper classes. Consult the Java API 
documentation for more details. 
The following two statements illustrate the difference between a primitive data type and an object 
of a wrapper class: 
int x = 25; 
Integer y = new Integer(33); 
The first statement declares an int variable named x and initializes it with the value 25. The 
second statement instantiates an Integer object. The object is initialized with the value 33 and 
a reference to the object is assigned to the object variable y. The memory assignments from 
these two statements are visualized in Figure 1. 


Clearly x and y differ by more than their values: x is a variable that holds a value; y is an object 
variable that holds a reference to an object. As noted earlier, data fields in objects are not, in 
general, directly accessible. So, the following statement using x and y as declared above is not 
allowed: 
int z = x + y; // wrong! 
The data field in an Integer object is only accessible using the methods of the Integer class.  
One such method — the intValue() method — returns an int equal to the value of the 
object, effectively "unwrapping" the Integer object: 
int z = x + y.intValue(); // OK! 
Note the format of the method call. The intValue() method is an instance method, because it 
is called through an instance of the class — an Integer object. The syntax uses dot notation, 
where the name of the object variable precedes the dot. 
Some of Java's classes include only instance methods, some include only class methods, some 
include both. The Integer class includes both instance methods and class methods. The class 
methods provide useful services; however, they are not called through instances of the class.  
But, this is not new. We met a class method of the Integer class earlier. The statement  
int x = Integer.parseInt("1234"); 
converts the string "1234" into the integer 1,234 and assigns the result to the int variable x.  
The method parseInt() is a class method. It is not called through an instance of the class.  

Although dot notation is used above, the term "Integer." identifies the class where the method 
is defined, rather than name of an Integer object. This is one of the trickier aspects of 
distinguishing instance methods from class methods. For an instance method, the dot is preceded 
by the name of an object variable. For a class method, the dot is preceded by the name of a class.  
It is interesting that the parseInt() method accepts a String argument and returns an int.  
Neither the argument nor the returned value is an Integer object. So, the earlier comment that 
class methods "provide useful services" is quite true. They do not operate on instance variables; 
they provide services that are of general use. The parseInt() method converts a String to 
an int, and this is a useful service — one we have called upon in previous programs. 
Another useful Integer class method is the toString() method. The following statement 
String s = Integer.toString(1234); 
converts the int constant 1,234 to a String object and returns a reference to the object. We 
have already met this method through the following shorthand notation: 
String s = "" + 1234; 

The most common methods of the Integer wrapper class are summarized in Table 1. Similar 
methods for the other wrapper classes are found in the Java API documentation. 
Table 1. Methods of the Integer Wrapper Class 
Method Purpose 
Constructors 
Integer(i)  constructs an Integer object equivalent to the integer i 
Integer(s)  constructs an Integer object equivalent to the string s 
Class Methods 
parseInt(s)  returns a signed decimal integer value equivalent to string s 
toString(i)   returns a new String object representing the integer i 
Instance Methods 
byteValue()   returns the value of this Integer as a byte 
doubleValue()   returns the value of this Integer as an double 
floatValue()   returns the value of this Integer as a float 
intValue()   returns the value of this Integer as an int 
longValue()   returns the value of this Integer as a long 
shortValue()   returns the value of this Integer as a short 

In the descriptions of the instance methods, the phrase "this Integer" refers to the instance 
variable on which the method is acting. For example, if y is an Integer object variable, the 
expression y.doubleValue() returns the value of "this Integer", or y, as a double.

Monday, January 19, 2009

past 13 years, Java has changed our world  

0 comments

For the past 13 years, Java has changed our world . . . and our expectations..

Today, with technology such a part of our daily lives, we take it for granted that we can be connected and access applications and content anywhere, anytime. Because of Java, we expect digital devices to be smarter, more functional, and way more entertaining.

In the early 90s, extending the power of network computing to the activities of everyday life was a radical vision. In 1991, a small group of Sun engineers called the "Green Team" believed that the next wave in computing was the union of digital consumer devices and computers. Led by James Gosling, the team worked around the clock and created the programming language that would revolutionize our world – Java.

The Green Team demonstrated their new language with an interactive, handheld home-entertainment controller that was originally targeted at the digital cable television industry. Unfortunately, the concept was much too advanced for the them at the time. But it was just right for the Internet, which was just starting to take off. In 1995, the team announced that the Netscape Navigator Internet browser would incorporate Java technology.

Today, Java not only permeates the Internet, but also is the invisible force behind many of the applications and devises that power our day-to-day lives. From mobile phones to handheld devises, games and navigation systems to e-business solutions, Java is everywhere!

History by years  

0 comments

The Java History Timeline

1991 

The Green Project Begins
MS DOS is the dominant operating system
Cell phones weigh half a pound
"Biosphere 2" project begins

1992

"Oak" is the language 
*7 Debuts
"Duke" is featured in the Interface
Johnny Carson signs off "The Tonight Show" on NBC

1993 

The Green Project becomes FirstPerson
Mosaic v1.0 is released
"Cheers" ends an 11-year run

1994 

WebRunner released — the first browser that supports moving objects and dynamic executable content
The Apple QuickTake 100, the first consumer digital camera, goes on sale for less than $1,000 
"Friends" debuts on NBC

1995 

Java technology released to a select group on the Web site wicked.neato.org
The San Jose Mercury News runs a front-page article about Java technology
Name changed from "Oak" to "Java"
Announced at Sun World -- Java technology is officially born

1996 

The first JavaOne Developer Conference
JDKtm 1.0 software is released
Chess computer Deep Blue defeats Garry Kasparov for the first time
"Dolly" the first cloned sheep is born

1997 

Over 220,000 downloads of JDK 1.1 software occur in just three weeks
JavaOne draws 8,000 attendees, becoming the world's largest developer conference
Java Card 2.0 platform is unveiled
43% of U.S. families own a computer

1998 

JDK 1.1 release downloads top 2 million
Visa launches world's first smart card based on Java Card technology
The Java Community Process (JCP) program formalized
"Who Wants to Be a Millionaire?" premieres in the U.K

1999 

Java 2 platform source code is released
JavaOne draws 20,000
J2EE beta software is released
"Star Wars Episode I: The Phantom Menace" released

2000 

Over 400 Java User Groups are established worldwide
Java Developer Connection program tops 1.5 million members
Steve Jobs joins Scott McNealy on stage at JavaOne to announce a major commitment by Apple in support of Java technology
Heavy Metal band Metallica sues Napster for copyright violations

2001 

First international JavaOne conference in Yokohama Japan
Over 1 million downloads of the Java Platform, Enterprise Edition (Java EE) SDK
Google Inc. PageRank search algorithm patent awarded
"The Lord of the Rings: The Fellowship of the Ring" is released

2002 

J2EE SDK downloads reach 2 million
78% of executives view J2EE technology as the most effective platform for building and deploying Web services
The Euro is introduced
"The Osbournes" becomes a surprise hit on MTV

2003 

Java technology runs in almost 550 million desktops
Almost 75% of professional developers use Java programming language as their primary development language
Commercial Voice-Over-Internet (VoiP) phone service begins
"The Da Vinci Code" is published

2004 

Java 2 Platform, Standard Edition 5 (Project Tiger) is released
The Java technology-powered Mars Rover (Spirit) touches down on Mars
Sun Java Studio Creator is launched

2005 

Java technology celebrates its 10th birthday
Approximately 4.5 million developers use Java technology
Over 2.5 billion Java technology-enabled devices are available
java.com bundles the Google Toolbar with the JRE download

2006 

Rich Green announces at the JavaOne 2006 Conference that it's not a matter of when Sun will open source Java technology, but how. The NetBeans IDE 5.0 is released. Sun open-sourced Java EE components as the Glassfish Project to java.net. Java SE and ME initial components are released as open source. Pirates of the Caribbean: Dead Man's Chest is released.

Extension Factory Builder