How Can a Variable Be Both 1 and 12? Exploring Impossible JS/Java Conditions
This article examines a puzzling code challenge where a variable appears to satisfy contradictory conditions simultaneously, explains why the JavaScript expression if(a==1 && a==12) can be true, and presents creative solutions in both JavaScript and Java to achieve the effect.
Recently I stumbled upon an intriguing post that posed the question: how can the JavaScript condition if(a == 1 && a == 12) ever evaluate to true? At first glance it seems impossible for a single variable to meet both conditions at once.
var a = ???;
if(a == 1 && a == 12){
console.log(a);
}After deeper thought, I realized the problem is interesting because it forces us to consider how a variable might change its value dynamically during evaluation.
Solution Overview
If we assume the condition can be true, the variable cannot be a normal primitive; it must be capable of altering its value on the fly.
JavaScript Version
One answer leverages object coercion tricks. The following image illustrates the approach:
This method may look baffling to Java or other OOP developers, but it demonstrates a viable way to satisfy the condition.
Java Version
The Java solution manipulates the internal Integer cache to make multiple integer instances reference the same value, allowing the same variable to appear equal to 1, 2, and 3 simultaneously:
Class cache = Integer.class.getDeclaredClasses()[0];
Field c = cache.getDeclaredField("cache");
c.setAccessible(true);
Integer[] array = (Integer[]) c.get(cache);
// array[129] is 1
array[130] = array[129]; // Set 2 to be 1
array[131] = array[129]; // Set 3 to be 1
Integer a = 1;
if(a == (Integer)1 && a == (Integer)2 && a == (Integer)3){
System.out.println("Success");
}Another more advanced answer uses PowerMockRunner to achieve the same effect, as shown in the following image:
Conclusion
The purpose of this article is not to deeply explore language internals, but to showcase a fun and thought‑provoking puzzle that tests both language‑specific knowledge and problem‑solving methodology.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
