Primitive Data Types


🙋 Need help? Ask an expert now!

Casting is the action of converting between two different data types such as converting an int to a double and vice versa. Examine the code below for examples of casting.
package exlcode;

public class CastingExample {

  // this converts 15.23 into an integer
  public static int exampleVariableOne = (int) 15.23;
  public static double exampleVariableTwo = exampleVariableOne;

  public static void main(String[] args) {

We just converted the double value 15.23 into an integer, which left only the whole number and the decimal places to be cut off. There is no rounding, it just ignores the numbers after the decimal point during casting. When you convert an int to a double, a decimal point will be added to match with the structure of a double. For example, double varOne = (double) 15; assigns 15.0 to varOne.

Even though it is possible to convert an int to a double without casting, it is best practice to always use casting for precision and thorough logic. Also, be careful with the loss of precision when converting data types. i.e. losing decimal points is losing precision.

Edit Me on GitHub!

Application Question

Consider the following code segment:

double piValue = 3.14159;
int radius = 5000;
int circumference = (int)(2 * piValue * radius);

What is printed as a result of executing this code segment?