What is Type casting in Java?

Some   times there  are  a  need to store a  value  of  one type  in to variable of  another  type.In such situations  we  must  casts  the value of  to be  stored  by preceding  is  by type name in process ( ).

The syntax is:

Type variable =(type) variable;

The  process of converting  one  data type  to another  is  called  casting.

Eg:-
       int m =50;
       byte  n=(byte)m;

Casting   is  often  necessary  when a method  returns a type  different  then the  one  we   requires.

Four  integer  types  can be  cost to any  other type  except  boolian.   Casting  in to a   smaller  type may research  in a loss of data. Similarly  the float (  )  double can be  cast to  any other  type  except bullion  . casting   a floating   point  value  to an  integer   will  research  in a loss of  the fractional  part.

Automatic  conversion:- 

For   some types  it  is  possible  to  assign value of  one type  to  a variable of different type  with out cast.  Java  does  the  conversion  of the assigned value   automatically.  This  is known as automatic type conversion.  Automatic    type  conversion  is  possible  only    if  the  definition  type has  enough  precession  to store  the  source value.

For eg:  int  is large  enough   to hold  a  byte  values.There  fore 

  byte    b= 75;
  int   a=b;

Explicit   type  conversion :-

The  process of  aiming  a smaller type  to a  larger one  is  known  as  widening  (or) promotion, and that of  assigning  a  larger  type  to  a  smaller one  is  known as  narrowing.

Note  that narrowing  may result  in   loss  of   information.

Related

Java 1694004439714865244

Post a Comment

emo-but-icon

item