Type Casting in Java | conversion | Variable | Examples

What is Type Casting in Java? Typecasting is in the Programming world used to convert objects or variables of one type into another. When we are converting or assigning one data type to another they might not compatible. If it is suitable then it will do smoothly otherwise chances of data loss.

Type Casting in Java conversion Variable Examples

In this Tutorial we will learn about type conversion (casting), casting types with examples in Java.

Typecasting Types in Java

Type casting is classified into the following two types.

  • Widening Casting(Implicit) – Automatic Type Conversion
  • Narrowing Casting(Explicitly done) – Need Explicit Conversion


A simple Java type casting syntax for variables.

Type casting examples in Java

Type conversion java and type casting java is both same.

Output screenshot:

Type conversion java and type casting java example output

Widening Casting (smaller to larger type)

When assigning a smaller data type to bigger than its data called implicit (Widening) casting.

Java Widening Casting or Automatic Type casting example

Widening Casting or Automatic Type casting take place when,

  • the two types are compatible
  • the target type is larger than the source type

Example of Widening Casting program.

Output: Int value Original 99
The long value after casting 99
Float value after casting 99.0

Narrowing Casting (larger to smaller type)

An assigning a larger data type value to a smaller data type, then you need to perform explicitly (Narrowing) typecasting. There are chances of data loss, for example, converting float 7.3 to int 7.

Java Narrowing Casting Need Explicit Conversion example

Example of Widening Casting program. How to do explicit type casting.

Output: Double value Original 99.74
The Long value 99
Int value 99

Conclusion: Type is very useful when you want to specify a data type in programming. It allows to you to handle many coding situations. But sometimes you need extra careful about data loss.

To know about Casting objects in Java must follow this link – Java Downcasting | Java Upcasting | Casting objects

Exercise Question: What is the Use of TypeCasting in java?

Write the answer below in comment section.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Type Casting in Java with example PDF are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.