Syntactical Errors in Java - dummies

By John Paul Mueller

A syntactical error in Java code is one in which the language you use to create your code is incorrect. For example, if you try to create an if statement that doesn’t include the condition in parentheses, even when the condition is present on the same line as the if statement, that’s a syntax error.

The compiler will catch most of these errors for you. If the syntax of your code is incorrect, then in most cases the compiler can’t use the code to create byte code for the JRE. Here’s a list of the most common syntax errors:

  • Using incorrect capitalization: One of the most common syntax errors that new developers make is to capitalize keywords, rather than use lowercase. Java is case sensitive, so using the proper case when you type your code is essential.

    This same error can occur with class names, variables, or any other code you type as part of your Java application. A variable named MyVar is always different from one named myVar.

  • Splitting a string over two lines: In most cases, Java doesn’t care if your code appears on one or more lines. However, if you split a string across lines so that the string contains a newline character, then the compiler will object.

    The answer is to end the string on the first line with a double quote, add a plus sign to tell the compiler you want to concatenate (add) this string with another string, and then continue the string on the next line like this:

          System.out.print("This is a really long " +
                "string that appears on two lines.");
  • Missing parentheses: If you make a method call and don’t include the parentheses after the method name (even if you aren’t sending any arguments to the method), the compiler registers an error. For example, this code is incorrect because print() requires parentheses after it:

          System.out.print;
  • Forgetting to import a class: Whenever you want to use a particular Java API feature, you must import the associated class into your application. For example, if your application contains String userName;, then you must add import java.lang.String; to import the String class.

  • Treating a static method as an instance method: Static methods are those that are associated with a specific class, while instance methods are associated with an object created from the class.

  • Missing curly braces: Anytime you want a Java feature to apply to multiple lines of code, you must enclose the entire block within curly braces ({}). In most cases, the compiler will catch this error for you.

    For example, if you try to end a class without including the closing curly brace, the compiler will generate an error. This is one error where the compiler may not show you the precise location of the error because it can’t detect where the curly brace is missing — it simply knows that one is missing.

    This sort of error can also create runtime errors. For example, when an if statement is supposed to apply to multiple lines of code, but you leave out the curly braces, the if statement affects only the next line of code, and the application works incorrectly.

  • Forgetting the class or object name as part of a method call: You always include the class or object associated with a method before making the method call. For example, Character.toUpperCase() and System.out.print() are correct, but simply calling toUpperCase() or print() is incorrect.

  • Omitting the break clause from switch statements: It’s easy to forget to add the break clauses to a switch statement. In addition, the compiler won’t catch this error. As a consequence of leaving out the break clause, your application will continue to execute the code in a switch statement until it encounters a break clause or the switch statement is complete.

    For example, the following snippet of code demonstrates executing a default task, but the break clauses are commented out.

    // Import the required API classes.
    import java.util.Scanner;
    import java.lang.Character;
    public class UseAMenu03
    {
       public static void main(String[] args)
       {
          // Create the scanner.
          Scanner GetChoice = new Scanner(System.in);
          // Obtain input from the user.
          System.out.println("Optionsn");
          System.out.println("A. Yellow");
          System.out.println("B. Orange");
          System.out.println("C. Greenn");
          System.out.print("Choose your favorite color: ");
          char Choice = GetChoice.findInLine(".").charAt(0);
          // Convert the input to uppercase.
          Choice = Character.toUpperCase(Choice);
          // Choose the right color based on a switch statement.
          switch (Choice)
          {
             case 'A':
                System.out.println("Your favorite color is Yellow!");
                //break;
             case 'B':
                System.out.println("Your favorite color is Orange!");
                //break;
             case 'C':
                System.out.println("Your favorite color is Green!");
                //break;
             default:
                System.out.println(
                      "Type A, B, or C to select a color.");
                //break;
          }
       }
    }

    When you execute this code and answer A, the application outputs all the possible responses, as shown in this figure. If you compare this output to the output shown in the second figure, you’ll see that the application isn’t working correctly.

    image0.jpg
    image1.jpg

  • Omitting a return statement: When you create a method that’s supposed to return a value and then don’t provide a return statement to return the value, the compiler will complain.

  • Mistyping the header for the main() method: The compiler won’t complain about this problem, but you’ll see it immediately when you try to start the application. Java will complain that it can’t find the main() method. Remember that a main() method must appear like this:

public static void main (String []args)

You can create many other syntax errors. As you’ve discovered by reading this list, the compiler will find some of them, the JRE will find others, but some, like omitting the break clause of a switch statement, are left for you to figure out. Of the three main types of error, syntactical errors tend to be the easiest to find.