Avoiding Mistakes in Java

The only people who never make mistakes are the people who never do anything at all. But careful planning can help you avoid some of the most common Java goofs, such as the following.

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 things 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.

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,");
}

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.

Adding components to a GUI

Here's a constructor for a Java frame:
public SimpleFrame() {
JButton button = new JButton("Thank you...");
setTitle("...Katie Feltman and Heidi Unger");
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.

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.

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.

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.

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.

Anticipating null pointers

In real-life Java programming, you see that exception all the time. A NullPointerException 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.

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.

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 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.
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com