How to check Java syntax in your sample code

Let’s say I’ve put together some sample Java code, and I want to check the syntax. What’s the easiest way to do that? This post compares two of the many possible solutions I’ve found. The first is to use the Java compiler (javac) from the command line. The second is to use Eclipse’s built-in syntax checker.

The Java compiler (javac) is part of the developer toolkit that comes with Java. You can run javac directly from the command line. Eclipse is a free and open source IDE (integrated development environment). For checking Java syntax, I prefer Eclipse because it’s smarter about figuring out the root cause of the problem, and the messages it gives are easier to understand.

I’m using a Mac running OS X, and Eclipse 4.2.1 bundled with the Android Developer Tools (ADT).

Kind reader, please note that I’m not a full-time Java programmer. I’m a technical writer building up her Java skills, and sharing information as she goes. So if I’ve made some silly mistakes, please tell me about them, and do it kindly. ;)

Getting Java

Check that you have Java, by opening a command window (called a “Terminal” window on a Mac) and running this command:

java -version

You should see something like this:

java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609)
Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)

If not, download and install Java, making sure you get a JDK (Java Development Kit) rather than just a JRE.

Confirm that you have the Java compiler by running this command:

javac -version

You should see something like this:

javac 1.6.0_65

If not, check your Java installation to ensure you have a JDK (Java Development Kit) installed.

Wrapping a Java class around your code

An important thing to understand is that you’ll need to wrap your code within a Java class. Even if you only want to check a single line of code or an itsy-bitsy method, you’ll need the framework of a class to give it context.

Let’s assume I want to build a string that includes some constant text plus two variables, representing someone’s favourite colour and toy. I’ve cobbled together this code, which builds the string and also prints it to the command window (the standard system output destination) for easy verification:

private void printToy(String colour, String toy) {
  String s = String.format("My favourite toys are %s %s.", colour, toy);
  System.out.println(s);
}

Here’s a simple class that includes the above code:

public class FavouriteToy {

   // Since I have only one class, 
   // I must include the "public static main()" method in this class.
   public static void main(String[] args) {

      // Make an object to hang my "printToy()" method on.
      FavouriteToy favToy = new FavouriteToy();

      // Check the number of arguments received as input.
      // Default to "purple koalas" if number is not 2.
      if (args.length == 2) {
         favToy.printToy(args[0], args[1]);
      } else {
         favToy.printToy("purple", "koalas");
      }
   }

   // Construct and print a text string showing the favourite colour and toy
   private void printToy(String colour, String toy) {
      String s = String.format("My favourite toys are %s %s.", colour, toy);
      System.out.println(s);
   }
}

Save the code in a text file called FavouriteToy.java. Note that the file name must match the class name.

Using the Java compiler to check your code

Run the Java compiler to compile your Java file into an executable class file:

javac FavouriteToy.java

If everything goes well, your code has passed the syntax checks and you’ll notice that you now have a new file called FavouriteToy.class.

But what if you’ve made a mistake? The compiler will display the error messages in your command window. For example, if I forget to put the semicolon at the end of this line:

FavouriteToy favToy = new FavouriteToy()

Then I’ll see this in the command line:

javac FavouriteToy.java
FavouriteToy.java:8: ';' expected
FavouriteToy favToy = new FavouriteToy()
                                        ^
1 error

That’s quite handy. It even tells me exactly where in the line the missing semicolon should be, by placing the circumflex (^) in the right spot.

Things get tricky, though, when there’s a more complex error or more than one error. For example, this is what happens if I leave out the closing curly bracket for the main() method:

