
Lex Fridman shows a Java reflection hack that rewires the Integer cache so 2+2 equals 5. By reassigning the cached object for 4 to point to 5 instead, Integer arithmetic breaks in unexpected ways. The trick exploits how Java caches Integer objects from -128 to 127.
Questions this video answers
Lex Fridman
-128 to 127
256 elements
132nd element
133rd element
Chapters
This video is about how we can hack Java by using reflection of its own source code to make this 2:2 statement output 5. Just as George Orwell, one of my favorite writers, warned us about in 1984 about propaganda machines that sublimate the nature of truth, this video is not about politics philosophy, nor is it about the apparent, as I have just learned. Woke Twitter madness around 225 though perhaps if we're living in the simulation and it's written in Java, this might be a way to make the simulation just a bit more dystopian. So here's what the full source code looks like, and it uses Java's ability to do reflection, which is the ability of a programming language to inspect itself. So so if we look at the code, it actually dives into the implementation of the integer class, pulls out the integer cache class from that implementation, makes it accessible and writable, pulls it into an array of integer object of size 256 and modifies that array. Now what does this array contain? So interestingly, if we look at the integer cache class inside the integer object implementation in Java, it defines a hard coded low of negative 128 and a high that's passed in as a parameter, that's 127 as a default. And what that does is create a cache of integer objects from negative 128 to 127, and then reuses this cache every time an integer object with a value in this range is used. Now this is exactly the cache with reflection that we pull out and modify it. So happens that the 132nd element in the cache is where the four resides. And so by way of obfuscation, it takes the 133rd element, which has the number 5 in it, and assigns it to 132. But you can just assign value 5 here and then the result anywhere else in the code. If you use integer objects and the number four comes up, it will instead output the number five. There you go. Two plus two equals five. Check out the link in the description that points to the stack. Exchange Code Golf has a bunch of interesting discussions around this, including the possibility of taking the entire 256 element array and shuffling it, thereby not only making two plus two equals five, but messing with the entirety of low value arithmetic in Java. So there you go. That's how you hack the simulation. Let me quickly thank the sponsors that somehow amazingly, support the podcast and the videos I make. This Time is Asleep Mattress. Click the link to get a discount in the description. And by the way I have a conversation with James Gosling, the creator of Java, coming up on the podcast. So check that out. And remember, try to learn something new every SA.










