Chapter 18

Ten Ways to Avoid Mistakes

In This Chapter

arrow Checking your capitalization and value comparisons

arrow Watching out for fall-through

arrow Putting methods, listeners, and constructors where they belong

arrow Using static and non-static references

arrow Avoiding other heinous errors

“The only people who never make mistakes are the people who never do anything at all.” One of my college professors said that. I don’t remember the professor’s name, so I can’t give him proper credit. I guess that’s my mistake.

Putting Capital Letters Where They Belong

Java is a case-sensitive language, so you really have to mind your Ps and Qs — along with every other letter of the alphabet. Here are some details to keep in mind as you create Java programs:

  • Java’s keywords are all completely lowercase. For instance, in a Java if statement, the word if can’t be If or IF.
  • When you use names from the Java API (Application Programming Interface), the case of the names has to match what appears in the API.
  • You also need to make sure that the names you make up yourself are capitalized the same way throughout your entire program. If you declare a myAccount variable, you can’t refer to it as MyAccount, myaccount, or Myaccount. If you capitalize the variable name two different ways, Java thinks you’re referring to two completely different variables.

For more info on Java’s case-sensitivity, see Chapter 3.

Breaking Out of a switch Statement

If you don’t break out of a switch statement, you get fall-through. For instance, if the value of verse is 3, the following code prints all three lines — Last refrain, He's a pain, and Has no brain.

  switch (verse) {
case 3:
   out.print("Last refrain, ");
   out.println("last refrain,");
case 2:
   out.print("He's a pain, ");
   out.println("he's a pain,");
case 1:
   out.print("Has no brain, ");
   out.println("has no brain,");
}

For the full story, see Chapter 5.

Comparing Values with a Double Equal Sign

When you compare two values with one another, you use a double equal sign. The line

  if (inputNumber == randomNumber)

is correct, but the line

  if (inputNumber = randomNumber)

is not correct. For a full report, see Chapter 5.

Adding Components to a GUI

Here’s a constructor for a Java frame:

  public SimpleFrame() {
   JButton button = new JButton("Thank you...");
   setTitle("...Connie Santisteban and Brian Walls");
   setLayout(new FlowLayout());
   add(button);
   button.addActionListener(this);
   setSize(300, 100);
   setVisible(true);
}

Whatever you do, don’t forget the call to the add method. Without this call, you go to all the work of creating a button, but the button doesn’t show up on your frame. For an introduction to such issues, see Chapter 9.

Adding Listeners to Handle Events

Look again at the previous section’s code to construct a SimpleFrame. If you forget the call to addActionListener, nothing happens when you click the button. Clicking the button harder a second time doesn’t help. For the rundown on listeners, see Chapter 15.

Defining the Required Constructors

When you define a constructor with parameters, as in

  public Temperature(double number)

then the computer no longer creates a default parameterless constructor for you. In other words, you can no longer call

  Temperature roomTemp = new Temperature();

unless you explicitly define your own parameterless Temperature constructor. For all the gory details on constructors, see Chapter 9.

Fixing Non-Static References

If you try to compile the following code, you get an error message:

  class WillNotWork {
   String greeting = "Hello";

   public static void main(String args[]) {
      System.out.println(greeting);
   }
}

You get an error message because main is static, but greeting isn’t static. For the complete guide to finding and fixing this problem, see Chapter 10.

Staying within Bounds in an Array

When you declare an array with ten components, the components have indices 0 through 9. In other words, if you declare

  int guests[] = new int[10];

then you can refer to the guests array’s components by writing guests[0], guests[1], and so on, all the way up to guests[9]. You can’t write guests[10], because the guests array has no component with index 10.

For the latest gossip on arrays, see Chapter 11.

Anticipating Null Pointers

This book’s examples aren’t prone to throwing the NullPointerException, but in real-life Java programming, you see that exception all the time. A Null
PointerException comes about when you call a method that’s supposed to return an object, but instead the method returns nothing. Here’s a cheap example:

  import static java.lang.System.out;
import java.io.File;

class ListMyFiles {

   public static void main(String args[]) {
      File myFile = new File("\windows");

      String dir[] = myFile.list();

      for (String fileName : dir) {
         out.println(fileName);
      }
   }
}

This program displays a list of all the files in the windows directory. (For clarification on the use of the double backslash in "\windows", see Chapter 8.)

But what happens if you change \windows to something else — something that doesn’t represent the name of a directory?

  File myFile = new File("&*%$!!");

Then the new File call returns null (a special Java word meaning nothing), so the variable myFile has nothing in it. Later in the code, the variable dir refers to nothing, and the attempt to loop through all the dir values fails miserably. You get a big NullPointerException, and the program comes crashing down around you.

To avoid this kind of calamity, check Java’s API documentation. If you’re calling a method that can return null, add exception-handling code to your program.

For the story on handling exceptions, see Chapter 13. For some advice on reading the API documentation, see Chapter 3 and this book’s website (www.allmycode.com/JavaForDummies).

Helping Java Find Its Files

You’re compiling Java code, minding your own business, when the computer gives you a NoClassDefFoundError. All kinds of things can be going wrong, but chances are good that the computer can’t find a particular Java file. To fix this, you must align all the planets correctly:

  • Your project directory has to contain all the Java files whose names are used in your code.
  • If you use named packages, your project directory has to have appropriately named subdirectories.
  • Your CLASSPATH must be set properly.

For specific guidelines, see Chapter 14 and this book’s website (www.allmycode.com/JavaForDummies).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.194