# Using Operators and Decision Constructs Flashcards

1
Q

Given that x is an int, the following is valid:
switch(x){
case x 5 :System.out.println(“SMALL”);
default :System.out.println(“CORRECT”); break;
}

A

False:

- the type of the case labels must be consistent with the type of the switch condition.

2
Q
```Given:
byte b = 1;
char c = 1;
short s = 1;
int i = 1;  ```

which of the following expressions are valid:

1. s = b * b ;
2. i = b
A

2, 3, 5

• b * b and c + b returns an int
• Anything bigger than an int can NEVER be assigned to an int or anything smaller than int ( byte, char, or short) without explicit cast.
• All compound assignment operators internally do an explicit cast.
3
Q

Given:
switch( m ){
case 32: System.out.println(“32”);break;
case 64: System.out.println(“64”);break;
case 128 : System.out.println(“128”);break; }

What is a valid type for m:

1. int
2. long
3. char
4. byte
5. short
A

1, 3, 5

• char’s range is from 0 to 65535.
• byte’s range is from -128 to 127
4
Q

Consider: o1 and o2 denote two object references to two different objects of same class.
Which of the following statements are true:
1. o1.equals(o2) will always be false.
2. o1.hashCode() == o2.hashCode() will always be false.
3. o1 == o2 will always be false
4. Nothing can be said about o1.equals(o2) regarding what it will return based on the given information.
5. Nothing can be said about o1 == o2.

A

3, 4
- Note that both equals() and hashCode() methods can be overridden by the programmer so you can’t say anything about what they will return without looking at the code.

5
Q

Which of the following will not give any error at compile time and run time:

1. if (8 == 81) {}
2. if (x = 3) {} // assume that x is an int
3. if (true) {}
4. if (bool = false) {}//assume that bool is declared as a boolean
5. if (x == 10 ? true:false) { } // assume that x is an int
A

1, 3, 4, 5

- All an if(…) needs is a boolean.

6
Q

Which of the following statements are true:

1. The condition expression in an if statement can contain method calls.
2. If a and b are of type boolean, the expression (a = b) can be used as the condition expression of an if statement.
3. An if statement can have either an ‘if’ clause or an ‘else’ clause.
4. The statement : if (false) ; else ; is illegal.
5. Only expressions which evaluate to a boolean value can be used as the condition in an if statement.
A

1, 2, 5

• if-clause and the else-clause can have empty statements. Empty statement ( i.e. just a semi-colon ) is a valid statement.
• if (false) ; else ; is legal
7
Q

True/false: A char value can always be assigned to an int variable

A

True.

- since the int type is wider than the char type.

8
Q

Which operators will always evaluate all the operands:

1. &&
2. l
3. ll
4. ? :
5. %
A

2, 5
- If the condition before ? returns true, only the first operand will be evaluated, otherwise only the second operand is evaluated (4).