Page 142 - ComputerScience_Class_11
P. 142

6.5 TYPE CONVERSION
              The process of converting 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,

                Program 1      Write a program to calculate the average of two numbers entered by the user.


                1      import java.util.*;
                2      class Average
                3      {

                4          public static void main(String[] args)

                5          {
                6              Scanner sc = new Scanner(System.in);
                7              double a, b, c;

                8              int avg;
                9              System.out.println("Enter two numbers:");

                10             a = sc.nextDouble();
                11             b = sc.nextDouble();

                12             c = (a + b) / 2;
                13             avg = (int)c;   // converting double value into int

                14             System.out.println("Average : " + avg);
                15         }

                16     }

              The output of the preceding program is as follows:

                       BlueJ: Terminal Window - Java
                   Options

                  Enter two numbers:
                  25
                  16
                  Average : 20

              Here, “a” and “b” are variables of double data type and their sum is 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;






                  140  Touchpad Computer Science (Ver. 3.0)-XI
   137   138   139   140   141   142   143   144   145   146   147