Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Type Casting

Java Type Casting

Type casting in Java occurs when you assign a value from one primitive data type to another.

In Java, casting can be categorized into two types:

Widening Casting(automatically) – Expanding the size of a type.

byte -> short -> char -> int -> long -> float -> double

Narrowing Casting (manually) – Reducing the size of a type.

double -> float -> long -> int -> char -> short -> byte

Widening Casting

Automatic widening casting occurs when passing a smaller-sized type to a larger-sized type.

Example

public class Main { 
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.println(myDouble); // Outputs 9.0 } }

Narrowing Casting

Manual narrowing casting is performed by enclosing the type in parentheses ( ) before the value.

Example

public class Main {
public static void main(String[] args) { double myDouble = 9.78d; int myInt = (int) myDouble; // Manual casting: double to int System.out.println(myDouble); // Outputs 9.78 System.out.println(myInt); // Outputs 9 } }

Real-Life Example

Below is an example demonstrating type casting in action, where we develop a program to determine the percentage of a user’s score relative to the maximum score achievable in a game.

We utilize type casting to ensure that the outcome is a floating-point value, as opposed to an integer.

Example

// Set the maximum possible score in the game to 500

int maxScore = 500;

// The actual score of the user int userScore = 423;

/* Calculate the percantage of the user’s score in relation to the maximum available score. Convert userScore to float to make sure that the division is accurate */

float percentage = (float) userScore / maxScore * 100.0f; 

System.out.println(“User’s percentage is “ + percentage);