023.
024.
byte bValue = (byte)i;
So, you need to specify the “byte”
keyword before the int
variable. Yes, it is necessary to cast an int variable to byte
explicitly, otherwise a compilation error will occur as below:
byte bValue = i; //compilation error
This is because int is a wider type as compared to byte. So, Java
cannot automatically
convert the int type to byte, you need to
specify an explicit cast.
Give an example of implicit casting.
Answer:
Implicit casting occurs when a value is
assigned to a variable of a
wider data type. In such cases,
the conversion happens by
default and there is no need of an explicit cast. For example, if
you assign
an int value to a long value, an implicit cast will occur.
The following code snippet demonstrates this:
int iValue = 250;
long lValue = iValue;
The above code demonstrates that an int value can always be
assigned to a long variable without
casting and the conversion
happens by default.
Write a code snippet that demonstrate how you can
assign a float value to a short variable.
Answer:
The following code demonstrates converting
a float value to a
short variable:
025.
026.
float fValue = 37000.02F;
short sValue = (short) fValue;
Here, the keyword short is specified before the float variable
fValue, this is known as explicit cast.
Since float is a wider data
type than short, an explicit cast is required.
Do'stlaringiz bilan baham: