Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Type Conversion in Java
3.
1. Widening or Automatic Type Conversion
4.
2. Narrowing or Explicit Conversion
5.
Examples of Type Casting in Java
6.
Type Promotion in Expressions
7.
Explicit Type Casting in Expressions
8.
Frequently Asked Questions
8.1.
What is the condition for type conversion in Java?
8.2.
Which type conversion is not accepted in Java?
8.3.
How many forms of type conversion are there in Java?
8.4.
Why do we need type casting in Java?
8.5.
What is difference between type casting and type conversion?
9.
Conclusion
Last Updated: Jun 4, 2024
Easy

Type Conversion in Java with Examples

Author Yashesvinee V
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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:

Widening or Automatic Type Conversion

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);
  }
}

 

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:

Narrowing or Explicit Conversion

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);
  }
}

 

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

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

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);
    }
}


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);
    }
}


Output:

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

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

Check out the official Coding Ninjas Blog site and visit our Library for more.

Previous article
Autoboxing and Unboxing
Next article
Introduction to Exception Handling
Live masterclass