Wrapper to primitive in java

Java Wrapper Class

The wrapper classes in Java are used to convert primitive types ( int , char , float , etc) into corresponding objects.

Each of the 8 primitive types has corresponding wrapper classes.

Primitive Type Wrapper Class
byte Byte
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
short Short

Convert Primitive Type to Wrapper Objects

We can also use the valueOf() method to convert primitive types into corresponding objects.

Example 1: Primitive Types to Wrapper Objects

class Main < public static void main(String[] args) < // create primitive types int a = 5; double b = 5.65; //converts into wrapper objects Integer aObj = Integer.valueOf(a); Double bObj = Double.valueOf(b); if(aObj instanceof Integer) < System.out.println("An object of Integer is created."); >if(bObj instanceof Double) < System.out.println("An object of Double is created."); >> > 
An object of Integer is created. An object of Double is created. 

In the above example, we have used the valueOf() method to convert the primitive types into objects.

Читайте также:  Php return all array keys

Here, we have used the instanceof operator to check whether the generated objects are of Integer or Double type or not.

However, the Java compiler can directly convert the primitive types into corresponding objects. For example,

int a = 5; // converts into object Integer aObj = a; double b = 5.6; // converts into object Double bObj = b; 

This process is known as auto-boxing. To learn more, visit Java autoboxing and unboxing.

Note: We can also convert primitive types into wrapper objects using Wrapper class constructors. But the use of constructors is discarded after Java 9.

Wrapper Objects into Primitive Types

To convert objects into the primitive types, we can use the corresponding value methods ( intValue() , doubleValue() , etc) present in each wrapper class.

Example 2: Wrapper Objects into Primitive Types

The value of a: 23 The value of b: 5.55 

In the above example, we have used the intValue() and doubleValue() method to convert the Integer and Double objects into corresponding primitive types.

However, the Java compiler can automatically convert objects into corresponding primitive types. For example,

Integer aObj = Integer.valueOf(2); // converts into int type int a = aObj; Double bObj = Double.valueOf(5.55); // converts into double type double b = bObj; 

This process is known as unboxing. To learn more, visit Java autoboxing and unboxing.

Advantages of Wrapper Classes

  • In Java, sometimes we might need to use objects instead of primitive data types. For example, while working with collections.
// error ArrayList list = new ArrayList<>(); // runs perfectly ArrayList list = new ArrayList<>();
 // generates an error int a = null; // runs perfectly Integer a = null; 

Note: Primitive types are more efficient than corresponding objects. Hence, when efficiency is the requirement, it is always recommended primitive types.

Table of Contents

Источник

Java Wrapper Classes, Autoboxing and Unboxing

Learn about Java wrapper classes, their usage, conversion between primitives and objects; and autoboxing and unboxing with examples.

In Java, we have 8 primitive data types. Java provides type wrappers, which are classes that encapsulate a primitive type within an Object.

  • A wrapper class wraps (encloses) around a primitive datatype and gives it an object appearance. Wherever the primitive datatype is required as an object type, this type wrapper can be used.
  • Wrapper classes include methods to unwrap the object and give back the data type.
  • The type wrappers classes are part of java.lang package.
  • Each primitive type has a corresponding wrapper class.

2. When to use Wrapper Classes

Java wrapper classes are used in scenarios –

  • When two methods wants to refer to the same instance of an primitive type, then pass wrapper class as method arguments.
  • Java Generics works only with object types and does not support primitive types.
  • Java Collections deal only with objects; to store a primitive type in one of these classes, you need to wrap the primitive type in a class.
  • When you want to refer null from data type, the you need object. Primitives cannot have null as value.

3.1. Converting Primitive Types to Wrapper Classes

There are two ways for converting a primitive type into an instance of the corresponding wrapper class –

// 1. using constructor Integer object = new Integer(10); // 2. using static factory method Integer anotherObject = Integer.valueOf(10);

In the above example, the valueOf() method is a static factory method that returns an instance of Integer class representing the specified int value.

Similarly, we can convert the other primitive types like boolean to Boolean , char to Character , short to Short , etc.

Java wrapper classes use internal caching which returns internally cached values upto a limit. This internal caching of instances makes the wrapper classes more efficient in perfomance and memory unilization.

