×

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators.

Type casting in Java is a technique or procedure that transforms a type of data into another type of data both manually and also automatically. The developer does manual translation, whereas the compiler performs the automated transformation.

The types of type casting

Type casting comes in two types:

1. Widening Type casting

2. Narrowing Type Casting

Widening

Widening type casting refers to transforming a low information type into a higher one. Casting down and implied conversion are other names for it. It happens on its own. It is secure since there is no possibility of data loss.

The event occurs when:

  • The two data kinds need to work together.
  • A greater target type than that of a smaller source type is required.

Byte, Short, Char, Int, Long, Float, Double

For instance, there is no automated translation from a numeric data form to a char or boolean data type. Additionally, the data types char and boolean are incompatible with one another. 

Example: WidiningExample.java

//this program is for type conversions in java
//importing the packages
import java.io.*;
import java.util.*;
public class WidiningExample
{  
public static void main(String[] args)  
{  
int n1 = 35;  
// the data is converted automatically
long n2 = n1;  
// the long data type is easily converted to float
float n3 = n2;  
System.out.println("The value of integer before conversion: "+n1);  
System.out.println("The value of long after the conversion from int: "+n2);  
System.out.println("The value of float after conversion form long: ”+n3);  
}  
}  

Output

The value of integer before conversion: 35
The value of long after the conversion from int: 35
The value of float after conversion form long: 35.0

In the example shown, a variable named n1 was changed into a long type. The long type is then changed into the float type.

Narrowing

Narrowing type casting refers to transforming a higher data type into the lesser one. Casting up and explicit translation are other names for it. The developer does it by hand. The compiler will raise a compile-time warning if the casting is not done.

double, float, long, int, char, short, and byte are all data types.

Here is an illustration of thin-type casting.

The narrower type casting has been done twice in the case below. First, the double data type was transformed into a long data type, and then the long data type was changed to an int type.

Example: NarrowingExample.java

//this program is for type conversions in java
//importing the packages
import java.io.*;
import java.util.*;
public class NarrowingExample 
{  
public static void main(String args[])  
{  
double d1 = 164.65;  
//switching from double to long data type  
long l1 = (long)d1;  
//long data type conversion to the  int data type  
int i1 = (int)l1;  
System.out.println("The double value before conversion: "+d1);  
// removing the fractional part 
System.out.println("The value of long data type after conversion from double: "+l1);  
//removing the fractional part 
System.out.println("The value of int after converting from long: "+i1);  
}  
}   

Output

The double value before conversion: 164.65
The value of long data type after conversion from double: 164
The value of int after converting from long: 164

Related Topics

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.