Skip to content

Instantly share code, notes, and snippets.

@Attumm
Last active February 19, 2025 21:13
Show Gist options
  • Save Attumm/d4337ebb68c29fe804c14355ed1b85f5 to your computer and use it in GitHub Desktop.
Save Attumm/d4337ebb68c29fe804c14355ed1b85f5 to your computer and use it in GitHub Desktop.
Integer caching
public class App {
public static void main(String[] args) {
System.out.println("Demonstrating Integer Caching in Java");
System.out.println("-------------------------------------\n");
// Test lower bound (-128)
Integer lowerBound1 = -128;
Integer lowerBound2 = -128;
System.out.println("Lower Bound (-128): " + (lowerBound1 == lowerBound2));
// Test just below lower bound (-129)
Integer justBelowLower1 = -129;
Integer justBelowLower2 = -129;
System.out.println("Just Below Lower (-129): " + (justBelowLower1 == justBelowLower2));
Integer cachedInt1 = 100;
Integer cachedInt2 = 100;
System.out.println("Cache Range (100): " + (cachedInt1 == cachedInt2));
// Test value at potential default upper bound (127)
Integer upperBound1 = 127;
Integer upperBound2 = 127;
System.out.println("Upper Bound (127): " + (upperBound1 == upperBound2));
// Test value just above potential default upper bound (128)
Integer justAboveUpper1 = 128;
Integer justAboveUpper2 = 128;
System.out.println("Just Above Upper (128): " + (justAboveUpper1 == justAboveUpper2));
// Test outside default cache range (initially, e.g., 200)
Integer nonCachedInt1 = 200;
Integer nonCachedInt2 = 200;
System.out.println("No Cache (200): " + (nonCachedInt1 == nonCachedInt2));
}
}
java --version
openjdk 17.0.2 2022-01-18
OpenJDK Runtime Environment (build 17.0.2+8-86)
OpenJDK 64-Bit Server VM (build 17.0.2+8-86, mixed mode, sharing)
Demonstrating Integer Caching in Java
-------------------------------------
Lower Bound (-128): true
Just Below Lower (-129): false
Cache Range (100): true
Upper Bound (127): true
Just Above Upper (128): true
No Cache (200): true
Demonstrating Integer Caching in Java
-------------------------------------
Lower Bound (-128): true
Just Below Lower (-129): false
Cache Range (100): true
Upper Bound (127): true
Just Above Upper (128): false
No Cache (200): false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment