Primitive Type Conversion in Java: Implicit and Explicit Type Casting - Quiz

Total: 8 questions

1. 

What does an implicit cast mean?

It means code for cast shouldn't be written, the conversion will be done automatically.

2. 

What does explicit cast mean?

The code for cast should be written.

3. 

How to fix this? 

class Casting {
    public void calculate() {
        int y = 3957.229;
    }
}
class Casting {
    public void calculate() {
        int y = (int)3957.229;
    }
}
4. 

What is a widening conversion?

A conversion from a smaller type to a larger one, for example from byte to int. It is automatic (implicit) and safe, with no data loss.

5. 

What is a narrowing conversion?

A conversion from a larger type to a smaller one, for example from int to byte. It must be written explicitly with a cast in parentheses, and it may cause data loss.

6. 

What type is the result of an expression that adds two byte values?

The result is of type int. In expressions, Java promotes operands smaller than int (byte, short) to int, so byte + byte gives an int, not a byte.

7. 

Why does b1 += b2 compile while b1 = b1 + b2 does not (for byte variables)?

Compound assignment operators (+=, -=, *=, /=) perform an implicit cast back to the variable's type automatically. So b1 += b2 compiles, while b1 = b1 + b2 produces an int result that cannot be assigned to a byte without an explicit cast.

8. 

Why is byte not automatically converted to char, even though char is wider?

Because byte and short are signed types, while char is unsigned. The compiler needs an explicit cast to know how to handle the sign bit, so the conversion is not automatic even though char is 16 bits wide.

Page 1 of 1