Can a Variable Be Both 1 and 12? Exploring Impossible JS & Java Tricks
This article examines a puzzling code condition where a variable appears to satisfy contradictory checks, presents creative JavaScript and Java solutions that exploit language quirks, and reflects on the broader learning value of such unconventional programming challenges.
While browsing a community post, I encountered a seemingly impossible JavaScript snippet:
var a = ???;
if (a == 1 && a == 12) {
console.log(a);
}At first glance the condition looks absurd because a single variable cannot simultaneously equal two different values. However, the problem becomes intriguing when we consider that the variable might change its value dynamically during evaluation.
JS Version
One clever answer manipulates the valueOf or toString methods so that the variable returns different numbers on each comparison. The solution is illustrated in the image below.
Java Version
A Java counterpart achieves a similar effect by tampering with the internal integer cache:
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 sophisticated answer uses PowerMockRunner to mock the integer cache, as shown in the following image.
Conclusion
The purpose of this article is not to exhaustively explore language internals, but to highlight how such puzzles can test one’s grasp of language features and encourage creative problem‑solving. They serve as both a fun challenge and a reminder of the depth hidden in everyday programming constructs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.
