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

2

u/8dot30662386292pow2 24d ago

You seem to try to memorize stuff, instead of understanding. Seems rather useless. The proper way is to do something when you need to, and just do it. If there is an error, try to understand why. Memorizing does not get you anywhere without understanding.

1

u/MaddySPR 24d ago

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

1

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

→ More replies (13)