Interchanging Numeric Values In Java

Try out the code

public class ConvertNumericVal {  	  	public static void main( String[] args ){  		int intVal = 30;  		int intVal1 = intVal;  //We got two copies of the value    		System.out.println("intVal1 is: " +intVal1);    		long longVal = intVal1;    		System.out.println("longVal is: " +longVal);    		//short shortVal = intVal1; //ERROR!    		short shortVal = (short) intVal1;  //typecasting -> narrowing the type    		System.out.println("shortVal is: " +shortVal);    		int intVal2 = 700;    		//byte byteVal =  intVal2; //ERROR!    		byte byteVal = (byte) intVal2;  //risk of losing data    		System.out.println("byteVal is: " +byteVal);    		double doubleVal = 1.91111d;    		int intVal3 = (int) doubleVal;  //narrowing. Truncation results in loss of data.    		System.out.println("intVal3 is: " +intVal3);  	}    }

Notes:

  • While working with primitives, you’re always making copy of value. You are not creating reference to original value.
  • Converting from a type which uses smaller amount of memory to a type which uses larger amount of memory is called widening the type.
  • From amount of memory type to smaller amount of memory type -> narrowing the type.
  • Widening type is automatic. No risk of losing data.
  • Narrowing type requires typecasting. Risk of losing data.

Output

  • intVal1 is: 30
  • longVal is: 30
  • shortVal is: 30
  • byteVal is: -68
  • intVal3 is: 1