Table of contents
1.
Introduction
2.
What is Type Conversion in Java
2.1.
1. Widening or Automatic Type Conversion
2.2.
2. Narrowing or Explicit Conversion
3.
Examples of Type Casting in Java
3.1.
Widening Casting Example:
3.2.
Narrowing Casting Example:
4.
Type Promotion in Expressions
5.
Explicit Type Casting in Expressions
6.
Difference Between Explicit and Implicit Conversion
6.1.
Implicit Conversion (Type Promotion)
6.2.
Explicit Conversion (Type Casting)
6.3.
Comparison Between Implicit and Explicit Conversion
7.
Frequently Asked Questions
7.1.
What is the condition for type conversion in Java?
7.2.
Which type conversion is not accepted in Java?
7.3.
How many forms of type conversion are there in Java?
7.4.
Why do we need type casting in Java?
7.5.
What is difference between type casting and type conversion?
8.
Conclusion
Last Updated: Apr 15, 2025
Easy

Type Conversion in Java with Examples

Author Yashesvinee V
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java is a statically typed programming language in which the data types and their variables are known at compile time. Once a variable is declared of a specific data type, it cannot be changed anywhere else in the later parts of the program. 

Type Conversion in Java

Data types, as we all know, can be primitive or non-primitive.

  • Primitive data types can hold only single values and have no special properties. Boolean, short, int, float, double, char, long and byte are the eight primitive data types in Java.
     
  • Non-primitive data types store the memory address of a variable value and not the value itself in the memory. Hence, they are also known as reference data types. Non-primitive data types can store multiple values under the same name and have their own set of properties. Arrays, strings, class, objects and interfaces are examples of non-primitive data types in Java.


In this article, we will explore the topic type conversion in Java with examples in detail.

What is Type Conversion in Java

Programs perform operations and calculations which may or may not involve variables of different data types. Compatible data types do not cause problems during execution. However, incompatible ones need to be cast or converted explicitly. Each data type is assigned a certain memory space to store its value, so if variables of different types are involved, finding the data type of the result is uncertain. Thus, types conversion is of two types.

  • Widening or Automatic Type Conversion
     
  • Narrowing or Explicit Conversion
     

It is important to note here that conversion between two primitive and two non-primitive data types is only possible. We cannot typecast a primitive to a non-primitive data type and vice versa. Implicit and explicit type conversions are performed based on a precedence structure where data types are arranged in a particular order.

1. Widening or Automatic Type Conversion

Automatic or implicit type conversion is done by the compiler internally. Converting a lower data type into a higher one is known as widening. If two variables involved in an operation are of the same data type, the result is also similar. If variables of different but compatible data types are involved, then implicit conversion is automatic.

Implicit conversion follows the given order:

 Implicit conversion follows the given order:

For example, char variables can be typecasted to int, float can be typecasted to double and so on.

