Page 252 - IT-802_class_12
P. 252
public static void main(String args[])
{
ExtendThread t1 =new ExtendThread();
t1.start();
}
Classes that you create by extending the Thread class cannot be extended further. The second method to create a
thread is to create a class that implements the Runnable interface and override the run() method. Implementing the
Runnable interface gives the flexibility to extend classes created by this method.
public class RunnableDemoimplements Runnable {
public void run()
{
System.out.println(“Created a Thread”); for (int count = 1; count <= 3; count++)
System.out.println(“Count=”+count);
}
}
To create a thread, first instantiate the class that implements the Runnable interface, then pass that object to a Thread
instance. As before, to start the execution of the thread call the start() method.
public static void main (String args[])
{
RunnableDemo r = new RunnableDemo();
Thread t1 = new Thread(r);
t1.start();
}
3.11 wraPPEr cLaSSES
By default, the primitive datatypes (such as int, float, and so on) of Java are passed by value and not by reference.
Sometimes, you may need to pass the primitive datatypes by reference. That is when you can use wrapper classes
provided by Java. These classes wrap the primitive datatype into an object of that class. For example, the Integer wrapper
class holds an int variable. Consider the following two declarations:
int a = 50; Integer b = new Integer(50);
In the first declaration, an int variable is declared and initialized with the value 50. In the second declaration, an object
of the class Integer is instantiated and initialized with the value 50. The variable a is a memory location and the variable
b is a reference to a memory location that holds an object of the class Integer.
Access to the value of a wrapper class object can be made through getter functions defined in the class. For example,
the intValue() member function of the Integer wrapper class allows access to the int value held in it.
int c = a + b.intValue();
Another useful function defined in the Integer wrapper class lets you convert a string into its integer value. The
following statement converts the string “3456” into the integer3456 and stores it in the int variable d.
int d = Integer.parseInt(“345”);
Note that the parseInt method is a static member of the Integer class and can be accessed using the name of the
class, that is, without creating an instance of the class. Similar to the parseInt method, the toString() method allows
conversion from an integer value to a String as shown in the statement below.
String s = Integer.toString(3456);
250 Touchpad Information Technology-XII

