Tag Archives: autoboxing

Java : Wrapper Classes

Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.

Wrapper classes  implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Advantages of Wrapper Class

Wrapper classes helps where we can’t use primitive type values only need objects. Compiler automatically converts primitive type to correspoing Wrapper classes as required.
Below are some most common advantages of wrappe classes:

  • Wrapper class required to convert the primitive data types in to objects. (Objects required when handling with collections)
  • In Generics programming, can be used with classes only not with primitive types.
  • Package java.util(Collections) contains only classes which only handles objects.
  • In multi threading, we need object to support synchronization.
  • These classes in java.lang package so no need to explicitly import it.

The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes are given below:

Primitive Type Wrapper Description
boolean Boolean The Boolean class wraps a value of the primitive type boolean in an object.
char Character The Character class wraps a value of the primitive type char in an object.
byte Byte The Byte class wraps a value of primitive type byte in an object.
short Short The Short class wraps a value of primitive type short in an object.
int Integer The Integer class wraps a value of the primitive type int in an object.
long Long The Long class wraps a value of the primitive type long in an object.
float Float The Float class wraps a value of primitive type float in an object.
double Double The Double class wraps a value of the primitive type double in an object.

Wrapper Type Class Hierarchy

Java Wrapper Classes for primitive Type
Java Wrapper Classes for Primitive Type

Note : The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.

Now you have learned about primitive type and corresponding wrapper Type and it’s class hierarchy. In further section you will lean about Autoboxing and Unboxing i.e conversion from primitive type to wrapper class or wrapper class to primitive type.

Autoboxing/Unboxing (Java 5+)

  • Autoboxing: Automatically converts primitive type into object/Wrapper Class.
    int a=30;
    //Manually covert int to Integer
    Integer k=Integer.valueOf(a);
    //Autoboxing, compiler will automatically convert to Integer and internally generate Integer.valueOf(a)
    Integer j=a;
    
  • Unboxing: Automatically converts object/Wrapper Class into primitive type.
    Integer a=new Integer(30);
    //Manually convert Integer to int
    int j=a.intValue();
    //Unboxing , compiler will automatically convert to int and internally generate a.intValue();
    int j=a;
    

From above example you can understand how internally conversion happen between primitive to wrapper class and wrapper class to primitive type.

Now here  corresponding to each wrapper class link you will get list of Constants, methods and exceptions.

References

https://docs.oracle.com/javase/8/docs/api/?java/lang/Integer.html
https://docs.oracle.com/javase/tutorial/java/data/numberclasses.htmlhttps://docs.oracle.com/javase/tutorial/java/data/numberclasses.html

Java : Widening ,Narrowing Type Casting and Type Promotion In Expression

 

Java Widening and Narrowing Type Casting
Java Widening and Narrowing Type Casting

Widening

Widening, also known as up-casting / automatic conversion that takes place in the following situations :

  • When a small primitive type value is automatically accommodated in a bigger/wider primitive data type.
  • When a reference variable of a subclass is automatically accommodated in the reference variable of its super class.

Note : Widening happen when data type are compatible or conversion from lower to bigger type. Widening is automatic process by Java compiler.

Primitive Type Widening Example

Order of Widening conversion

Byte->Short->Int->Long->Float->Double

public class PrimitiveWidening {

	public static void main(String[] args) {
		int i=200;
		float f=i;
		long l=i;

		System.out.println("Int :"+i);
		System.out.println("Float :"+f);
		System.out.println("Long :"+l);
	}
}

Output


Int :200
Float :200.0
Long :200

Here type conversion is from lower or upper that is widening of primitive type data and that’s not required any type of casting explicitly.

Reference Type Widening Example

public class Doctor {
	public void getDetail() {
		System.out.println("Doctor Detail !!!");
	}
}

public class Surgeon extends Doctor {
	public void getDetail() {
		System.out.println("Surgeon Detail !!!");
	}
}

public class ReferenceTypeWidening {

	public static void main(String[] args) {
		Surgeon s=new Surgeon();
        //Reference of Sub class(Surgeon) type is widened to the Super class (Doctor)
		Doctor d=s;
		d.getDetail();
	}
}

