DEBUGGING AND AVOIDING COMMON ERRORS IN JAVA

Image

While working through this book, you’ve probably made a few typos or mistakes along the way. In this appendix, I’ll go over a few common programming pitfalls to avoid. One nice feature of both Eclipse and Android Studio that is helpful when debugging is syntax coloring. Class names, functions, variable types, strings, comments, and so on are each colored differently in the IDE based on their syntax.

Syntax coloring can help you spot typos and other problems quickly. For example, if you forget to close a string with a second pair of double quotes, the semicolon at the end of that line will be colored differently from the other semicolons on the screen. As we go through these common errors, try introducing them into one of the apps you’ve written and look for the warnings given by Eclipse and Android Studio. It’s okay if you break an app—you can always go back and fix it, either by using the original code listing in the book or by pressing CTRL-Z (Image-Z) or clicking Edit Undo.

Spelling and Case

Spelling is important in any programming language, but in Java, case matters, too. For example, if you use a lowercase s to make a scanner or string, the text editor in Eclipse will underline the class name in red, and Android Studio will color the text red. It might seem silly, but Java only understands String, not string.

The same goes for variable names, such as playAgain or theNumber. For example, if we accidentally capitalize the P and use a lowercase a, spelling Playagain, Java doesn’t understand that we mean the variable playAgain. Let’s take a look at how each IDE helps us find and fix typographical errors like these, first in Eclipse and then in Android Studio.

Correcting Typos in Eclipse

Eclipse will alert us to an error by underlining the misspelled word in red, and Android will color the text. Figure A-1 shows how Eclipse highlights two errors I’ve introduced into the Hi-Lo guessing game from Chapter 2.

Image

Figure A-1: Eclipse helps us find misspellings and errors in capitalization.

Where I’ve used a lowercase s in system, Eclipse underlines the misspelling and adds an error alert along the left border of the screen that you can see by mousing over that line. The Java compiler issues the error "system cannot be resolved". That means Java can’t figure out what system is supposed to be because it only understands System with a capital S. Eclipse does the same with playagain on the next line—it should be playAgain.

Remember that you can use the content assist feature in Eclipse to fix many errors like these. Click one of the misspelled words from Figure A-1, and you’ll see a content assist menu like the ones shown in Figure A-2.

Image

Figure A-2: Eclipse’s content assist feature provides information about errors and offers possible fixes.

For the first misspelling, Eclipse not only tells us that it can’t resolve or understand system but also offers several possible corrections, including, fourth from the bottom in Figure A-2, Change to 'System' (java.lang). The content assist feature doesn’t always have the right answer, but in this case, one of the 11 quick fixes offered is the correct capitalization of System. For the second misspelling, the first quick fix Eclipse offers is the right answer, Change to 'playAgain'. If Eclipse’s content assist offers the right fix, click the correct entry, and your spelling or capitalization error will be replaced by the correct code.

Correcting Typos in Android Studio

Android Studio tries to help us find errors by coloring the suspected problem in red. In the example shown in Figure A-3, I’ve misspelled the keyword public by typing Public with a capital P.

Image

Figure A-3: Android Studio alerts us to an incorrectly capitalized keyword.

Notice that the error is similar to the one we saw in Eclipse earlier: Java is telling us that it can’t resolve or understand the symbol 'Public'. However, Android Studio may not always provide the same level of support in fixing errors, as shown in Figure A-4.

Image

Figure A-4: Pressing ALT-ENTER(or OPTION-ENTER) in Android Studio offers a quick fix, but not quite the right fix for this error.

In Figure A-4, I’ve incorrectly typed newGame() as NewGame() with a capital N. Android Studio correctly colored the code red to let me know there’s an error, but notice what happens when I click the code and press ALT-ENTER to attempt a quick fix. Instead of suggesting newGame as the correct spelling, Android Studio offers to create another method with the name NewGame. This isn’t the right fix for the mistyped method name, so you’ll need to find the correct spelling where the method public void newGame() was defined and manually fix the typo.

Both Android Studio and Eclipse will do their best to help you find errors, and they’ll often provide possible quick fixes, but knowing that spelling and capitalization are common issues can help you avoid and quickly correct errors as they pop up in your code.

Avoiding Other Common Spelling Errors

One error that is particularly difficult to debug is when the name of an event handler or other overridden method is mistyped. These typos can range from typing OnCreate() or OnDraw() instead of the correct onCreate() and onDraw(), to mistyping public void actionPerformed(ActionEvent e) inside an ActionListener for a button in a Java GUI app, or leaving off the “ed” in the mousePressed(), mouseClicked(), or mouseDragged() event handlers.

