Numerical Casting in Java

Numerical Casting in Java

 

Numerical Casting in Java, In this Article i will talk about what is Numerical Casting use in Java

There are alot of Numerical Types in Java ( byte, short, long , integer, double , float etc . Some time you might need to convert the types of numerical variable individually to suit your Application needs

In Java, when you try to do mathematical calculation  using different type of variable. Java will automatically convert the type of the result variable according to the rules listed below

  1. If one of the Value is double , the calculation result will be converted  to a double.
  2. If one of the Value is double , but the other value is float , the mathematical result will be converted to float
  3. If there are no value is float or double, but there is long the mathematical result will be converted to long
  4. If all 3  ( float , double , long ) does not exist , it will be coneverted to int.

Sample Code 

  1. In this Sample code i have list out all the different variable type
  2. And then i used the “(int) , (double) etc “ trying to convert different Data Type

 

package casting;

public class cast {

	public static void main(String[] args) {


		byte byteValue = 50;
		short shortValue = 60;
		int intValue = 70;
		long longValue = 24000;
		double doubleValue =24.5;
		float floatValue = 99.f;
		
		// The Integer Value automatically converted into a double
		
		doubleValue = intValue;
		
		
		System.out.println(doubleValue);
		
		// Convert Float Value into Integer
		
		intValue = (int)floatValue;
		
		System.out.println(floatValue);

	}

}



 

Results

Check out Encapsulation in Java Here

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × one =