Chapter 4
IN THIS CHAPTER
Identifying the words in a Java program
Using punctuation and indentation
Understanding Java statements and methods
I work in the science building at a liberal arts college. When I walk past the biology lab, I always say a word of thanks under my breath. I’m thankful for not having to dissect small animals. In my line of work, I dissect computer programs instead. Computer programs smell much better than preserved dead animals. Besides, when I dissect a program, I’m not reminded of my own mortality.
In this chapter, I invite you to dissect a program with me. I have a small program, named ThingsILike
. I cut apart the program and carefully investigate the program’s innards. Get your scalpel ready. Here we go!
I have a confession to make. The first time I look at somebody else’s computer program, I feel a bit queasy. The realization that I don’t understand something (or many things) in the code makes me nervous. I’ve written hundreds (maybe thousands) of programs, but I still feel insecure when I start reading someone else’s code.
The truth is, learning about a computer program is a bootstrapping experience. First, I gawk in awe of the program. Then I run the program to see what it does. Then I stare at the program for a while or read someone’s explanation of the program and its parts. Then I gawk a little more and run the program again. Eventually, I come to terms with the program. Don’t believe the wise guys who say they never go through these steps. Even experienced programmers approach a new project slowly and carefully.
In Listing 4-1, you get a blast of Java code. Like all novice programmers, you’re expected to gawk humbly at the code. But don’t be intimidated. When you get the hang of it, programming is pretty easy. Yes, it’s fun, too.
LISTING 4-1 A Simple Java Program
/*
* A program to list the good things in life
* Author: Barry Burd, [email protected]
* February 13, 2017
*/
class ThingsILike {
public static void main(String args[]) {
System.out.println("Chocolate, royalties, sleep");
}
}
When I run the program in Listing 4-1, I get the result shown in Figure 4-1: The computer shows the words Chocolate, royalties, sleep
on the screen. Now, I admit that writing and running a Java program is a lot of work just to get the words Chocolate, royalties, sleep
to appear on somebody’s computer screen, but every endeavor has to start somewhere.
You can run the code in Listing 4-1 on your computer. Here’s how:
Then follow the instructions in the first half of Chapter 3.
Those instructions tell you how to run the project named 03-01
, which comes in a download from this book’s website (http://allmycode.com/BeginProg
). To run the code in Listing 4-1, follow the same instructions for the 04-01
project, which comes in the same download.
If the program in Listing 4-1 ever becomes famous, someone will write a Cliffs Notes book to summarize the program. The book will be really short because you can summarize the action of Listing 4-1 in just one sentence. Here’s the sentence:
Display Chocolate, royalties, sleep
on the computer screen.
Now compare the preceding sentence with the bulk in Listing 4-1. Because Listing 4-1 has so many more lines, you may guess that it has lots of boilerplate code. Well, your guess is correct. You can’t write a Java program without writing the boilerplate stuff, but, fortunately, the boilerplate text doesn’t change much from one Java program to another. Here’s my best effort at summarizing all the Listing 4-1 text in 66 words or fewer:
This program lists the good things in life.
Barry Burd wrote this program on February 13, 2017.
Barry realizes that you may have questions about this
code, so you can reach him at [email protected]
,
on Twitter at @allmycode, or on Facebook at /allmycode.
This code defines a Java class named ThingsILike.
Here’s the main starting point for the instructions:
Display Chocolate, royalties, sleep
on the screen.
The rest of this chapter (about 5,000 more words) explains the Listing 4-1 code in more detail.
That both English and Java are called languages is no coincidence. You use a language to express ideas. English expresses ideas to people, and Java expresses ideas to computers. What’s more, both English and Java have things like words, names, and punctuation. In fact, the biggest difference between the two languages is that Java is easier to learn than English. (If English were easy, computers would understand English. Unfortunately, they can’t.)
Take an ordinary English sentence and compare it with the code in Listing 4-1. Here’s the sentence:
Ann doesn’t pronounce the “r” sound because she’s from New York.
In your high school grammar class, you worried about verbs, adjectives, and other such things. But in this book, you think in terms of keywords and identifiers, as summarized in Figure 4-2.
Ann’s sentence has all kinds of things in it. They’re the same kinds of things that you find in a computer program. So here’s the plan: Compare the elements in Figure 4-2 with similar elements in Listing 4-1. You already understand English, so you can use this understanding to figure out some new things about Java.
But first, here’s a friendly reminder: In the next several paragraphs, I draw comparisons between English and Java. As you read these paragraphs, keep an open mind. In comparing Java with English, I may write, “Names of things aren’t the same as dictionary words.” Sure, you can argue that some dictionaries list proper nouns and that some people have first names like Hope, Prudence, and Spike, but please don’t. You’ll get more out of the reading if you avoid nitpicking. Okay? Are we still friends?
A keyword is a dictionary word — a word that’s built right into a language.
In Figure 4-2, a word like “from” is a keyword because “from” plays the same role whenever it’s used in an English sentence. The other keywords in Ann’s sentence are “doesn’t,” “pronounce,” “the,” “sound,” “because,” and “she’s.”
Computer programs have keywords, too. In fact, the program in Listing 4-1 uses four of Java’s keywords (shown in bold):
class ThingsILike {
public static void main(String args[]) {
Each Java keyword has a specific meaning — a meaning that remains unchanged from one program to another. For example, whenever I write a Java program, the word public
always signals a part of the program that’s accessible to any other piece of code.
This chapter has little or no detail about the meanings of the keywords class
, public
, static
, and void
. You can peek ahead at the material in other chapters, or you can get along by cheating. When you write a program, just start with
class SomethingOrOther {
and then paste the text
public static void main(String args[]) {
into your code. In your first few programs, this strategy serves you well.
Table 4-1 has a complete list of Java keywords.
TABLE 4-1 Java Keywords
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Here’s one thing to remember about keywords: In Java, each keyword has an official, predetermined meaning. The people at Oracle, who have the final say on what constitutes a Java program, created all of Java’s keywords. You can’t make up your own meaning for any of the Java keywords. For example, you can’t use the word public
in a calculation:
//This is BAD, BAD CODE:
public = 6;
If you try to use a keyword this way, the compiler displays an error message and refuses to translate your source code. It works the same way in English. Have a baby and name it Because:
“Let’s have a special round of applause for tonight’s master of ceremonies — Because O. Borel.”
You can do it, but the kid will never lead a normal life.
I like the name Ann, but if you don’t like traditional names, make up a brand-new name. You’re having a new baby. Call her Deneen or Chrisanta. Name him Belton or Merk.
A name is a word that identifies something, so I’ll stop calling these things names and start calling them identifiers. In computer programming, an identifier is a noun of some kind. An identifier refers to a value, a part of a program, a certain kind of structure, or any number of things.
Listing 4-1 has two identifiers that you or I can define on our own. They’re the made-up words ThingsILike
and args
.
class ThingsILike {
public static void main(String args[]) {
Just as the names Ann and Chrisanta have no special meaning in English, the names ThingsILike
and args
have no special meaning in Java. In Listing 4-1, I use ThingsILike
for the name of my program, but I could also have used a name like GooseGrease
, Enzyme
, or Kalamazoo
. I have to put (String
someName
[])
in my program, but I could use (String args[])
, (String commandLineArguments[])
, or (String cheese[])
.
The args
in (String args[])
holds anything extra that you type when you issue the command to run a Java program. For example, if you get the program to run by typing java ThingsILike won too 3
, then args
stores the extra values won
, too
, and 3
. As a beginning programmer, you don’t need to think about this feature of Java. Just paste (String args[])
into each of your programs.
Many people are named Ann, but only one well-known city is named New York. That’s because there’s a standard, well-known meaning for the term “New York.” It’s the city that never sleeps. If you start your own city, you should avoid naming it New York because naming it New York would just confuse everyone. (I know, a town in Florida is named New York, but that doesn’t count. Remember, you should ignore exceptions like this.)
Most programming languages have identifiers with agreed-upon meanings. In Java, almost all these identifiers are defined in the Java API. Listing 4-1 has five such identifiers. They’re the words main
, String
, System
, out
, and println
:
public static void main(String args[]) {
System.out.println("Chocolate, royalties, sleep");
}
Here’s a quick rundown on the meaning of each of these names (and more detailed descriptions appear throughout this book):
out
represents the Console view. To read more about text-based programs, check the first several paragraphs of Chapter 3.)A literal is a chunk of text that looks like whatever value it represents. In Ann’s sentence (refer to Figure 4-2), “r” is a literal because “r” refers to the letter r.
Programming languages have literals, too. For example, in Listing 4-1, the stuff in quotes is a literal:
System.out.println("Chocolate, royalties, sleep");
When you run the ThingsILike
program, you see the words Chocolate
, royalties
, sleep
on the screen. In Listing 4-1, the text "Chocolate, royalties, sleep"
refers to these words, exactly as they appear on the screen (minus the quotation marks).
Most of the numbers that you use in computer programs are literals. If you put the statement
mySalary = 1000000.00;
in a computer program, then 1000000.00
is a literal. It stands for the number 1000000.00 (one million).
If you don’t enjoy counting digits, you can put the following statement in your Java 7 program:
mySalary = 1_000_000.00;
Starting with Java 7, numbers with underscores are permissible as literals.
A typical computer program has lots of punctuation. For example, consider the program in Listing 4-1:
class ThingsILike {
public static void main(String args[]) {
System.out.println("Chocolate, royalties, sleep");
}
}
Each bracket, each brace, each squiggle of any kind plays a role in making the program meaningful.
In English, you write all the way across one line and then you wrap the text to the start of the next line. In programming, you seldom work this way. Instead, the code’s punctuation guides the indenting of certain lines. The indentation shows which parts of the program are subordinate to which other parts. It’s as though, in English, you wrote a sentence like this:
Ann doesn’t pronounce the “r” sound because
,
as we all know
,
she’s from New York.
The diagrams in Figures 4-3 and 4-4 show you how parts of the ThingsILike
program are contained inside other parts. Notice how a pair of curly braces acts like a box. To make the program’s structure visible at a glance, you indent all the stuff inside of each box.
A comment is text that’s outside the normal flow. In Figure 4-2, the words “That’s a sentence” aren’t part of the Ann sentence. Instead, these words are about the Ann sentence.
The same is true of comments in computer programs. The first five lines in Listing 4-1 form one big comment. The computer doesn’t act on this comment. There are no instructions for the computer to perform inside this comment. Instead, the comment tells other programmers something about your code.
Comments are for your own benefit, too. Imagine that you set aside your code for a while and work on something else. When you return later to work on the code again, the comments help you remember what you were doing.
The Java programming language has three kinds of comments:
Traditional comments: The comment in Listing 4-1 is a traditional comment. The comment begins with
and ends with /*
. Everything between the opening */
and the closing /*
is for human eyes only. Nothing between */
and /*
gets translated by the compiler.*/
The second, third, and fourth lines in Listing 4-1 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 4-1 because, for some reason that I don’t entirely understand, most Java programmers add these extra asterisks.
class ThingsILike { //Two things are missing
public static void main(String args[]) {
System.out.println("sleep"); // Missing from here
}
}
An end-of-line comment starts with two slashes and extends to the end of a line of type.
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 example, turn System.out.println("Sleep");
into /* System.out.println("Sleep"); */
. This keeps the Java compiler from seeing the code while you try to figure out what’s wrong with your program.
/**
* Print a String and then terminate the line.
*/
This is a cool Java feature. The Java SE software that you download from Oracle’s website includes a little program called javadoc
. The javadoc
program looks for these special comments in your code. The program uses these comments to create a brand-new web page — a customized documentation page for your code. To find out more about turning Javadoc comments into web pages, visit this book’s website (http://allmycode.com/BeginProg
).
The following sections present, explain, analyze, dissect, and otherwise demystify the Java program in Listing 4-1.
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:
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’ve associated with the method.
If you believe all that stuff in the preceding section, 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 were to, the program might include a method named fixTheAlternator
. The list of instructions in my fixTheAlternator
method would look something like the text in Listing 4-2.
LISTING 4-2 A Method Declaration
void fixTheAlternator(onACertainCar) {
driveInto(car, bay);
lift(hood);
get(wrench);
loosen(alternatorBelt);
…
}
Somewhere else in my Java code (somewhere outside of Listing 4-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 4-3.
LISTING 4-3 Calling a Method
fixTheAlternator(junkyOldFord);
If you have a basic understanding of what a method is and how it works (see preceding section), you can dig a little deeper into some useful terminology:
fixTheAlternator
in it, up to but not including the open curly brace) is called a method header. The rest of Listing 4-2 (the part surrounded by curly braces) is a method body.For a handy illustration of all the method terminology, see Figure 4-5.
A method’s header and body are like an entry in a dictionary. An entry doesn’t really use the word that it defines. Instead, an entry tells you what happens if and when you use the word:
In contrast, a method call is like the use of a word in a sentence. A method call sets some code in motion:
In Listing 4-1, the bulk of the code is 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 — the words public
, static
, void
, String
, and args
. I explain these words (on a need-to-know basis) in the next several chapters.
Like any Java method, the main
method is a recipe:
How to make biscuits:
Preheat the oven.
Roll the dough.
Bake the rolled dough.
or
How to follow the main instructions in
the ThingsILike code:
Display Chocolate, royalties, sleep 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.
When the ThingsILike
program runs, the computer automatically finds the program’s main
method and executes any instructions inside the method’s body. In the ThingsILike
program, the main
method’s body has only one instruction. That instruction tells the computer to print Chocolate, royalties, sleep
on the screen.
Buried deep in the heart of Listing 4-1 is the single line that actually issues a direct instruction to the computer. The line
System.out.println("Chocolate, royalties, sleep");
tells the computer to display the words Chocolate, royalties, sleep
. (If you use Eclipse, the computer displays Chocolate, royalties, sleep
in the Console view.) I can describe this line of code in at least two different ways:
fixTheAlternator(junkyOldFord);
is an example of a method call, and so is
System.out.println("Chocolate, royalties, sleep");
Java has many different kinds of statements. A method call is just one kind.
In Java, each statement ends with a semicolon. The code in Listing 4-1 has only one statement in it, so only one line in Listing 4-1 ends with a semicolon.
Take any other line in Listing 4-1 — the method header, for example. The method header (the line with the word main
in it) doesn’t directly tell the computer to do anything. Instead, the method header describes some action for future reference. The header announces “Just in case someone ever calls the main
method, the next few lines of code tell you what to do in response to that call.”
The statement in the middle of Listing 4-1 calls a method named System.out.println
. This method is defined in the Java API. Whenever you call the System.out.println
method, the computer displays text on its screen.
Think about names. Believe it or not, I know two people named Pauline Ott. One of them is a nun; the other is a physicist. Of course, there are plenty of Paulines in the English-speaking world, just as there are several things named println
in the Java API. To distinguish the physicist Pauline Ott from the film critic Pauline Kael, I write the full name Pauline Ott. And to distinguish the nun from the physicist, I write “Sister Pauline Ott.” In the same way, I write either System.out.println
or DriverManager.println.
The first (which you use often) writes text on the computer’s screen. The second (which you don’t use at all in this book) writes to a database log file.
Just as Pauline and Ott are names in their own right, so System, out
and println
are names in the Java API. But to use println
, you must write the method’s full name. You never write println
alone. It’s always System.out.println
or another combination of API names.
Two methods play roles in the ThingsILike
program. Figure 4-6 illustrates the situation, and the next few bullets give you a guided tour.
main
method. I wrote the main
method myself. This main
method is called automatically whenever I start running the ThingsILike
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, refer to Chapter 1.
Have you heard the term object-oriented programming (also known as OOP)? OOP is a way of thinking about computer programming problems — a way that’s supported by several different programming languages. OOP started in the 1960s with a language called Simula. It was reinforced in the 1970s with another language, named Smalltalk. In the 1980s, OOP took off big-time with the language C++.
Some people want to change the acronym and call it COP — class-oriented programming. That’s because object-oriented programming begins with something called a class. In Java, everything starts with classes, everything is enclosed in classes, and everything is based on classes. You can’t do anything in Java until you’ve created a class of some kind. It’s like being on Jeopardy, 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.”
It’s important for you to understand what a class really is, so I dare not give a haphazard explanation in this chapter. Instead, I devote much of Chapter 17 to the question “What is a class?” Anyway, in Java, your main
method has to be inside a class. I wrote the code in Listing 4-1, so I got to make up a name for my new class. I chose the name ThingsILike
, so the code in Listing 4-1 starts with the words class ThingsILike
.
Take another look at Listing 4-1 and notice what happens after the line class ThingsILike
. The rest of the code is enclosed in curly braces. These braces mark all the stuff inside the class. Without these braces, you’d know where the declaration of the ThingsILike
class starts, but you wouldn’t know where the declaration ends.
It’s as though the stuff inside the ThingsILike
class is in a box. (Refer to Figure 4-3.) To box off a chunk of code, you do two things:
Don’t forget. You have to do both.
class
to the word bologna
. Look for an error message in Eclipse’s editor.Change one of the identifiers that you or I can define. For example, change the word args
to the word malarkey
. After doing so, can your program still run?
The word ThingsILike
is also a word that you or I can make up. So you can try changing the word ThingsILike
to a different word. If you’ve copied the code exactly as it is in Listing 4-1, your program still runs. But if your program starts with the word public
, as in
public class SomeOtherWord {
public
.println
to display
. Look for an error message in Eclipse’s editor.System.out.println("Chocolate, royalties, sleep");
line. (Use the end-of-line commenting style.) What happens when you run the program?System.out.println("Chocolate, royalties, sleep");
line. (Use the traditional commenting style.) What happens when you run the program?There are limits to the kinds of names you can make up. For example, a person’s name might include a dash, but it can’t include a question mark. (At least it can’t where I come from.) A well-known celebrity’s name can be an unpronounceable symbol. But for most of us, plain old letters, dashes, and hyphens are all we can use.
What kinds of names can you make up as part of a Java program? Find out by changing the word args
to these other words in Eclipse’s editor. Which of the changes are okay, and which are not?
helloThere
hello_there
args7
ar7gs
75
7args
hello there
hello-there
public
royalties
@args
#args
/args
Change the code in Listing 4-1 so that it displays things that you like. Run the program to make sure that it displays these things in the Eclipse Console view.
3.15.229.111