javac FavouriteToy.java
FavouriteToy.java:20: illegal start of expression
private void printToy(String colour, String toy) {
^
FavouriteToy.java:20: illegal start of expression
private void printToy(String colour, String toy) {
        ^
FavouriteToy.java:20: ';' expected
private void printToy(String colour, String toy) {
                     ^
FavouriteToy.java:20: ';' expected
private void printToy(String colour, String toy) {
                                           ^
FavouriteToy.java:20: not a statement
private void printToy(String colour, String toy) {
^
FavouriteToy.java:20: ';' expected
private void printToy(String colour, String toy) {
                                               ^
FavouriteToy.java:24: reached end of file while parsing
}
 ^
7 errors

Eek!

Running the code on the command line

By the way, assuming your code has passed the compiler checks, you can run it via the command line with the java command. Here’s the command to run our sample class with a couple of input parameters, and the resulting output:

java FavouriteToy pink kangaroos
My favourite toys are pink kangaroos.

Using Eclipse to check your code

Eclipse is a free and open source development platform, including an IDE (integrated development environment) and a number of useful tools. The IDE includes a nice editing environment. Provided you let it know that your project is a Java project, it can do all sorts of fancy things for you.

Download the right version of Eclipse for your operating system. Installing it is simple: It’s just a matter of unzipping the downloaded file into a directory of your choice. See the installation guide.

Start Eclipse, and choose a workspace directory as prompted. You can leave it at the default. If the “Welcome” screen appears, close it.

Now you need to add a Java project, so that Eclipse knows what sort of files and project structure it will be dealing with. Choose “File” > “New” > “Java Project”. Enter a project name (like “TestPony”) and click “Finish”. You can leave all the other project settings at their defaults.

Time to explore a bit. Find the panel called “Project Explorer” in your Eclipse work area. If you can’t see the Project Explorer, choose “Window” > “Show View” > “Project Explorer”. In the Project Explorer, click the twisty arrow next to your project, to open up the file structure below the project name. You’ll see a “src” directory, which is currently empty, and a JRE system library.

The next step is to add the code for your Java class. Choose “File” > “New” > “File”. Select the “src” directory as the destination for the new file, and enter a file name, like “FavouriteToy.java”. Click “Finish”. (You could also let Eclipse know up front that you’re adding a class, by choosing “File” > “New” > “Class” instead of “File” > “New” > “File”.)

The file will appear in the Project Explorer, and will also open in the editor panel that occupies most of your Eclipse work area.

Paste your Java code into the editor panel. Eclipse immediately analyses the code and highlights errors.

This screenshot shows the Eclipse editor with my sample code. Two red circles with cross in the left-hand margin indicate lines with errors in them. There’s also a red squiggly underline on the offending portion of the line. I can hover over the red circle or the red squiggly line to see the error message:

Eclipse editor highlighting syntax errors

Eclipse editor highlighting syntax errors

Here’s the neat error message for my second deliberate mistake, where I missed out a curly bracket:

Eclipse's explanation of the missing curly bracket

Eclipse’s explanation of the missing curly bracket

I think you’ll agree that Eclipse’s message is much easier to understand than the 7 errors given by the javac command.

Eclipse is really neat

It was when I started getting more complicated Java errors that I really fell in love with Eclipse. It gives you suggestions on how to fix the problem!

Suggestions from Eclipse

Suggestions from Eclipse

About these ads

About Sarah Maddox

Technical writer, author and blogger in Sydney

Posted on 1 December 2013, in technical writing and tagged , , . Bookmark the permalink. 4 Comments.

  1. Does your organization regularly run many many software tests? Maybe you could sneak your sample code into that system. Then you get some warning if someone changes an API out from under you a few months from now.

    • Hallo Larry
      That’s a very good idea! Our sample code resides in a repo and is subject to automated tests, so we get a report whenever someone breaks the build. I managed to break it a couple of weeks after starting at my new job, which I take as a sign of success. ;)
      Cheers
      Sarah

  2. Hi Sarah,

    learning Java as a Tech Writer is a challenging task. I can recommend the book ‘Head First Java’. You will like it. It is not only a good Java book, further more it is one of the best pieces of didactic text I ever read.

    Enjoy Java!

    • Hallo Stefan,

      Thanks so much for letting me know about that book. It looks very worth reading. The reviews on Amazon.com make for interesting reading too. Many very positive reviews, and one or two people who don’t like the pictures or the funny side of the book.

      Cheers
      Sarah

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,495 other followers

%d bloggers like this: