Skip to main content

Type casting in java

What is Type casting in java ?
  •  In casting one type of information is converted into another
    type of information.
  • It classified into two types

1. data type casting
2. class type casting

A data type casting done in two ways
1. widening
2. narrowing

data-type-casting

  •  Casting lower data type to higher data type is known as widening.
  • The widening can be done either implicit or explicit.
  • Casting higher data type to lower data type is known as narrowing.the narrowing operation should be done explicitly.

NOTE: whenever we perform narrowing there will be a loss of data.

Data type casting example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package casting; 
public class datatypecasting 
{ 
       public static void main(string[] args) 
       { 
          system.out.println(""); 
          double d=12; 
     //widening (integer type is converted into double) it done automatically 
 
          int a=(int)12.6;
     //narrowing(double type is converted into integer) 
 
          system.out.println("d value: "+d); 
          system.out.println("a value: "+a); 
          system.out.println(""); 
      } 
} 
output: 
 
d value: 12.0 
a value: 12