×

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

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.