Core Java Tutorials - Type Casting in Java, How to cast a type to another type in Java, Difference between implicit and explicit type casting in java

Type Casting in Java, How to cast a type to another type in Java, Difference between implicit and explicit type casting in java

In Java Casting is an operation that converts a value of one data type into a value of another data type. There are two type of Type Casting in Java (1)Implicit Type Casting, (2)Explicit Type Casting.
Casting a variable of a type with a small range to a variable of a type with a larger range is known as widening a type. Casting a variable of a type with a large range to a variable of a type with a smaller range is known as narrowing a type. Widening a type can be performed automatically without explicit casting. Narrowing a type must be performed explicitly. 
The syntax is the target type in parentheses, followed by the variable’s name or the value to be cast. For example, the following statement


Display Output 1 because, if a double value is cast into an int value, then the  fractional part is truncated.

The following statement

System.out.println((double)2 / 4);

Displays Output 0.5, because 2 is cast to 2.0 first, then 2.0 is divided by 4. 

See This Example again

System.out.println(2 / 4);

Displays Output 0, because 2 and 4 are both integers and the resulting value should be an integer.

Note:- Casting is necessary if you are assigning a value to a variable of a smaller type range, such as assigning a double value to an int variable. A compile error will occur if casting is not used in situations of this kind. Be careful when using casting. Loss of information might lead to inaccurate results.

Casting does not change the variable being cast. For example, d is not changed after casting in the following code:

double d = 7.5;
int i = (int)d; // i becomes 7, but d is not changed, still 7.5

To assign a variable of the int type to a variable of the short or byte type, explicit casting must be used. For example, the following statements have a compile error:

int i = 1;
byte b = i; // Error because explicit casting is required

{ 1 comments... read them below or add one }

Talib Hussain said...

You are welcome..

Post a Comment