Chapter 4

Exploring the Parts of a Program

IN THIS CHAPTER

check Identifying the words in a Java program

check Using punctuation and indentation

check 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!

Checking Out Java Code for the First Time

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.

Behold! A program!

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.

image

FIGURE 4-1: Running the program in Listing 4-1.

ontheweb Most of the programs in this book are text-based programs. When you run one of these programs, the input and output appears in Eclipse’s Console view. In contrast, a GUI (graphical user interface) program displays windows, buttons, text fields, and other widgets to interact with the user. You can see GUI versions of the program in Listing 4-1, and in many other examples from this book, by visiting the book’s website (http://allmycode.com/BeginProg).

You can run the code in Listing 4-1 on your computer. Here’s how:

  1. Follow the instructions in Chapter 2 for installing Eclipse.
  2. 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.

What the program’s lines say

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.

The Elements in a Java Program

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.

image

FIGURE 4-2: The things you find in a simple sentence.

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?

Keywords

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.

warning The java proGRAMMing lanGUage is case-sensitive. ThIS MEans that if you change a lowerCASE LETTer in a wORD TO AN UPPercase letter, you chANge the wORD’S MEaning. ChangiNG CASE CAN MakE the enTIRE WORD GO FROM BeiNG MEANINGFul to bEING MEaningless. In Listing 4-1, you can’t replace public with Public. If you do, the WHOLE PROGRAM STOPS WORKING.

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

abstract

continue

for

new

switch

assert

default

goto

package

synchronized

boolean

do

if

private

this

break

double

implements

protected

throw

byte

else

import

public

throws

case

enum

instanceof

return

transient

catch

extends

int

short

try

char

final

interface

static

void

class

finally

long

strictfp

volatile

const

float

native

super

while

technicalstuff In Java, the words true, false, and null have specific meanings. As with the keywords in Table 4-1, you can’t use true, false, and null to mean anything other than what they normally mean in a Java program. But for reasons that concern only the fussiest Java experts, true, false, and null are not called Java keywords. One way or another, if you scribble the words true, false, and null into Table 4-1, you’ll be okay.

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.

technicalstuff Despite my ardent claims in this section, two of Java’s keywords have no meaning in a Java program. Those keywords — const and goto — are reserved for nonuse in Java. If you try to create a variable named goto, Eclipse displays an Invalid VariableDeclaratorId error message. The creators of Java figure that if you use either of the words const or goto in your code, you should be told politely to move to the C++ programmers’ table.

Identifiers that you or I can define

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[]).

tip Make up sensible, informative names for the things in your Java programs. Names like GooseGrease are legal, and they’re certainly cute, but they don’t help you keep track of your program-writing strategy.

remember When I name my Java program, I can use ThingsILike or GooseGrease, but I can’t use the word public. Words like class, public, static, and void are keywords in Java.

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.

Identifiers with agreed-upon meanings

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):

  • main: The main starting point for execution in every Java program.
  • String: A bunch of text; a row of characters, one after another.
  • System: A canned program in the Java API. This program accesses some features of your computer that are outside the direct control of the Java Virtual Machine (JVM).
  • out: The place where a text-based program displays its text. (For a program running in Eclipse, the word out represents the Console view. To read more about text-based programs, check the first several paragraphs of Chapter 3.)
  • println: Displays text on your computer screen.

remember The name println comes from the words “print a line.” If you were allowed to write the name in uppercase letters, it would be PRINTLN, with a letter L near the end of the word. When the computer executes println, the computer puts some text in Eclipse’s Console view and then immediately moves to the beginning of the next line in preparation for whatever else will appear in the Console view.

technicalstuff 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 words like System or println, doing so isn’t a good idea — because you’d confuse the dickens out of other programmers, who are used to the standard API meanings for these familiar identifier names.

Literals

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.

warning In versions of Java before Java 7, you cannot use numbers such as 1_000_000.00 in your code.

technicalstuff Different countries use different number separators and different number formats. For example, in the United States, you write 1,234,567,890.55. In France, you write 1234567890,55. In India, you group digits in sets of two and three. You write 1,23,45,67,890.55. You can’t put a statement like mySalary = 1,000,000.00 in your Java program. Java’s numeric literals don’t have any commas in them. But you can write mySalary = 10_00_000.00 for easy-to-read programming in India. And for a program’s output, you can display numbers like 1234567890,55 using Java’s Locale and NumberFormat classes. (For more on Locale and NumberFormat, check out Chapter 18.)

Punctuation

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.

image

FIGURE 4-3: A pair of curly braces acts like a box.

image

FIGURE 4-4: The ideas in a computer program are nested inside one another.

