Home arrow Java arrow Page 4 - 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 - Labels
(Page 4 of 9 )

Labels are one of those obscure pieces of Java syntax that you see only once in a blue moon. They are a way to mark a statement with an identifier to be used by a break or continue statement.

The following code declares labels on two different lines in a program:

  LOGLINE: System.err.println("Invalid Point in Matrix"); 
  LINE:
for (int x = 0; x < values[0].length; x++) { ... }

The label is declared by simply prefacing the line with a legal variable name and then a colon. As usual with Java, any leading whitespace on the line will be ignored. However, keep in mind that you cannot declare a label unless it is the first statement on a line. The compiler would spit out all sorts of parsing errors if you tried something like the following:

  System.err.println("Invalid Point in Matrix");  LOGLINE2:

Once you have declared the label, you can use it in a break or a continue statement. The following code shows how you can use break to repair a faulty matrix:

  package oreilly.hcj.review;
 
public class SyntaxIssues {
    public static void matrixMeth2(final Point[][] values) {
      RESTART: {
        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)) {
              values[x][y].x = Math.max(values[x][y].x, 0);
              values[x][y].y = Math.max(values[x][y].y, 0);
              break RESTART; // Try to process again!
           
}
           
// do something with the value
          }
        }
      }
      // continue processing
   
}
  }

In this version, if an error condition is detected, the method will try to repair the error condition and then start to process the matrix all over again. This is accomplished by the break RESTART; statement. This statement tells the virtual machine to immediately transfer control to the statement labeled RESTART. This will work only if the break statement is nested inside the labeled statement. Otherwise, the compiler will just laugh at you sardonically and tell you that the label RESTART isnít declared.

Using labels with continue is slightly different. continue must be nested within the code block of any label to which it refers. Additionally, a continue can transfer control only to a label set on a looping construct such as a for, while, or do statement. For clarification on this rule, look at the following code:

  package oreilly.hcj.review;
 
public class SyntaxIssues {
    public static void matrixMeth3(final Point[][] values){
      {LINE: {
        for (int x = 0; x < values[0].length; x++) {
          COLUMN:for (int y = 0; y < values.length; y++) {
            if ((values[x][y].x < 0) || (values[x][y].y < 0)) {
              continue LINE; // skip the rest of the line;
            }
           
// do something with the value
          }
       
}
      }
      LOGLINE: System.err.println("Invalid Point in Matrix");
     
// continue processing
     
PASS_TWO:for (int x = 0; x < values[0].length; x++) {
      // do some code.
      }
    }
  }

In this example, instead of exiting to the log line, the programmer wants to simply skip the rest of the problematic line in the matrix. Using a continue statement without a label would have merely transferred control to the inner for loop. However, by telling the continue statement to continue at the LINE label, you can exit the inner for loop and skip the rest of the line properly. However, you could not use LOGLINE as a continue target because the statement after the label isnít a loop construct, such as a for, while, or do statement. You also couldnít use PASS_TWO as a target for the continue statement because although the label marks a looping statement, the continue statement is not nested in that looping statement. Furthermore, it would be impossible to break or continue to a label outside of the method.

Although labels can be useful in controlling the flow in a program, they can lead to a lot of confusion in development due to their idiosyncrasies. I recommend that you not use them as a rule; however, you should now be able to unwind the spaghetti code of another developer that did use them.

assert

The assert keyword is a new addition to Java that was introduced in JDK 1.4. It was a long overdue addition to the language, as it provides for error checking that C++ and other languages already have. However, since its introduction, I havenít seen it used nearly as much as it should be. The reason for this is a basic lack of understanding as to how assert works. The assert keyword has two forms. The first form of assertion uses the following grammar:

  assert Boolean_Expression;

In this form, Expression is replaced by an expression that evaluates to a boolean result. If the result is false, then an AssertionError will be thrown by the compiler:

  package oreilly.hcj.review;
 
public class Assertions {
    protected static void helperParseArgs (final String[] args) {
     
assert (args != null);
     
// ...code
    }
  }

In this example, the programmer wants to make sure that the user of the helperParseArgs( ) method didnít send a null for the arguments parameter. To accomplish this, he uses the assert keyword. If the user passes a null, then the virtual machine will throw an AssertionError with no description, but with a stack trace to help the errant user figure out what he did wrong. If the developer of the method wants to provide an error message, he could have used the second form of assert:

  package oreilly.hcj.review;
 
public class Assertions {
    protected static void helperParseArgs (final String[] args) {
     
assert (args != null) : "args cannot be null.";
     
// ...code
    }
  }

In this case, if the assertion is thrown, the second expression is evaluated and the result of that evaluation is used for the detail message of the AssertionError. Keep in mind that you can use any expression that evaluates to anything other than void as the second expression. For example, the following would be illegal:

  package oreilly.hcj.review;
 
public class Assertions {
    protected static void helperParseArgs (final String[] args) {
     
assert (args != null) : String s = "args cannot be null.";
     
// ...code
    }
  }

An attempt to do something like this would be rejected by the compiler since the evaluation of the expression is void. Similarly, any method that returns void is off limits as well.


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