3️⃣

3.3 Type-Casting

Chapter Table of Contents

💾
Ch. 3 Data

Subsection Table of Contents

What is Type Casting?

Type casting is where you can convert a variable’s numeric data type into another one. This is really handy if you want a variable to be more precise/less precise. There are two types of type casting in Java: widening casting and narrowing casting.
 

Widening Casting

Widening casting is where you want to convert from a smaller numeric data type to a larger data type. Fortunately, this is automatically done by Java, so you don’t have to do anything here. But, it is still important to understand the logic.
byte → short → char → int → long → float → double
 
Here’s an example:
public class MyClass { public static void main(String[] args) { int myInt = 9; double myDouble = myInt; //Automatic casting: int to double System.out.println(myInt); //Outputs 9 System.out.printlin(myDouble); //Outputs 9.0 } }
 

Narrowing Casting

Narrowing Casting is pretty much the opposite of widening casting in that you use it when you want to convert a larger data type into a smaller one. This is not automatically done by Java, so you have to manually do it.
double → float → long → int → char → short → byte
 
To narrow cast, you put the data type that you want to cast the variable into in a pair of parentheses. For example, if I have a variable of type double and I want to convert it into an int, then I would put int in front of the variable. Here’s an example:
public class MyClass { public static void main(String[] args) { double myDouble = 9.78; int myInt = (int) myDouble; //Manual casting: int to double System.out.println(myDouble); //Outputs 9.78 System.out.printlin(myInt); //Outputs 9 } }
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.