Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason for different output here?

Tags:

java

int a = 2;
int b = a + a;

Class cache = Integer.class.getDeclaredClasses()[0]; 
Field myCache = cache.getDeclaredField("cache"); 
myCache.setAccessible(true);

Integer[] newCache = (Integer[]) myCache.get(cache); 
newCache[132] =  newCache[133];

System.out.printf("%d",b); // 5
System.out.println(b); // 4

Here I change the value of cache[132] to cache[133] that means now cache[132] == 5 in printf() method it prints 5 fine but in println() why it prints 4 it should be 5 what's the reason behind on it?

like image 594
Newaz Sharif Amit Avatar asked Mar 26 '16 17:03

Newaz Sharif Amit


Video Answer


1 Answers

println has an overload which accepts an int. Therefore in the line

System.out.println(b);

the int is never converted to an Object using Integer.valueOf.

printf has signature

public PrintStream printf(String format, Object ... args)

so 4 is autoboxed to the Integer object 5 (using the modified cache), and so 5 is printed.

like image 167
Paul Boddington Avatar answered Sep 18 '22 12:09

Paul Boddington