Java Wrapper Classes

Introduction to Wrapper Classes in Java

Wrapper classes in Java are objects that encapsulate primitive data types. Each primitive data type has a corresponding wrapper class:

  • `boolean` - `Boolean`
  • `byte` - `Byte`
  • `short` - `Short`
  • `char` - `Character`
  • `int` - `Integer`
  • `long` - `Long`
  • `float` - `Float`
  • `double` - `Double`

Wrapper classes provide a number of advantages over primitive data types, including:

  • They can be used in generic collections and other APIs that only accept objects.
  • They provide methods for converting between primitive and object types.
  • They provide methods for comparing and manipulating primitive values.
  • They can be used to synchronize access to primitive values in multithreaded applications.

To create a wrapper object, you use the `new` keyword followed by the name of the wrapper class and the primitive value to be wrapped. For example, to create a `Integer` object wrapping the value `10`, you would use the following code:

Integer i = new Integer(10);

You can also use autoboxing to convert primitive values to wrapper objects automatically. Autoboxing is a feature of Java 5.0 and later that allows you to write code like this:

Integer i = 10;

The Java compiler will automatically convert the primitive value `10` to a `Integer` object before assigning it to the variable `i`.

Wrapper classes are an important part of the Java programming language. They provide a number of advantages over primitive data types, and they are used in a wide variety of Java APIs.

Here are some examples of how to use wrapper classes in Java:

// Create a wrapper object for the primitive value `10`.
Integer i = 10;

// Use the `intValue()` method to get the primitive value back from the wrapper object.
int j = i.intValue();

// Compare two wrapper objects.
if (i.equals(j)) {
  System.out.println("The two wrapper objects are equal.");
}

// Add two wrapper objects together.
Integer sum = i.intValue() + j.intValue();

// Use a wrapper object in a generic collection.
List list = new ArrayList<>();
list.add(i);
list.add(j);

Autoboxing and Unboxing

In Java, autoboxing and unboxing are mechanisms that automatically convert primitive data types (like int, double, boolean, etc.) to their corresponding wrapper class objects (like Integer, Double, Boolean, etc.) and vice versa, respectively. This simplifies programming by eliminating the need for manual conversion.

Autoboxing

When a primitive value is assigned to a wrapper class variable or passed as an argument to a method that expects a wrapper class object, the Java compiler automatically converts the primitive value into a wrapper class object. This is known as autoboxing.

int x = 10;
Integer y = x; // Autoboxing: x is automatically converted to an Integer object

In this example, the int value 10 is automatically converted to an Integer object and assigned to the variable y.

Unboxing

When a wrapper class object is used in a context where a primitive value is expected, the Java compiler automatically converts the wrapper class object into its corresponding primitive value. This is known as unboxing.

Integer z = 20;
int w = z + 5; // Unboxing: z is automatically converted to an int value

In this example, the Integer object z is automatically converted to an int value before the addition operation is performed.

Benefits of Autoboxing and Unboxing

  • Simplified code: Autoboxing and unboxing eliminate the need for manual conversion, making code more concise and readable.
  • Improved performance: The Java compiler often optimizes autoboxing and unboxing operations, resulting in efficient code execution.
  • Enhanced interoperability: Autoboxing and unboxing make it easier to work with collections and generic types that use wrapper classes.

Considerations

  • NullPointerException: Be cautious when using autoboxing with null values. If a wrapper class object is null and is unboxed, a NullPointerException will be thrown.
  • Memory usage: While autoboxing and unboxing are convenient, excessive use can potentially lead to increased memory consumption due to the creation of unnecessary wrapper objects.

Exercises

Code for converting an Integer to a String in Java using Wrapper classes.


  public class javalabclass 
  {
    public static void main(String args[])
      {
    
      Integer k = 23;
      String s = k.toString();
      System.out.println(s.length());
      
      }
  } 

Code for converting a String to an Integer using Wrapper Class in Java


  import java.util.Scanner;
  public class javalabclass 
  {
    public static void main(String args[])
     {
      Scanner input = new Scanner(System.in);
      System.out.println("Enter the number");
      String num = input.next();
      int a = Integer.parseInt(num);
      System.out.println(a+1);
     }
  } 

Code for finding max of two numbers using an Integer Wrapper Class in Java


  public class javalabclass 
  {
    public static void main(String args[])
      {
      Integer k;
      System.out.println(Integer.max(2, 3));
      }
  } 

Finding the sum of two Intgers using Wrapper Class method in Java


  public class javalabclass 
{
  public static void main(String args[])
    {
    System.out.println(Integer.sum(23, 45)); 
    }
} 

Code for comparing two Integer objects using Wrapper Class


  public class javalabclass 
  {
    public static void main(String args[])
      {
      Integer a = new Integer(52);
      Integer b = new Integer(52);
      System.out.println(a.equals(b)); 
      }
  } 

  Output - true   

