Java Type Casting


Java-W3schools Blog. Quick guide to Type Casting in Java. Type casting is used to convert an object or variable of one type into another.

1. Type Casting Overview

In this tutorial, We'll learn what is Type Casting and how it works in Java.

Type casting is used to convert an object or variable of one type into another.

This is done in two ways.

A) Implicit conversion or type casting
B) Explicit conversion or type casting

Java Type Casting

1.1 Syntax

DataType variableName = (DataType) variableNameToConvert;

The above syntax is to covert one type to another type by specifying the Data Type of Target.

2. Implicit Type Casting

This is also called as Automatic Type Conversion or Widening.

If we assign value of one variable type to another, two types may be compatible or not compatible to each other.

If compatible then conversion will be done automatically. This type of conversion is called Automatic Type Conversion.

DataType1 type_variable_name = another_type_variable_name

This implicit conversion is done in 2 scenario's.

1) If both types are compatible
2) If destination data type is bigger than source data type (Assigning smaller data type to bigger data type)

In java, Numeric primitive data types are converted automatically from smaller to bigger types.

But this is not applicable to the boolean and char types because these two are not compatible to each other.

2.1 Automatic conversion hierarchy

below is the valid conversion's flow in java.

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

2.2 Example on Primitive Types

Creating a int type variable. Next, assigned int to double without specifying any type casting. This looks working magically to the new java developers.

int number = 10;
double d = number;

The above code does not give compile time error and works perfectly fine. Here, implicit casting has been applied by compiler. So, no issue in this case.

2.3 Example with Inheritance

We will look at another example using inheritance.

Creating A class.

class A {
 public void sayHello() {
  System.out.println("hello developer");

Creating class B which extends class A.

class B extends A{
 public void sayBye() {
  System.out.println("Hope you come back to this site soon.");

Now, we are going to assign type B to type A as below.

A a = new B();

This works well, no doubt in that. Because assigning sub class object to the it's super class reference. All the code is tested against JDK 12.

If we assign type A to B then will get compile time error saying "cannot convert from A to B". The reason behind this is there is no relationship between class A and B.

B b = new A();


Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Type mismatch: cannot convert from A to B

2.4 Example on Generics with Wrapper classes

Example demonstration with Wrapper classes using Generics concepts.

Below example, Creating ArrayList instance which accepts any Number implementation classes such as Integer, Double, Float, BigInteger etc.

List numbers = new ArrayList();
numbers.add(new Integer(100));
numbers.add(new Double(100));
numbers.add(new BigInteger("123.5"));

Added Integer, Double and BigInteger objects but did not get any error because compiler does implicit casting for us based on those classes relation with Number class.

3. Explicit Type Casting

This is also called as Narrowing which means reducing the scope of the source type.

In other words, Assigning bigger data type to smaller data type or which are not compatible to each other.

We will see example program on each case with legal and illegal examples.

3.1 Example on primitive types

We will now implement a program to assign float to byte. We will see what will happen and how to eliminate error if anything comes.

float f = 30.087f;
byte b = f;


When we compile this code then will through compile time error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Type mismatch: cannot convert from float to byte

Because float type is getting assigned to byte which is having less capacity. There may be loss of precision of values.

For make above code to work, we should add explicit type casting from float to byte as below.

float f = 30.087f;
byte b = (byte)f;

Print the byte b value.


Because of narrowing, it will loose precision of value.

3.2 Example on User defined classes without any relation (Inheritance)

Let us create two classes C and D as below.

class C {
 // some methods

class D {
 // some methods

Now assign class C type to class D type. There is not relationship between class C and D. So, We must do explicit casting.

C c = new C();
D d = (D)c;

But, still compiler can determine that there no relationship among them. So, Will get compile time error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot cast from C to D


3.3 Loss of Precision

Float holds decimal points and double hold very big values as when compared to int. See the below example where casting to int type.

float f1 = 3.14f;
double d1 = 1234567890123456789d;

int i1 = (int)f1;
System.out.println("i1 : "+i1);

int i2 = (int) d1;
System.out.println("i2 : "+i2);


i1 : 3
i2 : 2147483647

It losts the actual float and double values because int can not hold the decimals. double value is completely changed after casting to int.

So, narrowing casting is not recommended to use unless it significantly effects.

4. Conclusion

We've seen What is type casting in java and how it works in different cases.

Discussed types of casting such as automatic and explicit type casting. Showed exmaple programs using primitive types, Wrapper classes with Generics and Inheritance.

Narrowing casting feature can not hold the actual values if the source type is bigger than the destination type.

All example code snippets shown in this article are available over GitHub.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: Java Type Casting
Java Type Casting
Java-W3schools Blog. Quick guide to Type Casting in Java. Type casting is used to convert an object or variable of one type into another.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content