Core java interview Questions You'll Most Likely Be Asked (Second Edition)


How will you cast an int variable to byte explicitly? Is it


Download 1.52 Mb.
Pdf ko'rish
bet14/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   10   11   12   13   14   15   16   17   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

How will you cast an int variable to byte explicitly? Is it
really necessary to cast int literal to byte?
Answer:
An int variable can be cast to byte as follows:
int i = 30;


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.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   10   11   12   13   14   15   16   17   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling