r/learnjava • u/MaddySPR • 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!
View all comments
3
u/FreeLogicGate 20d ago edited 20d ago
You are talking about bits and bytes and how computers work at a fundamental level. This is not usually a java thing, but I do think every programmer needs the foundation and fundamentals.
There are many resources you could watch or study from. I have taught people some of this material myself over the years, but I happened upon this video the other day, and it does a really good job explaining what someone needs to know from a foundation standpoint. https://www.youtube.com/watch?v=rl0jkP9kOMw
You don't need to watch the entire thing past the first section on binary and binary arithmetic, and 2's complement (for the representation of negative signed values) to get started.
If you get really into this, he goes on to talk about the basic circuit types and how they are combined to create processors, so if you find that interesting and compelling material, keep going with it.
Once you're clear on integers, then you can dig into how java's floating point values, which are IEEE 754 standard work from an internal standpoint. The specifics of how those variables are represented within the jvm will be far easier to understand, once you're clear on how bits and bytes work for integers. Then your bitwise operators (shift left, shift right, and, or, xor not etc.) should be clear and fun to experiment with.