When a Variable Can Be Both 1 and 12: Exploring JavaScript and Java Tricks
This article examines the seemingly impossible condition "if(a == 1 && a == 12)" and demonstrates clever JavaScript and Java techniques that allow a single variable to satisfy multiple equality checks, turning a puzzling interview question into a fun exploration of language quirks.
The article introduces a puzzling condition “if(a == 1 && a == 12)” that seems impossible, and uses it as a fun challenge to explore language-specific tricks in JavaScript and Java.
In the JavaScript section, a solution based on object coercion or getter properties is presented (the original answer is linked via an image, but the concept is that a variable can return different values on each access).
The Java section shows a more elaborate hack using reflection to manipulate the Integer cache, allowing the same Integer object to compare equal to multiple values; the full code is shown below.
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];
array[131] = array[129];
Integer a = 1;
if (a == (Integer)1 && a == (Integer)2 && a == (Integer)3) {
System.out.println("Success");
}The author concludes that while the article is not meant to deeply dissect language internals, the puzzle serves as a playful way to test one’s understanding of language features and problem‑solving mindset.
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.