Javatpoint Logo
Javatpoint Logo

Cast Operator in Java

What does Java's type conversion operator () do and how does it work?

The cast operator in Java is employed to convert between various data types.

Example

CastOperatorExpl.java

Output:

Cast Operator in Java

Programmers use the cast operator to type cast, which is the process of switching from one state to another. The programmer does typecast while creating the program. Narrow Conversion is also referred to as typecasting. Because the requirements of the operations frequently force us to Cast huge datatype items into smaller datatype values. Large datatype values can also be divided into smaller datatype values, which is why Type Casting is sometimes known as Narrow Casting.

Syntax: () is Cast Operator

Example 1:

CastOperatorExpl1.java

Output:

Cast Operator in Java

Type casting is the process of converting a value by one primitive data type to the other.

In Java, there are two types of casting:

  • Widening Conversion (automatically): Casting is the process of changing smaller type into larger type size.

byte -> short -> char -> int -> long -> float -> double

  • Narrowing Casting (manually): reducing the size of a larger font.

double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is carried out automatically when switching from one size type to another:

Example:

WideningExpl.java

Output:

10
10.0

Narrowing Casting

By adding the type in parentheses ahead of the value, the narrow casting must be done manually:

Example:

NarrowingExpl.java

Output:

9.89
9






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA