Java
  Home arrow Java arrow Page 4 - Java in Review
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Java in Review
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 5
    2005-06-16

    Table of Contents:
  • Java in Review
  • Syntax Issues
  • Collection iteration with for
  • Labels
  • Assertions versus exceptions
  • Assertions and deployment
  • Initialization
  • Access Issues
  • Common Mistakes

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

    More Java Articles
    More By O'Reilly Media


     

    Buy this book now. This article was excerpted from chapter one of Hardcore Java, edited by Robert Simmons Jr. (O'Reilly, 2004; ISBN: 0596005687). Check it out at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - 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 ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT