Primitive And Wrapper Classes

Primitive and Wrapper Classes in Java

In Java, data types can be categorized into two main groups: primitive types and reference types. Primitive types represent basic data types, such as numbers and characters, while reference types represent objects and provide more advanced functionality.

Primitive Types

Primitive types are predefined by the Java language and have a fixed size in memory. They are used to store simple values and do not have additional methods or properties.

Java provides eight primitive types:

  • byte: Represents a signed 8-bit integer.
  • short: Represents a signed 16-bit integer.
  • int: Represents a signed 32-bit integer.
  • long: Represents a signed 64-bit integer.
  • float: Represents a single-precision 32-bit floating-point number.
  • double: Represents a double-precision 64-bit floating-point number.
  • char: Represents a single character.
  • boolean: Represents a boolean value (true or false).

Wrapper Classes

Wrapper classes provide a way to treat primitive types as objects. They wrap the primitive values and provide additional methods and functionalities.

Java provides a set of wrapper classes, each corresponding to a primitive type:

  • Byte: Wrapper class for byte.
  • Short: Wrapper class for short.
  • Integer: Wrapper class for int.
  • Long: Wrapper class for long.
  • Float: Wrapper class for float.
  • Double: Wrapper class for double.
  • Character: Wrapper class for char.
  • Boolean: Wrapper class for boolean.

Example:

Here's an example that demonstrates the usage of primitive and wrapper classes:

    
      int num1 = 10; // primitive type
      Integer num2 = Integer.valueOf(num1); // wrapper class
      
      System.out.println("Primitive Type: " + num1);
      System.out.println("Wrapper Class: " + num2);
      
      int sum = num1 + num2.intValue(); // Unboxing: converting wrapper to primitive
      System.out.println("Sum: " + sum);
    
  

In the above example, we have an integer value stored in the primitive variable `num1`. We convert it to an `Integer` object using the `valueOf()` method of the `Integer` wrapper class.

We can then perform operations using both the primitive type and the wrapper class. In the example, we add the primitive value `num1` with the unboxed value of `num2` (obtained using the `intValue()` method).

Wrapper classes are commonly used when working with collections, generics, and other scenarios that require objects instead of primitive types. They provide additional functionalities and allow seamless integration with the Java API.

Go To OOPS Page Click Here

Post a Comment

Previous Post Next Post