The Java Program: Local.java

  1 // Local.java:  common programming mistakes
  2 
  3 /*
  4    Localize scope of variables; use declarations in for loops.
  5    Declare and initialize variables at the same time.
  6    Use "final" for single-assigment variables.
  7    Don't test, return, set, etc boolean constants.
  8    Use horizontal and vertical space wisely.
  9 */
 10 
 11 class Local  {
 12 
 13    public static void main (String args[])  {
 14 
 15       /*** The long way to do it.  ***/
 16       boolean b1;
 17       int temp1;     // a temporary variable
 18       int i1;        // a for-loop index
 19       int j1, k1;
 20       j1=5;
 21       k1=6;
 22       if (j1==k1) {
 23          b1 = true;
 24       } else {
 25          b1 = false;
 26       }
 27       for (i1=0; i1<78; i1++) {
 28          if (b1==true) {
 29             temp1 = j1;
 30             j1 = k1;
 31             k1 = temp1;
 32          }
 33       }
 34 
 35       /*** A better way to do it.  ***/
 36       int j2=5, k2=6;
 37       final boolean b2 = (j2==k2);
 38       for (int i2=0; i2<78; i2++) {
 39          if (b2) {
 40             final int temp2=j2; j2=k2; k2=temp2;
 41          }
 42       }
 43 
 44    }
 45 }