Type Casting Part 1
Part of the Fundamentals section of Coddy's Java journey — lesson 13 of 73.
Type casting is the process of converting a value from one data type to another.
In Java, we can convert integers to doubles, doubles to integers, and more. There are two types of casting: implicit (automatic) and explicit (manual) casting.
For example integer to double:
Implicit (automatic) casting:
int number = 5;
double decimal = number; // automatically becomes 5.0
// with calculation
int x = 7;
double result = x / 2.0; // result is 3.5Explicit (manual) Casting double to integer:
double decimal = 9.7;
int number = (int) decimal; // becomes 9 (decimal part is truncated)
// with calculation
double price = 19.99;
int roundedPrice = (int) price; // becomes 19Challenge
BeginnerWrite a Java program that demonstrates type casting. Perform the following operations:
- Declare a
doublevariable namedpriceand initialize it with the value99.99. - Cast the
pricevariable to anintand store the result in a new variable namedintPrice. - Print the values of
priceandintPrice, to the console.
Cheat sheet
Type casting converts a value from one data type to another. There are two types:
Implicit (automatic) casting - smaller to larger data types:
int number = 5;
double decimal = number; // automatically becomes 5.0Explicit (manual) casting - larger to smaller data types:
double decimal = 9.7;
int number = (int) decimal; // becomes 9 (decimal part is truncated)Try it yourself
public class Main {
public static void main(String[] args) {
// Declare and initialize variables
double price = 99.99;
int intPrice = ?;
// Output the values
System.out.println("Price: " + price);
System.out.println("Int Price: " + intPrice);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else