java primitive wrapper classes code example

Example 1: What are the primitives and wrapper classes in java?

In Java, for each Primitive type, there is a matching class type.
  We call them Wrapper classes:
	Primitive types are the most basic data types
    available within the Java language. 
	There are 8: boolean , byte , char , short ,
                  int , long , float and double . 
	These types serve as the building blocks of
    data manipulation in Java.
	Wrapper classes: Byte, Short, Integer, Long,
                 Float, Double, Boolean, Character
			
	All the wrapper classes are subclasses
    of the abstract class Number. 
	The object of the wrapper class contains or
      wraps its respective primitive data type. 
	Converting primitive data types into object
    is called boxing, and this is taken care by the compiler.
			
			Differences: 
				1. Wrappers classes are object 
				2. null can only be assigned to classes
				3. Wrapper class does have methods
				4. Primitives does have default values
						default value of primitives:  
								 byte, short, int, long ==> 0
								 float, double ==> 0.0;
								 boolean ==> false;
								 char ==> space		 
				5. Default values of wrapper class: null

Example 2: java get wrapper class for primitive

// safe because both Long.class and long.class are of type Class<Long>
  @SuppressWarnings("unchecked")
  private static <T> Class<T> wrap(Class<T> c) {
    return c.isPrimitive() ? (Class<T>) PRIMITIVES_TO_WRAPPERS.get(c) : c;
  }

  private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS
    = new ImmutableMap.Builder<Class<?>, Class<?>>()
      .put(boolean.class, Boolean.class)
      .put(byte.class, Byte.class)
      .put(char.class, Character.class)
      .put(double.class, Double.class)
      .put(float.class, Float.class)
      .put(int.class, Integer.class)
      .put(long.class, Long.class)
      .put(short.class, Short.class)
      .put(void.class, Void.class)
      .build();

Example 3: primitive vs wrapper classes in java

Differences: 
				1. Wrappers classes are object 
				2. null can only be assigned to classes
				3. Wrapper class does have methods
				4. Primitives does have default values
						default value of primitives:  
								 byte, short, int, long ==> 0
								 float, double ==> 0.0;
								 boolean ==> false;
								 char ==> space		 
				5. Default values of wrapper class: null

Tags:

Java Example