Archive for September, 2009

What is a thread priority?

Thread priorities are used by the scheduler to send a thread into the runnable state or the running state. The thread priorities are defined as static final variables within Thread. The higher priority threads are executed in preference to threads with lower priority.

When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread. The Thread class uses the following three constants to define the range of thread priorities:

  1. Thread.MIN_PRIORITY (1): Returns a thread to priority 1.
  2. Thread.NORM_PRIORITY (5): Returns a thread to priority 5.

  • Share/Bookmark

What is a constructor?

Constructors are typically used to create an object that is an instance of a class. A constructor is written by using the following general syntax:

[access modifier] class name([formal parameter list]) [throws clause] {
// Body of the constructor
}

where, the elements within square brackets are optional.

Although constructors look the same as methods, they are written by using the following conventions:

  1. A constructor is always given the name of the class in which it is defined.
  2. A constructor is always written without an explicit return type, not even void. This is because the implicit return type of a class constructor is the class itself.
  • Share/Bookmark

What is the comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.

The Comparable interface in the generic form is written as follows:

interface Comparable, where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows

int i = object1.compareTo(object2)

  • If object1 < object2: The value of i returned will be negative.
  • Share/Bookmark

What is an assertion?

An assertion is a statement that will be evauated during the execution of a program. It returns a boolean result. If the result is true, the code executes normally and no other action takes place. This confirms that the assumed statement is true. If the result is false, an AssertionError is thrown. The assertion condition is tested using the assert keyword. The assert keyword has the following two forms:

  • assert assertCondition;
    Here, assertCondition is an expression that evaluates to a boolean expression.
  • assert assertCondition : exp;
    Here, an expression exp is passed to the AssertionError in case an error is thrown at runtime.

An assertion can be enabled or disabled for a class or a package during runtime as follows:

  • Share/Bookmark