public class Main
{
  public static void main(String[] args)
  {
      char ch = 'a';
      int a = ch;
      System.out.println(a);
      long a = 20;
      float b = 24.62f;
      double x = a*b;
      System.out.println(x);
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

97
472.4000244140625

 

The char type is automatically converted to int. Variables a and b, which are of long and float data type, respectively, are multiplied to give a value stored in a double type variable. So, long and double are implicitly cast to double.

Note that if we try to typecast a float variable to a double without adding a float literal, it will result in an error stating lossy conversion. This is because variables of double data type have more precision than float. The error is a warning from the compiler indicating reduced precision.

2. Narrowing or Explicit Conversion

Narrowing or Explicit conversion involves casting a higher data type into a lower one. This type of conversion is not done automatically, and the desired data type needs to be explicitly mentioned within ( ). Data types need not be compatible with each other for explicit typecasting.

Explicit conversion uses the following order:

Explicit conversion uses the following order:

public class Main
{
  public static void main(String[] args)
  {
      int a = 102;
      char ch = (int) a;
      System.out.println(ch);
      double x = 328.288006786;
      long y = (long) x/20;
      System.out.println(x);
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

f
16

In the above example,  an int variable is explicitly converted to char, which is of lower order. Similarly, result y, by default, will be of double type but has been converted to long data type. Hence, y stores the integer answer of the division operation.

Examples of Type Casting in Java

Type casting in Java is a way of converting a variable from one data type to another. In Java, there are two types of casting:

Widening Casting (Implicit): This occurs when data from a smaller data type is converted into a larger data type automatically. For example, converting an int to a long.

Narrowing Casting (Explicit): This is done manually by the programmer. It converts a larger data type to a smaller size type. For example, converting a double to an int.

Examples

Widening Casting Example:


int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt);      // Outputs 9
System.out.println(myDouble);   // Outputs 9.0
You can also try this code with Online Java Compiler
Run Code

Explanation: Here, myInt is an integer. When it's assigned to myDouble, Java automatically converts the int to a double. This is a widening cast because a double is larger than an int.

Narrowing Casting Example:


double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble);   // Outputs 9.78
System.out.println(myInt);      // Outputs 9
You can also try this code with Online Java Compiler
Run Code


Explanation: In this, myDouble is a double with a value of 9.78. To assign it to myInt, which is an integer, we need to perform a narrowing cast. This is done by prefixing the value with (int). The fractional part (.78) is truncated, and myInt becomes 9.

Type Promotion in Expressions

In Java, Type Promotion is the process of converting a smaller data type into a larger data type and is done automatically by the Java compiler itself when an expression is evaluated. 

Type promotion helps in preventing errors as it ensures that all expressions are evaluated using the same data type.

Let's see the rules of type promotion:

  • Byte, short and char are upgraded to int 
     
  • one operand is long then the whole expression is promoted to long
     
  • one operand is float then the whole expression is promoted to float
     
  • If any operands are double, the result is double


Here is an example of type promotion in Java:

public class HelloWorld{
    public static void main(String []args){
        // Byte promoted to int
       byte i = 10;
       int x = i + 5;
       System.out.println("byte converted int -> "+x);
       
       // Short promoted to int
       short short_num = 15;
       int Big = short_num + 115;
       System.out.println("short converted int -> "+Big);
       
       // int promoted to double 
       int num = 5; 
       double Big_num = num + 15.5;
       System.out.println("int converted double -> "+Big_num);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

byte converted int -> 15
short converted int -> 130
int converted double -> 20.5

Explicit Type Casting in Expressions

Explicit Type Casting is the process of converting the data type of a variable to another data type manually by the programmer. It is done using the cast operator which is pair of parentheses containing the data type to which the value is being converted. like (data_type)
It is used whenever the compiler fails to convert the data type automatically to another data type and prevents the compile time error.

Here is an example of Explicit Type Casting in Java:

public class HelloWorld{
    public static void main(String []args){
        // Cast double to float
       double num = 10.51;
       float res = (float) num;
       System.out.println("double casted to float -> "+res);
       
       // Cast char to int
       char ch = 'z';
       int number = (int) ch;
       System.out.println("char casted to int -> "+number);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

double casted to float -> 10.51
char casted to int -> 122

Difference Between Explicit and Implicit Conversion

In Java, type conversion refers to changing a value from one data type to another. Java supports two types of conversions: Implicit Conversion and Explicit Conversion.

Implicit Conversion (Type Promotion)

Implicit conversion happens automatically when Java converts a smaller data type to a larger one. This process is also known as type promotion. Since it is handled by the Java compiler, you don’t need to write any extra code.

This type of conversion is safe because Java ensures that no data will be lost. For example, converting an int to a double happens automatically, as a double has a larger size and can hold all values of an int.

Example of Implicit Conversion:

int num = 10;
double result = num; // int is implicitly converted to double
System.out.println(result); // Output: 10.0

Explicit Conversion (Type Casting)

Explicit conversion, also known as type casting, is done manually by the programmer. It is used when you want to convert a larger data type into a smaller one. Since there's a chance of data loss (like precision loss or truncation), Java does not do this automatically.

You must use a cast operator to perform this kind of conversion.

Example of Explicit Conversion:

double value = 10.75;
int result = (int) value; // double is explicitly converted to int
System.out.println(result); // Output: 10


In the above case, the decimal part is lost because int cannot store fractional values.

Comparison Between Implicit and Explicit Conversion

FeatureImplicit ConversionExplicit Conversion
SyntaxNo extra syntax neededRequires manual casting (e.g., (int))
Data CompatibilityWorks with compatible data types onlyWorks with both compatible and incompatible types
Risk of Data LossNo risk of data lossPossible data loss during conversion
DirectionSmall type to larger type (e.g., int to double)Large type to smaller type (e.g., double to int)
Exampledouble d = intVal;int i = (int) doubleVal;

 

By understanding both types of conversion, Java developers can write safer and more efficient code. Use implicit conversion for basic type upgrades and explicit conversion when you're certain about the value and can handle any potential data loss.

Frequently Asked Questions

What is the condition for type conversion in Java?

The condition for type conversion in Java is that both of the datatypes should be compatible with each other. For example, we can convert the byte to int but not byte to float data type or string as it is not a valid conversion.

Which type conversion is not accepted in Java?

Type conversion that is not accepted in Java is when there is a conversion between two incompatible datatypes. For example, converting int to a string data type is not accepted.

How many forms of type conversion are there in Java?

There are basically two types of conversion one is the implicit type where the data type is converted automatically by the compiler and the other one is explicit data type conversion where in we manually convert the data type to another.

Why do we need type casting in Java?

We need typecasting in Java to ensure the compatibility between the data types of the operands. Type casting in Java helps in the prevention of errors and makes the program to run as expected.

What is difference between type casting and type conversion?

Type casting and type conversion both involve changing data types, but type casting is explicit and programmer-controlled, while type conversion can be implicit and automatic by the programming language.

Conclusion

Type conversions are essential when dealing with multiple variables of different data types. Implicit and Explicit conversions play an important role in obtaining the desired output. This blog discusses primitive and non-primitive data types in Java. It mainly focuses on type conversion in Java with examples in detail.

Related Links

Java Tokens

Java Verify

Multiple Inheritance in Java

Data types and identifiers in Java

Live masterclass