21 August 2023

Wrapper Class In Java - learngreen.net

 

Wrapper Class

In the realm of Java programming, data comes in different types, like numbers, letters, and true/false values. Sometimes, we want to treat these basic types as if they were fancier objects, giving us extra abilities to work with them. Enter wrapper classes – these are like cool jackets that wrap around simple data, making them look and behave like full-blown objects.


Java programmers frequently work with several forms of data, including numbers, characters, and true/false values. By offering "wrapper classes," Java makes it much more intriguing. These classes provide our fundamental data types a little magic, transforming them into adaptable objects. Let's explore wrapper classes using some straightforward examples.


Wrapper classes act as our companions, helping us transform our fundamental data types (such as int, char, boolean, etc.) into elegantly attired objects. They enable us to employ these basic types as though they were superhumans wearing capes who could perform additional feats.


Because they are object-oriented, generic classes do not support primitives. Wrapper classes are therefore necessary because they transform primitive data types into objects, and objects are essential if we need to modify the inputs supplied into a method. Now let's examine the Wrapper Classes in more detail.


The java.lang package, which is part of the Java programming language, contains classes that are crucial to the design, the most important of which being Object and Class.


The values of primitive data types are therefore wrapped in or represented by Java wrapper classes, which are objects. A field that can contain primitive data types is included when a wrapper class object is constructed.


A Double type object, for example, contains only fields of the Double type, representing that value such that a reference to it can be retained in a variable of reference type. An object of one type contains only fields of that type.


Need Of Wrapper Classes:-
Imagine you have a magical toolbox filled with amazing tools, but there's a rule  you can only use objects, not plain numbers or letters. But wait, most of our data is just plain numbers and letters, right? That's where wrapper classes swoop in. They turn your regular numbers, letters, and such into objects, so you can use them with all those magical tools in your toolbox.


The user frequently needs to work with objects in Collections, Synchronization, Serialization, and other areas even though Java is an object-oriented programming language. Let's look at a few situations where wrapper classes are necessary.
To conduct the serialization, we must first transform the objects into streams. The wrapper classes can be used to turn a primitive number into an object.


Java is limited to calling methods with arguments. Because of this, the original value is unaffected if a primitive value is passed. The original value is altered when a primitive value is turned into an object, though.
Java uses multi-threaded classes for synchronization.
Java's collection framework only functions with objects. 
All of the classes in the collection framework are object-oriented, including Vector, HashSet, LinkedHashSet, PriorityQueue, ArrayList, TreeSet, LinkedList, and ArrayDeque.


There are helpful classes for interacting with objects in the java.util package.


Autoboxing :-
It is the operation that convert primitive data type into objects with the proper wrapper classes. It transforms primitive type byte to Byte,
boolean to Boolean char to Character, double to Double, float to Float, long to Long and short to Short. The difference between primitive and wrapper types lies in their naming conventions. Primitive types are denoted with lowercase letters and often have short forms, whereas wrapper classes use their full names with the initial letter capitalized.


Unboxing:-
The process of instantly converting a wrapper type into its primitive type counterpart is known as unboxing. It's autoboxing done backward. Since Java 5, we are no longer required to convert wrapper types to primitives using the intValue() method of the wrapper classes. For instance, double to double, integer to int, and so forth.


The Java compiler uses unpacking when an object of a wrapper class is used as a parameter to a function that expects a value of the corresponding primitive type or when it is assigned to a variable of the corresponding primitive type.


Wrapper Class Methods:-


typeValue( ) – Converts a specific Number object's value to the returned primitive data type.


compareTo( ) compares the argument with the Number object.


equals( ) verifies that the Number object matches the supplied argument.


Returns an Integer object with the value of the provided primitive data type for valueOf( ).


Returns String object with the value of the supplied Integer type parameter using the
 toString( ) method.


parseInt( ) returns a value of the specified String representation as an Integer type.


The function decode( ) converts a String into an integer.


When comparing two inputs, min() delivers the lower number.


When comparing two inputs, max( ) returns the larger number.


round( ) - Depending on the method return type, returns the closest round off of an int or long value.




 //Integer Wrapper Illustration
 package Java;
 public class WrapperIllustration {
 public static void main(String[] args) {
 // Wrapping an int into an Integer	 
 Integer Number = new Integer(85);
 //Unwrapping: Converting Integer back to int
 int uwNumber = Number.intValue();
 System.out.println(Number);
 System.out.println(uwNumber);
 // Output-> 85
 //          85
	}
 }

 


 //Character Wrapper Illustration
  package Java;
  public class CharacterWrapperIllustration {
  public static void main(String[] args) {
  // Wrapping a char into a Character
  Character Letter = new Character('X');
  //Unwrapping: Converting Character back to char
  char uwLetter = Letter.charValue();
  System.out.println(Letter);
  System.out.println(uwLetter);
  // Output-> X
  //          X        
	}
  }

 


    //Boolean Wrapper Illustration
   package Java;
   public class BooleanWrapperIllustration {
   public static void main(String[] args) {
   // Wrapping a boolean into a Boolean	 
   Boolean Flag = new Boolean(true);
   // Unwrapping: Converting Boolean back to boolean
   boolean uwFlag = Flag.booleanValue();
   System.out.println(Flag);
   System.out.println(uwFlag);
   //Output-> true
   //         true
	  }
   }

 


   package Java;
   public class WrapperMethod {
   public static void main(String[] args) {
   String str = "852";
   //Converts string to Integer
   Integer ParsedInt = Integer.parseInt(str);
   //Print the parsed Integer value
   System.out.println(ParsedInt);
   //Output-> 852
	  }
   }

 


 // Autoboxing & Unboxing Illustration
  package Java;
  public class AxUx {
  public static void main(String[] args) {
  // Autoboxing: int to Integer
  Integer boxedInt = 35;
  // Unboxing: Integer to int
  int unboxedInt = boxedInt;
  System.out.println(boxedInt);
  System.out.println(unboxedInt);
	 }
  }

 


   //Comparison using Wrapper Method
    package Java;
    public class CNW {
    public static void main(String[] args) {
    Integer num1 = 8;
    Integer num2 = 28;
   //Compare two Integer objects
    int result = num1.compareTo(num2);
    System.out.println(result);
	}
  }
  

 


  //Handling Null Values
    package Java;
    public class WN {
    public static void main(String[] args) {
    // Declare an Integer variable and assign it a null value	 
   Integer missingNum = null;
   //Check if the missingNum variable is null
   if (missingNum == null) {
   /* If the variable is null, print a message
    * indicating the number is missing 
    */
	 System.out.println("Number is missing");
         }
      }
   }
  

The benefits of  Wrapper classes:-

Object-Oriented Capabilities:-

You can treat primitive data types as objects by utilizing wrapper classes. This entails that you can use inheritance, call methods on them, and other object-oriented characteristics.

Interoperability:-

Some Java libraries and APIs require objects rather than primitives. Wrapper classes, which enable the use of primitives as objects in such situations, aid in bridging this gap.


Handling Null Values:-

Primitive data types cannot represent null values; however, wrapper classes can. When you need to express the lack of a value, this is extremely helpful.


Closure:-

In Java, the primitive data type is contained within the class object via wrapper classes.Wrapper classes for Java are contained in the java.lang module. The Java Collection Framework's data structures, like ArrayList, only store objects; they do not store primitive types. The processes of autoboxing and unpacking convert simple data types into objects and back again. Instances of wrapper classes can be useful in a number of situations, such as synchronization, serialization, collections, and so forth. The primitive data type int does not allow us to assign an instance of the Integer class to null.


No comments:

Post a Comment