Chapter 3

Using the Basic Building Blocks

In This Chapter

arrow Speaking the Java language: the API and the Language Specification

arrow Understanding the parts of a simple program

arrow Documenting your code

“Все мысли, которые имеют огромные последствия всегда просты. (All great ideas are simple.)”

— Leo Tolstoy

The quotation applies to all kinds of things — things like life, love, and computer programming. That’s why this chapter takes a multilayered approach. In this chapter, you get your first details about Java programming. And in discovering details, you’ll see the simplicities.

Speaking the Java Language

If you try to picture in your mind the entire English language, what do you see? Maybe you see words, words, words. (That’s what Hamlet saw.) Looking at the language under a microscope, you see one word after another. The bunch-of-words image is fine, but if you step back a bit, you may see two other things:

  • The language’s grammar
  • Thousands of expressions, sayings, idioms, and historical names

The first category (the grammar) includes rules like, “The verb agrees with the noun in number and person.” The second category (expressions, sayings, and stuff) includes knowledge like, “Julius Caesar was a famous Roman emperor, so don’t name your son Julius Caesar, unless you want him to get beaten up every day after school.”

The Java programming language has all the aspects of a spoken language like English. Java has words, grammar, commonly used names, stylistic idioms, and other such things.

The grammar and the common names

The people at Sun Microsystems who created Java thought of Java as having two parts. Just as English has its grammar and commonly used names, the Java programming language has its specification (its grammar) and its Application Programming Interface (its commonly used names). Whenever I write Java programs, I keep two important pieces of documentation — one for each part of the language — on my desk:

  • The Java Language Specification: This documentation includes rules like, “Always put an open parenthesis after the word for” and “Use an asterisk to multiply two numbers.”
  • The Application Programming Interface: Java’s Application Programming Interface (API) contains thousands of tools that were added to Java after the language’s grammar was defined. These tools range from the commonplace to the exotic. For instance, the tools include a routine named pow that can raise 5 to the 10th power for you. A more razzle-dazzle tool (named JFrame) displays a window on your computer’s screen. Other tools listen for the user’s button clicks, query databases, and do all kinds of useful things.

ontheweb_fmt.eps You can download the Language Specification, the API documents, and all the other Java documentation (or view the documents online) by poking around at http://docs.oracle.com/javase/specs. But watch out! This web page is a moving target. By the time you read this book, the link in this paragraph will probably be out of date. The safest thing to do is to start at Java.Sun.com and then look for links to things like “Java SE” (short for “Java Standard Edition”) and “reference” or “documentation.”

The first part of Java, the Language Specification, is relatively small. That doesn’t mean you won’t take plenty of time finding out how to use the rules in the Language Specification. Other programming languages, however, have double, triple, or ten times the number of rules.

The second part of Java — the API — can be intimidating because it’s so large. The API contains nearly 4,000 tools and keeps growing with each new Java language release. Pretty scary, eh? Well, the good news is that you don’t have to memorize anything in the API. Nothing. None of it. You can look up the stuff you need to use in the documentation and ignore the stuff you don’t need. What you use often, you’ll remember. What you don’t use often, you’ll forget (like any other programmer).

remember.eps No one knows all there is to know about the Java API. If you’re a Java programmer who frequently writes programs that open new windows, you know how to use the API JFrame class. If you seldom write programs that open windows, the first few times you need to create a window, you can look up the JFrame class in the API documentation. My guess is that if you took a typical Java programmer and kept that programmer from looking up anything in the API documentation, the programmer would be able to use less than 2 percent of all the tools in the Java API.

ontheweb_fmt.eps You may love the For Dummies style, but unfortunately, Java’s official API documentation isn’t written that way. The API documentation is both concise and precise. For some help deciphering the API documentation’s language and style, see this book’s website (www.allmycode.com/JavaForDummies).

In a way, nothing about the Java API is special. Whenever you write a Java program — even the smallest, simplest Java program — you create a class that’s on par with any of the classes defined in the official Java API. The API is just a set of classes and other tools that were created by ordinary programmers who happen to participate in the official Java Community Process (JCP) and in the OpenJDK Project. Unlike the tools that you create, the tools in the API are distributed with every version of Java. (I’m assuming that you, the reader, are not a participant in the Java Community Process or the OpenJDK Project. But, with a fine book like Java For Dummies, 6th Edition, one never knows.)

