- Type Casting in Java
- Implicit casting
- Explicit type casting
- Java wrapper class
- Ways of creating wrapper objects
- 1. Using Double wrapper class constructor
- 2. Using Java Double valueOf() method
- Conclusion
- Type Casting in Java
- Introduction to Type Casting in Java
- Example
- What is Type Casting/Conversion in Java
- Primitive Data types
- Types of Casting in Java
- Widening Type Casting in Java
- Example
- Output:
- Narrow Type Casting in Java (on default data types)
- Syntax
- Example 1:
- Output:
- Lossy NarrowingType Casting in Java
- Type Conversion in Java
- Explicit Type Conversion
- Implicit Type Conversion
- Quick understanding of upcasting and downcasting
- When does Automatic type conversion in Java?
- Scenarios:
- Advantages and Disadvantage of Explicit Type casting in Java
- Advantages
- Disadvantages
- Difference Between Type Casting and Type Conversion in Java
- Conclusion
Type Casting in Java
Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion.
In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.
Note: type casting is not possible for a Boolean data type.
There are 13 types of conversion in Java. In this article, we will only look at 2 major types:
To read about the other types of casting, refer to this documentation.
Implicit casting
This type of conversion is also known as widening casting. It happens automatically when converting from a narrower range data type to a wider range data type. It also means converting a lower data type like an int to a higher data type like a double .
Implicit casting takes place under two conditions:
- Compatibility of the data types. For example, data types such as numeric are compatible with other numeric data types, but they are not compatible with boolean, char, or string data types. In the same way as string is not compatible with a boolean data type.
- If the targeted value to be converted has a smaller length e.g. 4 bytes, to a larger data type e.g. 8 bytes.
Implicit casting follows the order of conversion as shown below:
Byte -> Short -> Char -> Int -> Long -> Float -> Double
Let’s look at an example of implicit type casting in Java.
Here, we will convert an int value to a long value and finally to a double value by using a simple assignment operator:
public class Main public static void main(String[] args) int a = 20; long b = a; //implicit casting from int to long data type double c = b; // implicit casting from long to double data type System.out.println(a); System.out.println(b); System.out.println(c); > >
We can also convert an int into a double data type by instantiating a double class or by using the double.valueOf() method. This way also applies to converting an int to a long data type.
You can read more on this here.
Explicit type casting
This type of casting involves assigning a data type of high range to a lower range. This process of conversion is also referred to as narrowing type casting.
This is done manually as you need to do the casting using the “()” operator. If we fail to do the casting, a compile-time error will be returned by the compiler.
Explicit casting follows the order of conversion as shown below:
Double -> FLoat -> Long -> Int -> Char -> Short -> Byte
Lets look at an example of explicit casting in Java:
public class Main public static void main(String args[]) double d = 57.17; int i = (int)d; // Explicit casting from long to int data type System.out.println(d); System.out.println(i); //fractional part lost > >
In the example above, we converted the double data type into an int data type. The decimal part of the value is lost after type casting.
Java wrapper class
To convert a primitive data type into an object, we need the wrapper classes. We can take string inputs from the users e.g “1234”, then, convert it to int data type and vice versa. For example:
String a = "1234"; int b = Integer.parseInt(a); // converting string to int
In Java, all primitive wrapper classes are immutable i.e when we create a new object, the old object cannot be changed without exception.
Ways of creating wrapper objects
1. Using Double wrapper class constructor
We can cast an int to double data type by passing the value of int to the constructor of the Double wrapper class.
public class Main public static void main (String args[]) int num = 67; Double myDouble = new Double(num); // using Double wrapper class // showing the double value System.out.println("My double is " + myDouble); > >
2. Using Java Double valueOf() method
In this method, we convert int to double using the valueOf() method in the Double wrapper class.
public class Main public static void main (String[] args) int myInt = 67; Double myDouble = Double.valueOf(myInt);// converting int to double using the Double valueOf() method System.out.println("My double is " + myDouble); > >
Conclusion
In this article, we have looked at the different ways of type casting our data type. We can now easily type cast from one data type to another.
Peer Review Contributions by: Mohan Raj
Type Casting in Java
Type casting in Java is the process of converting one data type to another. It can be done automatically or manually. Automatic type casting occurs when a value of one data type is assigned to another compatible data type.
There are two types of casting: widening type casting and narrowing type casting.
Introduction to Type Casting in Java
First of all, let’s understand the literal meaning of Type Casting with context to programming. Type means the data type of a variable or entity and Casting means converting the data type of an entity to another data type.
Example
Let us see a quick example where we will convert a string to an integer using Integer.parseInt() method in Java.
Explanation:
- We have created a String variable s in the code above.
- Next, we have converted the string variable to an integer using Integer.parseInt() method.
What is Type Casting/Conversion in Java
Type casting, also known as type conversion, is the process of changing the data type of a variable in Java. It allows you to convert a variable from one type to another, either widening or narrowing the range of possible values.
Type casting is useful when you need to perform operations on variables of different types or when you want to assign a value of one type to a variable of another type. It can be seen in the above example, when we assigned the value of a String variable to an Integer .
Primitive Data types
There are eight types of primitive data types in Java as given below:
Primitive data types in Java are like the different kinds of Lego blocks you can use to build something. Type casting is like when you need to change one Lego block into another to make it fit or work together with a different block.
Types of Casting in Java
Type Casting in Java is mainly of two types.
Widening Type Casting in Java
Widening type casting refers to the conversion of a lower data type into a higher one. It is also known as implicit type casting or casting down. It happens on its own. It is secure since there is no possibility of data loss.
Widening Type Casting happens on the following scenarios or conditions:
- Both the data types must be compatible with each other. For example, converting a string to an integer is not possible as the string may contain alphabets that cannot be converted to digits.
- The target variable holding the type casted value must be larger than the value being type casted.
In the above image, double is larger data type than float , long , int , etc. Similarly, int is larger data type than short and byte . When converting from a lower data type to a larger data type, no loss of data occurs as the range of supported values is wider in the larger data type.
Example
Output:
Narrow Type Casting in Java (on default data types)
Narrowing Type Casting in Java refers to the conversion of a larger data type into a lower one. It is also known as explicit type casting or casting up. It does not happen on its own.
We must do it explicitly otherwise compile-time error is thrown.
Narrowing Type Casting in Java is not secure as loss of data can occur due to shorter range of supported values in lower data type.
Explicit Casting is done with the help of cast operator.
Syntax
In the above image, int is a lower data type as compared to double , float , long , etc. When we convert a long to an int , it is possible that the value of the long variable is out of range of int variable.
Example 1:
Output:
Explanation:
- As it is visible in the code, there is loss of decimal digits after conversion from double to either short or int .
- We perform explicit type casting using the cast () operator and mentioning the name of target data type inside the brackets.
Lossy NarrowingType Casting in Java
Example of data loss:
Explanation:
- As you can see the output, i contains -2147483648. This is because the range of int is -2147483648 to 2147483647 .
- And we are trying to store a value in i greater than its upper limit resulting in overflow situation.
Type Conversion in Java
Type conversion in Java refers to the process of converting one data type to another. It allows you to change the representation or format of a value to make it compatible with another data type.
There are two types of type conversion in Java:
Explicit Type Conversion
Explicit type conversion in Java, also known as type casting, is used when you want to convert a value of one data type to another data type that cannot be automatically done by the compiler.
Example 1: Converting an integer to a double
Example 2: Converting a double to an integer
Implicit Type Conversion
Implicit type conversion in Java, also known as automatic type promotion, occurs when the compiler automatically converts a value of one data type to another data type without requiring explicit instructions from the programmer.
Example 1: Converting an integer to a double
Example 2: Combining an integer with a long
Quick understanding of upcasting and downcasting
When does Automatic type conversion in Java?
Automatic type conversion occurs in Java when there is a need to convert a value from a smaller or narrower data type to a larger or wider data type.
Scenarios:
- Operations between different data types: Java automatically promotes smaller types to larger types for compatibility.
- Assignment to a larger type: Smaller values can be assigned to larger types without explicit conversion.
- Method parameter matching: Java automatically converts compatible argument types to match expected parameter types.
Advantages and Disadvantage of Explicit Type casting in Java
Advantages
- Precision Control: Explicit type casting allows precise control over data precision and range, ensuring accurate calculations or data representation.
- Data Compatibility: Explicit type casting enables seamless integration between different types, facilitating operations and assignments that require matching data types.
Disadvantages
- Data Loss: Explicit type casting can result in data loss or truncation when narrowing values from a larger type to a smaller type, potentially affecting accuracy and introducing inaccuracies.
- Potential Errors: Incorrect usage of explicit type casting can lead to runtime errors. Incompatible casting or exceeding the target type’s range may cause unexpected behavior or exceptions, such as ClassCastException , resulting in program instability or crashes.
Difference Between Type Casting and Type Conversion in Java
Type Casting | Type Conversion |
---|---|
Involves changing the data type of a variable. | Involves changing the representation or format of a value. |
Performs conversion between compatible data types. | Can involve conversion between incompatible data types as well. |
Requires explicit instructions using casting syntax. | Can be done implicitly by the Java compiler. |
Can result in loss of data or precision if narrowing conversion is performed. | Can involve manipulation or transformation of data without necessarily changing the data type. |
Example: (double) num converts num from an integer to a double explicitly. | Example: Integer.toString(num) converts num to a string without changing its data type. |
Conclusion
- Type Casting in Java refers to the process of converting one data type to another data type.
- The process of conversion of higher data type to lower data type is known as narrowing typecasting. It is also known as Explicit TypeCasting as it must be done explicitly.
- The process of conversion of lower data type to higher data type is known as widening typecasting. It is also called Implicit TypeCasting as it can be done implicitly by the compiler.