๐ŸŽ“ A1Learner
๐Ÿ”

Java Type Casting

Type casting is the conversion of a value from one type to another type. Widening conversions happen automatically, and narrowing conversions need a cast written in the code.

Widening happens automatically

An int value moves into a double variable with no cast. The printed value gains a decimal point.

public class Main {
  public static void main(String[] args) {
    int count = 5;
    double wide = count;
    System.out.println(wide);
  }
}

Narrowing needs a cast

The cast in front of the value turns it into an int. The decimal part drops away.

public class Main {
  public static void main(String[] args) {
    System.out.println((int) 5.9);
  }
}

The division pair

The first line divides two whole numbers. The second line casts 5 to double before the division.

public class Main {
  public static void main(String[] args) {
    System.out.println(5 / 2);
    System.out.println((double) 5 / 2);
  }
}

Example

public class Main {
  public static void main(String[] args) {
    int score = 7;
    double wideScore = score;
    double exact = 7.9;
    int whole = (int) exact;
    System.out.println(wideScore);
    System.out.println(whole);
  }
}

Key points

  • Widening moves a value into a larger type.
  • Widening happens automatically.
  • Narrowing moves a value into a smaller type.
  • Narrowing needs a cast written before the value.
  • A cast to int drops the decimal part of a value.
  • Division of two whole numbers gives a whole number.

In this example, score holds 7 as an int. The value widens into a double and prints as 7.0. A cast turns 7.9 into an int, and that value prints as 7.

Note

A cast changes a value for that one use, and the original variable keeps its value.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Java Compiler

Exercise

What does (int) 5.9 print?