Will Perone

Consider the following two pieces of code
if (screenSize==SCREEN_SMALL) x = 2; else
    if (screenSize==SCREEN_LARGE) x = 4; else
        if (screenSize==SCREEN_QVGA) x = 6; 
and
switch(screenSize) {
case SCREEN_SMALL: x = 2; break;
case SCREEN_LARGE: x = 4; break;
case SCREEN_QVGA:  x = 6; break;
}

Normally if the SCREEN variables are defined in order, a switch statement will optimize better than the if-else chain:
public static final int SCREEN_SMALL = 0;
public static final int SCREEN_LARGE = 1;
public static final int SCREEN_QVGA  = 2;

This is because the switch statement will optimize to become a table in the bytecode. You can actually optimize this further though if you consider that ScreenSize is always the same value at run time (either SCREEN_SMALL, SCREEN_LARGE or SCREEN_QVGA).
public static final int screenSize = ${screenSize};

In this case an if-else chain will actually optimize better because it will remove the dead code that's never called thus eliminating the entire check.


When concatenating a bunch of String's together, use StringBuffer.append instead of String + String. The String + method creates a temporary object and then frees it thus becoming less optimal than having a StringBuffer and appending the strings then doing .toString() on the StringBuffer.

The WTK emulator and many phones have a weird quirk where the ordering matters with static initializers. The following code will generate a heap overflow upon the second time this class instantiates:
static {
    try {        
        image = Image.createImage("/someimage.png");        
        colors = new int[3]; 
        image.getRGB(colors, 0, IMAGE_WIDTH, 0, 0, 3, 1);
    } catch (Exception e) {  }
}
However the following code WILL work... I have no idea why:
static {
    try {
        colors = new int[3]; 
        image = Image.createImage("/someimage.png");        
        image.getRGB(colors, 0, IMAGE_WIDTH, 0, 0, 3, 1);
    } catch (Exception e) {  }
}


Watch out for Date objects around Daylight Savings Time because Daylight Savings Time has changed a number of times in recent years and phones made before those changes probably don't have the update. The Date object may be an hour off around the end of October and beginning of November.
2 Comments
Deepak 0 0
Nice one......
Rita 2012/09/13 Contact Me0 0
yusef قال:ما شاء الله عليك الله لا يضركتكفى كمل و الله محتاج مثل هالدروس ولو بعد تشرح لنا المصفوفات بتعمق و تشرح كيف نضيف و كيف نحذف و هذه الاشياء ودي اعرفها الواجب :public class Family {public static void main ( String args [] ) {String [] names = new String [4] ;names [0] = mmhmoaed ;names [1] = monirah ;names [2] = saleh ;names [3] = aber ;int [] age = new int [7] ;age [0] = 52 ;age [1] = 45 ;age [2] = 22 ;age [3] = 18 ;System.out.println ( names [0] + + age [0] ) ;System.out.println ( names [1] + + age [1] ) ;System.out.println ( names [2] + + age [2] ) ;System.out.println ( names [3] + + age [3] ) ;}} هاه كيف شاطر ولا لا

<- for private contact