Other April fools quite difficult and a bit unfair quiz

Erel

B4X founder
Staff member
Licensed User
Longtime User
PI7jrPEBiD.gif


code:
B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI 
    Private Button1 As B4XView
    Private TextField1 As B4XView
    Private TextField2 As B4XView
    Private lblResult As B4XView
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
    Dim r As Reflector
#region Secret
 '3 lines here...................................
#end region

End Sub


Sub Button1_Click
    Dim FirstNumber As Int = TextField1.Text
    Dim SecondNumber As Int = TextField2.Text
    lblResult.Text = SumInts (Array(FirstNumber, SecondNumber))
End Sub

Sub SumInts (Ints As List) As Int
    Dim sum As Int = 0
    For Each i As Int In Ints
        sum = sum + i
    Next
    Return sum
End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Good job!
B4X:
   Dim r As Reflector
     #region Secret
    Dim cache() As Object = r.GetStaticField("java.lang.Integer$IntegerCache", "cache")
    cache(128+14)  = 3  
    #end region

That's the correct answer. Only 2 lines are needed (I corrected it in post #18).

Explanation:

For performance reasons, each numeric type is represented with two types: the primitive type (Java int) and the object type (Java Integer).
There are many cases where a primitive type needs to be converted to the object type and vice versa. This conversion is called boxing.

B4X:
Dim i As Int = 4 'primitive
Dim o As Object = 4 ' primitive converted to object
i = o 'object converted to primitive
List.Add(17) 'List holds objects so it will hold the object type - primitive converted to object

The compiler takes care of these conversions automatically.
As an optimization the JVM holds a small cache (array) that holds the object types of values between -128 to 127.
This is the relevant code:
B4X:
 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
The reflection code gets this cache and puts the object type with the value 3 in the place of the object type with the value 14.
The result is:
B4X:
Dim o As Object = 14 'The primitive type is converted to an object type using the small cache.
Log(o) '3
 
Upvote 0
Top