ontheweb_fmt.eps If you’re interested in the JCP’s activities, visit www.jcp.org. If you're interested in the OpenJDK Project, visit http://openjdk.java.net.

The folks at the JCP don’t keep the Java programs in the official Java API a secret. If you want, you can look at all these programs. When you install Java on your computer, the installation puts a file named src.zip on your hard drive. You can open src.zip with your favorite unzipping program. There, before your eyes, is all the Java API code.

The words in a Java program

A hard-core Javateer will say that the Java programming language has two kinds of words: keywords and identifiers. This is true. But the bare truth, without any other explanation, is sometimes misleading. So I recommend dressing up the truth a bit and thinking in terms of three kinds of words: keywords, identifiers that ordinary programmers like you and I create, and identifiers from the API.

The differences among these three kinds of words are similar to the differences among words in the English language. In the sentence “Sam is a person,” the word person is like a Java keyword. No matter who uses the word person, the word always means roughly the same thing. (Sure, you can think of bizarre exceptions in English usage, but please don’t.)

The word Sam is like a Java identifier because Sam is a name for a particular person. Words like Sam, Dinswald, and McGillimaroo aren’t prepacked with meaning in the English language. These words apply to different people depending on the context and become names when parents pick one for their newborn kid.

Now consider the sentence “Julius Caesar is a person.” If you utter this sentence, you’re probably talking about the fellow who ruled Rome until the Ides of March. Although the name Julius Caesar isn’t hard-wired into the English language, almost everyone uses the name to refer to the same person. If English were a programming language, the name Julius Caesar would be an API identifier.

So here’s how I, in my mind, divide the words in a Java program into categories:

  • Keywords: A keyword is a word that has its own special meaning in the Java programming language, and that meaning doesn’t change from one program to another. Examples of keywords in Java include if, else, and do.

    The JCP committee members, who have the final say on what constitutes a Java program, have chosen all the Java keywords. If you think about the two parts of Java, which I discuss earlier in the “The grammar and the common names” section, the Java keywords belong solidly to the Language Specification.

  • Identifiers: An identifier is a name for something. The identifier’s meaning can change from one program to another, but some identifiers’ meanings tend to change more.
    • Identifiers created by you and me: As a Java programmer (yes, even as a novice Java programmer), you create new names for classes and other things that you describe in your programs. Of course, you may name something Prime, and the guy writing code two cubicles down the hall can name something else Prime. That’s okay because Java doesn’t have a predetermined meaning for Prime. In your program, you can make Prime stand for the Federal Reserve’s prime rate. And the guy down the hall can make Prime stand for the “bread, roll, preserves, and prime rib.” A conflict doesn’t arise, because you and your co-worker are writing two different Java programs.
    • Identifiers from the API: The JCP members have created names for many things and thrown almost 40,000 of these names into the Java API. The API comes with each version of Java, so these names are available to anyone who writes a Java program. Examples of such names are String, Integer, JWindow, JButton, JTextField, and File.

Strictly speaking, the meanings of the identifiers in the Java API aren’t cast in stone. Although you can make up your own meanings for JButton or JWindow, this isn’t a good idea. If you did, you would confuse the dickens out of other programmers, who are used to the standard API meanings for these familiar identifier names. But even worse, when your code assigns a new meaning to an identifier like JButton, you lose any computational power that was created for the identifier in the API code. The programmers of Sun Microsystems, the Java Community Process, and the OpenJDK Project did all the work writing Java code to handle buttons. If you assign your own meaning to JButton, you’re turning your back on all the progress made in creating the API.

ontheweb_fmt.eps To see the list of Java keywords, visit this book's website (www.allmycode.com/JavaForDummies).

Checking Out Java Code for the First Time

The first time you look at somebody else’s Java program, you tend to feel a bit queasy. The realization that you don’t understand something (or many things) in the code can make you nervous. I’ve written hundreds (maybe thousands) of Java programs, but I still feel insecure when I start reading someone else’s code.

The truth is that finding out about a Java program is a bootstrapping experience. First, you gawk in awe of the program. Then you run the program to see what it does. Then you stare at the program for a while or read someone’s explanation of the program and its parts. Then you gawk a little more and run the program again. Eventually, you come to terms with the program. (Don’t believe the wise guys who say they never go through these steps. Even the experienced programmers approach a new project slowly and carefully.)

In Listing 3-1, you get a blast of Java code. (Like all novice programmers, you’re expected to gawk humbly at the code.) Hidden in the code, I’ve placed some important ideas, which I explain in detail in the next section. These ideas include the use of classes, methods, and Java statements.

Listing 3-1: The Simplest Java Program

  public class Displayer {

   public static void main(String args[]) {
      System.out.println("You'll love Java!");
   }
}

ontheweb_fmt.eps You don't have to type the code in Listing 3-1 (or in any of this book's listings). To download all the code in this book, visit the book's website (www.allmycode.com/JavaForDummies).

When you run the program from Listing 3-1, the computer displays You'll love Java! (Figure 3-1 shows the output of the Displayer program when you use the Eclipse IDE.) Now, I admit that writing and running a Java program is a lot of work just to get You'll love Java! to appear on somebody’s computer screen, but every endeavor has to start somewhere.

9781118407806-fg0301.tif

Figure 3-1: I use Eclipse to run the program in Listing 3-1.

ontheweb_fmt.eps To learn how to run the code in Listing 3-1, visit this book's website (www.allmycode.com/JavaForDummies).

In the following section, you do more than just admire the program’s output. After you read the following section, you actually understand what makes the program in Listing 3-1 work.

Understanding a Simple Java Program

This section presents, explains, analyzes, dissects, and otherwise demystifies the Java program shown previously in Listing 3-1.

The Java class

Because Java is an object-oriented programming language, your primary goal is to describe classes and objects. (If you’re not convinced about this, read the sections on object-oriented programming in Chapter 1.)

On those special days when I’m feeling sentimental, I tell people that Java is more pure in its object-orientation than most other so-called object-oriented languages. I say this because, in Java, you can’t do anything until you create a class of some kind. It’s like being on Jeopardy! and hearing Alex Trebek say, “Let’s go to a commercial” and then interrupting him by saying, “I’m sorry, Alex. You can’t issue an instruction without putting your instruction inside a class.”

In Java, the entire program is a class. I wrote the program, so I get to make up a name for my new class. I chose the name Displayer because the program displays a line of text on the computer screen. That’s why the first line in Listing 3-1 contains the words class Displayer. (See Figure 3-2.)

9781118407806-fg0302.tif

Figure 3-2: A Java program is a class.

The first two words in Listing 3-1, public and class, are Java keywords. (See the section “The words in a Java program,” earlier in this chapter.) No matter who writes a Java program, the words public and class are always used the same way. On the other hand, Displayer in Listing 3-1 is an identifier. I made up the word Displayer while I was writing this chapter. Displayer is the name of a particular class — the class that I'm creating by writing this program.

cross-reference.eps This book is filled with talk about classes, but for the best description of a Java class (the reason for using the word class in Listing 3-1) visit Chapter 7. The word public means (roughly) that other Java programs can use the features declared in Listing 3-1. For more details about the meaning of public and the use of the word public in a Java program, see Chapters 7 and 14.

warning.eps tHE jAVA PROGRAMMING LANGUAGE IS cASe-sEnsITiVE. If you change a lowercase letter in a word to an UpperCase letter, you can change the word’s meaning. cHANGING case can make the entire word go from being meaningful to being meaningless. In the first line of Listing 3-1, you can’t replace class with Class. iF YOU DO, THE WHOLE PROGRAM STOPS WORKING. The same holds true, to some extent, for the name of a file containing a particular class. For example, the name of the class in Listing 3-1 is Displayer, starting with an uppercase letter D. So it's a good idea to save the code of Listing 3-1 in a file named Displayer.java, starting with an uppercase letter D.

cross-reference.eps Normally, if you define a class named DogAndPony, the class's Java code goes in a file named DogAndPony.java, spelled and capitalized exactly the same way that the class name is spelled and capitalized. In fact, this file-naming convention is mandatory for most examples in this book.

The Java method

