r/learnjava • • 29d ago

Overflow/underflow + casting rules keep confusing me — any good video or notes that made it click for you?

Hey all, I'm learning Java (going through Tim Buchalka's masterclass after the Helsinki MOOC) and I'm stuck on the whole overflow / underflow / casting thing.

▎

▎ I've been trying to make my own flow diagram for "will this line compile, error, or wrap?" Stuff like:

▎

▎ int x = 5;

▎ byte b = x; // error

▎ byte b = 5; // fine

▎ byte c = (byte) 200; // -56 ??

▎

▎ Every time I think I've got it, a new case breaks the diagram: final variables, += hiding a cast, long literals needing L, why a double cast to long doesn't wrap but float gives Infinity, etc. I understand each piece on its own but I can't hold the whole picture in my head.

▎

▎ Is there a video, blog post, cheat sheet or notes that explains this cleanly in one place? Or how did you personally get comfortable with it? I'd especially like something that covers the compile-time checks and the runtime wrapping together.

▎

▎ Thanks!

1 Upvotes

23 comments sorted by

View all comments

Show parent comments

1

u/MaddySPR 29d ago

Tried to understand but it’s working different whenever I find something new

1

u/8dot30662386292pow2 29d ago

So what kind of "rules" have you established so far, and give me one example that breaks one of these rules? I can try to see if the rules are correct, or why are they broken.

1

u/MaddySPR 29d ago

══════ PART 1 · COMPILE (javac checks, no maths yet) ══════

START: LEFT = RIGHT;

│ │

│ └─ RIGHT type: byte/short/char maths → int,

│ else the biggest type in it

└──────── LEFT type: the variable's type

STEP 0, before anything (Q37):

a number bigger than 2147483647 written without L → ❌ "integer number too large"

a += 2147483900; → ❌ error, the diagram never starts

a += 2147483900L; → OK, go on to ①

FIRST, look at the RIGHT side (Q30):

byte a = 5; → a number → Java sees 5

final int k = 20; byte a = k; → a final → Java sees 20

int x = 5; byte a = x; → a variable → Java sees only "int"

│

│ sizes: byte < short, char < int < long < float < double

▼

① Is the LEFT type BIG ENOUGH for the RIGHT type? (same or bigger)

│ e.g. long l = a + 1; long ≥ int → YES

│ byte b = x + y; byte < int → NO

│

├─ YES ─► ✅ COMPILES → go to PART 2

│ ┌─ bigger box ───────────────────────────────┐

│ │ int i = 5; │

│ │ long big = i; │

│ └────────────────────────────────────────────┘

│ ┌─ same size ────────────────────────────────┐

│ │ int a = Integer.MAX_VALUE; │

│ │ int c = a + 1; │

│ └────────────────────────────────────────────┘

│ ┌─ int maths first, then a long ─────────────┐

│ │ int a = Integer.MAX_VALUE; │

│ │ long l = a + 1; │

│ └────────────────────────────────────────────┘

│

│ NO

▼

② Did you FORCE it? (a cast, += -= *= /=, or ++ --)

│

├─ YES ─► ✅ COMPILES → go to PART 2

│ ┌─ ++ has a hidden cast ─────────────────────┐

│ │ byte b = 127; │

│ │ b++; // b = (byte)(b + 1) │

│ └────────────────────────────────────────────┘

│ ┌─ += has a hidden cast ─────────────────────┐

│ │ byte b = 10; │

│ │ b += 120; // b = (byte)(b + 120) │

│ └────────────────────────────────────────────┘

│ ┌─ a cast you write ─────────────────────────┐

│ │ int n = 300; │

│ │ byte c = (byte) n; │

│ └────────────────────────────────────────────┘

│

│ NO

▼

③ Can Java SEE the number? YES only if all 3 are true:

│ a. Look LEFT of = Is the variable you store INTO a byte, short or char?

│ b. Look RIGHT of = Is its type int, short, char or byte? (not long, float, double)

│ c. Look RIGHT of = Is it a fixed number? 100 or final int k = 20; (same line)

│ ┌─ examples ─────────────────────────────────────────────┐

│ │ check YES (compiles) NO (error) │

│ │ │

│ │ a byte b = 100; int i = 5L; │

│ │ char c = 65; // 'A' │

│ │ │

│ │ b final short s = 50; final long big = 5; │

│ │ byte b = s; byte b = big; │

│ │ │

│ │ c final int k = 20; int k = 20; │

│ │ byte b = k; byte b = k; │

│ │ final int k; k = 20; │

│ │ byte b = k; │

│ └────────────────────────────────────────────────────────┘

│ all 3 YES → go to ④ (does it fit?) any 1 NO → ❌ LOSSY, ④ skipped