Output


Surgeon Detail !!!

In the previous code, we have a class Doctor extended by class Surgeon, hence Doctor is a super class and Surgeon is its subclass. Method getDetail() of super class Doctor is overridden in subclass Surgeon.
We have created an object of subclass Surgeon, which is assigned to its reference, s.
This subclass Surgeon reference, s is widened/up-casted and assigned to super class Doctor reference, d.

Narrowing

Narrowing also known as down-casting/explicit casting is conversion that take place in such situations:

  • Narrowing a wider/bigger primitive type value to a smaller primitive type value..
  • Narrowing the super class reference to the reference of its subclass, during inheritance.

Note : Narrowing happen when data type are incompatible or conversion from bigger to lower type. That require explicit casting of data. While narrowing of data type some of data values can lost.

Primitive Type Narrowing Example

Order of Narrowing conversion

Double->Float->Long->Int->Short->Byte

public class PrimitiveNarrowing {

	public static void main(String[] args) {
		double d=2567834.38;
		//Narrowing required explicitly type casting
		float f=(float)d;
		long l=(long)d;
		int i=(int)d;
		short s=(short)d;
		byte b=(byte)d;

		System.out.println("Double :"+d);
		System.out.println("Float :"+f);
		System.out.println("Long :"+l);
		System.out.println("Int :"+i);
		System.out.println("Short :"+s);
		System.out.println("Byte :"+b);
	}
}

Output


Double :2567834.38
Float :2567834.5
Long :2567834
Int :2567834
Short :11930
Byte :-102

Here type conversion is from upper or lower type that is narrowing of primitive type data and that’s required explicit type casting and will loss some of values because every smaller type data have limited range.

Reference Type Widening Example

public class Doctor {
	public void getDetail() {
		System.out.println("Doctor Detail !!!");
	}
}

public class Surgeon extends Doctor {
	public void getDetail() {
		System.out.println("Surgeon Detail !!!");
	}
}

public class ReferenceTypeNarrowing {

	public static void main(String[] args) {
		//Object of sub class is reference by reference of super class(Doctor)
		Doctor d=new Surgeon();
        //Reference of Superclass(Doctor) type is narrowing to the Sub class (Surgeon)
		Surgeon s=(Surgeon)d;
		s.getDetail();
	}

}

Output


Surgeon Detail !!!

In the previous code, we have a class Doctor extended by class Surgeon, hence Doctor is a super class and Surgeon is its subclass. Method getDetail() of super class Doctor is overridden in subclass Surgeon.
We have created an object of subclass(Surgeon), which is assigned to the reference of super class(Doctor), d.
This super class(Doctor) reference, d is narrowed/down-casted and assigned to subclass(Surgeon) reference, s.

Now we have understand the concept of Widening and Narrowing of data type/reference type values. These are straight forward case where we can easily understand like that required widening or narrowing of data.
In next part we will see how to handle widening or narrowing of data while executing an expression.

Type Promotion in Expressions

While execution of an expression intermediate value may exceed that range of operands and hence expression value will be promoted. Some conditions for type promotion are:

  • Java automatically promotes each byte, short, or char operand to int when evaluating an expression.
  • If one operand is a long, float or double the whole expression is promoted to long, float or double respectively.

Example

public class TypePromotionInExpression {

public static void main(String[] args) {
byte b = 52;
char c = 'b';
short s = 1026;
int i = 60000;
float f = 4.57f;
double d = .4231;

// The Expression
double result = (f * b) + (i / c) - (d * s);

//Result after all the promotions are done as double
System.out.println("Expression Result = " + result);

//Explicit Type Casting as Int. As Int is whole number
//that's what above double result will lost precision.
int intResult=(int)result;
System.out.println("Int Result = " + intResult);
}
}

Expression Result = 415.5394146484375
Int Result = 415

As per above type promotion conditions for expression there is one value type is double as bigger type that’s what complete expression result will convert to double type.

As we have learn about narrowing of data required between incompatible type or bigger to lower type conversion. Here expression result is double and want to convert as int that required explicit type conversion and that will lost precision value because int is whole number and not have any precision value.

References

https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html