Page 135 - Cs_withBlue_J_C11_Flipbook
P. 135

6.5 TYPE CONVERSION
                 The process of changing the value of one type to another type is known as type conversion. It is also known as type
                 casting. It is required in situations when a method or an expression returns one type of value and it is stored in a
                 variable of a different data type. For example,

                   import java.util.*;
                   class average
                   {
                       public static void main()
                       {
                           Scanner sc = new Scanner(System.in);
                           double a,b,c;
                           int avg;
                           System.out.println("Enter two numbers:");
                           a = sc.nextInt();
                           b = sc.nextInt();
                           c = a+b;
                           avg = (int)c;
                           System.out.println("Average : "+avg);
                       }
                   }
                 Here, “a” and “b” are variables of double data type and they are converted to int data type and stored in the “avg”
                 variable.
                 The casting is performed by keeping the target data type in parentheses to the left of the value which is being converted.

                                   Syntax of conversion:
                                      Datatype variable = (datatype)variable_to_be_converted;

                 There are two types of conversions in Java, which are as follows:
                 •  Implicit Type Conversion
                 •  Explicit Type Conversion

                 6.5.1 Implicit Type Conversion
                 Implicit type conversion takes place when the target data type is larger than the source type, i.e., when we assign the
                 value of a smaller data type to a larger data type.
                                                                   byte




                                                                  short




                                                    char            int          float




                                                                   long         double


                 In implicit type conversion, the resultant data types are automatically chosen by the compiler. It is a process of widening.



                                                                                                                       133
                                                                         Primitive Values, Wrapper Classes, Types and Casting   133
   130   131   132   133   134   135   136   137   138   139   140