Working with Java Data Types practice questions

From OCP Java SE 17 (1Z0-829) · 23 questions on this topic

Working with Java Data Types practice questions from OCP Java SE 17 (1Z0-829). This pack has 23 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 does this print? ```java public class Main { public static void main(String[] args) { System.out.println(5 / 2 + " " + 5 % 2 + " " + 5.0 / 2); } } ```

    1. A. 2.5 1 2.5

      Shows 2.5 for the first result, which would require a floating-point operand in 5 / 2, but both operands there are int.

    2. B. 2.5 0 2.5

      Shows 0 for the remainder, but 5 % 2 is 1; only an even dividend would give remainder 0.

    3. C. 2 1 2.5Correct answer

      5 / 2 is integer division giving 2, 5 % 2 gives remainder 1, and 5.0 / 2 promotes the int operand to double giving 2.5, so the concatenation prints 2 1 2.5.

    4. D. 2 1 2

      Truncates the last result to 2, but 5.0 / 2 has a double operand and so evaluates to 2.5.

    Explanation

    Division and remainder on two int operands stay in integer arithmetic, so 5 / 2 truncates to 2 and 5 % 2 is 1. Promotion to double happens only for an operation that actually has a floating-point operand, so 5.0 / 2 yields 2.5 while the earlier all-int subexpressions are unaffected. Each operation's operand types are considered independently.

  2. Question 2

    Addition and string concatenation are mixed in one expression. What does this program print? ```java public class Main { public static void main(String[] args) { System.out.println(1 + 2 + "3" + 4 + 5); } } ```

    1. A. 12345

      Wrong: this assumes the presence of a String anywhere makes every + a concatenation. The operator is resolved for each pair left to right, and the leftmost pair (1 + 2) is still arithmetic.

    2. B. 1239

      Wrong: this assumes the numbers on the right are added first, as if + were right-associative. 4 + 5 is never evaluated as a pair; + is left-associative.

    3. C. 3345Correct answer

      Correct: + is left-associative, so 1 + 2 is arithmetic (3), then 3 concatenated with the string 3 gives a String and everything after stays a String, building 3345.

    4. D. 15

      Wrong: this assumes the string 3 is coerced back to a number so everything is summed. Java never implicitly converts a String to a number.

    Explanation

    Trace: `+` is left-associative and its meaning is decided pair by pair. `1 + 2` — both numeric, so this is addition, giving `3`. `3 + "3"` — one operand is a `String`, so this is concatenation, giving `"33"`. `"33" + 4` gives `"334"`, and `"334" + 5` gives `"3345"`. The program prints `3345`. Why the others are wrong: `12345` assumes the presence of a `String` anywhere in the expression makes every `+` a concatenation. The operator is resolved for each pair from left to right, and the leftmost pair is still pure arithmetic. `1239` assumes the numbers on the right are added together first, as if `+` were right-associative or as if arithmetic bound tighter than concatenation. `4 + 5` is never evaluated as a pair here. `15` assumes `"3"` is coerced back to a number so that everything is summed. Java never converts a `String` to a number implicitly. Exam tip: read `+` chains strictly left to right and ask at each step "is either side a String yet?". Once the accumulated value is a `String`, it stays one. The reverse trap: `System.out.println("" + 1 + 2)` prints `12`, while `System.out.println(1 + 2 + "")` prints `3`.

  3. Question 3

    What does this print? ```java public class Main { public static void main(String[] args) { String a = "Java"; String b = "Ja" + "va"; String c = new String("Java"); System.out.println((a == b) + " " + (a == c)); } } ```

    1. A. false false

      Assumes both comparisons are false, missing that b is a folded compile-time constant rather than a string built at run time.

    2. B. false true

      Inverts both results; the interned constant matches a, and the new String does not.

    3. C. true true

      Assumes both are true, but new String always creates a fresh object and never returns the pooled instance unless intern() is called.

    4. D. true falseCorrect answer

      "Ja" + "va" is a compile-time constant expression folded to "Java" and interned to the same pool object the literal uses, so a == b is true, while new String("Java") allocates a fresh object, so a == c is false.

    Explanation

    A concatenation of string literals is a compile-time constant, so it is folded into a single literal and interned into the shared string pool, making it the same object as an equal literal. A new String(...) expression, by contrast, always allocates a distinct object, so reference comparison against the pooled literal is false. Reference equality therefore hinges on whether each value is interned.

  4. Question 4

    The same numeric value is held in two wrappers and one primitive, then compared with ==. What is the output? ```java public class Main { public static void main(String[] args) { Integer boxed = 500; Integer other = 500; int raw = 500; System.out.println((boxed == other) + " " + (boxed == raw)); } } ```

    1. A. true true

      Assumes == always compares values; with two Integer operands it is a reference comparison, and 500 is outside the -128..127 cache, so the boxed objects differ and the first result is false.

    2. B. false false

      Correct that two boxed 500s are distinct objects, but forgets that mixing an Integer with an int unboxes, making the second comparison 500 == 500, which is true.

    3. C. false trueCorrect answer

      Correct — 500 is outside the cached range so the two Integer objects are distinct (false), while comparing an Integer with an int triggers unboxing to 500 == 500 (true) (JLS 17 §5.1.7).

    4. D. true false

      Inverts both results; the two boxed objects are unequal by reference (false) and the Integer-vs-int comparison unboxes to true.

    Explanation

    Both Integer operands make == a reference comparison. Boxing conversion is only required to cache values in -128..127, and 500 is outside that range, so boxed and other are distinct objects and the first comparison is false. The second comparison mixes an Integer with an int, which forces binary numeric promotion — boxed is unboxed and 500 == 500 is true. Answering 'true true' assumes == always compares values; answering 'false false' forgets that a primitive operand triggers unboxing.

  5. Question 5

    What is the output? ```java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abcdef"); sb.delete(1, 3).insert(1, "XY").reverse(); System.out.println(sb); } } ```

    1. A. aXYdef

      aXYdef is the builder's state just before reverse() runs, so it omits the final reversal.

    2. B. fedXYa

      fedXYa reverses everything except the inserted XY, but reverse() flips the whole sequence and so turns XY into YX.

    3. C. fedYX a

      fedYX a inserts a stray space that no operation in the chain ever adds.

    4. D. fedYXaCorrect answer

      delete(1, 3) removes indices 1 and 2 ("bc") to give adef, insert(1, "XY") gives aXYdef, and reverse() flips the entire sequence to fedYXa; each method mutates and returns the same builder so the chain composes.

    Explanation

    delete uses an end index that is exclusive, so delete(1, 3) removes exactly the two characters at indices 1 and 2. The subsequent insert and reverse operate on the same builder because each StringBuilder method mutates the object and returns it, letting the calls chain. reverse flips every character in the sequence, including the freshly inserted pair.

  6. Question 6

    What is the result of compiling and running this program? ```java public class Main { public static void main(String[] args) { var list = new java.util.ArrayList<String>(); list.add("a"); var x = 5; System.out.println(list.size() + x); } } ```

    1. A. Compilation fails: var cannot be used here

      Assumes var is misused here, but both declarations are local variables with initializers — exactly where var is permitted — so nothing fails to compile.

    2. B. 51

      Expects string concatenation to produce 51, but both operands of + are int, so the operator performs arithmetic rather than concatenation.

    3. C. 5a

      Expects 5a, which would require a String operand and the operands in reversed order; neither is present.

    4. D. 6Correct answer

      var legally infers ArrayList<String> for list and int for x, since both are initialized local variables. list.size() is 1 and 1 + 5 is int addition, so 6 is printed.

    Explanation

    var is permitted for any local variable that has an initializer, so inferring ArrayList<String> and int here is legal. Because both operands of + are int, the operator performs integer arithmetic rather than string concatenation, and list.size() returns 1. Adding 1 and 5 therefore yields 6 before println is invoked.

  7. Question 7

    What is the result? ```java public class Main { public static void main(String[] args) { Integer i = null; boolean pick = false; int x = pick ? 1 : i; System.out.println(x); } } ```

    1. A. Throws NullPointerExceptionCorrect answer

      Because one branch is int and the other Integer, the conditional expression's type is int, so the selected operand is unboxed; pick is false, so the null Integer is chosen and unboxing it throws NullPointerException.

    2. B. Compilation fails

      Expects a compile error, but the expression is well-typed; the problem surfaces only at run time.

    3. C. 1

      1 is the value of the true branch, but pick is false, so that branch is not selected.

    4. D. 0

      Assumes unboxing null falls back to a default of 0, but unboxing a null wrapper always throws rather than producing 0.

    Explanation

    When a conditional expression has one int operand and one Integer operand, its overall type is int, which forces the chosen operand to be unboxed. The false condition selects the null wrapper, and unboxing null invokes intValue() on a null reference, raising a NullPointerException at run time. Making both branches Integer would change the expression's type and avoid the unboxing entirely.

  8. Question 8

    What is printed? ```java public class Main { public static void main(String[] args) { byte b = 10; b += 5; System.out.println(b); } } ```

    1. A. 5

      5 ignores the original value 10, but += adds to the existing value rather than replacing it.

    2. B. Compilation fails: cannot assign int to byte

      Predicts a compile error, but the implicit cast built into += is exactly what lets it compile where b = b + 5 would not.

    3. C. 10

      10 assumes the assignment has no effect, but += executes and updates b.

    4. D. 15Correct answer

      A compound assignment b += 5 is defined as b = (byte)(b + 5), including an implicit narrowing cast back to byte; 10 + 5 is 15, which fits in a byte, so 15 is printed. (JLS 17 §15.26.2.)

    Explanation

    A compound assignment operator carries an implicit narrowing cast back to the type of the left-hand variable, so the byte addition compiles even though the equivalent explicit b + 5 would produce an int that cannot be assigned to a byte. The sum of 10 and 5 fits within byte range, so no truncation occurs and the result is 15. This hidden cast is why += succeeds where a plain assignment of the same arithmetic would fail.

Practise all 23 Working with Java Data Types questions

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

Open OCP Java SE 17

Other topics in this pack