You’re working as an auto mechanic in an upscale garage. Your boss, who’s always in a hurry and has a habit of running words together, says, “fixTheAlternator on that junkyOldFord.” Mentally, you run through a list of tasks. “Drive the car into the bay, lift the hood, get a wrench, loosen the alternator belt,” and so on. Three things are going on here:

  • You have a name for the thing you’re supposed to do. The name is fixTheAlternator.
  • In your mind, you have a list of tasks associated with the name fixTheAlternator. The list includes “Drive the car into the bay, lift the hood, get a wrench, loosen the alternator belt,” and so on.
  • You have a grumpy boss who’s telling you to do all this work. Your boss gets you working by saying, “fixTheAlternator.” In other words, your boss gets you working by saying the name of the thing you’re supposed to do.

In this scenario, using the word method wouldn’t be a big stretch. You have a method for doing something with an alternator. Your boss calls that method into action, and you respond by doing all the things in the list of instructions that you associate with the method.

If you believe all that (and I hope you do), then you’re ready to read about Java methods. In Java, a method is a list of things to do. Every method has a name, and you tell the computer to do the things in the list by using the method’s name in your program.

I’ve never written a program to get a robot to fix an alternator. But, if I did, the program might include a fixTheAlternator method. The list of instructions in my fixTheAlternator method would look something like the text in Listing 3-2.

warning.eps Don’t scrutinize Listings 3-2 and 3-3 too carefully. All the code in Listings 3-2 and 3-3 is fake! I made up this code so that it looks a lot like real Java code, but it’s not real. What’s more important, the code in Listings 3-2 and 3-3 isn’t meant to illustrate all the rules about Java. So, if you have a grain of salt handy, take it with Listings 3-2 and 3-3.

Listing 3-2: A Method Declaration

  void fixTheAlternator() {
   driveInto(car, bay);
   lift(hood);
   get(wrench);
   loosen(alternatorBelt);
   ...
}

Somewhere else in my Java code (somewhere outside of Listing 3-2), I need an instruction to call my fixTheAlternator method into action. The instruction to call the fixTheAlternator method into action may look like the line in Listing 3-3.

Listing 3-3: A Method Call

  fixTheAlternator(junkyOldFord);

Now that you have a basic understanding of what a method is and how it works, you can dig a little deeper into some useful terminology:

  • If I’m being lazy, I refer to the code in Listing 3-2 as a method. If I’m not being lazy, I refer to this code as a method declaration.
  • The method declaration in Listing 3-2 has two parts. The first line (the part with fixTheAlternator in it, up to but not including the open curly brace) is a method header. The rest of Listing 3-2 (the part surrounded by curly braces) is a method body.
  • The term method declaration distinguishes the list of instructions in Listing 3-2 from the instruction in Listing 3-3, which is known as a method call.

remember.eps A method’s declaration tells the computer what happens if you call the method into action. A method call (a separate piece of code) tells the computer to actually call the method into action. A method’s declaration and the method’s call tend to be in different parts of the Java program.

The main method in a program

Figure 3-3 has a copy of the code from Listing 3-1. The bulk of the code contains the declaration of a method named main. (Just look for the word main in the code’s method header.) For now, don’t worry about the other words in the method header — public, static, void, String, and args. I explain these words in the next several chapters.

9781118407806-fg0303.tif

Figure 3-3: The main method.

Like any Java method, the main method is a recipe.

How to make biscuits:
   Heat the oven.
   Roll the dough.
   Bake the rolled dough.

or

How to follow the main instructions for a Displayer:
   Print "You_ll love Java!" on the screen.

The word main plays a special role in Java. In particular, you never write code that explicitly calls a main method into action. The word main is the name of the method that is called into action automatically when the program begins running.

So look back at Figure 3-1. When the Displayer program runs, the computer automatically finds the program’s main method and executes any instructions inside the method’s body. In the Displayer program, the main method’s body has only one instruction. That instruction tells the computer to print You’ll love Java! on the screen. So in Figure 3-1, You’ll love Java! appears on the computer screen.

remember.eps The instructions in a method aren’t executed until the method is called into action. But, if you give a method the name main, that method is called into action automatically.

technicalstuff.eps Almost every computer programming language has something akin to Java’s methods. If you’ve worked with other languages, you may remember things like subprograms, procedures, functions, subroutines, subprocedures, or PERFORM statements. Whatever you call it in your favorite programming language, a method is a bunch of instructions collected and given a new name.

How you finally tell the computer to do something

Buried deep in the heart of Listing 3-1 is the single line that actually issues a direct instruction to the computer. The line, which is highlighted in Figure 3-4, tells the computer to display You'll love Java! This line is a statement. In Java, a statement is a direct instruction that tells the computer to do something (for example, display this text, put 7 in that memory location, make a window appear).

9781118407806-fg0304.tif

Figure 3-4: A Java statement.

remember.eps In System.out.println, the next-to-last character is a lowercase letter l, not a digit 1.

Of course, Java has different kinds of statements. A method call, which I introduce in the earlier “The Java method” section, is one of the many kinds of Java statements. Listing 3-3 shows you what a method call looks like, and Figure 3-4 also contains a method call that looks like this:

System.out.println("You'll love Java!");

When the computer executes this statement, the computer calls a method named System.out.println into action. (Yes, in Java, a name can have dots in it. The dots mean something.)

warning.eps I said it already, but this is worth repeating: In System.out.println, the next-to-last character is a lowercase letter l (as in the word “line”), not a digit 1 (as in the number “one”). If you use a digit 1, your code won’t work. Just think of println as a way of saying “print line,” and you won’t have any problem.

To learn the meaning behind the dots in Java names, see Chapter 9.

Figure 3-5 illustrates the System.out.println situation. Actually, two methods play active roles in the running of the Displayer program. Here’s how they work:

  • There’s a declaration for a main method. I wrote the main method myself. This main method is called automatically whenever I run the Displayer program.
  • There’s a call to the System.out.println method. The method call for the System.out.println method is the only statement in the body of the main method. In other words, calling the System.out.println method is the only thing on the main method’s to-do list.

    The declaration for the System.out.println method is buried inside the official Java API. For a refresher on the Java API, see the sections “The grammar and the common names” and “The words in a Java program,” earlier in this chapter.

9781118407806-fg0305.tif

Figure 3-5: Calling the System.out.println method.

technicalstuff.eps When I say things like, “System.out.println is buried inside the API,” I’m not doing justice to the API. True, you can ignore all the nitty-gritty Java code inside the API. All you need to remember is that System.out.println is defined somewhere inside that code. But I’m not being fair when I make the API code sound like something magical. The API is just another bunch of Java code. The statements in the API that tell the computer what it means to carry out a call to System.out.println look a lot like the Java code in Listing 3-1.

In Java, each statement (like the boxed line in Figure 3-4) ends with a semicolon. Other lines in Figure 3-4 don’t end with semicolons, because the other lines in Figure 3-4 aren’t statements. For instance, the method header (the line with the word main in it) doesn’t directly tell the computer to do anything. The method header announces, “Just in case you ever want to do main, the next few lines of code tell you how to do it.”

remember.eps Every complete Java statement ends with a semicolon.

Curly braces

Long ago, or maybe not so long ago, your schoolteachers told you how useful outlines are. With an outline, you can organize thoughts and ideas, help people see forests instead of trees, and generally show that you’re a member of the Tidy Persons Club. Well, a Java program is like an outline. The program in Listing 3-1 starts with a big header line that says, “Here comes a class named Displayer.” After that first big header, a subheader announces, “Here comes a method named main.

Now, if a Java program is like an outline, why doesn’t a program look like an outline? What takes the place of the Roman numerals, capital letters, and other things? The answer is twofold:

  • In a Java program, curly braces enclose meaningful units of code.
  • You, the programmer, can (and should) indent lines so that other programmers can see the outline form of your code at a glance.

In an outline, everything is subordinate to the item in Roman numeral I. In a Java program, everything is subordinate to the top line — the line with class in it. To indicate that everything else in the code is subordinate to this class line, you use curly braces. Everything else in the code goes inside these curly braces. (See Listing 3-4.)

Listing 3-4: Curly Braces for a Java Class

  public class Displayer {

   public static void main(String args[]) {
      System.out.println("You'll love Java!");
   }
}

In an outline, some stuff is subordinate to a capital letter A item. In a Java program, some lines are subordinate to the method header. To indicate that something is subordinate to a method header, you use curly braces. (See Listing 3-5.)

Listing 3-5: Curly Braces for a Java Method

  public class Displayer {

   public static void main(String args[ ]) {    
      System.out.println("You'll love Java!");
   }                                  
}

In an outline, some items are at the bottom of the food chain. In the Displayer class, the corresponding line is the line that begins with System.out.println. Accordingly, this System.out.println line goes inside all the other curly braces and is indented more than any other line.

remember.eps Never lose sight of the fact that a Java program is, first and foremost, an outline.

If you put curly braces in the wrong places or omit curly braces where the braces should be, your program probably won’t work at all. If your program works, it’ll probably work incorrectly.

If you don’t indent lines of code in an informative manner, your program will still work correctly, but neither you nor any other programmer will be able to figure out what you were thinking when you wrote the code.

If you’re a visual thinker, you can picture outlines of Java programs in your head. One friend of mine visualizes an actual numbered outline morphing into a Java program. (See Figure 3-6.) Another person, who shall remain nameless, uses more bizarre imagery. (See Figure 3-7.)

9781118407806-fg0306.tif

Figure 3-6: An outline turns into a Java program.

9781118407806-fg0307.tif

Figure 3-7: A class is bigger than a method; a method is bigger than a statement.

ontheweb_fmt.eps I appreciate a good excuse as much as the next guy, but failing to indent your Java code is inexcusable. In fact, many Java IDEs have tools to indent your code automatically. Visit this book’s website (www.allmycode.com/JavaForDummies) for more information.

And Now, a Few Comments

People gather around campfires to hear the old legend about a programmer whose laziness got her into trouble. To maintain this programmer’s anonymity, I call her Jane Pro. Jane worked many months to create the holy grail of computing — a program that thinks on its own. If completed, this program could work independently, learning new things without human intervention. Day after day, night after night, she labored to give the program that spark of creative, independent thought.

One day, when she was almost finished with the project, she received a disturbing piece of paper mail from her health insurance company. No, the mail wasn’t about a serious illness. It was about a routine office visit. The insurance company’s claim form had a place for her date of birth, as if her date of birth had changed since the last time she sent in a claim. She had absentmindedly scribbled 2014 as her year of birth, so the insurance company refused to pay the bill.

Jane dialed the insurance company’s phone number. Within 20 minutes, she was talking to a live person. “I’m sorry,” said the live person. “To resolve this issue you must dial a different number.” Well, you can guess what happened next. “I’m sorry. The other operator gave you the wrong number.” And then, “I’m sorry. You must call back the original phone number.”

Five months later, Jane’s ear ached, but after 800 hours on the phone, she had finally gotten a tentative promise that the insurance company would eventually reprocess the claim. Elated as she was, she was anxious to get back to her programming project. Could she remember what all those lines of code were supposed to be doing?

No, she couldn’t. She stared and stared at her own work and, like a dream that doesn’t make sense the next morning, the code was completely meaningless to her. She had written a million lines of code, and not one line was accompanied by an informative explanatory comment. She had left no clues to help her understand what she’d been thinking, so in frustration, she abandoned the whole project.

Adding comments to your code

Listing 3-6 has an enhanced version of this chapter’s sample program. In addition to all the keywords, identifiers, and punctuation, Listing 3-6 has text that’s meant for human beings to read.

Listing 3-6: Three Kinds of Comments

  /*
* Listing 3-6 in "Java For Dummies, 6th Edition"
*
* Copyright 2014 Wiley Publishing, Inc.
* All rights reserved.
*/

/**
* The Displayer class displays text
* on the computer screen.
*
* @author Barry Burd
* @version 1.0 10/24/13
* @see    java.lang.System
*/
public class Displayer {

    /**
    * The main method is where
    * execution of the code begins.
    *
    * @param args  (See Chapter 11.)
        */
   public static void main(String args[]) {    
      System.out.println("I love Java!"); //I? You?
   }                                  
}

A comment is a special section of text inside a program whose purpose is to help people understand the program. A comment is part of a good program’s documentation.

The Java programming language has three kinds of comments:

  • Traditional comments: The first five lines of Listing 3-6 form one traditional comment. The comment begins with /* and ends with */. Everything between the opening /* and the closing */ is for human eyes only. No information about "Java For Dummies, 6th Edition" or Wiley Publishing, Inc. is translated by the compiler.

    cross-reference.eps To read about compilers, see Chapter 2.

    The second, third, fourth, and fifth lines in Listing 3-6 have extra asterisks (*). I call them extra because these asterisks aren’t required when you create a comment. They just make the comment look pretty. I include them in Listing 3-6 because, for some reason that I don’t entirely understand, most Java programmers add these extra asterisks.

  • End-of-line comments: The text //I? You? in Listing 3-6 is an end-of-line comment. An end-of-line comment starts with two slashes and goes to the end of a line of type. Once again, the compiler doesn’t translate the text inside the end-of-line comment.
  • Javadoc comments: A javadoc comment begins with a slash and two asterisks (/**). Listing 3-6 has two javadoc comments — one with the text The Displayer class...and another with the text The main method is where....

    A javadoc comment is a special kind of traditional comment. A javadoc comment is meant to be read by people who never even look at the Java code. But that doesn’t make sense. How can you see the javadoc comments in Listing 3-6 if you never look at Listing 3-6?

    Well, a certain program called javadoc (what else?) can find all the javadoc comments in Listing 3-6 and turn these comments into a nice-looking web page. Figure 3-8 shows the page.

Javadoc comments are great. Here are several great things about them:

  • The only person who has to look at a piece of Java code is the programmer who writes the code. Other people who use the code can find out what the code does by viewing the automatically generated web page.
  • Because other people don’t look at the Java code, other people don’t make changes to the Java code. (In other words, other people don’t introduce errors into the existing Java code.)
  • Because other people don’t look at the Java code, other people don’t have to decipher the inner workings of the Java code. All these people need to know about the code is what they read on the code’s web page.
  • The programmer doesn’t create two separate things — some Java code over here and some documentation about the code over there. Instead, the programmer creates one piece of Java code and embeds the documentation (in the form of javadoc comments) right inside the code.
  • Best of all, the generation of web pages from javadoc comments is automatic. So everyone’s documentation has the same format. No matter whose Java code you use, you find out about that code by reading a page like the one in Figure 3-8. That’s good because the format in Figure 3-8 is familiar to anyone who uses Java.

ontheweb_fmt.eps You can generate your own web pages from the javadoc comments that you put in your code. To discover how, visit this book’s website (www.allmycode.com/JavaForDummies).

9781118407806-fg0308.tif

Figure 3-8: The javadoc page generated from the code in Listing 3-6.

What’s Barry’s excuse?

For years, I’ve been telling my students to put comments in their code, and for years, I’ve been creating sample code (like the code in Listing 3-1) with no comments in it. Why?

Three little words: “Know your audience.” When you write complicated, real-life code, your audience is other programmers, information technology managers, and people who need help deciphering what you’ve done. When I write simple samples of code for this book, my audience is you — the novice Java programmer. Instead of reading my comments, your best strategy is to stare at my Java statements — the statements that Java’s compiler deciphers. That’s why I put so few comments in this book’s listings.

Besides, I’m a little lazy.

Using comments to experiment with your code

You may hear programmers talk about commenting out certain parts of their code. When you’re writing a program and something’s not working correctly, it often helps to try removing some of the code. If nothing else, you find out what happens when that suspicious code is removed. Of course, you may not like what happens when the code is removed, so you don’t want to delete the code completely. Instead, you turn your ordinary Java statements into comments. For instance, you turn the statement

  System.out.println("I love Java!");

into the comment

  // System.out.println("I love Java!");

This change keeps the Java compiler from seeing the code while you try to figure out what’s wrong with your program.

Traditional comments aren’t very useful for commenting out code. The big problem is that you can’t put one traditional comment inside of another. For instance, suppose you want to comment out the following statements:

  System.out.println("Parents,");
System.out.println("pick your");
/*
 * Intentionally displays on four separate lines
 */
System.out.println("battles");
System.out.println("carefully!");

If you try to turn this code into one traditional comment, you get the following mess:

  /*
 System.out.println("Parents,");
 System.out.println("pick your");
  /*
   * Intentionally displays on four separate lines
   */
 System.out.println("battles");
 System.out.println("carefully!");
*/

The first */ (after Intentionally displays) ends the traditional comment prematurely. Then the battles and carefully statements aren’t commented out, and the last */ chokes the compiler. You can’t nest traditional comments inside one another. Because of this, I recommend end-of-line comments as tools for experimenting with your code.

ontheweb_fmt.eps Most IDEs can comment out sections of your code for you automatically. For details, visit 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.227.72.212