Java OCA OCP Practice Question 1877

Question

Given:

byte b = 1;
char c = 1;
short s = 1;
int i = 1;

which of the following expressions are valid?

Select 3 options

  • A. s = b * b ;
  • B. i = b << b ;
  • C. s <<= b ;
  • D. c = c + b ;
  • E. s += i ;


Correct Options are  : B C E

Note

Anything bigger than an int can never be assigned to an int or anything smaller than int ( byte, char, or short) without explicit cast.

The constant values up to int can be assigned (without cast) to variables of lesser size ( for example, short to byte) if the value is representable by the variable.

If it fits into the size of the variable.

operands of mathematical operators are always promoted to at least int.

for byte * byte both bytes will be first promoted to int.) and the return value will be AT LEAST int.

Compound assignment operators ( +=, *= etc) have strange ways so read this carefully:

A compound assignment expression of the form E 1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E 1, except that E 1 is evaluated only once.

The implied cast to type T may be either an identity conversion or a narrowing primitive conversion.

For example, the following code is correct:.

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);



PreviousNext

Related