All wrapper classes in java are

Java Wrapper Classes

Each of Java’s eight primitive data types has a class dedicated to it. These are known as wrapper classes because they «wrap» the primitive data type into an object of that class. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs.

The wrapper classes in java servers two primary purposes.

  • To provide a mechanism to ‘wrap’ primitive values in an object so that primitives can do activities reserved for the objects like being added to ArrayList, Hashset, HashMap etc. collection.
  • To provide an assortment of utility functions for primitives like converting primitive types to and from string objects, converting to various bases like binary, octal or hexadecimal, or comparing various objects.

The following two statements illustrate the difference between a primitive data type and an object of a wrapper class:

int x = 25; Integer y = new Integer(33);

The first statement declares an int variable named x and initializes it with the value 25. The second statement instantiates an Integer object. The object is initialized with the value 33 and a reference to the object is assigned to the object variable y.

Below table lists wrapper classes in Java API with constructor details.

Primitive Wrapper Class Constructor Argument
boolean Boolean boolean or String
byte Byte byte or String
char Character char
int Integer int or String
float Float float, double or String
double Double double or String
long Long long or String
short Short short or String

Below is wrapper class hierarchy as per Java API

wrapper class image 1

As explain in above table all wrapper classes (except Character) take String as argument constructor. Please note we might get NumberFormatException if we try to assign invalid argument in the constructor. For example to create Integer object we can have the following syntax.

Integer intObj = new Integer (25); Integer intObj2 = new Integer ("25");

Here in we can provide any number as string argument but not the words etc. Below statement will throw run time exception (NumberFormatException)

Integer intObj3 = new Integer ("Two");

The following discussion focuses on the Integer wrapperclass, but applies in a general sense to all eight wrapper classes.

The most common methods of the Integer wrapper class are summarized in below table. Similar methods for the other wrapper classes are found in the Java API documentation.

returns a signed decimal integer value equivalent to string s

Let’s see java program which explains few wrapper classes methods.

package WrapperIntro; public class WrapperDemo < public static void main (String args[])< Integer intObj1 = new Integer (25); Integer intObj2 = new Integer ("25"); Integer intObj3= new Integer (35); //compareTo demo System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(intObj2)); System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(intObj3)); //Equals demo System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.equals(intObj2)); System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.equals(intObj3)); Float f1 = new Float("2.25f"); Float f2 = new Float("20.43f"); Float f3 = new Float(2.25f); System.out.println("Comparing using compare f1 and f2: " +Float.compare(f1,f2)); System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3)); //Addition of Integer with Float Float f = intObj1.floatValue() + f1; System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+" wrapper class image 2" style="max-width:100%;display:block;height:auto;border: 2px solid silver;"> 

valueOf (), toHexString(), toOctalString() and toBinaryString() Methods:

This is another approach to creating wrapper objects. We can convert from binary or octal or hexadecimal before assigning a value to wrapper object using two argument constructor. Below program explains the method in details.

 package WrapperIntro; public class ValueOfDemo < public static void main(String[] args) < Integer intWrapper = Integer.valueOf("12345"); //Converting from binary to decimal Integer intWrapper2 = Integer.valueOf("11011", 2); //Converting from hexadecimal to decimal Integer intWrapper3 = Integer.valueOf("D", 16); System.out.println("Value of intWrapper Object: "+ intWrapper); System.out.println("Value of intWrapper2 Object: "+ intWrapper2); System.out.println("Value of intWrapper3 Object: "+ intWrapper3); System.out.println("Hex value of intWrapper: " + Integer.toHexString(intWrapper)); System.out.println("Binary Value of intWrapper2: "+ Integer.toBinaryString(intWrapper2)); >> 

wrapper class image 3

  • Each of primitive data types has dedicated class in java library.
  • Wrapper class provides many methods while using collections like sorting, searching etc.

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Java Wrapper Classes

Wrapper classes provide a way to use primitive data types ( int , boolean , etc..) as objects.

The table below shows the primitive type and the equivalent wrapper class:

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

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):

Example

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

Creating Wrapper Objects

To create a wrapper object, use the wrapper class instead of the primitive type. To get the value, you can just print the object:

Example

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:

Example

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":

Example

Источник

Wrapper Classes in Java | Use, Example

Scientech Easy

A class that wraps a primitive data type into an object is called wrapper class in java.

In simple words, wrapper class provides a mechanism to convert primitive data type value into an object and vice-versa.

For example, wrapping int into Integer class, wrapping double into Double class, and wrapping char into Character class.

When we create an object of wrapper class, it contains a variable where we store the primitive data type value. In simple words, we can wrap a primitive type value into a wrapper class object.

For example, if we create an object of Integer wrapper class, it contains a single variable (or field) that will store an int value like 25, as shown in the below figure. Thus, Integer is a wrapper class of int data type.

Wrapper classes in Java

Code for Wrapping and Unwrapping an int value

int x = 25; Integer iWrap = new Integer(x); // Pass the primitive type to the wrapper constructor.
int unWrapped = iWrap.intValue();

Why we need or use wrapper classes in Java?

There are several reasons to use wrapper classes in java that are as follows:

1. We have seen several applications on the Internet that receive data from the user and send it to the server. For example, in a business application like Amazon, we enter our details like name, debit or credit card number, address, phone number, etc at the time of purchasing anything.

All these data are sent to the server. The server expects these data in the form of objects. In our data,” ‘name’ is a String type object, but debit card number is an int type value, that is not an object.

This primitive data type value must be converted into an object before being sent to the server. To overcome this conversion, we need wrapper classes in java.

A wrapper class contains a variable that stores the primitive data type value. When we create an object of a wrapper class, it carries the primitive data type value within it.

The object then is sent to the server. The server retrieves the primitive type value from the object and uses it.

2. In Java, collection classes (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) of Java collections framework are defined in java.util package which stores only objects, not primitive type values.

If we want to use collection classes on primitive type values, we should convert them into objects.

For example, we cannot directly store primitive data types in an ArrayList because elements in an ArrayList must be objects.

There is no such thing as “ArrayList”. Here, double is a primitive data type but it is not an object. Therefore, ArrayList will not compile.

To convert primitive type values into objects, the Java platform includes wrapper classes in the Java API. It provides a convenient way to incorporate or wrap a primitive data type into an object.

3. Java synchronization works with objects in Multithreading.

4. Since Java supports only call by value, therefore, if we pass a primitive value, it will not change the original value.

But, if we want to change the original value, we need to convert the primitive type value into an object that can be done using the wrapper class.

5. To perform serialization in java, we need to convert objects into streams. If we have a primitive value, we can convert it into objects with the help of java wrapper classes.

6. There are several utility classes defined in java.util package that deals with objects.

Java 5.0 version introduced two important new features autoboxing and unboxing that convert primitive data type values into objects and objects into primitive data type values automatically.

The process of automatic conversion of primitive data type into an object is known as autoboxing and vice versa unboxing.

Look at the source code and see how auto boxing and unboxing are automatically done by java compiler when we want to make an ArrayList to hold int value.

// With autoboxing (Java versions 5.0 or greater) ArrayList ar = new ArrayList(); // Making an ArrayList of type Integer. ar.add(3); int num = ar.get(0);

List of Wrapper classes in Java

Java platform provides the list of eight wrapper classes for each of the primitive types. These wrapper classes are defined in java.lang package.

All the java wrapper classes are immutable and final whose objects each hold a single primitive value. Immutable means once objects are created, their internal values cannot be changed. Methods of wrapper classes are implicitly final and may not be overridden.

They are useful to convert primitive data types into object forms. They are listed in the table below:

Table: Primitive Date types and their Corresponding Wrapper classes

Primitive Data type Corresponding Wrapper class
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean

Naming convention:

Names of the java wrapper class start with uppercase letters. Most wrapper class names are the same as primitive data type names, except Integer and Character.

The object of the Boolean class wraps the Boolean value true or false. To store double values in an ArrayList, we use an ArrayList.

Wrapper Classes Example Program

1. Let’s take an example program where we will convert a primitive data type int value into an Integer object explicitly. Java compiler will also convert automatically from int to Integer. This is called autoboxing. Look at the source code to understand better.

Program code 1:

The valueOf() method of Integer class is used to int number into Integer object. The return type of this method is object. This method is static in nature. Therefore, we call it using its class name.

2. We can also convert from Integer to int explicitly and implicitly by the compiler. Let’s write code for it.

Program code 2:

The intValue() method of Integer class is used to convert Integer object into a primitive int type value. This is called unboxing. The return type of this method is int.

Program code 3:

public class WrappingUnwrapping < public static void main(String[] args) < char ch = 'a'; // char data type. Character chrobj = new Character(ch); // Wrapping char type value into Character object. byte a = 10; // byte data type value. Byte byteobj = new Byte(a); // Wrapping byte type value into Byte object. int b = 20; // int type value. Integer intobj = new Integer(b); // Wrapping int type value into Integer object. float c = 18.6f; // float type value. Float floatobj = new Float(c); // Wrapping float type value into Float object. double d = 250.5; // double data type value. Double doubleobj = new Double(d); // Wrapping double data type value into Double object. // Displaying the values from wrapper class objects. System.out.println("Displaying values of Wrapper class objects:"); System.out.println("Character object: " + chrobj); System.out.println("Byte object: " + byteobj); System.out.println("Integer object: " + intobj); System.out.println("Float object: " + floatobj); System.out.println("Double object: " + doubleobj); System.out.println("\n"); // Retrieving primitive data type values from objects. // Unwrapping objects to primitive data type values. char chr = chrobj; byte by = byteobj; int in = intobj; float fl = floatobj; double db = doubleobj; // Displaying the values of data types. System.out.println("Displaying unwrapped values: "); System.out.println("char value: " + chr); System.out.println("byte value: " + by); System.out.println("int value: " + in); System.out.println("float value: " + fl); System.out.println("double value: " + db); >>
Output: Displaying values of Wrapper class objects: Character object: a Byte object: 10 Integer object: 20 Float object: 18.6 Double object: 250.5 Displaying unwrapped values: char value: a byte value: 10 int value: 20 float value: 18.6 double value: 250.5

1. Wrapper class in Java provides several constructors, constants, and conversion methods for manipulating various primitive data type values.

2. Wrapper classes have no no-arg constructors.

3. Character class does not have a constructor with String as a parameter.

4. The instances of all wrapper classes are immutable and final. That means once the object is created, its internal value cannot be changed.

Hope that this tutorial has covered important points related to wrapper classes in java with example programs. I hope that you will have understood this topic and enjoyed it.

If you find anything incorrect in this tutorial, then please inform our team via email. Your email will be precious to us.
Thanks for reading.

Источник

Читайте также:  Node js with php mysql
Оцените статью