Java Conversion Types and Conversion Contexts

When an expression evaluated in Java programing language it either produce a result or nothing. An expression denotes nothing if and only if it is a method invocation. An expression produce a result has a type that can be deduced at compile time from the structure of the expression, the types of the literals, variables, and methods mentioned in the expression.

The expression that produce a result will always evaluated in some context and it must be compatible with a type expected in that context; this type is called the target type.

The compatibility of expression with it's surrounding context type is determined as 

  • The expression the deduced type can be influenced by the target type
  • After the type of the expression has been deduced, an implicit conversion from the type of the expression to the target type can be performed

If neither of the above strategy is able to produce the appropriate type, a compile-time error occurs. In some cases context is able to accept a expression type but require a programmer intervention to type conversion explicitly.

Note:-

  • Implicit conversion automatically done by java and there is no error at compile time
  • Explicit conversion requires the programmer intervention to type cast expression type to target type otherwise occurs a compile time error

Kind Of Conversion

In every conversion context, only certain specific conversions are permitted. For convenience of description, the specific conversions that are possible in the Java programming language are grouped into given categories


Identity conversion

In Java every type permitted a conversion from a type to that same type.

 

Widening primitive conversions

Below specific conversion are called widening primitive

byte to short, int, long or float, double
short to int, long, float or double
char to int, long, float or double
int to long, float or double
long to float or double
flout to double

  • A widening primitive conversion does not lose information about the overall magnitude of a numeric value
  • A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode

example:-

public static void main(String[] args){
    int intValue = 1000000001;
    float floatValue = intValue; // widening conversion
    System.out.println(intValue - (int) floatValue);
}

result: 1

  • Widening primitive conversion never results in a run-time exception

 

Narrowing primitive conversions

Below specific conversion are called narrowing primitive conversion

short to byte or char
char to byte or short
int to byte, short, or char
long to byte, short, char, or int
float to byte, short, char, int, or long
double to byte, short, char, int, long, or float

  • A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range
  • double to float conversion can lose precision, and also lose the range
  • A narrowing conversion of a signed integer to an integral type simply discards all the bits except the n lowest order bits, where n is the number of bits used to represent integral type. Here there is a possibility of information loss about the magnitude of the numeric value
  • byte to char : this conversion combines both widening and narrowing primitive conversions. First, the byte is converted to an int via widening primitive conversion and then the resulting int is converted to a char by narrowing primitive conversion


Widening reference conversions

A widening reference conversion exists from any reference type S to any reference type T, where S is a sub type of T.

example:-

public class A{

//class statements

}

public class B extends A{

// class statements

}

public class Main{

 public static void main(String ...s){

 B bObject = new B(); 

 A a = bObject; // widening reference conversion

 }

}

Narrowing reference conversions

Six kinds of conversions are called the narrowing reference conversions

  • From any reference type S to any reference type T, provided that S is a super-type of T
  • From any class type C to any non-parameterized interface type K, provided that C is not final and does not implement K
  • From any interface type J to any non-parameterized class type C that is not final
  • From any interface type J to any non-parameterized interface type K, provided that J is not a sub-interface of K
  • From the interface types Cloneable and java.io.Serializable to any array type T[]
  • From any array type SC[] to any array type TC[], provided that SC and TC are reference types and there is a narrowing reference conversion from SC to TC

Such conversions require a test at run time to find out whether the actual reference value is a legitimate value of the new type. If not, then a ClassCastException is thrown.

Boxing conversions

Boxing conversion converts expressions of primitive type to corresponding expressions of reference type.

example:- from type boolean to type Boolean as

boolean a = true;
Boolean b = a;

Unboxing conversions

Unboxing conversion converts expressions of reference type to corresponding expressions of primitive type

example:- from type Boolean to type boolean

Unchecked conversions

Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a non-generic (non qualified) type.

There is an unchecked conversion from the raw class or interface type G to any parameterized type of the form G<T1,...,Tn>.

example:-

Set<String> set = new HashSet();

here compiler issued a unchecked warning. The unchecked warning is suppressed by the Suppress Warnings annotation but you should try to improve your code instead of suppressing the warning.

Capture conversions

Capture conversion is what allows the compiler to manufacture a placeholder type name for the captured wildcard, so that type inference can infer it to be that type

Value set conversions
Value set conversion is the process of mapping a floating-point value from one value set to another without changing its type


Kind Of Conversion Context

There are five conversion contexts in which conversion of expressions may occur

Assignment conversion context
converts the type of an expression to the type of a specified variable. the type of the expression must be converted to the type of the variable.

Assignment conversion may cause an below exemption at runtime.

  • OutOfMemoryError in case of boxing conversion
  • NullPointerException as a result of an unboxing conversion on a null reference
  • ClassCastException if the resulting value of expression is type of object which is not the instance of subclass or subinterface of the type of variable

Invocation conversion context
Invocation contexts allow an argument value in a method or constructor invocation to be assigned to a corresponding formal parameter. If the type of the expression cannot be converted to the type of the parameter by a conversion permitted invocation context, then a compile-time error occurs.
Except some cases invocation context allows the same conversion as assignment context and can cause the same runtime exception.

Casting conversion context
Converts the type of an expression to a type explicitly specified by a cast operator. It is more inclusive than assignment or method invocation conversion, allowing any specific conversion other than a string conversion, it allows the primitive type as well as the reference type casting but certain casts to a reference type may cause an exception at run time.

String conversion context
String contexts applies only to an operand of the binary + operator which is not a String when the other operand is a String. The target type of these context is always a String type.
String conversion may cause an OutOfMemoryError to be thrown at run time

Numeric promotion context
Numeric contexts apply to the operands of an arithmetic operator. brings the operands of a numeric operator to a common type so that an operation can be performed.
It is a process by which, given an arithmetic operator and its argument expressions, the arguments are converted to an inferred target type T. T is chosen during promotion such that each argument expression can be converted to T and the arithmetic operation is defined for values of type T.
There are two kinds of numeric promotion as Unary numeric promotion and Binary numeric promotion.


For deep dive into conversion and promotion/context refer Oracle Documentation

Comments

Popular Posts

Load Balancing usign HAProxy for Openfire

Enable JMX Port in Tomcat with authentication