SteelReed

Search

Search posts, questions…

Java CoreQuestion 5 / 43

Junior

What is the difference between implicit and explicit casting? Why does s = s + 1 fail but s += 1 compile?

Short answer

Converting from a smaller to a bigger type (widening) is automatic; bigger to smaller (narrowing) needs a cast (int) x and can lose data.

s + 1assign back to shorts += 1automatic wideningnarrowing, explicit castshort sint resultcompile errorimplicit (short)(s + 1)long, float, doublemay lose data

3 points to say:

  1. (byte) 130 gives -126, (int) 3.99 gives 3.
  2. short + 1 becomes int, so s = s + 1 fails.
  3. s += 1 casts implicitly, so it compiles.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.