CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Data

Data
Basic skills
Casting

How implicit casting works

Casting from less precise to more precise data types

  • If you assign a less precise data type to a more precise data type, Java automatically converts the data type. This can be referred to as an implicit cast or a widening conversion.
  • Java also does implicit casting in arithmetic expressions.
byte=>short=>int=>long=>float=>double

Examples

double grade = 93; // convert int to double
double d = 95.0;
int i = 86, j = 91;
double average = (d+i+j)/3; // convert i and j to double values average = 90.666666...

How you can code an explicit cast

  • An explicit cast (or narrowing conversion) is from a more precise data type to a less precise data type, and you must use parentheses to specify the less precise data type. In an arithmetic expression, an explicit cast is done before the arithmetic operations.
(type) expression

Examples

int grade = (int) 93.25; // convert double to int (grade = 93)
double d = 95.0;
int i = 86, j = 91;
double average = ((int)d+i+j)/3; // convert d to int value (average = 90)
double result = (double) i / (double) j; // result has decimal places

How to cast between char and int types

  • Since each char value has a corresponding int value, you can implicitly or explicitly cast between these types
char letterChar = 65; // convert int to char (letterChar = 'A')
char letterChar2 = (char) 65; // this works too
int letterInt = 'A'; // convert char to int (letterInt = 65)
int letterInt2 = (int) 'A'; // this works too

Previous | Primitive data types | Variables | Constants | Assignment statements and arithmetic expressions | Order of preference | Casting | Next