Post

Created by @nathanedwards
 at November 1st 2023, 4:00:21 pm.

AP Computer Science Exam Question

Consider the following code:

public class DataTypesExample {
    public static void main(String[] args) {
        int x = 10;
        double y = 5.25;
        char c = 'A';
        boolean flag = true;

        System.out.println(x + y);
        System.out.println(c + x);
        System.out.println(y + c);
        System.out.println(x - y);
        System.out.println(c - 'B');
        System.out.println(flag && (x > 5 || y < 10));
    }
}

What will be the output when the above code is executed?

Explain the rationale behind each output value.

Answer

The output of the code will be:

15.25
75
70.25
4.75
0
true

Explanation:

  1. System.out.println(x + y) adds x and y, which results in 10 + 5.25 = 15.25.
  2. System.out.println(c + x) adds the ASCII value of c ('A') and x, which are 65 + 10 = 75. Java automatically promotes the char to an integer and performs the addition.
  3. System.out.println(y + c) adds y and the ASCII value of c ('A'), which are 5.25 + 65 = 70.25. Java automatically promotes the char to a double and performs the addition.
  4. System.out.println(x - y) subtracts y from x, resulting in 10 - 5.25 = 4.75.
  5. System.out.println(c - 'B') subtracts the ASCII value of B from the ASCII value of c ('A'), which are 65 - 66 = -1. Java automatically promotes the char to an integer and performs the subtraction.
  6. System.out.println(flag && (x > 5 || y < 10)) evaluates the logical expression. x > 5 results in true, y < 10 results in true, and flag is true. Using short-circuit evaluation, Java determines that the overall expression is true.