3.2. Converting Wrapper Class to Primitive Type

Converting from wrapper class to primitive type is simple. We can use the corresponding instance methods to get the primitive type. e.g. intValue(), doubleValue(), shortValue() etc.

Integer object = new Integer(10); int val = object.intValue(); //wrapper to primitive

4. Autoboxing and Unboxing

Beginning with JDK 5, Java added two important features:

4.1. Autoboxing

Autoboxing is the automatic conversion of the primitive types into their corresponding wrapper class.

For example, converting an int to an Integer , a char to a Character , and so on.

We can simply pass or assign a primitive type to an argument or reference accepting wrapper class type.

Java Autoboxing Example
 List integerList = new ArrayList<>(); for (int i = 1; i < 10; i ++) < integerList.add(i); //int to Integer >

In given example, integerList is a List of Integer s. It is not a list of primitive type int values.

Here compiler automatically creates an Integer object from int and adds the object to integerList . Thus, the previous code turns into the following at runtime:

List integerList = new ArrayList<>(); for (int i = 1; i < 10; i ++) < integerList.add(Integer.valueOf(i)); //autoboxing >

4.2. Unboxing

Unboxing happens when the conversion happens from wrapper class to its corresponding primitive type. It means we can pass or assign a wrapper object to an argument or reference accepting primitive type.

Java Unboxing Example
public static int sumOfEven(List integerList) < int sum = 0; for (Integer i: integerList) < if (i % 2 == 0) sum += i; //Integer to int >return sum; >

In the above example, the remainder ( %) and unary plus (+=) operators do not apply on Integer objects. The compiler automatically converts an Integer to an int at runtime by invoking the intValue() method.

Autoboxing and unboxing lets developers write cleaner code, make it easier to read.

Источник

Using wrapper classes in Java

Learn Algorithms and become a National Programmer

A Wrapper class is a class whose object contains a primitive data types. We can think this as a primitive data type with an additional layer which enables it is get benefits of a custom user defined objects in Java.

Why we need Wrapper Classes?

  1. Methods cannot modify data of primitive data types which have been passed an arguments. To do this, we need to use a wrapper class over the primitive data type.
  2. The classes in java.util package handles only objects and hence wrapper classes help in converting primitive types to objects and hence, use the utilities
  3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects and not primitive types.
  4. Only an object can support synchronization in multithreading.

Syntax

Consider a class named prev_class which can be a primitive datatype like int as well. To wrap it in a wrapper class, we create a new class with any valid name like new_class like:

Example of wrapping an int:

Following this, we can create objects and set new data like:

int_wrapper int_object(); int_object.data = 1; int_object.set_data(2); 

In-built wrapper classes

The seven classes of java.lang package are known as wrapper classes in java. The list of seven wrapper classes are given below:

Autoboxing and Unboxing

As we know, Java automatically converts between datatypes to minimize the loss in accuracy. In this process, we have different rules for conversion of supported wrapper classes like Integer.

The two type of conversions are:

Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.

// Java program to demonstrate Autoboxing public class WrapperExample1 < public static void main(String args[])< //Converting int into Integer int a=21; Integer i=Integer.valueOf(a);//converting int into Integer Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally System.out.println(a+" "+i+" "+j); >> 

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double etc.

// Java program to demonstrate Unboxing public class WrapperExample2 < public static void main(String args[])< //Converting Integer to int Integer a=new Integer(5); int i=a.intValue();//converting Integer to int int j=a;//unboxing, now compiler will write a.intValue() internally System.out.println(a+" "+i+" "+j); >> 

Implemetation

Following implementation demonstrates autoboxing and unboxing:

// Java program to demonstrate Wrapping and UnWrapping // in Java Classes class AutoBoxingUnBoxing < public static void main(String args[]) < // byte data type byte a = 1; // wrapping around Byte object Byte byteobj = new Byte(a); // int data type int b = 11; //wrapping around Integer object Integer intobj = new Integer(b); // float data type float c = 11.6f; // wrapping around Float object Float floatobj = new Float(c); // double data type double d = 251.5; // Wrapping around Double object Double doubleobj = new Double(d); // char data type char e='a'; // wrapping around Character object Character charobj=e; // printing the values from objects System.out.println("Values of Wrapper objects (printing as objects)"); System.out.println("Byte object byteobj: " + byteobj); System.out.println("Integer object intobj: " + intobj); System.out.println("Float object floatobj: " + floatobj); System.out.println("Double object doubleobj: " + doubleobj); System.out.println("Character object charobj: " + charobj); // objects to data types (retrieving data types from objects) // unwrapping objects to primitive data types byte bv = byteobj; int iv = intobj; float fv = floatobj; double dv = doubleobj; char cv = charobj; // printing the values from data types System.out.println("Unwrapped values (printing as data types)"); System.out.println("byte value, bv: " + bv); System.out.println("int value, iv: " + iv); System.out.println("float value, fv: " + fv); System.out.println("double value, dv: " + dv); System.out.println("char value, cv: " + cv); >> 
Values of Wrapper objects (printing as objects) Byte object byteobj: 1 Integer object intobj: 11 Float object floatobj: 11.6 Double object doubleobj: 251.5 Character object charobj: a Unwrapped values (printing as data types) byte value, bv: 1 int value, iv: 11 float value, fv: 11.6 double value, dv: 251.5 char value, cv: a 

Using with Collection Objects

Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList , where primitive types cannot be used (the list can only store objects):

ArrayList myNumbers = new ArrayList(); // Invalid ArrayList myNumbers = new ArrayList(); // Valid 

Utility Methods of Wrapper Classes

Since you’re now working with objects, you can use certain methods to get information about the specific object.

For example, the following methods are used to get the value associated with the corresponding wrapper object: intValue() , byteValue() , shortValue() , longValue() , floatValue() , doubleValue() , charValue() , booleanValue() .

This example will output the same result as the example above:

Another useful method is the toString() method, which is used to convert wrapper objects to strings.

In the following example, we convert an Integer to a String, and use the length() method of the String class to output the length of the «string»:

Primitive Wrapper Classes are Immutable in Java

Consider below Java program.

// Java program to demonstrate that prmitive // wrapper classes are immutable class Wrapper < public static void main(String[] args) < Integer i = new Integer(14); System.out.println(i); modify(i); System.out.println(i); >private static void modify(Integer i) < i = i + 1; >> 

The parameter i is reference in modify and refers to same object as i in main(), but changes made to i are not reflected in main(), why?

Explanation:

All primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.

The below line of code in the modify method is operating on wrapper class Integer, not an int

  • Unwrapping i to an int value
  • Add 1 to that value
  • Wrapping the result into another Integer object
  • Assign the resulting Integer to i

Since object references are passed by value, the action taken in the modify method does not change i that was used as an argument in the call to modify. Thus the main routine still prints 14 after the method returns.

Comparison of Autoboxed Integer objects

When we assign an integer value to an Integer object, the value is autoboxed into an Integer object. For example the statement “Integer x = 1” creates an object ‘x’ with value 1.

Following are some interesting output questions based on comparison of Autoboxed Integer objects.

Predict the output of following Java Program

Since x and y refer to different objects, we get the output as “Not Equal”

The output of following program is a surprise from Java.

In Java, values from -128 to 127 are cached, so the same objects are returned. The implementation of valueOf() uses cached objects if the value is between -128 to 127.

If we explicitly create Integer objects using new operator, we get the output as “Not Same”. See the following Java program. In the following program, valueOf() is not used.

Predict the output of the following program.

Explanation: Two objects will be created here. First object which is pointed by X due to calling of new operator and second object will be created because of Auto-boxing.

Parth Maniyar

Parth Maniyar

Competitive Programmer | Intern at OpenGenus | Bachelor of Technology (2017 to 2021) in Information Technology at Ahmedabad University

OpenGenus Tech Review Team

Software Engineering

Find height or depth of a binary tree

Length of the longest path from the root node to a leaf node is the height of the binary tree. We find it in linear time using a recursive algorithm

Akshay Gopani

Akshay Gopani

Introduction to Q Learning and Reinforcement Learning

Read on to learn the basics of reinforcement learning and Q-Learning through an intuitive explanation, and a TensorFlow implementation!

Источник

Оцените статью