Back to Index

2+2=5 in Java


Transcript

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 2+2=5.

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 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 -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 -128 to 127, and then reuses this cache every time an integer object with a value in this range is used.

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 4 resides, and so by way of obfuscation, it takes the 133rd element, which has the number 5 in it, and it sizes it to 132nd, but you can just assign value 5 here.

And then the result, and you are else in the code, if you use integer objects and the number 4 comes up, it will instead output the number 5. There you go, 2+2=5. 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 2+2=5, 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 it's 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 day. Bye!