source:http://enigma.vm.bytemark.co.uk/webstart.html John Meyers's SCJP 5 mock exam:question 7
Answer:false true false
lthree and lfour are two seperate objects. if the lines 1 and 2 were lthree = 2 and lfour = 2 the result would have been true. This is when the objects are created in the pool. When the references i and eye in the pool are compared 2==2 results in true and 2000==2000 is false since it exceeds 127.
I thought the answer would be false flase false why number smaller than 128 get true?they are wrapped, they should be different objects.
This is because integer from -128 to 127 are cached by the Intger class. so when a int within this range is created it is retrived from cache rather than creating a new Inetegr object.
You can find the cache for Integer class... private static class IntegerCache { private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }
Tarun Kumar
Gary Kevin
Ranch Hand
Joined: Jul 24, 2006
Posts: 43
posted
0
Originally posted by Tarun Kumar: This is because integer from -128 to 127 are cached by the Intger class. so when a int within this range is created it is retrived from cache rather than creating a new Inetegr object.
You can find the cache for Integer class... private static class IntegerCache { private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }
Tarun:Thinks very much!
I have seen the source code of Integer class. [CODE private static class IntegerCache { private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }
/** * Returns a <tt>Integer</tt> instance representing the specified * <tt>int</tt> value. * If a new <tt>Integer</tt> instance is not required, this method * should generally be used in preference to the constructor * {@link #Integer(int)}, as this method is likely to yield * significantly better space and time performance by caching * frequently requested values. * * @param i an <code>int</code> value. * @return a <tt>Integer</tt> instance representing <tt>i</tt>. * @since 1.5 */ public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); } [/CODE]
It defines an statci inner class and only uses it in method valueOf,Is that means when we invoke
JVM wrap the int to Integer just like this:
JVM implictly invokes The Integer's method valueOf?
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.