Wrapper Class Usage in Java

Hello! After a very long break, I decided to continue my posts with Java series. Initally, I want to mention the usage of wrapper classes in Java. Let the coding begin.

The general purpos of the Wrapper Classes are to use primitive data types with alternatives. Here comes the primitive data types in Java (I assume you already know primitive types).

Primitive Data TypeWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter
Java Primitive Type List – Source: W3schools

Why do we need Wrapper Classes?

Here are the reasons of Wrapper Class usages

  1. In case you want to primitive types as objects
  2. java.util package can handle only classes and we can use wrapper classes by the way.
  3. Like ArrayList and Vector, we can handle primitive types by using wrapper classes in data structures.
  4. To create required objects for Multithreading syncronization.

Let’s have a look at the sample below:

I inserted the following lines in Main java file which is under root directory:

public class Main {
    public static void main(String [] args)
    {
        int number = 4;
        String string_degisken = Integer.toString(number);
        System.out.println("Sayı int tipinde: "+ number);
        System.out.println("Sayı string  tipinde: "+ string_degisken);
    }
}

The codeblock above will return the following output:

Sayı int tipinde: 4
Sayı string  tipinde: 4

As you realize in the sample codeblcok, we created two variables with string and integer type and printed both of them. For the first line, the output “46” was in integer primitive type and for the second line, the output “46” was in String type. I used toString method of Integer wrapper class to create the string variable as well. It is also possible to create other sample by using different methods of Integer wrapper class. Happy coding!