Welcome to the Java Data Types Coding Quiz. In this quiz, we present 10 coding MCQ questions to test your coding knowledge of Java Data Types. Each question has a correct and brief explanation.
1. What is the output of the following Java code snippet?
char ch = 'A';
int num = ch;
System.out.println(num);
Answer:
Explanation:
In Java, char values are stored as Unicode characters. The Unicode value of 'A' is 65, so when ch is implicitly cast to an int, it displays 65.
2. What does this Java code snippet output?
double value = 9.78;
int number = (int) value;
System.out.println(number);
Answer:
Explanation:
Casting a double to an int truncates the decimal part. Therefore, 9.78 becomes 9.
3. Identify the output of the following code:
byte b1 = 127;
byte b2 = -128;
System.out.println(b1 + " " + b2);
Answer:
Explanation:
The byte data type in Java has a range from -128 to 127. Thus, b1 is 127 and b2 is -128.
4. What will be printed by this Java code?
float f = 100.001f;
double d = f;
System.out.println(d);
Answer:
Explanation:
When a float is assigned to a double, precision may be added. float has less precision than double.
5. What does this code snippet output?
long l = 100L;
float f = l;
System.out.println(f);
Answer:
Explanation:
The long value is implicitly cast to a float. float is a floating-point type, so the output is 100.0.
6. What is the result of executing this code?
boolean flag = false;
if (!flag) {
System.out.println("False");
} else {
System.out.println("True");
}
Answer:
Explanation:
The ! operator negates the boolean value. Since flag is false, !flag is true, so "False" is printed.
7. What will the following Java code snippet output?
short s = 10;
s = (short) (s + s);
System.out.println(s);
Answer:
Explanation:
The expression s + s results in an int type. It must be cast back to short to be reassigned to s. The value of s becomes 20.
8. What does the following code snippet print?
String str = "12345";
int num = Integer.parseInt(str);
System.out.println(num);
Answer:
Explanation:
Integer.parseInt converts the String "12345" to the int 12345.
9. Determine the output of this Java code:
int a = '2' - '0';
System.out.println(a);
Answer:
Explanation:
In Java, char values are stored as Unicode values. The Unicode value of '2' is 50 and '0' is 48. Thus, 50 - 48 equals 2.
10. What is the result of the following code snippet?
double d1 = 0.1;
double d2 = 0.2;
double sum = d1 + d2;
System.out.println(sum);
Answer:
Explanation:
Floating-point arithmetic in Java can lead to precision errors. Here, adding 0.1 and 0.2 results in a minor precision error, producing 0.30000000000000004 instead of the exact 0.3.
Comments
Post a Comment
Leave Comment