│ e.g. byte b = 200; → a b c YES → ④ 200 > 127 → ❌

│

├─ NO ──► ❌ LOSSY

│ ┌─ a fails: LEFT is float ───────────────────┐

│ │ float a = 5.25; // error (Q25) │

│ └────────────────────────────────────────────┘

│ ┌─ b fails: RIGHT is a long constant ────────┐

│ │ final long big = 5; │

│ │ byte b = big; // error │

│ └────────────────────────────────────────────┘

│ ┌─ c fails: final, but value set later ──────┐

│ │ final int x; │

│ │ x = 5; │

│ │ byte b = x; // error │

│ └────────────────────────────────────────────┘

│ ┌─ variables: Java can't see ────────────────┐

│ │ short x = 10, y = 20; │

│ │ short z = x + y; // error │

│ └────────────────────────────────────────────┘

│ ┌─ one plain variable: same rule (Q26) ──────┐

│ │ int x = 5; │

│ │ byte b = x; // error │

│ │ final int x = 5; byte b = x; // ✅ 5 │

│ └────────────────────────────────────────────┘

│ ┌─ fix: force it → goes to ② YES ────────────┐

│ │ short z = (short) (x + y); │

│ └────────────────────────────────────────────┘

│

│ YES

▼

④ Does the VALUE FIT? (byte max 127 · short max 32,767)

│

├─ NO ──► ❌ LOSSY

│ ┌─ too big ──────────────────────────────────┐

│ │ byte b = 100 + 28; // 128 > 127 │

│ └────────────────────────────────────────────┘

│

│ YES

▼

✅ COMPILES → go to PART 2

┌─ plain numbers ────────────────────────────┐

│ short s = 100 + 200; │

└────────────────────────────────────────────┘

┌─ final ────────────────────────────────────┐

│ final int k = 20; │

│ byte b = k * 6; │

└────────────────────────────────────────────┘

══════ PART 2 · RUN (only if it compiled: the maths happens) ══════

Each result fits its box?

│

├─ YES ─► stored as is

│ ┌─ fits ─────────────────────────────────────┐

│ │ long big = i; → 5 │

│ │ short s = 100 + 200; → 300 │

│ │ byte b = k * 6; → 120 │

│ │ short z = (short)(x + y) → 30 │

│ └────────────────────────────────────────────┘

│

└─ NO ──► WRAPS

The number goes through 2 boxes:

RIGHT side ─► [ A · MATHS box ] ─► cast? ─► [ B · LEFT box ]

fits? NO → WRAP fits? NO → WRAP

A = picked by the RIGHT side's types (at least int)

B = only when a cast squeezes it (cast, +=, ++)

┌─ A · wraps in the maths ───────────────────┐

│ int x = 2_000_000_000; │

│ long y = x + x; │

│ │

│ int box : 4 billion → too big → WRAP │

│ result : -294967296 │

└────────────────────────────────────────────┘

┌─ B · wraps at the cast ────────────────────┐

│ byte b = 127; │

│ b++; │

│ │

│ int box : 128 → fits │

│ byte box: 128 → too big → WRAP │

│ result : -128 │

└────────────────────────────────────────────┘

Too big? 3 possible results (Q33):

  1. WRAP whole number → whole box (byte) 200 → -56

which number? too big → − 256 (byte), too small → + 256 (§18)

2. MAX decimal → whole box (long) 1e30 → 9223372036854775807

3. Infinity anything → float / double (float) 1e39 → Infinity

2

u/8dot30662386292pow2 29d ago

I think you are stuck in listing examples, instead of figuring out the actual "rules".

Java operates in ints. int is the default type in all possible places.

  1. Any integer literal is always an int, unless the literal is long (L-suffix is added).

     long x = 234234; // the literal is int, but it fits to a wider type.
  2. Any calculation with literals always results to an int, unless one of the literals is long.

      long l = 2000000000 + 2000000000;  // overflow.
  3. Any calculation with variables is always an int, unless one of the variables is long.

     byte a = 23;
     short s = 34;
     byte result = a+s; // ALWAYS an int, unless any of the operands is long.
  4. If a literal fits in byte or short, it can be stored without casting.

     byte x = 127; 

I think one of the main things you are confused about is the order of operations. It does not matter at all, what is said on the left hand side of the = sign. That has absolutely zero effect on anything. The one and only thing matters is the right hand side: What the expression is doing. The expression is always calculated first, and the result is always int, unless one operator is a long. Only after the calculation, it is assigned to the variable, widening the result if needed. We still get a compile error though: Java looks into a line of code and sees: "this expression here is doing maths on a byte, integer, and another byte. The end result is an integer in any case. How ever, the variable is declared as short -> compile error, because it's possible that the result does not fit, so an explicit cast is required.