Code for comparing two Integer Objects using compareTo Method.


  //comparing two equal Integers.
  public class javalabclass 
  {
    public static void main(String args[])
      {
      Integer a = new Integer(52);
      Integer b = new Integer(52);
      System.out.println(a.compareTo(b)); 
      }
  }
  
  Output is 0 
                
  //Integer a is greater than Integer b
  public class javalabclass 
  {
    public static void main(String args[])
     {
      Integer a = new Integer(51);
      Integer b = new Integer(52);
      System.out.println(a.compareTo(b)); 
     }
  }
  Output <0 
  
  //Integer a is lesser than Integer b
  public class javalabclass 
  {
    public static void main(String args[])
     {
      Integer a = new Integer(52);
      Integer b = new Integer(51);
      System.out.println(a.compareTo(b)); 
     }
  }
  Output >0 

Code for Comparing two characters using the Character Wrapper Class Methods in Java.


  //when char1 > char2

  package satish12bce10;
  import java.util.Scanner;
  public class satish12bce10 {
  
    public static void main(String[] args) {
      
       System.out.println(Character.compare('a', 'S'));
    }
  }
  
  output
  14
  
  //when char1 < char2
  
  package satish12bce10;
  import java.util.Scanner;
  public class satish12bce10 {
  
    public static void main(String[] args) {
      
       System.out.println(Character.compare('S', 'a'));
    }
  }
   
  output
  -14
  
  //When char1 = char2
  
  package satish12bce10;
  import java.util.Scanner;
  public class satish12bce10 {
  
    public static void main(String[] args) {
      
       System.out.println(Character.compare('S', 'S'));
    }
  }
  
  output
  0    

Code for Checking if a character is a digit using the Character Wrapper Class Methods


//When a entered character is a digit
package satish12bce10;
import java.util.Scanner;
public class satish12bce10 {

	public static void main(String[] args) {
		
	   System.out.println(Character.isDigit('9'));
	}
}

output 
true

//When a entered character is not a digit
package satish12bce10;
import java.util.Scanner;
public class satish12bce10 {

	public static void main(String[] args) {
		
	   System.out.println(Character.isDigit('a'));
	}
}
output 
false  

Checking if a character is a letter using the Character Wrapper Class Methods


  //When the entered character is a letter
  package satish12bce10;
  import java.util.Scanner;
  public class satish12bce10 {
  
    public static void main(String[] args) {
      
       System.out.println(Character.isLetter('a'));
    }
  }
  
  output
  true
  
  //When the entered character is not a letter
  package satish12bce10;
  import java.util.Scanner;
  public class satish12bce10 {
  
    public static void main(String[] args) {
      
       System.out.println(Character.isLetter('9'));
    }
  }
  
  output
  false 

Checking if a character is a whitespace using the Character Wrapper Class Methods


//Entered Character is a whitespace
package satish12bce10;
import java.util.Scanner;
public class satish12bce10 {

	public static void main(String[] args) {
		
	   System.out.println(Character.isWhitespace(' '));
	}
}

output 
true

Entered Character is not a whitespace
package satish12bce10;
import java.util.Scanner;
public class satish12bce10 {

	public static void main(String[] args) {
		
	   System.out.println(Character.isWhitespace('s'));
	}
}

output
false  

Check if a character is an upper case/ lower case character using the Character Wrapper Class Methods


  Character is an uppercase character
  package satish12bce10;
  import java.util.Scanner;
  public class satish12bce10 {
  
    public static void main(String[] args) {
      
     System.out.println( Character.isUpperCase('A'));
    }
  }
  
  output
  true
  
  Character is a lower case character
  package satish12bce10;
  import java.util.Scanner;
  public class satish12bce10 {
  
    public static void main(String[] args) {
      
     System.out.println( Character.isLowerCase('a'));
    }
  }
  
  output
  true   

Read a String from the user. The user may enter the string with leading or trailing spaces. Remove the leading and trailing spaces and display only the string without using the trim method.If the entry is only spaces then display an error message to the user.


  package satish12bce10;
  import java.util.Scanner;
  public class satish12bce10 {
  
    public static void main(String[] args) {
      
      System.out.println("Enter the String");
      Scanner obj = new Scanner(System.in);
      String input = obj.nextLine();
      char k[]= input.toCharArray();
      boolean spaceflag=true;
      for(char m: k)
      {
        if(Character.isWhitespace(m))
        {
          continue;
        }
        System.out.print(m);
        spaceflag = false;
      }
      if(spaceflag)
      {
        System.out.println("Enter a valid string. Only spaces entered");
      }
    }
  }
  
  //Output for only input spaces
  
  Enter the String
      
  Enter a valid string. Only spaces entered
  
  //Output for a string with leading and trailing spaces
  
  Enter the String
    Satish
  Satish