Home arrow Java arrow Page 3 - Java in Review
JAVA

Java in Review


Tired of hearing about the gory syntax details of Java? Keep reading for a more conceptual view of the language, focusing on important issues that deserve more attention than they usually receive. Even an advanced programmer will find useful information in this article. It was excerpted from chapter one of Hardcore Java, edited by Robert Simmons Jr. (O'Reilly, 2004; ISBN: 0596005687).

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 12
June 16, 2005
TABLE OF CONTENTS:
  1. · Java in Review
  2. · Syntax Issues
  3. · Collection iteration with for
  4. · Labels
  5. · Assertions versus exceptions
  6. · Assertions and deployment
  7. · Initialization
  8. · Access Issues
  9. · Common Mistakes

print this article
SEARCH DEVARTICLES

Java in Review - Collection iteration with for
(Page 3 of 9 )

Iterating through collections offers you another chance to have a bit of fun with the for loop. Letís begin with typical code used to iterate through a collection of objects:

  package oreilly.hcj.review;
 
public class ForLoops {
   
public static void forLong() {
      Properties props = System.getProperties();
      Iterator iter = props.keySet()
                           
.iterator();
     
String key = null;
     
while (iter.hasNext()) {
        key = (String)iter.next();
        System.out.println(key + "=" + System.getProperty(key));
        }
     }
  }

This snippet will iterate through all of the system properties and dump them to System.out. It works fine but it is very wordy and can be slightly problematic. For example, try the following bug on for size:

  package oreilly.hcj.review;
 
public class ForLoops {
   
public static void propsDump(final Set customKeys) {
        Properties props = System.getProperties();
        Iterator iter = props.keySet()
                            
.iterator();
       
String key = null;
        System.out.println("All Properties:");
        while (iter.hasNext()) {
         
key = (String)iter.next();
          System.out.println(key + "=" + System.getProperty(key));
        }
       
System.out.println("Custom Properties:");
        iter = customKeys.iterator();
        while (iter.hasNext()) {
         
System.out.println(key + "=" + System.getProperty(key));
        }
      }
    }
  }

If you didnít see the bug in this piece of code instantly, then you are in trouble. The problem is that this code generates a logic error. In the second iteration, key = (String)iter.next( ) wasnít called. However, since key is still in scope from the previous loop, the code compiles and runs. Trivial errors such as this can consume tons of hours in complex applications.

It would be great if you could scope the key variable and the iter variable to the for loop where they are used. You can do this and make your program more elegant with the following code:

  package oreilly.hcj.review;
 
public class ForLoops {
   
public static void forShort(){
      Properties props = System.getProperties();
      for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
       
String key = (String)iter.next(); 
        System.out.println(key + "=" + System.getProperty(key));
      }
    }
  }

In this example, the ability of for was leveraged to isolate your iteration variable. In this example, key is defined only within the for    loop, and any attempt to access it outside the for loop will generate a compiler error. Additionally, the iterator itself is scoped to the for loop, which guards against a user that forgets to set up his iterator. Finally, the increment portion of the for loop has no value at all, which is completely legal.

When looking at forShort(), you may be inclined to object that key is being allocated in a loop and that loop allocation is bad. In fact, in this example, the compiler notices that as well and optimizes out the variable to be allocated once while keeping it scoped to the for loop.

Abrupt Flow Control

Two of the more poorly understood pieces of Java syntax are the break and continue keywords. Both are used to control flow within loops or other complex statements. They can be very useful in some situations, but you need to be aware of their limitations.

break

The break keyword is probably familiar to most Java programers who have a flair for using switch statements. An example of a common usage is shown here:

  package oreilly.hcj.review;
 
public class SyntaxIssues {
      
public static String decode(final int input) {
       
String decoded = null;
       
switch (input) {
         
case 1:
           
decoded = "Option 1";
           
break;
         
case 2:
         
case 3:
           
decoded = "Option 2";
           
break;
         
default:
           
return "Option 3";
       
}
       
return decoded;
      }
    }
  }

The break keyword tells the virtual machine to exit the switch statement. In this switch statement, if the user inputs a 1, the result will be "Option 1". If the user inputs a 2 or a 3, the result will be "Option 2". Finally, if she inputs anything else, the result will be "Option 4". The break statement lets certain cases, such as 2, fall through, but breaks out when it is done with the relevant logic. Without the break, you would always get "Option 4" as the result of the method because all lines inside the switch statement would run.

The break statement is a great way to make decisions such as those in the previous example. However, every now and then you get silly people that do something like the following:

  package oreilly.hcj.review;
 
public class SyntaxIssues {
     
public static String decode(final int input) {
        String decoded = null;
        switch (input) {
         
case 1:
            decoded = "Option 1";
            break;
         
case 2:
         
case 3:
            decoded = "Option 2";
            break;
         
default:
            return "Option 3";
           
break; // <= someone doesn't get it!
        
}
        return decoded;
      }
    }
  }

In this code, the final break statement is completely unnecessary, and also unreachable. The code will exit the switch statement regardless of whether the break was there. If you find it hard to believe people actually write code like this, the templates to generate switch statements that come with Eclipse do exactly this. However, this is a rather minor, if somewhat silly, problem. Some problems with break are a lot more serious. Consider the following code:

  package oreilly.hcj.review;
 
public class SyntaxIssues {
      public static void matrixMeth(final Point[][] values) {
        for (int x = 0; x < values[0].length; x++) {
          for (int y = 0; y < values.length; y++) {
            if ((values[x][y].x < 0)
               || (values[x][y].y < 0)) {
              
break; // exit to the System.err line.
            }
            // do something with the value
          }
        }
        System.err.println("Invalid Point in Matrix");
        // cleanup processing resources
      }
    }
  }

In this piece of code, the developer wants the nested for loops to exit if a bad Point is detected in the matrix. However, the break statement doesnít do this. It merely breaks out of its current loop. The outer loop still runs, and the method processes bad data with potentially disastrous results.

When you use break in your code, you should be aware of these limitations and plan accordingly. The break keyword can be extremely useful for quick and abrupt termination of complex loops but its limitations can bite you if you arenít careful.

continue

The continue keyword is similar to break in that it abruptly changes the flow control of a method. However, where as break exits a loop completely, continue merely skips back to the loop clause itself:

  package oreilly.hcj.review;
 
public class SyntaxIssues {
   
public static void continueFunc() {
     
for (int idx = 0; idx < 1000; idx++) {
       
// ...do some complex code.
       
if (idx == 555) {
         
break;
        }
       
// ...processing code
      }
     
for (int idx = 0; idx < 1000; idx++) {
       
// ...do some complex code.
       
if (idx == 555) {
         
continue;
        }
       
// ...processing code.
      }
    }
  }

In the first loop, the processing code is executed only 554 times. When the value of idx is 555, the break statement is hit and the loop exits. However, in the second loop the processing code is executed 999 times. In this case, when idx is 555, the continue statement is hit, and the remainder of the logic inside the for loop is skipped. Subsequently, the loop then continues on normally with 556; therefore, the processing code is skipped only for element 555.

Although this example is trivial, the use of the continue statement can be a significant asset to your development when the code inside the loop is very complex. With many such possible ďskipĒ conditions, your code can become deeply nested. The continue statement simplifies things dramatically. Without the continue statement, you would have to enclose the entire remainder of the for loop inside an if statement.


The continue statement has the same semantics as the break statement in that it applies only to the loop in which the continue is enclosed.

Next: Labels >>

blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials