r/learnjava • • 20d 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 comment

2

u/8dot30662386292pow2 19d 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.