Test Series - java

Test Number 14/64

Q: Which are the compatible Data Types for Type Promotion or Type Casting?
A. byte, char, short
B. char, int, float
C. float, long, double
D. All the above
Solution: Number to Number conversions are possible with or without a data loss.
Q: What is the output of the following Java Code?
int a=9;
float b = a/2;
System.out.println(b);
A. 4.0
B. 4.5
C. 5.0
D. None of the above
Solution: You need to type cast at least one number in that expression to float or double to do real number division.


float b = 9*1f/2;
//4.5
Q: What is the output of the below Java code snippet?
float a = 8.2/2;
System.out.println(a);
A. 4.1
B. 8.1
C. 4
D. Compiler error
Solution: Add a suffix f or F 
float a = 8.2f/2;
(or)
explicit typecast
float a = (float)8.2/2;
System.out.println(a);
Q: What is the output of the Java code snippet?
byte b = 25;
b++;
b = b+1;
System.out.println(b);
A. 25
B. 26
C. 27
D. Compiler error
Solution: Explicit type casting is required.
Expression b+1 gives int value
byte b = 25;
b++;
b = (byte)(b+1);
System.out.println(b);
//OUTPUT = 27
Q: What is the output of the Java code snippet?
int a = 260;
byte b= (byte)a;
System.out.println(b);
A. 0
B. 4
C. 255
D. 260
Solution: If a number is too big for a data type, it applies Modulo Division by the highest number possible of that data type. Byte range is -128 to +127. 260 > 127. So, modulo division is applied.


260%256 = 4
Q: In a lossy Type Casting or Type Conversion, how is the number truncated to the target data type in Java?
A. That big number is divided by the target data type highest possible number say 2^N.
B. That big number is Modulo Divided by the target data type highest possible number say 2^N and the Remainder is taken.
C. That big number is Modulo Divided by the target data type highest possible number say 2^N and the Quotient is taken.
D. None of the above
Solution: byte Maximum = 256 = (*2^8)
short maximum = 2^16 = 65536
int maximum = 2^32
long maximum = 2^64
Q: What is the output of the Java code snippet?
short a = (short)65540;
System.out.println(a);
A. 0
B. 4
C. 65536
D. 65540
Solution: 65540 is bigger than short range -32768 to +32767.
So, 65540 % 2^32 = 65540%65536 = 4
Q: A boolean literal in Java can be type casted to which data type?
A. byte
B. short
C. int
D. None of the above
Solution: A boolean literal or variable takes only true or false. So, it does not accept numbers for type conversion.
Q: If a variable or operand in an expression is type long, then all the operands are type promoted to which data type?
A. int
B. long
C. float
D. double
Solution: All other operands are type promoted to the highest data type available in that expression. If the highest data type is double in an expression, the final result will also be a double value.

You Have Score    /9