Working with Java Data Types practice questions

From OCA Java SE 7 (1Z0-803) · 27 questions on this topic

Working with Java Data Types practice questions from OCA Java SE 7 (1Z0-803). This pack has 27 questions tagged Working with Java Data Types, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Working with Java Data Types

  1. Question 1

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { String x = "java7"; String y = "java" + "7"; String z = new String("java7"); System.out.println((x == y) + " " + (x == z) + " " + x.equals(z)); } } ```

    1. A. false false true

      This treats "java" + "7" as a runtime concatenation producing a distinct object. It is a compile-time constant folded to "java7" and interned, so x == y is true, not false.

    2. B. true false trueCorrect answer

      "java" + "7" is a constant expression folded and interned to the same pooled object as x (x == y true); new String(...) is a fresh heap object (x == z false); its contents match, so equals is true (JLS 7 §3.10.5).

    3. C. true true true

      new String("java7") always allocates a distinct object on the heap, so x == z is false even though the contents are equal; only the pooled literal comparison is true.

    4. D. false false false

      The folded literal is pooled, so x == y is true, and equals() compares contents, which match, so the last value is true; not all three are false.

    Explanation

    "java" + "7" is a compile-time constant expression, folded to "java7" and interned in the string pool — the same pooled object x refers to, so x == y is true. `new String(...)` always creates a fresh object on the heap, so x == z is false, but the contents match, so equals is true.

  2. Question 2

    What is the result of compiling and running the following program? ```java public class Main { public static void main(String[] args) { byte b = 10; b = b + 1; System.out.println(b); } } ```

    1. A. 11

      This assumes `b = b + 1;` compiles and computes 11. b + 1 is int arithmetic, and storing that int back into a byte requires an explicit cast, so the code does not compile.

    2. B. 10

      Nothing leaves b unchanged at 10, and the code fails to compile anyway because assigning the int result of b + 1 to a byte needs an explicit cast.

    3. C. An exception is thrown at runtime

      The incompatible-types issue is caught at compile time, so the program never runs and cannot throw a runtime exception.

    4. D. Compilation failsCorrect answer

      b is promoted to int in b + 1, and assigning that int back to a byte requires an explicit cast, so `b = b + 1;` fails with incompatible types / possible loss of precision (JLS 7 §15.26.2).

    Explanation

    b + 1 is int arithmetic (b is promoted), and assigning an int back to a byte needs an explicit cast — so `b = b + 1;` fails with "possible loss of precision / incompatible types". Note the contrast: `b += 1` and `b++` DO compile, because compound assignment and increment include an implicit cast back to the variable's type.

  3. Question 3

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { Integer boxed = null; try { int n = boxed; System.out.println(n); } catch (NullPointerException e) { System.out.println("NPE"); } } } ```

    1. A. 0

      There is no default-to-zero behavior for unboxing; unboxing a null Integer calls intValue() on null and throws rather than yielding 0.

    2. B. NPECorrect answer

      Assigning the Integer to an int compiles by inserting an unboxing call (intValue()); at runtime that call on null throws NullPointerException, which the catch block prints (JLS 7 §5.1.8).

    3. C. null

      A primitive int can never hold null; the unboxing conversion throws NullPointerException before any value could be printed.

    4. D. Compilation fails because an Integer cannot be assigned to an int

      Assigning an Integer to an int is legal via unboxing conversion, so the code compiles; the failure is at runtime, not compile time.

    Explanation

    Assigning an Integer to an int compiles fine — the compiler inserts an unboxing call (boxed.intValue()). At runtime that call is made on null, throwing NullPointerException. There is no default-to-zero behavior for unboxing (`0`).

  4. Question 4

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { char c = 'A'; int i = c + 2; System.out.println((char) i + "" + i); } } ```

    1. A. C67Correct answer

      'A' promotes to 65 in arithmetic, so i = 67; the (char) cast binds tighter than +, printing 'C' first, then the int 67, giving C67 (JLS 7 §5.6.2).

    2. B. A2

      This treats 'A' and 2 as characters concatenated rather than added. char is promoted to int in arithmetic, so 'A' + 2 computes the number 67, not the text "A2".

    3. C. 6767

      This ignores the (char) cast and prints the number 67 twice. The cast converts 67 back to the character 'C', so the first part prints 'C', not 67.

    4. D. Compilation fails because a char cannot be used in arithmetic

      char is a numeric type and is fully valid in arithmetic (promoted to int), so the expression compiles without error.

    Explanation

    char is a numeric type: in arithmetic it is promoted to int, so 'A' (65) + 2 = 67. Casting 67 back to char gives 'C'. The expression prints the cast result first ("C") then the int (67): C67. The cast binds tighter than +, so (char) i is converted before concatenation.

  5. Question 5

    Which statements about garbage collection in Java are true?

    1. A. An object becomes eligible for collection when it is no longer reachable through any live referenceCorrect answer

      Eligibility for collection is defined purely by reachability, so an object with no live reference to it becomes eligible.

    2. B. Calling System.gc() guarantees that eligible objects are collected immediately

      System.gc() is only a suggestion to the JVM; it guarantees nothing about when or whether collection happens.

    3. C. Setting the only reference to an object to null makes that object eligible for collectionCorrect answer

      Setting the sole reference to null removes reachability, so the object becomes eligible for collection.

    4. D. An object referenced from a live static field can still be collected

      Anything reachable from a live root such as a static field of a loaded class cannot be collected.

    Explanation

    Eligibility is purely about reachability (`An object becomes eligible for collection when...`); nulling the last reference removes reachability (`Setting the only reference to an object to null...`). System.gc() is only a SUGGESTION to the JVM (`Calling System.gc() guarantees that eligible...`), and anything reachable from a live root — like a static field of a loaded class — cannot be collected (`An object referenced from a live static field...`).

  6. Question 6

    What is the result of compiling and running the following program? ```java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("data"); sb.append("x").substring(1, 3).reverse(); System.out.println(sb); } } ```

    1. A. atax

      This assumes the chain runs and that substring/reverse mutate the builder. substring() returns a String and never changes the builder, and the code fails to compile before running.

    2. B. datax

      This assumes the program compiles and prints the appended builder. The reverse() call is made on the String returned by substring(), which has no reverse() method, so it fails to compile.

    3. C. An exception is thrown at runtime

      The problem is a missing method (String has no reverse()), which the compiler rejects; the program never runs, so no runtime exception occurs.

    4. D. Compilation failsCorrect answer

      substring() returns a String, not the StringBuilder, and String has no reverse() method, so chaining reverse() from it fails to compile.

    Explanation

    Unlike append/insert/delete, substring() returns a String — not the StringBuilder — so nothing more can be chained from it that String doesn't have. String has no reverse() method, so the chain fails to compile. substring() also never mutates the builder.

  7. Question 7

    Which of the following are valid variable declarations?

    1. A. int 2count = 5;

      A Java identifier cannot start with a digit, so 2count is illegal and this declaration fails to compile.

    2. B. double _ratio = 0.5;Correct answer

      Identifiers may begin with an underscore, so _ratio is a valid name and 0.5 is a valid double literal.

    3. C. int x = 010;Correct answer

      A leading zero makes 010 an octal literal with value 8, which is a valid int assignment (JLS 7 §3.10.1).

    4. D. boolean flag = 1;

      Java booleans are not numeric; only true or false may be assigned, so initializing a boolean with 1 fails to compile.

    5. E. char c = 65;Correct answer

      An int constant within char range converts implicitly to char, so char c = 65; is valid and assigns 'A' (JLS 7 §5.2).

    Explanation

    `double _ratio = 0.5;` is fine (identifiers may start with _). `int x = 010;` is valid — a leading zero makes 010 an OCTAL literal with value 8. `char c = 65;` works because an int constant in char range converts implicitly. `int 2count = 5;` fails (identifier can't start with a digit) and `boolean flag = 1;` fails because Java booleans are not numbers — only true/false are allowed.

  8. Question 8

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { String s = "hoop"; s.toUpperCase(); s.concat("!"); System.out.println(s); } } ```

    1. A. hoopCorrect answer

      toUpperCase() and concat() each return a new String and leave the original unchanged; since those return values are discarded and s is never reassigned, s still refers to "hoop".

    2. B. HOOP

      This assumes toUpperCase() mutates the string in place. String is immutable: the uppercased result is returned as a new object and here it is discarded, so s is unaffected.

    3. C. HOOP!

      This assumes both calls mutate s cumulatively (uppercase then append). Neither method changes the original string, and both returned results are discarded.

    4. D. hoop!

      This assumes concat("!") appends to s in place. concat returns a new String with the "!" added, and that result is discarded, so s remains "hoop".

    Explanation

    String is immutable: toUpperCase() and concat() each RETURN a new String and leave the original untouched. Since the return values are discarded, s still refers to "hoop". To change it you must reassign: s = s.toUpperCase().

Practise all 27 Working with Java Data Types questions

OCA Java SE 7 has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open OCA Java SE 7

Other topics in this pack