Java MODULE-5
Java MODULE-5
MODULE 5
Syllabus:
• Multithreaded programming
• Enumerations
• Type Wrappers
• Auto Boxing
Multithreading
There are two distinct types of multitasking: Process-based and Thread-based. It is important to
understand the difference between two. The Program in execution is defined as Process. Thus, the process
based multi tasking is the feature that allows your computer to run two or more programs concurrently.
For example we are able to use the java compiler and text editor at the same time. Another example is, we
are able to hear the music and also able to get the print outs from the printer.
In the thread-based multitasking environment, the thread is the smallest unit of dispatchable code.
This means that the single program can contain two or more parts, each part of the program is called,
Thread. For example the text editor can be formatting the text and also printing the text. Although the
Java programs make use of the process-based multi tasking environments, but the process-based multi
tasking is not under the control of java, Where as the thread-based multitasking is under the control of
Java.
Process-Based Multitasking Thread-Based Multitasking
This deals with "Big Picture" This deals with Details
These are Heavyweight tasks These are Lightweight tasks
Inter-process communication is expensive and Inter-Thread communication is inexpensive.
limited
Context switching from one process to another is Context switching is low cost in terms of memory,
costly in terms of memory because they run on the same address space
This is not under the control of Java This is controlled by Java
//Body
} //ending
Multithreaded Program
A unique property of the java is that it supports the multithreading. Java enables us the multiple
flows of control in developing the program. Each separate flow of control is thought as tiny program
known as "thread" that runs in parallel with other threads. In the following example when the main
thread is executing, it may call thread A, as the Thread A is in execution again a call is mad for Thread
B. Now the processor is switched from Thread A to Thread B. After the task is finished the flow of
control comes back to the Thread A. The ability of the language that supports multiple threads is called
"Concurrency". Since threads in the java are small sub programs of the main program and share the
same address space, they are called "light weight processes".
Main
thread
Start
Start
Start
switch
Thread A
Thread B switch Thread C
Dept.of ISE,RNSIT Page 2
Object Oriented Concepts with Java BCS306A
static Thread.currentThread( )
This method returns a reference to the thread in which it is called. Once you have a referenceto the
main thread, you can control it just like any other thread.
Let’s begin by reviewing the following example:
CurrentThreadDemo.java
// Controlling the main
Thread. class
CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " +
t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " +
t); try
{
for(int n = 5; n > 0; n--)
{
System.out.println(n)
; Thread.sleep(1000);
}
}
Dept.of ISE,RNSIT Page 3
Object Oriented Concepts with Java BCS306A
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}
Output
Creation of Thread
Creating the threads in the Java is simple. The threads can be implemented in the form of object
that contains a method "run()". The "run()" method is the heart and soul of any thread. It makes up the
entire body of the thread and is the only method in which the thread behavior can be implemented.
There are two ways to create thread.
1. Declare a class that implements the Runnable interface which contains the run() method .
2. Declare a class that extends the Thread class and override the run() method.
1. Implementing the Runnable Interface
The Runnable interface contains the run() method that is required for implementing the threadsin
our program. To do this we must perform the following steps:
I. Declare a class as implementing the Runnable interface
II. Implement the run() method
III. Create a Thread by defining an object that is instantiated from this "runnable" class as the target
of the thread
IV. Call the thread's start() method to run the thread.
Example program:
Runnable.java
class x implements Runnable
{ //1 STEP
public void run()
{ //2 STEP
for(int i=0;i<=5;i++)
System.out.println("The Thread x is:"+i);
System.out.println("End of the Thread x");
}
}
class RunnableTest
{
public static void main(String args[])
{
x r=new x();
Thread threadx=new Thread(r);
threadx.start();
System.out.println("The end of the main thread");
}
Starting the new Thread
To actually to create and run an instance of the thread class, we must write the following:
Example program:
ThreadTest.java
import java.io.*;
import java.lang.*;
Second Run: Produces different out put in the second run, because of the processor switching from one
thread to other.
It is often very important to know which thread is ended. This helps to prevent the main from
terminating before the child Thread is terminating. To address this problem "Thread" class provides
two methods: 1) Thread.isAlive() 2) Thread.join().
This method returns the either "TRUE" or "FALSE" . It returns "TRUE" if the thread is alive,returns
"FALSE" otherwise.
While isAlive( ) is occasionally useful, the method that you will more commonly use to wait fora thread
to finish is called join( ), shown here:
Example Program:
class DemoJoin
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.This is
its general form:
Here, level specifies the new priority setting for the calling thread. The value of level must be within the
range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To
return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are
defined as static final variables within Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:
Example Program:
class PTest
{
public static void main(String args[])
{
//setting the priorities to the thread using the setPriority() method
PThread1 pt1=new PThread1();
pt1.setPriority(1); PThread2 pt2=new
PThread2(); pt2.setPriority(9);
PThread3 pt3=new PThread3();
pt3.setPriority(6);
pt1.start();
pt2.start();
pt3.start();
//getting the priority
Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an
object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given
time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to
enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are
said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so
desires.
Let us try to understand the problem without synchronization. Here, in the following example to threads
are accessing the same resource (object) to print the Table. The Table class contains one method,
printTable(int ), which actually prints the table. We are creating two Threads, Thread1 and Thread2,
which are using the same instance of the Table Resource (object), to print the table. When one thread is
using the resource, no other thread is allowed to access the same resource Table to print the table.
void printTable(int n)
{ //method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(InterruptedException ie)
{
System.out.println("The Exception is :"+ie);
}
}
} //end of the printTable() method
}
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
} //end of the Thread1
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one objectMyThread1
t1=new MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();
t2.start();
}
}
The output for the above program will be as follow:
Output: 5
100
10
200
15
300
20
400
25
500
In the above output, it can be observed that both the threads are simultaneously accessing the Table object
to print the table. Thread1 prints one line and goes to sleep, 400 milliseconds, and Thread1 prints its task.
If you declare any method as synchronized, it is known as synchronized method. Synchronized method is
used to lock an object for any shared resource. When a thread invokes a synchronized method, it
automatically acquires the lock for that object and releases it when the thread completes its task.
The general form of the synchronized method is:
synchronized type method_name(para_list)
{
//body of the method
}
where synchronized is the keyword, method contains the type, and method_name represents thename of
the method, and para_list indicate the list of the parameters.
Class Table
{
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one objectMyThread1
t1=new MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500
In the above output it can be observed that when Thread1 is accessing the Table object, Thread2 is not allowed to
access it. Thread1 preempts the Thread2 from accessing the printTable() method.
Note:
1. This way of communications between the threads competing for same resource is
called implicit communication.
2. This has one disadvantage due to polling. The polling wastes the CPU time. To save
the CPU time, it is preferred to go to the inter-thread communication.
Inter-Thread Communication
If two or more Threads are communicating with each other, it is called "inter thread" communication.
Using the synchronized method, two or more threads can communicate indirectly. Through, synchronized
method, each thread always competes for the resource. This way of competing is called polling. The
polling wastes the much of the CPU valuable time. The better solution to this problem is, just notify other
threads for the resource, when the current thread has finished its task. This is explicit communication
between the threads.
Java addresses this polling problem, using via wait(), notify(), and notifyAll() methods. These
methods are implemented as final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized context.
wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of
the threads will be granted access.
Although wait( ) normally waits until notify( ) or notifyAll( ) is called, there is a possibility that
in very rare cases the waiting thread could be awakened due to a spurious wakeup. In this case, a waiting
thread resumes without notify( ) or notifyAll( ) having been called. (In essence, the thread resumes for no
apparent reason.) Because of this remote possibility, Sun recommends that calls to wait( ) should take
place within a loop that checks the condition on which the thread is waiting. The following example shows
this technique.
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}//end of Consumer
class PCFixed
{
public static void main(String args[])
{
Q q = new Q(); new
Producer(q); new
Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Example program:
The following program demonstrates these methods:
// Using suspend() and resume().
{
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 15; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(200);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");try
{
Thread.sleep(1000); ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume(); System.out.println("Resuming
thread One"); ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume(); System.out.println("Resuming
thread Two");
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Life Cycle of a Thread
During the life time of the thread, there are many states it can enter. They include the following:
Newborn state
Runnable State
Running State
Blocked state
Dead state
A thread can always in any one of the five states. It can move from one state to other via variety of
ways as shown in the fig.
Newborn state Stop
Start
suspend() resume()
sleep() notify()
wait()
Blocked State
Runnable State: A runnable state means that a thread is ready for execution and waiting
for the availability of the processor. That is the thread has joined the queue of the threads for
execution. If all the threads have equal priority, then they are given time slots for execution
in the round rabin fashion, first-come, first-serve manner. The thread that relinquishes the
control will join the queue at the end and again waits for its turn. This is known as time
slicing.
Running State:
Running state: Running state means that the processor has given its time to the thread for it
execution. The thread runs until it relinquishes the control or it is preempted by the other
higher priority thread. As shown in the fig. a running thread can be preempted using the
suspen(), or wait(), or sleep() methods.
Blocked state: A thread is said to be in the blocked state when it is prevented from entering
into runnable state and subsequently the running state.
Dead state: Every thread has a life cycle. A running thread ends its life when it has
completed execution. It is a natural death. However we also can kill the thread by sending
the stop() message to it at any time.
Enumerations
Enumerations included in JDK 5. An enumeration is a list of named constants.
It is similar to final variables.
Enum in java is a data type that contains fixed set of constants.
An enumeration defines a class type in Java. By making enumerations into
classes, so it can have constructors, methods, and instance variables.
An enumeration is created using the enum keyword.
Ex:
Enumeration variable can be created like other primitive variable. It does notuse the
new for creating object.
Ex:Apple ap;
Ap is of type Apple, the only values that it can be assigned (or can contain)are
those defined by the enumeration. For example, this assigns:
ap = Apple.RedDel;
Example Code-1
class EnumDemo
{
public static void main(String args[])
{
Apple ap;
ap = Apple.RedDel;
System.out.println("Value of ap: " + ap);// Value of ap: RedDel
ap = Apple.GoldenDel;
if(ap == Apple.GoldenDel)
System.out.println("ap contains GoldenDel.\n"); // ap contains GoldenDel.
switch(ap)
{
case Jonathan:
System.out.println("Jonathan is red.");
break;
case GoldenDel:
System.out.println("Golden Delicious is yellow.");// Golden Delicious is yellow
break;
case RedDel:
System.out.println("Red Delicious is red.");
break;
case Winesap:
System.out.println("Winesap is red.");
break;
case Cortland:
System.out.println("Cortland is red.");
break;
}
}
}
The values( ) and valueOf( ) Methods All enumerations automatically contain two predefined
methods: values( ) and valueOf( ).
The values( ) method returns an array that contains a list of the enumeration
constants.
The valueOf( ) method returns the enumeration constant whose value corresponds to thestring
passed in str.
Example Code-2:
class EnumExample1{
System.out.println(s);
Season s = Season.valueOf("WINTER");
} }
Example Code-3
class EnumExample5{
case SUNDAY:
System.out.println("sunday");break;
case MONDAY:
System.out.println("monday");break;
default: System.out.println("other
}}
class EnumDemo3 {
{ Apple ap;
for(Apple a : Apple.values())
The first is the instance variable price, which is used to hold the price of eachvariety
of apple.
The second is the Apple constructor, which is passed the price of an apple.The
the arguments to the constructor are specified, by putting them inside parentheses after each
constant, as shown here:
These values are passed to the parameter of Apple(),which then assigns this value to price.The
constructor is called once for each constant.
Because each enumeration constant has its own copy of price, you can obtain the price ofa
specified type of apple by calling getPrice().
Enum class defines several methods that are available for use by all enumerations.
ordinal( )
To obtain a value that indicates an enumeration constant’s position in the list of constants. This
is called its ordinal value, and it is retrieved by calling the ordinal( ) method,shown here:
It returns the ordinal value of the invoking constant. Ordinal values begin at zero. Thus, in the
Apple enumeration, Jonathan has an ordinal value of zero, GoldenDel has an ordinal value of 1,
RedDel has an ordinal value of 2, and so on.
compareTo( )
To compare the ordinal value of two constants of the same enumeration by using the
compareTo( ) method. It has this general form:
equals()
equals method is overridden method from Object class, it is used to compare the
enumeration constant. Which returns true if both constants are same.
EnumDemo4
System.out.println("Here are all apple constants" + " and their ordinal values: ");
for(Apple a : Apple.values())
ap = Apple.RedDel; ap2
= Apple.GoldenDel;ap3 =
Apple.RedDel;
System.out.println();
System.out.println();
Wrappers Classes
Java uses primitive types such as int or double, to hold the basic data types supportedby the
language.
The primitive types are not part of the object hierarchy, and they do not inherit Object.
Despite the performance benefit offered by the primitive types, there are times when youwill
need an object representation.
Many of the standard data structures implemented by Java operate on objects, whichmeans
that you can’t use these data structures to store primitive types.
To handle the above situation, Java provides type wrappers, which are classes that
encapsulate a primitive type within an object.
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These
classes offer a wide array of methods that allow you to fully integrate the primitive types into
Java’s object hierarchy.
Character:
Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object being
created.
To obtain the char value contained in a Character object, call charValue( ), shownhere:
char charValue( )
Boolean:
Boolean(boolean boolValue)
Boolean(String boolString)
In the second version, if boolString contains the string “true” (in uppercase or
lowercase), then the new Boolean object will be true. Otherwise, it will be false.
To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:
boolean booleanValue( )
Integer(int num)
Integer(String str)
class Wrap
This program wraps the integer value100 inside an Integer object called iOb.
The program then obtains this value by calling intValue() and stores the result in i.The
Thus, in the program, this line boxes the value 100 into an Integer:
int i = iOb.intValue();
AutoBoxing
whenever an object of that type is needed. There is no need to explicitly construct anobject.
Auto-unboxing
= iOb; // auto-unbox
Example Program:
class AutoBoxUnBox
i = iOb; // auto-unbox
int m(Integer v)
{ return v ; }
System.out.println(iOb);// 100
In the program, notice that m( ) specifies an Integer parameter and returns an intresult.
Then, m( ) returns the int equivalent of its argument. This causes v to be auto-unboxed.
The outcome of the expression is reboxed, if necessary. For example, consider thefollowing
program:
class AutoBox3
iOb = 100;
++iOb;
It works like this: iOb is unboxed, the value is incremented, and the result is reboxed.
Auto-unboxing also allows you to mix different types of numeric objects in an expression.
Once the values are unboxed,the standard type promotions and conversionsare applied.For
example, the following program is perfectly valid:
switch(iOb) {
case 1: System.out.println("one");break;
case 2: System.out.println("two");break;
default:
System.out.println("error");
When the switch expression is evaluated, iOb is unboxed and its int value is obtained.
box a char
+ ch2);
}}
Enumerations
An enumeration is a list of named constants. In Java, enumerations define class types. That is, in Java, enumerations
can have constructors, methods and variables. An enumeration is created using the keyword enum. Following is an
example –
enum Person
{
Married, Unmarried, Divorced, Widowed
}
The identifiers like Married, Unmarried etc. are called as enumeration Constants. Each such constant is implicitly
considered as a public static final member of Person.
After defining enumeration, we can create a variable of that type. Though enumeration is a class type, we need not
use new keyword for variable creation, rather we can declare it just like any primitive data type. For example,
Person p= Person.Married;
We can use == operator for comparing two enumeration variables. They can be used in switch-case
also. Printing an enumeration variable will print the constant name. That is,
System.out.println(p); // prints as Married
enum Person
{
Married, Unmarried, Divorced, Widowed
}
class EnumDemo
{
public static void main(String args[])
{
Person p1;
p1=Person.Unmarried; System.out.println("Value of p1 :" + p1);
switch(p1)
{
case Married: System.out.println("p1 is Married");break;
case Unmarried: System.out.println("p1 is Unmarried");
break;
case Divorced: System.out.println("p1 is Divorced");break;
case Widowed: System.out.println("p1 is Widowed");
break;
}
}
}
The values()method returns an array of enumeration constants. The valueOf()method returns theenumeration
constant whose value corresponds to the string passed in str.
enum Person
{
Married, Unmarried, Divorced, Widowed
}
class EnumDemo
{ public static void main(String args[])
{ Person p;
for(Person p1:all)
System.out.println(p1);
enum Apple
{
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);private int price;
Apple(int p)
{
price = p;
}
int getPrice()
{
return price;
}
}
class EnumDemo
{
public static void main(String args[])
{
Apple ap;
System.out.println("Winesap costs " + Apple.Winesap.getPrice());System.out.println("All apple
prices:");
for(Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");
}
}
Output:
Winesap costs 15
All apple prices:
Jonathan costs 10 cents.
GoldenDel costs 9 cents.
RedDel costs 12 cents.
Winesap costs 15 cents.
Cortland costs 8 cents.
Here, we have member variable price, a constructor and a member method. When the variable ap isdeclared in
main( ), the constructor for Apple is called once for each constant that is specified.
Although the preceding example contains only one constructor, an enum can offer two or moreoverloaded forms,
just as can any other class. Two restrictions that apply to enumerations:
– an enumeration can’t inherit another class.
– an enum cannot be a superclass.
It returns the ordinal value of the invoking constant. Ordinal values begin at zero. We can compare the ordinal
value of two constants of the same enumeration by using the compareTo() method. It has this general form:
final int compareTo(enum-type e)
Here, e1 and e2 should be the enumeration constants belonging to same enum type. If the ordinal value of e1 is less
than that of e2, then compareTo() will return a negative value. If two ordinal values are equal, the method will
return zero. Otherwise, it will return a positive number.
We can compare for equality an enumeration constant with any other object by using equals( ), which overrides the
equals( ) method defined by Object.
enum Person
{
Married, Unmarried, Divorced, Widowed
}
enum MStatus
{
Married, Divorced
}
class EnumDemo
{
public static void main(String args[])
{
Person p1, p2, p3;
are: ");
for(Person p:Person.values())
System.out.println(p + " has a value " + p.ordinal());
p1=Person.Married; p2=Person.Divorced;
p3=Person.Married;
if(p1.compareTo(p2)<0)
System.out.println(p1 + " comes before "+p2);else
if(p1.compareTo(p2)==0)
System.out.println(p1 + " is same as "+p2);
else
System.out.println(p1 + " comes after "+p2);
if(p1.equals(p3))
System.out.println("p1 & p3 are same");
if(p1==p3)
System.out.println("p1 & p3 are same");
if(p1.equals(m))
System.out.println("p1 & m are same");
else
System.out.println("p1 & m are not same");
Type Wrappers
Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported by
the language. Primitive types, rather than objects, are used for these quantities for the sake of performance. Using
objects for these values would add an unacceptable overhead to even the simplest of calculations. Thus, the
primitive types are not part of the object hierarchy, and they do not inherit Object. Despite the performance benefit
offered by the primitive types, there are times when you will need an object representation. For example, you can’t
pass a primitive type by reference to a method. Also, many of the standard data structures implemented by Java
operate on an object, which means that you can’t use these data structures to store primitive types. To handle these
(and other) situations, Java provides type wrappers, which are classes that encapsulate a primitive type within an
object.
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a
wide array of methods that allow you to fully integrate the primitive types into Java’s objecthierarchy.
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
Character Wrappers: Character is a wrapper around a char. The constructor for Character is
Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object being created. Toobtain the
char value contained in a Character object, call charValue(), shown here:
char charValue( )
Boolean Wrappers: Boolean is a wrapper around boolean values. It defines these constructors:
Boolean(boolean boolValue)
Boolean(String boolString)
In the first version, boolValue must be either true or false. In the second version, if boolString
contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true.
Otherwise, it will be false. To obtain a boolean value from a Boolean object, useboolean
booleanValue( )
The Numeric Type Wrappers: The most commonly used type wrappers are those that represent numeric
values. All of the numeric type wrappers inherit the abstract class Number. Number declares methods that
return the value of an object in each of the different number formats. Thesemethods are shown here:
byte byteValue( ) double
doubleValue( )float floatValue(
) int intValue( )
long longValue( ) short
shortValue( )
For example, doubleValue( ) returns the value of an object as a double, floatValue( ) returns thevalue as a
float, and so on. These methods are implemented by each of the numeric type wrappers.
All of the numeric type wrappers define constructors that allow an object to be constructed from a given
value, or a string representation of that value. For example, here are the constructors defined for Integer:
Integer(int num)
Integer(String str)
If str does not contain a valid numeric value, then a NumberFormatException is thrown. All of the type
wrappers override toString(). It returns the human-readable form of the value contained within the wrapper.
This allows you to output the value by passing a type wrapper object to println(), for example, without
having to convert it into its primitive type.
EXAMPLE
Output:
Character is #
Boolean is true
Boolean is false
12 is same as 12
x is 21
s is 25