remember I can’t emphasize this point enough: If you don’t indent your code or if you indent but you don’t do it carefully, your code still compiles and runs correctly. But this successful run gives you a false sense of confidence. The minute you try to update some poorly indented code, you become hopelessly confused. Take my advice: Keep your code carefully indented at every step in the process. Make its indentation precise, whether you’re scratching out a quick test program or writing code for a billionaire customer.

tip Eclipse can indent your code automatically for you. Select the .java file whose code you want to indent. Then, on Eclipse’s main menu, choose Source ⇒   Format. Eclipse rearranges the lines in the editor, indenting things that should be indented and generally making your code look good.

Comments

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.

  • End-of-line comments: Here’s some code with end-of-line comments:

    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.

    tip 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.

  • Javadoc comments: A special Javadoc comment is any traditional comment that begins with an extra asterisk:

    /**
    * 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).

Understanding a Simple Java Program

The following sections present, explain, analyze, dissect, and otherwise demystify the Java program in Listing 4-1.

What is a 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’ve associated with the method.

Java methods

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);

warning Don’t scrutinize Listings 4-2 and 4-3 too carefully. All the lines of code in Listings 4-2 and 4-3 are fakes! 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 4-2 and 4-3 isn’t meant to illustrate all the rules about Java. So if you have a grain of salt handy, take it with Listings 4-2 and 4-3.

technicalstuff 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, Sub procedures, or PERFORM statements. Whatever you call it in your favorite programming language, a method is a bunch of instructions collected together and given a new name.

The declaration, the header, and the call

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:

  • If I’m being lazy, I refer to the code in Listing 4-2 as a method. If I’m not being lazy, I refer to this code as a method declaration.
  • The method declaration in Listing 4-2 has two parts. The first line (the part with the name 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.
  • The term method declaration distinguishes the list of instructions in Listing 4-2 from the instruction in Listing 4-3, which is known as a method call.

For a handy illustration of all the method terminology, see Figure 4-5.

image

FIGURE 4-5: The terminology describing methods.

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:

  • chocolate (choc-o-late) n.1. The most habit-forming substance on earth. 2. Something you pay for with money from royalties. 3. The most important nutritional element in a person’s diet.
  • fixTheAlternator(onACertainCar) Drive the car into the bay, lift the hood, get the wrench, loosen the alternator belt, and then eat some chocolate.

In contrast, a method call is like the use of a word in a sentence. A method call sets some code in motion:

  • “I want some chocolate, or I’ll throw a fit.”
  • “fixTheAlternator on that junkyOldFord.”

remember A method’s declaration tells the computer what will happen 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

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.

remember None of the instructions in a method is executed until the method is called into action. But if you give a method the name main, that method is called into action automatically.

How you finally tell the computer to do something

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:

  • It’s a statement. In Java, a direct instruction that tells the computer to do something is called a statement. The statement in Listing 4-1 tells the computer to display some text. The statements in other programs may tell the computer to put 7 in a certain memory location or make a window appear on the screen. The statements in computer programs do all kinds of things.
  • It’s a method call. Earlier in this chapter, I describe something named a method call. The statement

    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.

Ending a statement with a semicolon

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.”

remember Every complete Java statement ends with a semicolon. A method call is a statement, so it ends with a semicolon, but neither a method header nor a method declaration is a statement.

The method named System.out.println

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.

warning The Java programming language is cAsE-sEnSiTiVe. If you change a lowercase letter to an uppercase letter (or vice versa), you change a word’s meaning. You can’t replace System.out.println with system.out.Println. If you do, your program won’t work.

Methods, methods everywhere

Two methods play roles in the ThingsILike program. Figure 4-6 illustrates the situation, and the next few bullets give you a guided tour.

  • There’s a declaration for a 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.

image

FIGURE 4-6: Calling the System.out.println method.

technicalstuff 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 4-1.

The Java class

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:

  • You use curly braces. These curly braces tell the compiler where a chunk of code begins and ends.
  • You indent code. Indentation tells your human eye (and the eyes of other programmers) where a chunk of code begins and ends.

Don’t forget. You have to do both.

THE WORDS IN A PROGRAM

tryitout Listing 4-1 contains several kinds of words. Find out what happens when you change some of these words.

  • Change one of the keywords. For example, change the word 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 {

  • you might have some trouble. If you do, simply remove the word public.
  • Change an identifier that has an agreed-upon meaning. For example, change println to display. Look for an error message in Eclipse’s editor.
  • Change the program’s punctuation. For example, remove a pair of curly braces. Look for an error message in Eclipse’s editor.
  • Comment out the entire System.out.println("Chocolate, royalties, sleep"); line. (Use the end-of-line commenting style.) What happens when you run the program?
  • Comment out the entire System.out.println("Chocolate, royalties, sleep"); line. (Use the traditional commenting style.) What happens when you run the program?

VALID IDENTIFIERS

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

YOUR FAVORITE THINGS

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.

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

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