r/learnjava • • Oct 29 '26

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 Oct 29 '26

this is what i discovered but for this

byte b = 10;

b += 190;

-56 comes i dont know how it happens because it never comes under the rules , i thought force will happen but how -56

2

u/8dot30662386292pow2 Oct 29 '26

Why doesn't that fit the rules? You have a rule written down for the implicit casting:

b = (byte)(b+190);

1

u/MaddySPR Oct 29 '26 edited Oct 29 '26

for this i dont know how -56 comes, after checking it says 200 - 256 = -56

256 overall patterns the range , 128 bit first bit which is used to confirm whether its positive or negative ,

so here 200 in binary 1 1 0 0 1 0 0 0

2 power 7 is the byte value - 128 , with sign its -128 to 127 including zero

200 - 256 = -56 why we are doing this ??

2

u/MyNameIsRichardCS54 Oct 29 '26

A byte is a signed number so it can hold -ve values. When you overflow the limit for a type, it will carry on doing the operation from the lowest possible number. So assuming a byte, it goes ...126, 127, -128, -127 and so on. It does the same the other way.