Archive for August, 2009

run() is a method of the Thread class and the Runnable interface. It makes up the entire body of a thread. It is the only method in which a thread’s behavior can be implemented. The return type of the run() method must be void. In Java, it is quite easy to overload the run() method. However, the overloaded run() method will be ignored by the Thread class unless it is called by the programmer. The Thread class expects a run() method without any argument and will execute the overloaded method when the programmer calls the method by a separate call. For example:

  • Share/Bookmark

What is an instanceOf operator?

The instanceof operator is a binary operator that determines at runtime whether its left operand is an instance of its right operand.
Syntax:

obj instanceof type

where, obj (the left operand) must be an instance of a class and type (the right operand) may be a class, interface, or an array type. The instanceof operator evaluates to true if the left operand is of the specified type or can be cast to the specified type. Otherwise, it evaluates to false. The instanceof operator cannot be used with primitive data types.

  • Share/Bookmark

Generics

Generics is the most powerful feature of J2SE 5. It is most useful with collections such as Set and List. Collections are bound to contain a specific type of object. It allows a Java programmer to abstract over types. Therefore, if a programmer tries to insert any element other than the specified type into the collection, a compile time error will be thrown.

For example, a method declared as static void genericsexample(Collection c) will allow only strings to be inserted into the collection.

Generics has the following advantages:

  • No typecasting is required when an element is taken out of a collection.
  • Share/Bookmark

equals() method checks whether or not the instances refer to the same object. equals() method. It is defined in the java.lang.Object class. It is used to test the equality of objects.The following will occur if a program does not override the equals() method:

  1. Objects will not be used as a hashing key.
  2. Objects will not be considered equal.

Key rules:

  • The equals() method in the class Object uses only the == operator and the instanceof operator for comparisons. Unless a user overloads the equals() method, it will not compare the different objects because they are considered equal if their references refer to the same object.

  • Share/Bookmark