Java MCQ

Previous Java Multiple Choice Questions Next

Java Tricky Variables and Data Types Questions

1

What is the output?
public class Test {
  static int a;
  int b;
  public static void main(String[] args) {
    int c;
    System.out.println(a);
    System.out.println(new Test().b);
    System.out.println(c);
  }
}

Correct Answer: B) 0 0 Compilation Error

Static and instance variables get default values (0), but local variables must be initialized before use. Variable 'c' is not initialized.

2

What will be printed?
byte b1 = 10;
byte b2 = 20;
byte b3 = b1 + b2;
System.out.println(b3);

Correct Answer: B) Compilation Error

Arithmetic operations on byte/short promote to int. Need explicit cast: byte b3 = (byte)(b1 + b2);

3

What is the output?
int x = 5;
int y = x++ + ++x;
System.out.println(y);

Correct Answer: C) 12

x++ returns 5 (then x=6), ++x returns 7 (x becomes 7), so 5 + 7 = 12.

4

What will be printed?
double d1 = 0.1;
double d2 = 0.2;
double d3 = 0.3;
System.out.println(d1 + d2 == d3);

Correct Answer: B) false

Due to floating-point precision, 0.1 + 0.2 = 0.30000000000000004, which is not exactly equal to 0.3.

5

What is the output?
char c = 'A';
int i = c;
char c2 = (char)(c + 1);
System.out.println(i + " " + c2);

Correct Answer: A) 65 B

char to int conversion gives ASCII value (A=65). c+1=66, cast to char gives 'B'.

6

What will be printed?
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i1 == i2);
System.out.println(i3 == i4);

Correct Answer: C) true false

Integer caching for values -128 to 127. 100 is cached (same object), 200 creates new objects.

7

What is the output?
short s = 10;
char c = 'A';
int result = s + c;
System.out.println(result);

Correct Answer: B) 75

char 'A' has ASCII value 65. short + char promotes to int: 10 + 65 = 75.

8

What will be printed?
final int x = 10;
byte b = x;
final int y = 200;
byte b2 = y;
System.out.println(b + " " + b2);

Correct Answer: B) Compilation Error for b2

final variables within byte range (10) can be assigned to byte, but 200 exceeds byte range (-128 to 127).

9

What is the output?
int x = 5;
int y = 2;
double result = x / y;
System.out.println(result);

Correct Answer: B) 2.0

Integer division 5/2 = 2 (truncated), then assigned to double becomes 2.0.

10

What will be printed?
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));

Correct Answer: B) true false true

s1 and s2 point to same string literal in pool. s3 is new object in heap. equals() compares content.

Previous Java Multiple Choice Questions Next