We have programming conventions in order to avoid these types of errors. Forgetting to use lowercase to start method or variable names but uppercase to start class names may not necessarily be an error, but it’s bad form in Java. If you get into the habit of using Java conventions like these from the beginning, you’ll save time and avoid frustration in the future.

Comparison Trouble

Remember that the double equal sign (==) is the comparison operator for “is equal to.” Don’t confuse it with the assignment operator (=). For example, to assign the value 5 to a variable named number, you would enter:

int number = 5; // Assigns the value 5 to number

But, to compare the value of the variable, you use the double equal sign:

if (number == 5) // If number "is equal to" 5

Also, remember that we check strings using the equals() method instead of the == operator. For example, the condition if (playAgain == "y") would always evaluate to false. The correct if statement would be this:

if (playAgain.equals("y"))

The equals() method of the String class checks whether the contents of the strings match, which is usually what we want when we compare strings. The equals() method is also what we use whenever we compare two objects, as in if (bubble1.equals(bubble2)) to see whether two Bubble variables refer to the same Bubble object in the BubbleDraw app, for example.

Grouping Symbols

When coding in Java, it’s also important to keep your parentheses, brackets, and braces balanced. We call these grouping symbols because they group other programming elements together and because you should never have an opening grouping symbol without a closing grouping symbol. Both Eclipse and Android Studio offer different ways to spot and fix unclosed grouping symbols.

Quick Fixes in Eclipse

Eclipse can help us with grouping symbols in a couple of ways. If you leave out a parenthesis from a condition or function, Eclipse will indicate the error with a red underline beneath the word closest to the missing parenthesis, as shown in Figure A-5.

Image

Figure A-5: Eclipse helps find errors with parentheses and sometimes offers a fix.

Again, Eclipse will do its best to help you spot errors while you type. In Figure A-5, I left out closing parentheses at the ends of two lines, which Eclipse marked with a red error symbol. Clicking the red error marker on the left margin of the editor for the first line offers the suggestion to insert a closing parenthesis.

If you place the cursor beside a closing or opening brace, Eclipse will outline the corresponding brace that either opens or closes that block of text. Try it out by clicking the cursor next to a brace in any of your programs.

Also, remember that Eclipse can correct indentation for us if we highlight the code to indent and press CTRL-I. For short programs, this may just be a nice convenience, but for longer programs that span multiple pages, correct indentation can be very helpful in avoiding errors due to missing or misplaced braces.

Code Completion in Android Studio

Android Studio offers even more help for missing grouping symbols. The code completion feature in Android Studio can automatically fill in both opening and closing parentheses, brackets, or braces.

For example, open the GuessingGame project from Chapter 4 and, inside the onCreate() function, find the line that calls a new game:

lblOutput = (TextView) findViewById(R.id.lblOutput);
newGame();
btnGuess.setOnClickListener(new View.OnClickListener() {

Delete the parentheses and the semicolon at the end of the line:

lblOutput = (TextView) findViewById(R.id.lblOutput);
newGame
btnGuess.setOnClickListener(new View.OnClickListener() {

Android Studio will color the text red to let you know there’s an error, and then you can use code completion to fill in the missing parentheses and semicolon. To complete the statement automatically, position the cursor just after newGame, as shown in Figure A-6, and press CTRL-space to perform basic code completion.

Image

Figure A-6: Place the cursor next to a line with missing parentheses (top) and press CTRL-space to finish the statement using Android Studio’s code completion (bottom).

Notice that code completion filled in both the missing parentheses and the semicolon to end the line. The CTRL-space combination is just the first of three code completion shortcuts in Android Studio. The second one, CTRL-SHIFT-space, is called smart completion and displays relevant options in a pop-up window. Press the keyboard shortcut twice to expand the list of code completion options. Finally, statement completion (CTRL-SHIFT-ENTER on Windows and Linux, Image-SHIFT-ENTER on macOS) will add closing parentheses/brackets/braces and a finishing semicolon if needed. Try statement completion by deleting just the closing parenthesis from a method, if statement, or for loop and pressing CTRL-SHIFT-ENTER. The statement completion feature in Android Studio will often close your grouping symbols and add semicolons or braces wherever they’re needed, making your job easier and faster and helping you avoid errors while you code.

Summary

These are far from the only errors you’ll run across while programming in Java, but you can see that both Eclipse and Android Studio offer very helpful tools for beginners and experienced professionals alike. You’ll get better at spotting and correcting errors the more you code in Java, but your code will probably never be completely error-free. I’ve been programming for over 30 years, and I still have to debug my code. To avoid, find, and fix errors in your code as you go, it’s important to learn good programming practices from the beginning and to take advantage of the support built into professional tools such as Eclipse and Android Studio.

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

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