UNIT 5 Notes.docx

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Module 5:

Multithreaded Programming:
Multithreading is a Java feature that allows concurrent execution of two or more
parts of a program for maximum utilization of CPU. Each part of such program is
called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the
run() method available in the Thread class. A thread begins its life inside run()
method. We create an object of our new class and call start() method to start the
execution of a thread. Start() invokes the run() method on the Thread object.

The Java Thread Model:

A thread is a subpart of a process that can run individually. A thread is a subpart of


a process that can run individually. In java, a thread goes through different states
throughout its execution. These stages are called thread life cycle states or phases.
A thread may in any of the states like new, ready or runnable, running, blocked or
wait, and dead or terminated state.
The Main Thread:

Java provides built-in support for multithreaded programming. A multi-threaded


program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.
When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of our program because it is the one that is executed
when our program begins.
There are certain properties associated with the main thread which are as follows:
It is the thread from which other “child” threads will be spawned.
Often, it must be the last thread to finish execution because it performs various
shutdown actions
The main thread is created automatically when our program is started. To control it
we must obtain a reference to it. This can be done by calling the
method currentThread( ) which is present in Thread class. This method returns a
reference to the thread on which it is called. The default priority of Main thread is
5 and for all remaining user threads priority will be inherited from parent to child.
import java.io.*;
import java.util.*;
public class Test extends Thread {
public static void main(String[] args)
{
Thread t = Thread.currentThread();
System.out.println("Current thread: "+ t.getName());
t.setName("VTU");
System.out.println("After name change: "+ t.getName());
System.out.println("Main thread priority: "+ t.getPriority())
t.setPriority(MAX_PRIORITY);
System.out.println("Main thread new priority: "+ t.getPriority());
for (int i = 0; i < 5; i++) {
System.out.println("Main thread");
}
Thread ct = new Thread() {
// run() method of a thread
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println("Child thread");
}
}
};
System.out.println("Child thread priority: "+ ct.getPriority());
ct.setPriority(MIN_PRIORITY);
System.out.println("Child thread new priority: "+ ct.getPriority());
ct.start();
}
}
class ChildThread extends Thread {

@Override public void run()


{
for (int i = 0; i < 5; i++) {
System.out.println("Child thread");
}
}
}
OUTPUT:
Current thread: main
After name change: VTU
Main thread priority: 5
Main thread new priority: 10
Main thread
Main thread
Main thread
Main thread
Main thread
Child thread priority: 10
Child thread new priority: 1
Child thread
Child thread
Child thread
Child thread
Child thread

Creating a Thread:

Multithreading is a fundamental concept in Java programming, allowing


developers to execute multiple tasks concurrently within a single
program. Threads are lightweight processes that run within the context of a larger
process, enabling efficient utilization of system resources and enhancing
application responsiveness. In this section, we will explore how to create threads in
Java, covering various approaches, best practices.

In Java, threads are represented by instances of the Thread class or by


implementing the Runnable interface. The Thread class provides built-in support
for multithreading, while the Runnable interface defines a single method, run() that
contains the code to be executed by the thread. By implementing the Runnable
interface, we can decouple the task from the thread itself, promoting better code
organization and reusability.

There are the following two ways to create a thread:

o By Extending Thread Class


o By Implementing Runnable Interface

Thread Class
The simplest way to create a thread in Java is by extending the Thread class and
overriding its run() method. Thread class provide constructors and methods to
create and perform operations on a thread. Thread class extends Object class and
implements Runnable interface.

Constructors of Thread Class

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r, String name)

Thread Class Methods

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread
to sleep (temporarily cease execution) for the specified number of
milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10.public Thread currentThread(): returns the reference of currently
executing thread.
11.public int getId(): returns the id of the thread.
12.public Thread.State getState(): returns the state of the thread.
13.public boolean isAlive(): tests if the thread is alive.
14.public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15.public void suspend(): is used to suspend the thread(depricated).
16.public void resume(): is used to resume the suspended thread(depricated).
17.public void stop(): is used to stop the thread(depricated).
18.public boolean isDaemon(): tests if the thread is a daemon thread.
19.public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20.public void interrupt(): interrupts the thread.
21.public boolean isInterrupted(): tests if the thread has been interrupted.
22.public static boolean interrupted(): tests if the current thread has been
interrupted.

By Implementing Runnable Interface


Another approach to creating threads in Java is by implementing the Runnable
interface. The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface have only
one method named run(). This approach is preferred when we want to separate the
task from the thread itself, promoting better encapsulation and flexibility.

public void run(): is used to perform action for a thread.

Starting a Thread
The start() method of the Thread class is used to start a newly created thread. It
performs the following tasks:

o A new thread starts (with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Thread Creation
1) Creating Thread by Extending Thread Class

File Name: Multi.java

class Multi extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:

thread is running...
Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
Output:

thread is running...

Creating Multiple Threads

Creating more than one thread to perform multiple tasks is called multithreading
in Java. In multiple threading programming, multiple threads are executing
simultaneously that improves the performance of CPU because CPU is not idle if
other threads are waiting to get some resources.
Multiple threads share the same address space in the heap memory. Therefore, it is
good to create multiple threads to execute multiple tasks rather than creating
multiple processes.

Example:

// Two threads performing two tasks at a time.


public class MyThread extends Thread
{
// Declare a String variable to represent task.
String task;

MyThread(String task)
{
this.task = task;
}
public void run()
{
for(int i = 1; i <= 5; i++)
{
System.out.println(task+ " : " +i);
try {
Thread.sleep(1000); // Pause the thread execution for 1000 milliseconds.
} catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
} // end of for loop.
} // end of run() method.
public static void main(String[] args)
{
MyThread th1 = new MyThread("Cut the ticket");
MyThread th2 = new MyThread("Show your seat number");
constructor of Thread class.
Thread t1 = new Thread(th1);
Thread t2 = new Thread(th2);
t1.start();
t2.start();
}
}
Output:
Cut the ticket : 1
Show your seat number : 1
Show your seat number : 2
Cut the ticket : 2
Show your seat number : 3
Cut the ticket : 3
Show your seat number : 4
Cut the ticket : 4
Show your seat number : 5
Cut the ticket : 5

Using isAlive()and join():

The isAlive() method works in tandem with the join() method, which allows one
thread to wait for the completion of another. By invoking isAlive() on a target
thread and subsequently calling join(), a waiting thread can be sure that the target
thread has completed its execution before proceeding further.

While the isAlive() method provides valuable insights into the status of a thread,
it's important to note that it only provides a snapshot of the thread's status at the
time of invocation. The thread's status can change immediately after the isAlive()
method call, rendering the obtained result outdated.
// Create a thread
Thread thread = new Thread(() -> {
System.out.println("Thread started");
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Thread finished");
});

// Start the thread


thread.start();

// Check if thread is alive


System.out.println("Is thread alive? " + thread.isAlive());

// Wait for thread to finish


try {
thread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Main thread continued");

Output:

Thread started
Is thread alive? true
Thread finished
Main thread continued

public class IsAliveExample extends Thread {


public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
IsAliveExample thread = new IsAliveExample();
System.out.println("Thread status before starting: " + thread.isAlive());
thread.start();
System.out.println("Thread status after starting: " + thread.isAlive());
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread status after completion: " + thread.isAlive());
}
}
Output:

Thread status before starting: false


Thread status after starting: true
Thread status after completion: false
Using join() method, we tell our thread to wait until the specified thread completes
its execution. There are overloaded versions of join() method, which allows us to
specify time for which you want to wait for the specified thread to terminate.

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}
OUTPUT:
r1
r1
r2
r2

Thread Priorities:

Priorities in threads is a concept where each thread is having a priority which in


layman’s language one can say every object is having priority here which is
represented by numbers ranging from 1 to 10.
The default priority is set to 5 as excepted.
Minimum priority is set to 1.
Maximum priority is set to 10.

