Archive for September, 2013


Exception Handling…

Let us have some illustrations to get hold of  Exception Handling..

Exceptions Methods:

Following is the list of important medthods available in the Throwable class.

SN Methods with Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{

   public static void main(String args[]){
      try{
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}

This would produce following result:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Example:

Here is code segment showing how to use multiple try/catch statements.

try
{
   file = new FileInputStream(fileName);
   x = (byte) file.read();
}catch(IOException i)
{
   i.printStackTrace();
   return -1;
}catch(FileNotFoundException f) //Not valid!
{
   f.printStackTrace();
   return -1;
}

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throwkeyword. Try to understand the different in throws and throw keywords.

The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}

Amethod can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:

import java.io.*;
public class className
{
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
       // Method implementation
   }
   //Remainder of class definition
}

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   //The finally block always executes.
}

Example:

public class ExcepTest{

   public static void main(String args[]){
      int a[] = new int[2];
      try{
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      finally{
         a[0] = 6;
         System.out.println("First element value: " +a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

This would produce following result:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note the followings:

  • A catch clause cannot exist without a try statement.
  • It is not compulsory to have finally clauses when ever a try/catch block is present.
  • The try block cannot be present without either catch clause or finally clause.
  • Any code cannot be present in between the try, catch, finally blocks.

Declaring you own Exception:

You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:

class MyException extends Exception{
}

You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example:

// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception
{
   private double amount;
   public InsufficientFundsException(double amount)
   {
      this.amount = amount;
   } 
   public double getAmount()
   {
      return amount;
   }
}

To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount
{
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
   public void deposit(double amount)
   {
      balance += amount;
   }
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
   public double getBalance()
   {
      return balance;
   }
   public int getNumber()
   {
      return number;
   }
}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.

// File Name BankDemo.java
public class BankDemo
{
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      try
      {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println("Sorry, but you are short $"
                                  + e.getAmount());
         e.printStackTrace();
      }
    }
}

Compile all the above three files and run BankDemo, this would produce following result:

Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
        at CheckingAccount.withdraw(CheckingAccount.java:25)
        at BankDemo.main(BankDemo.java:13)

Common Exceptions:

In java it is possible to define two catergories of Exceptions and Errors.

  • JVM Exceptions: – These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,
  • Programmatic exceptions . These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException.

Exceptions JAVA…

You  must have seen somewhere.when we run a program in an IDE if the coding is not proper or there is some other sort of mistake e.g. accessing a file that does not exist etc. then the console shows up with highlighted exception errors.

Lets talk about those..

 Exceptions

Java Exceptions

In the first two sections in this lesson, you worked with errors: compile-time errors which are violations of Java’s strict grammar, and runtime errors which are often caused by meaning one thing, but saying quite another. Such logical or semantic errors must be carefully and systematically expunged from your code.

However, runtime “errors” are not always the result of logical errors. Sometimes, runtime errors are caused by unusual–you could almost say exceptional–situations.

For instance, most of the time, when you read and write to a file, everything goes along normally. Sometimes, however, “bad things” happen; the disk may be full, for instance, or the file you want to write to may be a read-only file.

These kinds of situations are not mistakes that you’ve made in your code; instead they are unusual occurrences that you must allow for. If you just assume that everything will always go normally, your program is not very robust. Exceptional situations are often confused with error conditions, but they are a tiny bit different.

The Traditional Method

The traditional way of dealing with this kind of situation is through the use of completion codes. Every time you perform an operation that may fail, you must first check to be sure that the operation succeeded before you continue. If the operation fails, you have to decide whether to handle the failure at that point or to pass it back to the method that invoked the operation.

Here’s some psuedocode that shows the traditional method of dealing with exceptional situations. Consider the steps you need to follow to open a file, read some data, process the data, write the changed data back to the file, and finally, close the file:

Open, Read, Write, Close
GET A FILENAME 
OPEN THE FILE 
IF NO ERROR OPENING THE FILE 
   READ SOME DATA 
   IF NO ERROR READING THE DATA 
      PROCESS THE DATA 
      WRITE THE DATA
      IF NO ERROR WRITING THE DATA 
         CLOSE THE FILE 
         IF NO ERROR CLOSING FILE 
            RETURN OK
         ELSE
            RETURN CLOSE_ERROR
         ENDIF
      ELSE
         RETURN WRITE_ERROR
      ENDIF
   ELSE
      RETURN READ_ERROR
   ENDIF
ELSE
   RETURN FILE_OPEN_ERROR
ENDIF

There are three things to notice about this code:

  • Most of these operations, except for “PROCESS THE DATA” can fail, and so the program has to be prepared.
  • It is very difficult to determine the normal course of action. The program is so taken up with what can go wrong, that it’s hard to be certain you are doing the right things in the right order.
  • It is very difficult to write a library that depends upon code like this, because every function in the library has to return several different error codes.
The Exceptional Method

Using an exception mechanism, the same pseudocode looks like this:

Open, Read, Write, Close
TRY TO DO THESE THINGS:
   GET A FILENAME 
   OPEN THE FILE 
   READ SOME DATA 
   PROCESS THE DATA 
   WRITE THE DATA
   CLOSE THE FILE
   RETURN
IF ERROR OPENING FILE THEN ...
IF ERROR READING FILE THEN ...
IF ERROR WRITING FILE THEN ...
IF ERROR CLOSING FILE THEN ...

Compare this code to the previous code, and you’ll immediately see that the code that uses an exception strategy:

  • is shorter and easier to read.
  • makes the normal logic–what you are actually trying to do with the method–its focus. In the traditional method, the error-handling often obscures the normal logic.
  • allows you to handle an error or pass it back to the caller. Using exceptions, the caller is not forced to manually pass errors back up the “chain” of command. This is done automatically making it very easy to implement a centralized error-handling strategy.

Exception and Error Objects

In Java, when an exceptional situation occurs–if you try to write to a file that cannot be written to, if you try to write past the end of an array, or if you try to divide by zero, even though your mother warned you not to–Java will create one of two types of Throwable objects: an Error object or an Exception object.

It will then take that Throwable object and throw it right back up the call stack where the method was called from. Any method, anywhere along the way, can decide to deal with thatThrowable object, by catching it. [click the image to enlarge it]

Image shows exceptions passed up the call stack

Types of Exceptions

This illustration shows a small portion of Java’s exception hierarchy. [Click the image to enlarge it] As you can see, and as was previous mentioned, Throwable has two subclasses,Exception and Error.

Image shows a small section of Java's Exception hierarchy

Error Objects

An Error is an unusual situation, like the other exceptions, but it is the kind of situation that has no easy solution. If, for instance, the JVM throws an InternalError, there is nothing you can put in your code that will cure it.

Because of Java’s reliance on automatic memory management and garbage collection, an OutOfMemoryError is likewise fatal. And, even if you could catch the wileyUnknownError, what would you do with it after you’d caught it?  When your program throws an Error object, it’s about to give up the ghost, and there’s nothing you can do about it.

Checked and Unchecked Exceptions

If you can’t do anything about the Error side of the Throwable family, how about the Exception side? The Exception class represents unusual situations that you may want to handle in your own code. Like Throwable, the Exception class is also subdivided into two branches–commonly called the checked and the unchecked exceptions.

The RuntimeException Class

Unchecked exceptions are those thrown by the Java runtime system, and are descended the RuntimeException class. These kinds of exceptional situations–accessing an element past the end of an array, for instance, or dividing by zero–represent unusual situations that you would normally prevent by careful programming.

These are called unchecked exceptions because you are not required to specifically handle these exceptions in your code if they occur. Most of the time, in fact, you will not handle them at all. Some times, however, handling one of these unchecked exceptions provides an easy way to accomplish a difficult task. Here’s an example. Type a number in theTextField shown here, and press ENTER. Now try typing a word, like “one.” What happens now?

The NumberFormatException class provides an easy way to recover when converting between Strings and ints using Integer.parseInt(). Writing the logic necessary to determine if a String contains a well-formed number is more work than manually converting the String to an int.

Instead of going to all that work, you can simply create a try block, [which you’ll learn to do in the next lesson], and catch NumberFormatException when someone types in “one hundred” instead of “100”.

Other Exceptions

To use the other exceptions you have to do two things. First, you have to put the code that may cause an exceptional situation into a “try” block. Then, you provide one or more “catch” blocks immediately following the “try” block.

If a method throws one of these checked exceptions–an exception not derived from the RuntimeException class–you must handle the exception, you can’t simply ignore it like you can with the unchecked exceptions.

Using try-catch-finally

In the last section, you learned about the different kinds of Throwable objects that are generated when an exception occurs. In this section, you’ll learn to trap those Throwableobjects and put them to work. You’ll learn:

  • How to use try-catch to respond to specific errors.
  • How to use the throws clause when you want to allow the Java runtime system to handle an exception for you.
  • How to use try-catch-finally to make sure that necessary portions of your program are executed whether or not an exception occurs.

Using try-catch

If you are a long-time programmer, Java’s try-catch mechanism, shown here, looks kind of strange the first time you see it.

Most programming structures–loops, selection statements, method definitions–have the same basic “shape” in every programming language, even though the details might differ.

Image illustrates the syntax of the try-catch block

That’s not true with try-catch, which seems to combine elements of loops and methods together in a package that just doesn’t “look right.” Once you understand how try-catchworks, though, the strangeness goes away, and it starts to look a little bit more natural.

The try Block

The first portion of a try-catch statement is the try block. This is the easiest part to understand. A try block consists of the keyword try followed by a brace-delimited block. The braces are part of the try-catch syntax, and are required. This is different than a loop body or the body of an if statement, where the braces are optional.

Inside the braces you can put any number of statements that may throw an exception.

A try Block
int a = 3, b = 0;
int n = 0, x = 0;
try
{
  n = System.in.read();
  Thread.sleep(100);
  x = a / b;
}

If you use a method that throws a checked exception–that is, an exception that is not a subclass of the RuntimeException class–then you must put the statement inside a tryblock. Common methods that throw checked exceptions include the System.in.read() method, [which throws IOException], the Thread.sleep() method, and the MediaTrackerwaitFor() methods which you’ll encounter when we start using Image objects.

The statements inside the try block are not restricted to those that may throw checked exceptions; you can place any statements you like inside the try block. If you call a method or perform an operation that generates an unchecked exception–say a NullPointerException or a NumberFormatException–then you can handle the exception by adding an appropriate catch block, which you’ll meet shortly.

You are not required to provide a catch block for the unchecked exceptions which may be generated inside your try block, but you are required to provide a catch block for eachchecked exception that might be thrown.

The catch Blocks

Immediately following your try block you must supply one or more catch blocks. The syntax for the catch blocks looks like this:

catch (<Exception1-Class> <var1>)
{
  // Handle exception1 here
}
catch (<Exception2-Class> <var2>)
{
  // Handle exception 2 here
}

This is the part that gets a little tricky. Each catch block starts with the keyword catch, which is followed by parentheses. Inside the parentheses you declare an exception variablewhich is used to hold the exception object if that particular exception is thrown inside the try block.

You must provide a name for each exception object, and, although this looks like a method header, the scoping rules are somewhat different. Each exception variable used in one try-catch situation must have a unique name.

Following the exception variable declaration is a brace-delimited block where you add the actions you want to take when that particular exception is thrown. As with the try block, the braces around the catch block body are required. [Early versions of javac did not enforce this restriction, so you may still see some code that has no braces surrounding the body of the catch block].

You must provide a catch block for every checked exception that may be thrown inside your try block. Let’s continue the example we started earlier. Because you know thatSystem.in.read() throws an IOException, and that IOException is a checked exception, you can add a catch block like this:

A catch Block
int a = 3, b = 0;
int n = 0, x = 0;
try
{
  n = System.in.read();
  Thread.sleep(100);
  x = a / b;
}
catch (IOException ioe)
{
  System.out.println("No read()");
}

To compile this, you must import the java.io package, where IOException is defined. Once you do that, you can recompile. When you do, here’s what you’ll see:

C:\JavaOnline\unit7>javac TryCatch.java
TryCatch.java:15: Exception java.lang.InterruptedException must be caught, 
or it must be declared in the throws clause of this method.
      Thread.sleep(100);
                  ^
1 error

As you can see, the Thread.sleep() method throws an InterruptedException. This is a checked exception, so you must catch it as well. Let’s add a catch block forInterruptedException and see what happens.

A Second catch Block
int a = 3, b = 0;
int n = 0, x = 0;
try
{
  n = System.in.read();
  Thread.sleep(100);
  x = a / b;
}
catch (IOException ioe)
{
  System.out.println("No read()");
}
catch (InterruptedException ie)
{
  System.out.println("No sleep()");
}

Because InterruptedException is part of the automatically-included java.lang package, you don’t have to add any new import statements. You must make sure that your new exception variable has a different name than the first, however, or Java will complain that a variable with that name already exists. The new variable is named ie instead of ioe like the first.

Unchecked Exceptions

Once you do that, the program compiles without error. If you put this code into a console-mode application and run it, however, this is what you’ll see:

Console display when running TryCatch.java

As you can see, an ArtithmeticException is being thrown because we are dividing by zero. ArithmeticException is a sublcass of RuntimeException, so it is unchecked. The Java compiler does not require you to catch it, nor do you have to place the code that causes the exception inside a try block. If you move the line

x = a / b;

outside of the try-catch, the program runs just the same.

Although you don’t have to use try-catch with unchecked exceptions, you certainly can. If you add a catch block for ArithmeticException to your program, you can catch and handle the divide-by-zero exception in your own code. Generally, you don’t want to do this, because runtime exceptions usually indicate a programming error that should be fixed. For certain tasks, however, such as checking to see if a String is properly formatted as a number by using NumberFormatException, catching an unchecked exception is the smart way to go.

Exception Matching

Because the various exception classes are arranged in a hierarchy, it is possible to catch several exceptions using a single catch block. If, for instance, you add a catch block forException, the superclass for all exceptions, then your catch block will intercept every exception that can be generated. [This is not a good idea, by the way.]

Image shows how different exception types can be caught. Click to enlarge.

You can use this hierarchy of exceptions to handle certain exceptions and to defer handling others.

When an exception occurs, the catch blocks are searched in order, looking for a match. That means, you should place your most specific catch blocks first, and the more general ones later.

If you place your general [superclass] catch blocks first, then the more specific [subclass] catch blocks will never be searched.

An Alternative to try-catch

One of the beauties of Java’s exception mechanism is its flexibility. If you decide that you don’t want to handle a particular exception, then you don’t have to: you can pass it, like a hot-potato, back to the Java runtime system, and let Java handle it. Here’s how that works.

Suppose you want to write a method for a console-mode application that reads integers from the keyboard. You want the method to return an int if it succeeds, but, if the user types in “cat” or “100”, you don’t want to be bothered correcting them. You’re happy to let Java do that.

Image shows the use of throws Exception with a method that may throw several types of exceptions

As you can see from the illustration [click to enlarge], there are two possible things that can go wrong inside your method. The System.in.read() method, used to read from the keyboard, can throw an IOException. Also, the Integer.parseInt() method can throw a NumberFormatException.

Correcting Figure 8-14
This is taken from Figure 8-14 in your book which has two errors. The method readInt() should return an int, not a String, and the Integer.parseInt() method throws a NumberFormatException, not the non-existent NumericFormatException.

Because NumberFormatException is an unchecked exception, you don’t have to do anything to pass it on to the Java runtime. IOException is a different matter. If you try to useSystem.in.read() in your code without placing the statement inside a trycatch block, then Java will not compile your code.

You don’t have to use trycatch for IOException, however. Instead, you can defer to the caller of your method by adding “throws IOException” to the method definition. This means that any method which calls readInt() must place the call in a trycatch block, or throw the exception as well.

If you wanted to add a Thread.sleep() to the readInt() method, you would have to add the InterruptedException to your throws clause as well, like this:

public int readInt() 
     throws IOException, InterruptedException
{
  // Code here
}

If you don’t want to be bothered with handling any exceptions at all, however, you can simply use throws Exception, and be done with it.

Exception Strategies

When should you use trycatch and when should you rely on the throws clause? Here are some simple guidelines that might help you:

  • If you know how to handle a situation, use trycatch.
  • If you don’t know how to handle an error, or, if you think there may be situations where users of your code will want to handle an error differently, then use throws.

In any event, you should make sure you use exceptions for exceptional situations only. Don’t let exception handling make up for sloppy programming. You should never, for instance, rely on exception handling to tell you when you have exceeded the bounds of an array.

The finally Clause

As you’ve just seen, when an exception is thrown in a try block, program control jumps to the catch block that handles that particular exception.

Sometimes, however, this can lead to problems because code necessary for managing resources may be skipped. For instance, every time you open a file, you should close the file. Files are an operating system resource that must be manually returned to the O/S by closing the file. But, where should you put the code to close the file? Here’s an example:

A Problem with try-catch
try
{
  openFile();
  readData();  // Exception thrown
  closeFile(); // This is skipped
}
catch (IOException ioe)
{
  // closeFile() not executed if no exception
}// closeFile() possibly executed

As you can see, there are three possible places where the call to closeFile() can go:

  1. In the try block, following readData()
  2. In the catch block
  3. After the try-catch block

Each of these locations has a problem.

  • If you put the code in the try block, then it will not be executed if an exception is thrown in the readData() method.
  • If you put the code only in the catch block, it won’t be called unless an error occurs.
  • If you put the code after the try-catch block, and the catch block terminates the program, you’ll have failed to close the file as well.

The first alternative is to put the code in multiple places; a better solution is to place the code, once, in a finally block.  To fix this problem, try-catch has an optional finally clause, which will always be called.

You can use the finally clause to guard against resource depletion of items like file handles and graphic context handles [which you’ll meet in upcoming units].

Image shows the syntax of the finally block.

Errors Continued…

After Syntax errors its time to get hold on another category of errors, the RunTime Errors.we’ll have a look at some other error categories too.

Runtime Errors

That “stern and pedantic taskmaster,” the Java compiler, always tells you when you’ve made a mistake, even if you don’t understand its error messages. Unfortunately, the Java compiler is unable to catch all of your errors  because it cannot, among other things, read your mind.

Runtime errors are the errors that occur when you try to run your program. Runtime errors really come in three varieties:

  • For some errors, the Java Virtual Machine will step in and tell you that you’ve done something wrong. Like syntax errors, such “program crashes” are often annoying, but ultimately for the best.
  • For other errors, the JVM is unable to print an error message, but your program just quits working altogether. With such hanging programs, it’s obvious that something is wrong, but, other than the symptoms, you receive no other help in solving the problem.
  • The last group of errors, the really difficult errors, occur silently and without warning. These logical errors are those that cause your program to behave incorrectly, but, unless you’re on the lookout, you might not even notice that anything is wrong.

Runtime Exceptions

Runtime exceptions are nice for two reasons.

  • First, when a runtime exception occurs, the Java Virtual Machine [JVM] notices that something is wrong, and it makes an effort to notify you.
  • Second, Java’s exception-handling mechanism allows you to intercept and handle runtime exceptions. You’ll learn more about the exception mechanism and how to put it to work in the next two sections in this lesson.

Let’s see what a runtime exception looks like.

Here’s the applet, RuntimeError, from Chapter 7 in the textbook. Before you jump on ahead, and start pressing it’s buttons, take a moment to open your browser’s Java Console window, or use the Appletviewer to run the program. If you use Appletviewer, the error messages will show up in the Command Window that starts the Appletviewer program.

This applet, RuntimeError.java allows the user to trigger three types of runtime errors by pressing an appropriate button [as discussed in the lesson].

NullPointerException

Once your Java console is open, go ahead an press the “Nobody’s Home” button. You’ll see something that looks like this:

NullPointerException stack trace displayed in the Java ConsoleAs you can see from the JVM’s error message, the error is a NullPointerException and the problem occurs in RuntimeError‘s tryNull() method, at line 49.

Here is the code for the tryNull() method:

RuntimeError.tryNull()
void tryNull()
{
  b.setLabel("Uh Oh!");
}

Looking at this code, it’s not immediately obvious what the problem is. We could trace back through the code to the actionPerformed() method that called tryNull(), but that still won’t lead us to the problem.

Instead, you have to understand what NullPointerException means. A NullPointerException is Java’s way of saying: “This object variable doesn’t refer to a real object.” You can’t send a setLabel() message to a Button object that doesn’t exist, and so the JVM simply steps in and prints an error message.

Remember, anytime you see a NullPointerException, it really means “Unititialized Object.” Looking back through the code to where the Button variable b is defined you’ll find:

Button b; // This has the value null

ArithmeticException

When you press the “Problems with Math” button, your Java Console window will look something like this:

ArithmeticException displayed in the Java ConsoleJava’s VM throws an ArtithmeticException whenever you ask it to perform an illegal artithmetic operation. As you can see from the message, the error occurred in the divideZero() method. If you pull up the method, which is shown here, you can see that, sure enough, the program attempts the impossible:

RuntimeError.divideZero()
void divideZero()
{
  int numerator = 3;
  int denominator = 0;
  int problem = numerator / denominator;
}

Unlike NullPointerException, the ArtithmeticException is usually not a puzzle when it occurs. The solution, too, is usually stratightforward: “don’t do that”. With careful programming you should be able to eliminate this exception.

NumberFormatException

The third runtime error exposed by the RuntimeError applet is a little different than the other two. Java generates a NullPointerException in an attempt to protect the integrity of the JVM, and it throws an ArtithmeticException to protect the integrity of the mathematical universe as we know it.

The last runtime error generated by this applet falls into neither of these categories. If you press the “How Much is a Cat” button, Java generates a message that says, essentially, “I don’t know how to do that:”

NumberFormatException displayed in the Java ConsoleFollowing the line numbers, you can see that the error occurs in the Integer.parseInt() method–a method in the standard Java class library. Both of the previous runtime errors were intrinsic runtime errors–errors generated directly by the JVM. This is not.

If you trace back from where the original error occurred, you find that the method convertCat() was the last time that RuntimeError.java had hold of the code. Let’s take a look:

RuntimeError.convertCat()
void convertCat()
{
   String num = "Cat";
   int bad = Integer.parseInt( num );
}

As you can see, the error is caused by asking the Integer class to convert the String “Cat” into an int. This is not an impossible task–at least not impossible in the same sense that dividing by zero is impossible.

It is also harder to protect against. As you found out in Homework 2, “CalcIt”, when you get input from your users, they can type, essentially, anything into a TextField. When you convert the text contained into that TextField to a number, it is almost impossible to first check the contents of the TextField to be sure that the conversion will succeed.

For that reason, Java provides a way to recover from this sort of runtime error–the trycatch mechanism. You’ll learn how to apply trycatch later in this unit.

Hanging Programs

Programs that stop responding are called hanging programs. It’s obvious, when you run such a program, that something is wrong. Discovering what the problem is, and fixing it, however, is sometimes a little more difficult. Knowing about the most common reasons for hanging programs helps.

Hanging programs usually stop responding for one of two reasons:

  1. You’ve written an “endless” or “dead” loop.
  2. You have a “system” error.

Endless Loops

Endless loops are the most common reason for your program to hang. To avoid endless loops in your program, double check for the unavoidable condition that you met in Lessons 5 and 6.

Remember that an unavoidable condition is one where the loop is always entered and is impossible to exit. An unavoidable condition almost always involves confusing the AND andOR operators in a compound boolean condition like this program which, supposedly, collects pension payments from employees between 21 and 65, and, then, at age 65, disburses the payments:

int age = getAge();
while (age >= 21 || age < 65)
{
  makePensionContribution();
  age++;
}
getPensionPayout();

What actually happens is that, because the programmer used OR instead of AND, the program collects pension contributions forever, but never pays out a dime. There is one other situation where an endless or semi-endless loop is common in Java programs–wayward animation attempts.

Wayward Animation

Often, programmers will attempt to create an animation loop inside the paint() method like this:

An Unsuccessful Animation Attempt
public void paint(Graphics g)
{
  int x = getSize().width / 2;
  int y = getSize().height / 2;
  int dx = 5, dy = 5;  while (true)
  {
    x += dx;
    y += dy;     if (x > getSize().width || x < 0)
      dx = -dx;
    if (y > getSize().height || y < 0)
      dy = -dy;    g.drawString("@", x, y);
  }
}

This loop attempts to move a bouncing @ around the screen. The problem is that, under normal operations, the paint() method never actually display its ouput on the screen. This “display updating” occurs “behind the scenes” after the paint() method is finished.  By coding an endless loop inside the paint() method, your program never gives Java’s background tasks a chance to run. If you create an applet using this code, and then run it in appletviewer, you’ll see that you won’t even be able to close the appletviewer window by clicking on the close button. Java doesn’t have any time to pay attention to the close button because you’re hogging all of its attention.

System Errors

In addition to hanging because of an endless loop, your program might also hang because of a “system error.” This catchall phrase covers a lot of ground. Most of the time, the system error really doesn’t have anything to do with your program at all, and there’s nothing you can do about it. Sometimes, though, you can change something in your program that will prevent the system error from occurring.

Most system errors, at least those where the system hangs, occur for one of two reasons:

  1. A necessary computer resource is depleted.
  2. Multiple programs have deadlocked waiting for access to the same resource.

An example of a system resource is the Graphics class. If you confine your use of the Graphics class to the Graphics object you receive in the paint() method, you won’t have any problems. If, however, you use the Component getGraphics() method to draw outside of the paint() method, without calling the dispose() method after your are finished, you may exhaust your operating system’s supply of graphic device contexts. When this happens, your Java program becomes unable to repaint itself. It doesn’t hang, exactly, but for all intents and purposes, it’s dead.

Other resources that are often similarly limited and that can result in similar resource depletion include Color objects, threads, streams, and network connections. Deadlock occurs when two processes both attempt to acquire a resource used by the other. If you have an input and output file, for instance, one program may open the input file first, while the other opens the output file first. Both programs can get stuck and wait forever for the other program to give up the resource which it needs. Deadlock is common when it comes to writing multi-threaded programs

Regaining Control

When your program goes into an endless loop, or when you run out of memory or Graphics objects, what can you do? There’s no hard and fast answer, but you should start with the least drastic remedy before you resort to pulling the plug or pulling out the sledgehammer.

Here are some suggestions:

  • Try the “Stop,” “Exit,” or “Quit” button included in your applet or GUI application. Try to load a different page into your browser. Click the CLOSE icon in the upper left corner ofappletviewer or your GUI application’s window. Make the MS-DOS window you used to start appletviewer or the MS-DOS window of your application the current window by clicking on its title bar. Then type CTRL-C, by holding down the CTRL key and simultaneously pressing the c key. This should “cancel” or terminate the program. Exit your browser. Use CTRL-ALT-DELETE to cancel the task. Shut down your computer.
  • When all else fails, cycle power to your computer. This may result in serious loss of data, so it’s definitely a last resort.

Logical Errors

Logical errors are different than the other errors we’ve discussed up to this point. It’s not just that logical errors are harder to correct–and they are–it’s that it is incredibly difficult to discover that an error has occurred at all. In fact, an entire phase of the software development cycle–the testing phase–is devoted to discovering hidden, unrevealed errors.

The parts of a program specification

You’ll read more about testing your software in “Testing and Debugging.” Before you can even think about testing your software, however, you must have some idea of what it is supposed to do. The process of testing begins with a precise and unambiguous description of your program’s correct behavior. This description is called the program specification.

Errors…

Before moving on to next topic,we shall study the basic errors or the most commonly seen bugs in programs so that we can handle them easily rather try to avoid them.

Syntax Errors

Compile-Time Errors

One of Bill McCarty’s pet phrases which he repeats in the opening paragraphs of Chapter 7 of the recommended textbook for this course likens the Java compiler to a “…stern and pedantic taskmaster…” that “…tolerates absolutely no departure from the official rules of the Java language.” I really like the image that this conveys. I also like to think of the Java compiler as a particularly tough Marine Drill Sergeant.

The reason that I like both these images is that they both hint at the reason why the compiler is so strict. It is good to learn to speak and think and write well while you are young and in school; doing so opens up opportunities that aren’t available otherwise. It is much less costly for a soldier to learn on the training ground than to learn in the heat of battle.

That is why you want your compiler to be as picky as possible. Let me give you an example. The Basic language allows progammers to create variables by simply using them. This is called implicit declaration. If you use implicit declaration, your Basic compiler will not generate a syntax error when it encounters a new variable it hasn’t seen before. Your compiler is much friendlier.

This sounds great, but professional programmers almost always turn this feature off, if possible. Why? Because allowing implicitly declared variables in your program also allows misspelled variable names to slip through, and those errors don’t show up until your program runs.

Professional programmers quickly learn that it is better to catch every possible error in your program before you ship it off into battle, even if that requires a compiler that seems, well, a little “pedantic”.

In this lesson, we’re going to look at the kind of errors that the Java compiler is able to find. Such errors are called compile-time or, more generally, syntax errors. Such errors violate the very strict rules governing Java’s formal grammar.

Not all errors in your program can be found by the compiler. The most difficult and intractable problems are not errors in expression, but errors in logic. We’ll cover those kinds of errors in Lesson 7.2, “Run-time Errors.”

Error Messages

The following program, a variation of Listing 7-1 in your textbook, contains several syntax errors. Before you go any further, why don’t you just walk through the listing and see how many errors you can identify?

Error1.java
import java.Applet.*;
import java.awt.*;public class error1 extends Applet
{
  int num;
  num = 32;  public static void main(String args[])
  (
    int var;
    System.out.println("var = " + var);
    System.out.println("Now " + num);
    return true;
   )
}

When you compile this program with javac, [JDK 1.1.8, Sun Version], you get the five error messages which can be seen here. [click on the image to enlarge]. That doesn’t necessarily mean that the program has five errors, however. Often, a single error can cause “cascading errors” as one error leads to more errors, as subsequent lines are misinterpreted.

Error messages appearning in console window when compiling Error1.java

That occurs with the first two errors in this case. Because the name of the java.applet package was accidentally capitalized, the compiler is unable to find the Applet class. Thus, you get two error messages: the first message pointing out the misspelling, and the second message caused by the first.

If you use a different compiler, like javac from the Java2 SE version 1.3, you’ll see different errors, as shown here. This version of javac reports seven different messages.

Error messages after compiling with Java 2 compiler 1.3. [click to enlarge]

Remember, though, there aren’t necessarily seven errors; one mistake, such as a mistake on the import line, leads the compiler to treat other lines incorrectly.

Common Errors

Although there are a wide variety of error messages, compile-time errors really come in four basic categories:

  1. Structural errors
  2. “Real” syntax errors
  3. Typographical errors
  4. Type errors

Understanding these basic categories, and the different ways to correct them and avoid them, will go a long way toward helping you write code that compiles cleanly the first time. Of course, once you’ve done that, the real error correction begins.

Let’s take a look at these three categories.

Structural Errors

We think of the Java compiler as a machine that takes source code in one end and spits compiled byte-code out the other. The problem with this analogy is that it leads us to think of the compiler like a log chipper processing our source code in a purely sequential manner. In fact, that’s not what happens at all.

Before the Java compiler can even think about turning your source code into byte-code, it first must read your entire program, and then organize it. This organization phase is calledparsing or tokenizing your program.

When the compiler parses your code, it breaks the entire program up into individual pieces called tokens. This tokenizing phase is almost exclusively dependent upon the precisematching of pairs of delimiters–single quotes, double quotes, parentheses, and braces.

For instance, look at this program, which has more syntax errors than Error1.java:

  • ink and integer are used as primitive types, instead of int
  • The C++ pointer-to-member operator is used, despite the fact that Java does not have a similar operator.
  • The keywords public and static are both misspelled.
  • void function returns something called TRUE.
  • An assignment is performed outside of a method.
  • Parentheses are used as delimiters around both the class and method definitions.
  • String constants are not correctly delimited.
Error2.java [Structural Errors]
import java.applet.*;
import java.awt.*;public class Error2 extends Applet
(
  ink num;
  num = 32;  Public Static void main(String args[])
  (
    integer var;
    System->out.println("var =  + var);
    System->out.println("Now ' + num);
    return TRUE;
  )
)

Despite all of these problems, when you compile this program, with the JDK 1.1.8 javac compiler, this is what you’ll see:

Error messages displayed when compileing Error2.java

The result? Fewer errors than displayed for Error1.java.

During the parsing phase, the compiler attempts to organize the program by matching keywords such as class, along with delimiters. When you fail to get the essential organizationof your program correct, then the compiler really can’t go any further.

This program doesn’t really have only four errors; the remaining errors are hidden by the structural errors. Only after the entire program is organized, can it go through and make sure the right tokens are in the correct order.

Preventing structural errors is really much easier than correcting them afterwards. Here are three things you can do to prevent them from occurring in the first place:

    1. Understand what goes where. Don’t just copy code and place it at random in your Java programs. Know where each element belongs. Specifically, make sure you understand that:
      • import and package statements must appear at the beginning of your file.
      • Field definitions must appear inside a class defintion, but outside of a method definition.
      • Method definitions must be inside a class defintion.
      • Program statements, except for field definitions, must appear inside methods. Program statements must end with semicolons.
      • Formal arguments go inside the parentheses following a method name, and must include both a type and an argument name for each argument.
  1. Write structural elements in one piece. Beginning programmers often start at the beginning of a structural element–a class or method definition, or a selection or iteration statement–and work through to the bottom. Experienced programmers will put the structure in place first–write the header and add the opening and closing braces–before turning to the body of the class or method.
  2. Use a consistent and easily checked indenting style. Your indenting style should allow you to easily tell if all your braces are in the right place. Failing to indent and line up your braces makes your code almost impossible to check.

“Real” Syntax Errors

After the Java compiler has tokenized your code, a second phase of parsing takes place. This is lexical analysis–making sure that the correct kinds of elements [tokens] are in the correct places. Errors in the lexical analysis phase are “really” syntax errors.

Using two keywords in a row, for instance, results in a syntax error like this:

int double a;

Using a keyword when it is not necessary results in a syntax error. This is a common example:

int a = 10, int b = 20;

Omitting a required token results in a similar syntax error, like this:

public void myMethod(int a, b) { }

Using a token in an incorrect context [such as the keyword void] can also result in a syntax error like this:

public void class MyApplet extends Applet

There is no “magic bullet” for detecting and preventing this kind of syntax error. You simply have to learn to put the right keywords and tokens in the correct order.

Typographical Errors

Typographical errors are somewhat easier to deal with than structural errors because the Java compiler usually pinpoints them fairly accurately.

Here are the three most common typographical errors you’re likely to make:

  1. Missing semicolon. Let’s face it, semicolons are small, and hard to see. Even worse, the colon, which looks almost exactly like a semicolon, is on the same key and is the character you’re likely to insert when you mistype.
  2. Using assignment [=] instead of equality [==]. Fortunately, unlike C, Java will usually catch this error. Still, it’s annoying to have to go back and fix it.
  3. Using the wrong case. Java is a case sensitive language, and that case sensitivity extends to Java filenames, even on operating systems that are not, themselves case sensitive, like Windows and the Mac.

Type Errors

Remember that a variable is a “bucket” where you store values. When you ask the compiler to create a variable for you, you tell it what kind of values you intend to store in your bucket. This allows Java to prevent you from storing milk or soda in a cardboard box designed to hold dry cereal, so to speak.

Java’s type system is designed to keep you from losing information, not to make life difficult for you. Understanding these three simple rules should help you to go along with the program:

  1. You can store a little value in a big bucket, but not vice-versa. This means you can store byteshortint, and long values in a long variable, but you cannot store a longvalue in a byteshort, or int variable.
  2. You can store a less-precise value in a more-precise bucket, but not vice-versa. This means you can store byteshortintlong, and float values in a double variable, butyou cannot store double values in a byteshortintlong, or float variable; the bucket is incapable of retaining the necessary precision.
  3. You can only store like things in similar buckets. You can store different numeric values in different kinds of numeric variables, but you cannot store boolean values or object references in numeric variables.

Finding the Error

If your program has only a single compile-time error, and if the error is straightforward, finding and fixing it is usually no problem. The compiler’s error message will tell you the name of the file and the line where the error occurred. You just fire up your text editor, fix the problem, and recompile. Problem solved.

What do you do when you get 25 errors, or when the error message produced by Java’s compiler doesn’t seem to make any sense at all? When this occurs, you really need to have a strategy. Systematically attacking the problem will help you avoid frustration and will help you eliminate syntax errors in record time.

If you have a multitude of errors, often, you can’t even see the first one, because it scrolls off the screen as the rest of the errors are displayed. When this happens, you need to “divide and conquer” by “commenting out” sections of code.

Here’s how it works. The following applet generates five errors, but the strategy we’ll follow will help you regardless of the number of errors:

Error3
import java.applet.*;
import java.awt.*;public class Error3 extends Applet
{
  integer: first, second;
  double b, double c;
  goButton Button as new Button("Go");  public viod init(goButton)
  {
    add(goButton);
    new(10, "Bob");
  }

  public int new(int a, string b);
  {
    println("a = ", a, ", b = ", b);
  }
}

Compiling the code, this is what you see:

Errors displayed after compiling Error3.java

Step 1: Structure First

Begin by “commenting out” the entire body of your applet’s class. Do that by using the multi-line comment symbols [/**/] like this:

Error3 – Step 1
import java.applet.*;
import java.awt.*;public class Error3 extends Applet
{
/*
  integer: first, second;
  double b, double c;
  goButton Button as new Button("Go");  public viod init(goButton)
  {
    add(goButton);
    new(10, "Bob");
  }

  public int new(int a, string b);
  {
    println("a = ", a, ", b = ", b);
  }
*/
}

Now when you compile your program you won’t see any errors at all. If any errors did appear, you’d know that you had:

  • made an error in the basic structure of your class.
  • made an error in one of your import statements.
  • made an error in the class header.
Step 2: Reveal the Attributes

Once the basic structure of your applet compiles cleanly, move the opening comment character down to “expose” the applet’s attributes, and recompile. When you do this, you’ll see the following errors displayed:

Error messages after commenting-out all but the class attributes

Now you have isolated the errors that have to do with defining attributes. Make sure you understand how to define an attribute. For this example, you’d make the following changes:

int first, second;
double b, c;
Button goButton = new Button("Go");

Step 3: Method by Method

Continue this divide and conquer approach by moving the opening comment marker to reveal the first method. Recompile and fix the errors you find. Continue to reveal the rest of the class, method by method, until the entire program compiles without error.

Upgraded Ubuntu

Recently upgraded my Operating System with the latest version of Ubuntu-12.04 LTS.

 

 

 

 

  • Earlier i used to work on Ubuntu 10.10 Maverick Meerkat.

  • I had a problem with installing new softwares….it was an aptdaemon programming error.
  • then i reported that error at the following link   https://launchpad.net/,but dint get positive response.
  • Atlast upgraded my system with Ubuntu 12.04

The graphics are quite good.

Switch continued….

Last time we used Switch statement in case of integers.Now we will make use of the construct to compare two strings. Before moving onto that lets consider the following flow chart that outlays our previous discussion about Switch :

CODE :

package Constructs;

/**
*
* @author aprimit
*/
import java.util.Scanner;

public class compare_strings {

public static void main(String[] args) {
System.out.println(“This program compares two strings using EQUALS method…”);
Scanner input = new Scanner(System.in);
System.out.println(“Enter the two strings to be compared…”);
String expression1 = input.next();
String expression2 = input.next();
int c;
c = input.nextInt();//c reprresents case number…..
switch (c) {
case 1:

System.out.println(“This case is CASE Sensitive…”);

if (expression1.equals(expression2)) {
System.out.println(“Both expressions are equal…”);
} else {
System.out.println(“Expressions entered are not equal…”);
}
break;

case 2:
System.out.println(“This case is not CASE Sensitive…”);

if (expression1.equalsIgnoreCase(expression2)) {
System.out.println(“Both expressions are equal…”);
} else {
System.out.println(“Expressions entered are not equal…”);
}
break;
default:
System.out.println(“Neither of the two cases….”);
}
}
}

OUTPUT : This program compares two strings using EQUALS method…

Enter the two strings to be compared…

APRIMIT

aprimit

1

This case is CASE Sensitive…

Expressions entered are not equal…

Switch…

Since we are done with the loops and jumps in JAVA,its the right time to get started with the Switch statement which has been used earlier but will be explained here.

This is very simple Java program for implementing the switch statement. Here, you will learn how to use the switch statement in your java program for developing java application. This section provides you the best illustration about some mathematical operations like Addition, Subtraction, Multiplication and division.

Program Overview And Result:
This section also provides you an example with complete java source code for understanding more about the switch statement in Java. The following java program tells you for entering numbers for involving in mathematical operations as your choice (whatever you want to do with both number). Four type of operations are listed through the program in sequence. Whatever you have to perform the operation firstly you have to enter you choice as an existing operation number for selecting operation what you want to do with entered two numbers.

Lets view the code itself…

package Constructs;

/**
*
* @author aprimit
*/
import java.util.Scanner;

public class Switch {

public static void main(String[] args) {
System.out.println(“This program illustrates the use of SWITCH construct…”);
System.out.println(“Switch construct makes use of CASES….”);
System.out.println(“Input the numbers…a and b”);
Scanner input;//reference variable
input = new Scanner(System.in);//memory alloction
int a, b, add, sub, mul, div;//variable declaration
int c;
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();//c represents case number..
switch (c) {
case 1:
add = a + b;
System.out.println(“This case prints the addition operation ” + add);

break;
case 2:
sub = a – b;
System.out.println(“This case prints the subtraction operation ” + sub);

break;
case 3:
mul = a * b;
System.out.println(“This case prints the multiplication operation ” + mul);

break;
case 4:
div = a / b;
System.out.println(“This case prints the division operation ” + div);

break;

default:
System.out.println(“Invalid Operation”);
}
}
}

OUTPUT : This program illustrates the use of SWITCH construct…

Switch construct makes use of CASES….

Input the numbers…a and b

5,3

3

15

JAVA Jumps….

After completing the loops,we are going to study another important part of the Iteration section i.e Jumps.

Java Jumps

Java’s selection and iteration statements are called flow-of-control statements because they provide a highly structured method of conditionally and repeatedly executing a particular section of code.

In days past, however, before the control structures we use today, programmers still needed the equivalent of if statements and loops. Rather than relying on built-in language features, though, those iron-age programmers constructed their own flow of control statements, using the jump.

The jump statement often uses another name; even programmers who have never heard of the jump have heard of its nom de plum, the goto statement. The goto is one of Java’s fifty reserved words, but it isn’t actually implemented as part of the language.

When it comes to loop control, however, Java hasn’t abandoned the jump altogether. Java has two statements–break and continue–that let you do your jumping in a controlled fashion.

The break Statement

The break statement is used in two different circumstances, but both circumstances are quite similar.

Image shows the use of break in a while loop.

The break statement allows you to jump out of:

  • switch statement [as you saw earlier]
  • a loop

When a break statement is encountered in the body of a loop, your program jumps to the statement immediatly following the loop body, as you can see in the illustration shown here. Any remaining statements within the loop body are skipped. The test expression is not re-evaluated; the termination occurs regardless of the value the test expression would have.

Although it can be misused, allowing you to write code that is as convoluted as any produced by the goto statement, the break can sometimes be used to make your loops simpler and clearer. Here’s an example, BreakFor.java, that shows how the break statement can be used to simulate a sentinel loop that chops off the first sentence [ending with a period] in a String, and displays it in a TextField. Note that the loop bounds does not need to test for the sentinel value.

Using the break Statement
String str = myTF.getText();String ans = "";
char ch; for (int i = 0; i < str.length(); i++)
{
  ch = charAt(i);
  if (ch == '.')
    break;
  ans += ch;
}myTF.setText(ans);

Type some sentences into the TextField below and press ENTER.

The continue Statement

The continue statement is a jump statement like break, but unlike break, the continue jumps back to the loop condition.
Exactly what that means depends upon the loop you’re using:

  • For the while loop and the dowhile loop, the continue statement jumps to the boolean test, skipping backward [while] or forward [dowhile] as necessary.
  • With the for loop, control jumps to the update expression.

Image shows the operation of the continue statement

Converting Numbers

Here is an example that shows you how to use the continue statement with a for loop. The applet, ContinueFor.java, allows you to type an integer number into a TextField, using commas, like this:

2,345,567

The Integer.parseInt() method is unable to convert such a String containing commas, but you can easily do it yourself by following this simple algorithm.

  1. Using a loop, step through each character in the String If the character is not a digit, then use the continue statement to jump to the next repetition in the loop. Convert the digit character to a binary number by subtracting the character ‘0’. [Remember that ‘0’ has a numeric (Unicode) value of 48 decimal, while 0 has a numeric value of 0. If you subtract ‘0’ from ‘0’, the result is a binary 0; if you subtract ‘0’ from ‘1’, the result is a binary 1, and so on.]
  2. As each digit is encountered, multiply the sum of all converted digits [val in the example shown here] by 10, and add the newly converted digit.

Here’s the algorithm written in Java. See the entire ContinueFor.java applet.

Using continue with a for Loop
String str = numTF.getText();
int val = 0;for (int i = 0; i < str.length(); ++i)
{
  char ch = str.charAt(i);   if (! Character.isDigit(ch))
    continue;  val = val * 10;
  val += (ch - '0');
}
numTF.setText("" + val);
Type an integer into the TextArea, using the format, 999,999,999 and press ENTER.

Nested Loops

When you put one if statement inside the body of another if statement, you have a nestedif statement. You can do the same thing with loops. As you’d expect, these are callednested loops. When you stick one loop inside another loop, the first loop encountered is called the outer loop, and the next is called the inner loop.

Here’s an example of a pair of nested for loops that print a multiplication table. This is taken from the applet Times.java.

A Nested Loop
for (outer = 1; outer <= 10; ++outer)
{
  for (inner = 1; inner <= 10; ++inner)
  {
    int product = inner * outer;    if (product < 10)
       output.appendText("   " + product)
    else if (product < 100)
       output.appendText("  " + product)
    else
       output.appendText(" " + product);
  }
  output.appendText("");
}

With a the nested loops shown here, every repetition of the outer loop contains ten repetitions of the inner loop. Everytime the outer loop goes round once, the inner loop goes through it’s entire set of repetitions.

Labeled break and continue

One of the problems with nested loops, is that the break and continue statements stop “working.” Actually, they don’t stop working, exactly; they just don’t work quite the way you’d like. Here’s the problem.

Both break and continue work on the current loop. That means, when you are in an inner loop, a break statement only exits the inner loop; it doesn’t get you out of the outer loop. Java has a facility to address this deficiency, called the labeled break and the labeled continue. Here’s how they work:

  1. Before each loop, add a label. A label is simply an identifier that ends in a colon.
  2. Inside the loop, use the name of the label, along with the keyword break or continue, to jump to the loop following the label.

Here’s an example:

Labeled break and continue
int count = 0;Outer: // label ends with a colon
for (int outer = 1; outer < 1000; outer++)
{
  for(int inner = 1; inner < 1000; inner++)
  {
    count++;    if ( inner % 2 == 0 )   continue;
    if ( inner % 201 == 0 ) break;
    if ( outer % 25 == 0 )  continue Outer;
    if ( outer % 51 == 0 )  break Outer;
  }
}

Can you follow the flow of control in this nested loop? Let’s analyze it:

  1. The outer loop goes from 1 to 999, and for every revolution of the outer loop, the inner loop should also go around 999 times. If there were no breaks or continues, then the loop would repeat 998,001 times. In the inner loop, every even value (inner % 2 == 0) uses continue to skip back to the update expression of the inner loop. However, when inner reaches 201 (an odd number) break ends the inner loop. The inner loop, then, never executes more than 201 times per revolution of the outer loop. On the 25th repetition of the outer loop, there is a labeled continue. The target of this continue is the label Outer. This causes a jump to the expression outer++, [after updating count] and the 25th and 50th iterations of the inner loop are skipped.
  2. Finally, on the 51st repetition of the outer loop, the labeled break is encountered. This jumps to the statement following the closing brace of the loop labeled by Outer.

The result? The variable count records 201 iterations of the inner loop times 48 iterations of the outer loop, plus 3 entries to the inner loop with early exit [two continue Outer and onebreakOuter]. The final total for count is 9,648 instead of 998,001.

Do While JAVA…

Do-while loop

The Java programming language also provides a do-while statement, which can be expressed as follows:

do {
     statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once

Lets have a look at the code that follows:

package Loops_Iterators;

/**
*
* @author aprimit
*/
public class do_while {

public static void main(String[] args) {
System.out.println(“This program illustrates the ‘DO-WHILE’ loop…..”);
int i = 10;
do {
System.out.println(“Print the series…” + i);
i++; //i– here will enter the program into infinite loop…
} while (i < 10);
System.out.println();
System.out.println(i);
}
}

OUTPUT : This program illustrates the ‘DO-WHILE’ loop…..

Print the series…

10

While JAVA continued…

Lets code a program to illustrate while loop.

package Loops_Iterators;

/**
*
* @author aprimit
*/import java.util.Scanner;
public class While_loop {

public static void main(String[] args) {

System.out.println(“This program illustrates the while loop….”);
int i = 1;
System.out.println(“Print first ‘n’ natural numbers….”);
System.out.println(“Enter the number ‘n’ upto which you want to print the series…”);
Scanner input=new Scanner(System.in);
int n=input.nextInt();
while (i <= n) {
System.out.println(i);
i++;
}
}
}

OUTPUT : This program illustrates the while loop….

Print first ‘n’ natural numbers….

10

1

2

3

4

5

6

7

8

9

10