In: Computer Science
10. We are trying to assign the value of a variable named “FirstNumber” to a variable named “SecondNumber”. They are declared as shown below. Which of the following statements is correct?
double FirstNumber = 25.5;
int SecondNumber;
Group of answer choices
c. SecondNumber = int.Parse (FirstNumber);
b. SecondNumber = (double) FirstNumber;
d. SecondNumber = double.Parse (FirstNumber);
a. SecondNumber = (int)FirstNumber;
From given options option a is correct that is:
SecondNumber = (int)FirstNumber;
Now let's discuss why option a is correct.
In the given question we have to assign a value of a Double datatype variable FirstNumber to an Integer datatype variable SecondNumber. So Typecasting will be used to do so because both variables are of different data types. Let's discuss what is typecasting.
Typecasting:
Typecasting is nothing but a method of assigning the value of a primitive data type(i.e integer, float, char, double) to another datatype. Typecasting can be done by two methods:
1. Implicit Typecasting: In implicit typecasting one datatype is automatically converted to another data type. Usually implicit typecasting is done from lower value datatype to higher value datatype
2. Explicit Typecasting: In explicit typecasting we have to inform the compiler that we are doing this typecasting by passing the name of datatype in () brackets while assigning value. This typecast is mainly used to typecast larger value datatype to lower value datatype.
In the given question we have two datatypes int and double
Double is a higher value data type so it can not be implicitly typecasted to int
This is the reason we have passed (int) while explicitly typecasting FirstNumber to SeconNumber.
I am attaching screenshots of my compiler which is showing correct syntax along with the output we are getting after running the program in java