import java.lang.*;
class GFG extends Thread {
public void run()
{
System.out.println("Inside run method");
}
public static void main(String[] args)
{
Thread.currentThread().setPriority(6);
System.out.println("main thread priority :
"+Thread.currentThread().getPriority());
GFG t1 = new GFG();

System.out.println("t1 thread priority : "+ t1.getPriority());


}
}
Output
main thread priority : 6
t1 thread priority : 6

Synchronization:

Java provides a way of creating threads and synchronizing their tasks using
synchronized blocks.
A synchronized block in Java is synchronized on some object. All synchronized
blocks synchronize on the same object and can only have one thread executed
inside them at a time. All other threads attempting to enter the synchronized block
are blocked until the thread inside the synchronized block exits the block. If you
want to master concurrency and understand how to avoid common pitfalls.
Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization
1. Process Synchronization in Java
Process Synchronization is a technique used to coordinate the execution of multiple processes. It ensures
that the shared resources are safe and in order.
2. Thread Synchronization in Java
Thread Synchronization is used to coordinate and ordering of the execution of the threads in a
multi-threaded program. There are two types of thread synchronization are mentioned below:
● Mutual Exclusive
● Cooperation (Inter-thread communication in Java)

import java.io.*;
import java.util.*;
// A Class used to send a message
class Sender {
public void send(String msg)
{
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}

// Class for send a message using Threads


class ThreadedSend extends Thread {
private String msg;
Sender sender;

// Receives a message object and a string


// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}

public void run()


{
// Only one thread can send a message
// at a time.
synchronized (sender)
{
// synchronizing the send object
sender.send(msg);
}
}
}

// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);

// Start two threads of ThreadedSend type


S1.start();
S2.start();

// wait for threads to end


try {
S1.join();
S2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
}
Output
Sending Hi

Hi Sent
Sending Bye

Bye Sent

Interthread Communication:

Inter-thread communication is important when you develop an application where two or more
threads exchange some information. Inter-thread communication is achieved by using
the wait(), notify(), and notifyAll() methods of the Object class.
Sr.No. Method & Description
public void wait()
1 Causes the current thread to wait until another thread invokes the
notify().
public void notify()
2
Wakes up a single thread that is waiting on this object's monitor.
public void notifyAll()
3
Wakes up all the threads that called wait( ) on the same object.

public class A {
int i;
boolean flag = false; // flag will be true when data production is over.
synchronized void deliver(int i)
{
if(flag)
try {
wait(); // Wait till a notification is received from Thread2. There will be no
wastage of time.
}
catch(InterruptedException ie) {
System.out.println(ie);
}
this.i = i;
flag = true; // When data production is over, it will store true into flag.
System.out.println("Data Delivered: " +i);
notify(); // When data production is over, it will notify Thread2 to use it.
}
synchronized int receive()
{
if(!flag)
try {
wait(); // Wait till a notification is received from Thread1.
}
catch(InterruptedException ie){
System.out.println(ie);
}
System.out.println("Data Received: " + I);
flag = false; // It will store false into flag when data is received.
notify(); // When data received is over, it will notify Thread1 to produce next
data.
return i;
}
}
public class Thread1 extends Thread
{
A obj;
Thread1(A obj)
{
this.obj = obj;
}
public void run()
{
for(int j = 1; j <= 5; j++){
obj.deliver(j);
}
}}
public class Thread2 extends Thread
{
A obj;
Thread2(A obj)
{
this.obj = obj;
}
public void run()
{
for(int k = 0; k <= 5; k++) {
obj.receive();
}
}
}
public class Communication {
public static void main(String[] args)
{
A obj = new A(); // Creating an object of class A.
// Creating two thread objects and pass reference variable obj as parameter to
Thread1 and Thread2.
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
// Run both threads.
t1.start();
t2.start();
}
}
Output
Output:
Data Delivered: 1
Data Received: 1
Data Delivered: 2
Data Received: 2
Data Delivered: 3
Data Received: 3
Data Delivered: 4
Data Received: 4
Data Delivered: 5
Data Received: 5

Suspending, Resuming, and Stopping Threads:

It is used to perform complicated tasks in the background without disturbing the main program. In order
to suspend the thread temporarily by making it go through from running state to waiting for the state. The
concept used in achieving the goal is the suspend() function.

Thread.stop() is being phased out due to its inherent risk. When you stop a thread, it unlocks all the
monitors it has locked. Other threads might see these objects in an inconsistent state if any of the objects
previously protected by these monitors were in an inconsistent state.
Threads acting on damaged objects can act erratically, whether consciously or unconsciously.
ThreadDeath, unlike other uncontrolled exceptions, silently kills threads, leaving the user with no warning
that the program may be corrupted. After the damage has occurred, the corruption may appear at an
unpredicted moment. Also, killing a thread will create a problem while working with DBMS – JDBC in a
multithreaded environment.
Thread.suspend() is deprecated because it is inherently deadlock-prone. As a
result, Thread.resume() must be deprecated as well. When the target thread is suspended, it holds a lock
on the monitor protecting a crucial system resource, and no other thread may access it until the target
thread is resumed. Deadlock occurs if the thread that would restart the target thread tries to lock this
monitor before invoking resume().
class NumVal {
private int num[] = null;
boolean valueSet = false;
int i = 0;
NumVal()
{
// Creating integer array of 10 elements
num = new int[10];
}
// method to set the values in the array
public void setVal(int n)
{
if (i < 9) {
System.out.println("Putting value " + n
+ " in the NumVal Array");
num[i] = n;
i++;
}
}
// method to get the values from the array
public int getVal()
{
if (i >= 0) {

System.out.println("Giving n = " + num[i]);


i--;
return num[i + 1];
}
else {
return -1;
}
}
}
// Creating Our Thread Class
class MyThread extends Thread {

// MyThread want mutually exclusive


// lock on the object
// referred by: NumObjToSetVal
NumVal NumObjToSetVal = null;
// Constructor
public MyThread(String threadName, NumVal numV)
{
super(threadName);
NumObjToSetVal = numV;
}

public void run()


{
// Only 1 thread at a time an access the object
// referred by : NumObjToSetVal
synchronized (NumObjToSetVal)
{
int n = 0;
while (n < 5) {
System.out.println(
"THREAD NAME : "
+ Thread.currentThread().getName());
n++;
NumObjToSetVal.setVal(n);
try {
// Make the thread sleep for 100 ms
Thread.sleep(100);
System.out.println(
Thread.currentThread().getName()
+ "is awake now");
}
catch (Exception e) {
System.out.println("Exception Caught");
}
// If n is 2 , we suspend this thread
if (n == 2) {
// suspend the thread, now this thread
// will release lock on NumObjToSetVal
// only when resume() method is called
// on this thread, thread will go in
// waiting state
Thread.currentThread().suspend();
}
}
}
}
}

public class Main {


public static void main(String[] args)
{
// TODO Auto-generated method stub
NumVal v = new NumVal();

// Creating thread 1 that want exclusive lock on


// object referred by v
MyThread thread1 = new MyThread("Thread1 ", v);

// Creating thread 2 that want exclusive lock on


// object referred by v
// thread1 is not going to release lock on Object
// referred by v until resume() method is not called
// and for acquiring lock on v Object refred by v ,
// thread1 must have released lock on Object
// referred by v, if lock is not released, thread2
// will keep on waiting for thread1 to release lock
// onbject referred by v & deadlock will be formed
MyThread thread2 = new MyThread("Thread2 ", v);

// starting both threads


thread1.start();
thread2.start();

for (int i = 500; i <= 501; i++) {


System.out.println("Main Thread " + i);
}
}
}
Output:

THREAD NAME : Thread1


Putting value 1 in the NumVal Array
Main Thread 500
Main Thread 501
Thread1 is awake now
THREAD NAME : Thread1
Putting value 2 in the NumVal Array
Thread1 is awake now
//Deadlock is created & hence no output after this

Obtaining a Thread’s State:

A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of
the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram shown below represents various states of a thread at any instant in time.

Life Cycle of a Thread

There are multiple states of the thread in a lifecycle as mentioned below:


1. New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run
when the thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t
started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread
might actually be running or it might be ready to run at any instant of time. It is the responsibility of
the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every
thread runs for a short while and then pauses and relinquishes the CPU to another thread so that other
threads can get a chance to run. When this happens, all such threads that are ready to run, waiting for
the CPU and the currently running thread lie in a runnable state.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock is
acquired by the other thread. The thread will move from the blocked state to runnable state when it
acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will
move to the runnable state when other thread will notify or that thread will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is received.
For example, when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:

● Because it exits normally. This happens when the code of the thread has been entirely executed by
the program.
● Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled
exception.

// Java program to demonstrate thread states


class thread implements Runnable {
public void run()
{
// moving thread2 to timed waiting state
try {
Thread.sleep(1500);
}
catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(
"State of thread1 while it called join() method on thread2 -"
+ Test.thread1.getState());
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Test implements Runnable {


public static Thread thread1;
public static Test obj;

public static void main(String[] args)


{
obj = new Test();
thread1 = new Thread(obj);

// thread1 created and is currently in the NEW


// state.
System.out.println(
"State of thread1 after creating it - "
+ thread1.getState());
thread1.start();

// thread1 moved to Runnable state


System.out.println(
"State of thread1 after calling .start() method on it - "
+ thread1.getState());
}

public void run()


{
thread myThread = new thread();
Thread thread2 = new Thread(myThread);

// thread2 created and is currently in the NEW


// state.
System.out.println(
"State of thread2 after creating it - "
+ thread2.getState());
thread2.start();

// thread2 moved to Runnable state


System.out.println(
"State of thread2 after calling .start() method on it - "
+ thread2.getState());

// moving thread2 to timed waiting state


try {
// moving thread2 to timed waiting state
Thread.sleep(200);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"State of thread2 after calling .sleep() method on it - "
+ thread2.getState());

try {
// waiting for thread2 to die
thread2.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"State of thread2 when it has finished it's execution - "
+ thread2.getState());
}
}

Output
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it - RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it - RUNNABLE
State of thread2 after calling .sleep() method on it - TIMED_WAITING
State of thread1 while it called join() method on thread2 -WAITING
State of thread2 when it has finished it's execution - TERMINATED

Enumerations, Type Wrappers and Autoboxing:


An enum is a special "class" that represents a group of constants

A Java enumeration is a class type. Although we don’t need to instantiate an enum using new, it has the
same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just like
classes, you can give them constructors, add instance variables and methods, and even implement
interfaces.
enum Level {
LOW,
MEDIUM,
HIGH
}

public class Main {


public static void main(String[] args) {
Level myVar = Level.MEDIUM;

switch(myVar) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
}
}
}

The output will be:

Medium level

Type Wrappers:

A Wrapper class in Java is a class whose object wraps or contains primitive data types. When we create
an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other
words, we can wrap a primitive value into a wrapper class object.

1. Collections allowed only object data.


2. On object data we can call multiple methods compareTo(), equals(), toString()
3. Cloning process only objects
4. Object data allowed null values.
5. Serialization can allow only object data.

public class Main {


public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}
}
Autoboxing:
In Java, primitive data types are treated differently so do there comes the introduction of wrapper
classes where two components play a role namely Autoboxing and Unboxing. Autoboxing refers to the
conversion of a primitive value into an object of the corresponding wrapper class is called autoboxing.
For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value
is:
● Passed as a parameter to a method that expects an object of the corresponding wrapper class.
● Assigned to a variable of the corresponding wrapper class.

import java.util.ArrayList;

class Main {
public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();

//autoboxing
list.add(5);
list.add(6);

System.out.println("ArrayList: " + list);


}
}
OUTPUT:
ArrayList: [5, 6]
Enumerations (Enumeration Fundamentals, The values() and valueOf() Methods),

Value: basic concept of Enum


public enum Color {

RED,

GREEN,

public static void main(String[] args) {

Color c1 = Color.RED;

System.out.println(c1);

}
Output
RED

valueOf() method converts data from its internal form into a human-readable form. It is a static method
that is overloaded within a string for all of Java’s built-in types so that each type can be converted
properly into a string.
It is called when a string representation of some other type of data is needed for example during a
concatenation operation. You can call this method with any data type and get a reasonable String
representation valueOf() returns java.lang.Integer, which is the object representative of the integer.

// Java program to demonstrate


// working of valueOf() methods
class ValueOfExa {
public static void main(String arg[])
{
int iNum = 30;

double fNum = 4.56789;


String s = "91";

// Returns the string representation of int iNum.


String sample = String.valueOf(iNum);

System.out.println(sample);

// concatenating string with iNum


System.out.println(sample + s);
// Returns the string representation of the float
// fnum.
sample = String.valueOf(fNum);
System.out.println(sample);

// concatenating string with fNum


System.out.println(s + sample);
}
}
Output
30
3091
4.56789
914.56789
Type Wrappers (Character, Boolean, The Numeric Type Wrappers):

1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments
passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.

Autoboxing (Autoboxing and Methods, Autoboxing/Unboxing Occurs in Expressions,


Autoboxing/Unboxing Boolean and Character Values).

Unboxing on the other hand refers to converting an object of a wrapper type to its corresponding
primitive value. For example conversion of Integer to int. The Java compiler applies to unbox when an
object of a wrapper class is:
● Passed as a parameter to a method that expects a value of the corresponding primitive type.
● Assigned to a variable of the corresponding primitive type.

class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing

Integer a3=5;//Boxing

System.out.println(a2+" "+a3);
}
}

Output:50 5

class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;

System.out.println(a);
}
}
Output:

50

********************************************* END***********************************

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy