Categories

# Java SE 8 OCA exam: Chapter 2

Note:

1.Binary operations such as +,-,*,/,% will always convert both of the variables to to Int!

2.  Compound Assignment Operators (ex: y*=z or x+=b) will cast the values to the one which is on the left most.

3. But remember that if left hand side of equation is bigger in terms of data type then, it will be cast implicitly.

ex.:

short a=1;
short b=2;
double c=a+b;             // Compiles, because of implicit conversion

4.

short a=1;
short b=2;
short c=a+b;             // Doesn’t compile, because need to cast resulting int from addition must be cast to short adding casting so it becomes: short c=(short)(a+b)

## Tricky questions:

1. What is the data type of x + y?
double x = 39.21;
float y = 2.1;

This is actually a trick question, as this code will not compile! As you may remember
from Chapter 1, ﬂoating-point literals are assumed to be
double, unless postfxed with
an
f, as in 2.1f. If the value was set properly to 2.1f, then the promotion would be
similar to the last example, with both operands being promoted to a
double, and the
result would be a
double value

2.  Keep an eye out for questions on the exam that use the logical complement
operator or numeric values with
boolean expressions or variables. Unlike
some other programming languages, in Java
1 and true are not related in
any way, just as
0 and false are not related

3.  2147483647 is limit for int so adding any more value than that will convert it to negative value

 System.out.print(2147483647+1);               // -2147483648

4.

short x = 10;
short y = 3;
short z = x * y; // DOES NOT COMPILE

If you remember, short values are automatically promoted to int when applying any arithmetic operator, with the resulting value being of type int. Trying to set a short variable to an int results in a compiler error, as Java thinks
you are trying to implicitly convert from a larger data type to a smaller one.

short x = 10;
short y = 3;
short z = (short)(x * y);

By performing this explicit cast of a larger value into a smaller data type, you are
instructing the compiler to ignore its default behavior.

5.

long x = 5;
long y = (x=3);
System.out.println(x); // Outputs 3
System.out.println(y); // Also, outputs 3

6.

double a=3.2;
int b=5;
b+=a;  // b will be equal to 8, because when a converted to int, it loses some of precision

7.

Be wary of short-circuit behavior on the exam, as questions are known to alter a variable on the right-hand side of the expression that may never be reached. For example, what
is the output of the following code?
int x = 6;
boolean y = (x >= 6) || (++x <= 7);
System.out.println(x);
Because x >= 6 is true, the increment operator on the right-hand side of the expression
is never evaluated, so the output is
6.

8.  In Java 1 does not mean true and 0 does not mean false and vice versa.

 int x = 1; if(x) { // DOES NOT COMPILE … }

9.

 int x = 1; if(x = 5) { // DOES NOT COMPILE … }

10.
System.out.println((y > 5) ? 21 : “Zebra”);
int animal = (y < 91) ? 9 : “Horse”; // DOES NOT COMPILE

11.

 int y = 1; int z = 1; final int x = y<10 ? y++ : z++; System.out.println(y+”,”+z); // Outputs 2,1

12.

int dayOfWeek = 6;
switch (dayOfWeek) {
case 0:
System.out.println(“Sunday”);
default:
System.out.println(“Weekday”);
// case 17:
// System.out.println(“WHATTTT???”);
// break;
case 6:
System.out.println(“Saturday”);
case 7:
System.out.println(“Weee!”);
}

// Output
// Saturday
// Weee!

13.

The case statement value must also be a literal, enum constant, or final constant
variable.

private int getSortOrder(String firstName, final String lastName) {
String middleName = “Patricia”;
final String suffix = “JR”;
int id = 0;
switch(firstName) {
case “Test”:
return 52;

case middleName: // DOES NOT COMPILE

id = 5;
break;
case suffix:
id = 0;
break;
case lastName: // DOES NOT COMPILE
id = 8;
break;
case 5: // DOES NOT COMPILE
id = 7;
break;
case ‘J’: // DOES NOT COMPILE
id = 10;
break;
case java.time.DayOfWeek.SUNDAY: // DOES NOT COMPILE
id=15;
break;
}
return id;
}

The frst case statement compiles without issue using a String literal and is a good
example of how a
return statement, like a break statement, can be used to exit the switch
statement early. The second case statement does not compile because middleName is not a final variable, despite having a known value at this particular line of execution. The third
case statement compiles without issue because suffix is a final constant variable.
In the fourth
case statement, despite lastName being final, it is not constant as it is
passed to the function; therefore, this line does not compile as well. Finally, the last three
case statements don’t compile because none of them have a matching type of String; the
last one is an
enum value.

14.

a. int x = 0;
for(long y = 0, z = 4; x < 5 && y < 10; x++, y++) {
System.out.print(y + ” “);
}
System.out.print(x);
// will compile

b.

for(long y = 0, int x = 4; x < 5 && y<10; x++, y++) { // DOES NOT COMPILE
System.out.print(x + ” “);
}
// will not compile because y and x are different data types

15.

String[] names = new String;
for(int name : names) { // DOES NOT COMPILE
System.out.print(name + ” “);
}

// to fix change int to String

16.

List<Integer> myList = new ArrayList<>();
for(int numberInList:myList){
System.out.println(numberInList);
}

// this will compile and work, because myList is Iterable

17.

The switch statement is the only one that supports a variety of data types, including String variables as of Java 7 . If and other statements only support boolean.

# Casting Primitive Values

Casting primitives is required any time you are going from a larger numerical data
type to a smaller numerical data type, or converting from a ﬂoating-point number to an
integral value.

int x = (int)1.0;
short y = (short)1921222;              // Stored as 20678

int z = (int)9l;
long t = 192301398193810323L

## Compound Assignment Operators

long x = 10;
int y = 5;
y = y * x; // DOES NOT COMPILE
because can’t convert long to int

long x = 10;
int y = 5;
y *= x;
// will compile

# Relational Operators

We now move on to relational operators, which compare two expressions and return a
boolean value. If the two numeric operands are not of the same data type, the
smaller one is promoted in the manner as previously discussed.

int x = 10, y = 20, z = 10;
System.out.println(x < y); // Outputs true
System.out.println(x <= y); // Outputs true
System.out.println(x >= z); // Outputs true
System.out.println(x > z); // Outputs false ## Difference between logical operators and conditional operators(short circuit operator)

Logical operators are: &, | and ^(xor)

Conditional operators are: &&, ||

The difference is that Conditional operators(aka short circuit operators) will not execute all the statements if the left most or left conditions are true ex:

boolean x = true || (y < 4);

Logical operators can be applied to numbers as well for boolean data.

A more common example of where short-circuit operators are used is checking for null
objects before performing an operation, such as this:
if(x != null && x.getValue() < 5) {
// Do something
}

In this example, if x was null, then the short-circuit prevents a NullPointerException
from ever being thrown, since the evaluation of x.getValue() < 5 is never reached.

Alternatively, if we used a logical &, then both sides would always be evaluated and when x
was null this would throw an exception:
if(x != null & x.getValue() < 5) { // Throws an exception if x is null
// Do something
}

## Equality Operators

The equality operators are used in one of three scenarios:

1. Comparing two numeric primitive types. If the numeric values are of different data
types, the values are automatically promoted as previously described. For example,
5 == 5.00 returns true since the left side is promoted to a double.
2. Comparing two boolean values.
3. Comparing two objects, including null and String values.

File x = new File(“myFile.txt”);
File y = new File(“myFile.txt”);
File z = x;
System.out.println(x == y); // Outputs false
System.out.println(x == z); // Outputs true

## Overflow and Underflow

 Overflow is when a number is so large that it will no longer fit within the data type, so the system “wraps around” to the next lowest value and counts up from there.

Underflow ex.:

int underflowExample = -2147483648;

System.out.println(“Underflow: “+ (underflowExample – 1));   //     Underflow:  2147483647

Overflow ex.:

int overflowExample = 2147483647;

System.out.println(“Overflow: “+ (overflowExample + 1)); // Overflow: -2147483648

## Ternary Operator

booleanExpression ? expression1 : expression2

## Switch

Data types supported by switch statements include the following:
int and Integer
byte and Byte
short and Short
char and Character
int and Integer
String
enum values
For the exam, we recommend you memorize this list. Note that
boolean and long, and
their associated wrapper classes, are not supported by
switch statements

int dayOfWeek = 5;
switch(dayOfWeek) {
case 0:
System.out.println(“Sunday”);
default:
System.out.println(“Weekday”);
case 6:
System.out.println(“Saturday”);
break;
}

// Will output Weekday
//Saturday  Because default does not have break statement

Basically everything after default will execute, IF default doesn’t have break, and it will run next statements until it reaches break.

When evaluating switch statements on the exam, always consider that multiple branches may be visited in a single execution

## Enhanced For loop (aka For-each) The for-each loop declaration is composed of an initialization section and an object to
be iterated over. The right-hand side of the
for-each loop statement must be a built-in Java array or an object whose class implements java.lang.Iterable, which includes most of
the Java
Collections framework.

## Continue and Break optional labels ## Chapter 2 Test highlights:

2. What data type (or types) will allow the following code snippet to compile? (Choose all that
apply)
byte x = 5;
byte y = 10;
_____ z = x + y;
A. int
B. long
C. boolean
D. double
E. short
F. byte

A, B, D. The value x + y is automatically promoted to int, so int and data types that
can be promoted automatically from
int will work. Options A, B, D are such data
types. Option C will not work because
boolean is not a numeric data type. Options E
and F will not work without an explicit cast to a smaller data type.

4. What change would allow the following code snippet to compile? (Choose all that apply)
3: long x = 10;
4: int y = 2 * x;
A. No change; it compiles as is.
B. Cast x on line 4 to int.
C. Change the data type of x on line 3 to short.
D. Cast 2 * x on line 4 to int.
E. Change the data type of y on line 4 to short.
F. Change the data type of y on line 4 to long

B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * x
is automatically promoted to long and cannot be automatically stored in y, which is
in an
int value. Options B, C, and D solve this problem by reducing the long value to
int. Option E does not solve the problem and actually makes it worse by attempting
to place the value in a smaller data type. Option F solves the problem by increasing the
data type of the assignment so that
long is allowed

8. What is the output of the following code snippet?
3: boolean x = true, z = true;
4: int y = 20;
5: x = (y != 10) ^ (z=false);
6: System.out.println(x+”, “+y+”, “+z);
A. true, 10, true
B. true, 20, false
C. false, 20, true
D. false, 20, false
E. false, 20, true
F. The code will not compile because of line 5.

B. This example is tricky because of the second assignment operator embedded in line
5. The expression
(z=false) assigns the value false to z and returns false for the
entire expression. Since
y does not equal 10, the left-hand side returns true; therefore,
the exclusive or (
^) of the entire expression assigned to x is true. The output reflects
these assignments, with no change to
y, so option B is the only correct answer. The
code compiles and runs without issue, so option F is not correct.

9. How many times will the following code print “Hello World”?
3: for(int i=0; i<10 ; ) {
4: i = i++;
5: System.out.println(“Hello World”);
6: }
A. 9
B. 10
C. 11
D. The code will not compile because of line 3.
E. The code will not compile because of line 5.
F. The code contains an infinite loop and does not terminate

F. In this example, the update statement of the for loop is missing, which is fine as the
statement is optional, so option D is incorrect. The expression inside the loop increments
i but then assigns i the old value. Therefore, i ends the loop with the same value
that it starts with: 0. The loop will repeat infinitely, outputting the same statement over
and over again because
i remains 0 after every iteration of the loop.

13.
What is the output of the following code snippet?
3: int x1 = 50, x2 = 75;
4: boolean b = x1 >= x2;
5: if(b = true) System.out.println(“Success”);
6: else System.out.println(“Failure”);
A. Success
B. Failure
C. The code will not compile because of line 4.
D. The code will not compile because of line 5.

A. The code compiles successfully, so options C and D are incorrect. The value of b
after line 4 is false. However, the if-then statement on line 5 contains an assignment,
not a comparison. The variable
b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success, so the answer is option A.

15.
3: int x = 1, y = 15;
4: while x < 10
5: y––;
6: x++;
7: System.out.println(x+”, “+y);
A. 10, 5
B. 10, 6
C. 11, 5
D. The code will not compile because of line 3.
E. The code will not compile because of line 4.
F. The code contains an infinite loop and does not terminate

E. This is actually a much simpler problem than it appears to be. The while statement
on line 4 is missing parentheses, so the code will not compile, and option E is the correct answer. If the parentheses were added, though, option F would be the correct
answer since the loop does not use curly braces to include
x++ and the boolean expression never changes. Finally, if curly braces were added around both expressions, the
output would be
10, 6 and option B would be correct.

16.
3: do {
4: int y = 1;
5: System.out.print(y++ + ” “);
6: } while(y <= 10);
A. 1 2 3 4 5 6 7 8 9
B. 1 2 3 4 5 6 7 8 9 10
C. 1 2 3 4 5 6 7 8 9 10 11
D. The code will not compile because of line 6.
E. The code contains an infinite loop and does not terminate.

D. The variable y is declared within the body of the do-while statement, so it is out of
scope on line 6. Line 6 generates a compiler error, so option D is the correct answer.

18.
What is the output of the following code snippet?
3: int count = 0;
4: ROW_LOOP: for(int row = 1; row <=3; row++)
5: for(int col = 1; col <=2 ; col++) {
6: if(row * col % 2 == 0) continue ROW_LOOP;
7: count++;
8: }
9: System.out.println(count);
A. 1
B. 2
C. 3
D. 4
E. 6
F. The code will not compile because of line 6

B. The expression on line 5 is true when row * col is an even number. On the first
iteration,
row = 1 and col = 1, so the expression on line 6 is false, the continue is
skipped, and
count is incremented to 1. On the second iteration, row = 1 and
col = 2, so the expression on line 6 is true and the continue ends the outer loop with
count still at 1. On the third iteration, row = 2 and col = 1, so the expression on line
6 is
true and the continue ends the outer loop with count still at 1. On the fourth
iteration,
row = 3 and col = 1, so the expression on line 6 is false, the continue is
skipped, and
count is incremented to 2. Finally, on the fifth and final iteration, row
= 3
and col = 2, so the expression on line 6 is true and the continue ends the outer
loop with
count still at 2. The result of 2 is displayed, so the answer is option B

19.
What is the result of the following code snippet?
3: int m = 9, n = 1, x = 0;
4: while(m > n) {
5: m–;
6: n += 2;
7: x += m + n;
8: }
9: System.out.println(x);
A. 11
B. 13
C. 23
D. 36
E. 50
F. The code will not compile because of line 7

D. Prior to the first iteration, m = 9, n = 1, and x = 0. After the iteration of the first
loop,
m is updated to 8, n to 3, and x to the sum of the new values for m + n, 0 + 11 =
11
. After the iteration of the second loop, m is updated to 7, n to 5, and x to the sum
of the new values for
m + n, 11 + 12 = 23. After the iteration of the third loop, m is
updated to
6, n to 7, and x to the sum of the new values for m + n, 23 + 13 = 36. On
the fourth iteration of the loop,
m > n evaluates to false, as 6 < 7 is not true. The
loop ends and the most recent value of
x, 36, is output, so the correct answer is option
D