In this chapter, you find the basics of writing simple Java programs. The programs you see in this chapter don't do anything very interesting; they just display simple information on a console (in Windows, that's a command-prompt window). You need to cover a few more chapters before you start writing programs that do anything worthwhile. But the simple programs you see in this chapter are sufficient to illustrate the basic structure of Java programs.
Be warned that in this chapter I introduce you to several Java programming features that are explained in greater detail in later chapters. For example, you see some variable declarations, a method, and even an if statement and a for loop. The goal of this chapter isn't to march you into instant proficiency with these programming elements, but just to introduce you to them.
REMEMBER |
You can find all the code listings used in this book at http://www.dummies.com/go/javaaiofd2e. |
Many programming books begin with a simple example program that displays the text “Hello, World!” on the console. In Book I, Chapter 1, I show you a Java program that does that to compare it with a similar program written in C. Now, take a closer look at each element of this program, shown in Listing 1-1.
Listing 1-1: The HelloApp Program
public class HelloApp → 1 { → 2 public static void main(String[] args) → 3 { → 4 System.out.println("Hello, World!"); → 5 } → 6 } → 7
Later in this chapter, you discover in detail all the elements that make up this program. But first, I want to walk you through it word by word.
Lines 1 and 2 mark the declaration of a public class named HelloApp:
→ 1 |
public: A keyword of the Java language that indicates that the element that follows should be made available to other Java elements. In this case, what follows is a class named HelloApp. As a result, this keyword indicates that the HelloApp class is a public class, which means other classes can use it. (In Book III, Chapter 2, I cover the most common alternative to public: private. There are also other alternatives, but they're covered in later chapters.) |
class: Another Java keyword that indicates that the element being defined here is a class. All Java programs are made up of one or more classes. A class definition contains code that defines the behavior of the objects created and used by the program. Although most real-world programs consist of more than one class, the simple programs you see in this minibook have just one class. |
|
HelloApp: An identifier that provides the name for the class being defined here. While keywords, such as public and class, are words that are defined by the Java programming language, identifiers are words that you create to provide names for various elements you use in your program. In this case, the identifier HelloApp provides a name for the public class being defined here. (Although identifier is the technically correct term, sometimes identifiers are called symbols or names.) |
|
→ 2 |
{: The opening brace on line 2 marks the beginning of the body of the class. The end of the body is marked by the closing brace on line 7. Everything that appears within these braces belongs to the class. As you work with Java, you'll find that it uses these braces a lot. Pretty soon the third and fourth fingers on your right hand will know exactly where they are on the keyboard. |
Open table as spreadsheet
Lines 3 through 6 define a method of the HelloApp class named main:
→ 3 |
public: The public keyword is used again, this time to indicate that a method being declared here should have public access. That means classes other than the HelloApp class can use it. All Java programs must have at least one class that declares a public method named main. The main method contains the statements that are executed when you run the program. |
static: You find all about the static keyword in Book III, Chapter 3. For now, just take my word that the Java language requires that you specify static when you declare the main method. |
|
void: In Java, a method is a unit of code that can calculate and return a value. For example, you could create a method that calculates a sales total. Then the sales total would be the return value of the method. If a method doesn't need to return a value, you must use the void keyword to indicate that no value is returned. Because Java requires that the main method not return a value, you must specify void when you declare the main method. |
|
main: Finally, the identifier that provides the name for this method. As I've already mentioned, Java requires that this method be named main. Besides the main method, you can also create additional methods with whatever names you want to use. You discover how to create additional methods in Book II, Chapter 7. Until then, the programs consist of just one method named main |
|
(String[] args): Oh boy. This Java element is too advanced to thoroughly explain just yet. It's called a parameter list, and it's used to pass data to a method. Java requires that the main method must receive a single parameter that's an array of String objects. By convention, this parameter is named args. If you don't know what a parameter, a String, or an array is, don't worry about it. You can find out what a String is in the next chapter, and parameters are in Book II, Chapter 7; arrays in Book IV. In the meantime, realize that you have to code (String[] args) on the declaration for the main methods in all your programs. |
|
→ 4 |
Another {: Another set of braces begins at line 4 and ends at line 6. These mark the body of the main method. Notice that the closing brace in line 6 is paired with the opening brace in line 4, while the closing brace in line 7 is paired with the one in line 2. This type of pairing is commonplace in Java. In short, whenever you come to a closing brace, it is paired with the most recent opening brace that hasn't already been closed-that is, that hasn't already been paired with a closing brace. |
→ 5 |
System.out.println("Hello, World!");: This is the only statement in the entire program. It calls a method named println that belongs to the System.out object. The println method displays a line of text on the console. The text to be displayed is passed to the println method as a parameter in parentheses following the word println. In this case, the text is the string literal Hello, World! enclosed in a set of quotation marks. As a result, this statement displays the text Hello, World! on the console. Note that in Java, statements end with a semicolon. Because this is the only statement in the program, this line is the only one that requires a semicolon. |
→ 6 |
}: Line 6 contains the closing brace that marks the end of the main method body that was begun by the brace on line 4. |
→ 7 |
Another }: Line 7 contains the closing brace that marks the end of the HelloApp class body that was begun by the brace on line 2. Because this program consists of just one class, this line also marks the end of the program. |
Open table as spreadsheet
To run this program, you must first use a text editor to enter it-exactly as it appears in Listing 1-1-into a text file named HelloApp.java. Then you can compile it by running the following command at a command prompt:
javac HelloApp.java
This command creates a class file named HelloApp.class that contains the Java bytecodes compiled for the HelloApp class.
You can run the program by entering this command:
java HelloApp
Now that you've seen what a Java program actually looks like, you're in a better position to understand exactly what this command does. First, it loads the Java Virtual Machine into memory. Then it locates the HelloApp class, which must be contained in a file named HelloApp.class. Finally, it runs the main method of the HelloApp class. The main method, in turn, displays the message “Hello, World!” on the console.
The rest of this chapter describes some of the basic elements of the Java programming language in greater detail.
A keyword is a word that has a special meaning defined by the Java programming language. The program shown earlier in Listing 1-1 uses four keywords: public, class, static, and void. In all, Java has 53 keywords. They're listed in alphabetical order in Table 1-1.
abstract |
default |
goto |
package |
synchronized |
assert |
do |
if |
private |
this |
boolean |
double |
implements |
protected |
throw |
break |
else |
import |
public |
throws |
byte |
enum |
instanceof |
return |
transient |
case |
extends |
int |
short |
true |
catch |
false |
interface |
static |
try |
char |
final |
long |
strictfp |
void |
class |
finally |
native |
super |
volatile |
const |
float |
new |
switch |
while |
continue |
for |
null |
TECHNICAL STAUFF |
Strangely enough, three keywords listed in Table 1-1-true, false, and null-aren't technically considered to be keywords. Instead, they're called literals. Still, they're reserved for use by the Java language in much the same way that keywords are, so I lumped them in with the keywords. |
Stranger still, two keywords-const and goto-are reserved by Java but don't do anything. Both are carryovers from the C++ programming language. The const keyword defines a constant, which is handled in Java by the final keyword. As for goto, it's a C++ statement that is considered anathema to object-oriented programming purists, so it isn't used in Java. Java reserves it as a keyword solely for the purpose of scolding you if you attempt to use it.
Warning |
Like everything else in Java, keywords are case-sensitive. Thus, if you type If instead of if or For instead of for, the compiler complains about your error. Because Visual Basic keywords begin with capital letters, you'll make this mistake frequently if you have programmed in Visual Basic. |
Considering the Java community's disdain for Visual Basic, it's surprising that the error messages generated when you capitalize keywords aren't more insulting. Accidentally capitalizing a keyword in Visual Basic style can really throw the Java compiler for a loop. For example, consider this program, which contains the single error of capitalizing the word For:
public class CaseApp { public static void main(String[] args) { For (int i = 0; i<5; i++) System.out.println("Hi"); } }
When you try to compile this program with Java 1.6, the compiler generates a total of four error messages for this one mistake:
C:Java AIOCaseApp.java:5: '.class' expected For (int i = 0; i<5; i++) ^ C:Java AIOCaseApp.java:5: illegal start of type For (int i = 0; i<5; i++) ^ C:Java AIOCaseApp.java:5: not a statement For (int i = 0; i<5; i++) ^ C:Java AIOCaseApp.java:5: ';' expected For (int i = 0; i<5; i++) ^ 4 errors For (int i = 0; i<5; i++)
Even though this single mistake generates four error messages, not one of the messages actually points to the problem. The little arrow beneath the source line indicates what part of the line is in error, and none of these error messages have the arrow pointing anywhere near the word For! The compiler isn't smart enough to realize that you meant for instead of For. So it treats For as a legitimate identifier, and then complains about everything else on the line that follows it. It would be much more helpful if it generated an error message like this:
C:Java AIOCaseApp.java:5: 'For' is not a keyword For (int i = 0; i<5; i++) ^
The moral of the story is that keywords are case-sensitive, and if your program won't compile and the error messages don't make any sense, check for keywords that you've mistakenly capitalized.
Like most programming languages, Java uses statements to build programs. Unlike most programming languages, Java doesn't use statements as its fundamental unit of code. Instead, it gives that honor to the class. However, every class must have a body, and the body of a class is made up of one or more statements. In other words, you can't have a meaningful Java program without at least one statement. The following sections describe the ins and outs of working with Java statements.
Java has many different types of statements. Some statements simply create variables that you can use to store data. These types of statements are often called declaration statements, and tend to look like this:
int i; String s = "This is a string"; Customer c = new Customer();
Another common type of statement is an expression statement, which performs calculations. Here are some examples of expression statements:
i = a + b; salesTax = invoiceTotal * taxRate; System.out.println("Hello, World!");
Notice that the last statement in this group is the same as line 5 in Listing 1-1. Thus, the single statement in the HelloApp program is an expression statement.
There are many other kinds of statements besides these two. For example, if-then statements execute other statements only if a particular condition has been met. And statements such as for, while, or do execute whole groups of statements one or more times.
Tip |
It's often said that every Java statement must end with a semicolon. Actually, this isn't quite true. Some types of Java statements must end with semicolons-but others don't have to. The basic rule is that declaration and expression statements must end with a semicolon, but most other statement types do not. Where this rule gets tricky, however, is that most other types of statements include one or more declaration or expression statements that do use semicolons. For example, here's a typical if statement: |
if (total > 100) discountPercent = 10;
Here the variable named discountPercent is given a value of 10 if the value of the total variable is greater than 100. The expression statement ends with semicolons, but the if statement itself doesn't. (The Java compiler lets you know if you use a semicolon when you shouldn't.)
In Java, the term white space refers to one or more consecutive space characters, tab characters, or line breaks. All white space is considered the same. In other words, a single space is treated the same as a tab or line break or any combination of spaces, tabs, or line breaks.
If you've programmed in Visual Basic, white space is different from what you're used to. In Visual Basic, line breaks mark the end of statements unless special continuation characters are used. In Java, you don't have to do anything special to continue a statement onto a second line. Thus the statement
x = (y + 5) / z;
is identical to this statement:
x = (y + 5) / z;
In fact, you could write the above statement like this if you wanted:
x = ( y + 5 ) / z ;
I wouldn't advise it, but the statement does compile and execute properly.
Tip |
Using white space liberally in your programs is a good idea. In particular, you should routinely use line breaks to place each statement on a separate line-and use tabs to line up elements that belong together. The compiler ignores the extra white space, so it doesn't affect the bytecode that's created for your program. As a result, using extra white space in your program doesn't affect your program's performance in any way, but it does make the program's source code easier to read. |
A block is a group of one or more statements that's enclosed in braces. A block begins with an opening brace ({) and ends with a closing brace (}). Between the opening and closing braces, you can code one or more statements. For example, here's a block that consists of three statements:
{ int i, j; i = 100; j = 200; }
TECHNICAL STAUFF |
A block is itself a type of statement. As a result, any time the Java language requires a statement, you can substitute a block to execute more than one statement. For example, in Book II, Chapter 4, you discover that the basic syntax of an if statement is this: if (expression) statement |
Here the statement can be a single statement or a block. If you find this idea confusing, don't worry. It will make more sense when you turn to Book II, Chapter 4.
Tip |
You can code the braces that mark a block in two popular ways. One is to place both braces on separate lines, and then indent the statements that make up the block. For example: |
if (i > 0) { String s = "The value of i is " + i; System.out.print(s); }
The other style is to place the opening brace for the block on the same line as the statement the block is associated with, like this:
if (i > 0) { String s = "The value of i is " + i; System.out.print(s); }
Which style you use is a matter of personal preference. I prefer the first style, and that's the style I use throughout this book. But either style works-and many programmers prefer the second style because it's more concise.
An identifier is a word that you make up to refer to a Java programming element by name. Although you can assign identifiers to many different types of Java elements, they're most commonly used for the following elements:
TECHNICAL STAUFF |
Identifiers are also sometimes called names. Strictly speaking, a name isn't quite the same thing as an identifier; a name is often made up of two or more identifiers connected with periods (called dots). For example, in line 5 of Listing 1-1, System and out are both identifiers. But System.out is a name. In practice, the terms name and identifier are used interchangeably. |
You must follow a few simple rules when you create identifiers:
Tip |
The Java language specification recommends that you avoid using dollar signs in names you create. Instead, dollar signs are used by code generators to create identifiers. Thus avoiding dollar signs helps you avoid creating names that conflict with generated names. |
A comment is a bit of text that provides explanations of your code. Comments are completely ignored by the compiler, so you can place any text you wish in a comment. Using plenty of comments in your programs is a good idea to explain what your program does and how it works.
Java has three basic types of comments: end-of-line comments, traditional comments, and JavaDoc comments. More about that coming right up.
An end-of-line comment begins with the sequence // and ends at the end of the line. You can place an end-of-line comment at the end of any line. Everything you type after the // is ignored by the compiler. For example:
total = total * discountPercent; // calculate the discounted total
If you want, you can also place end-of-line comments on separate lines, like this:
// calculate the discounted total total = total * discountPercent;
You can place end-of-line comments in the middle of statements that span two or more lines. For example:
total = (total * discountPercent) // apply the discount first + salesTax; // then add the sales tax
A traditional comment begins with the sequence /* and ends with the sequence */ and can span multiple lines. Here's an example:
/* HelloApp sample program. This program demonstrates the basic structure that all Java programs must follow. */
A traditional comment can begin and end anywhere on a line. If you want, you can even sandwich a comment between other Java programming elements, like this:
x = (y + /* a strange place for a comment */ 5) / z;
Usually traditional comments appear on separate lines. One common use for traditional comments is to place a block of comment lines at the beginning of a class to indicate information about the class-such as what the class does, who wrote it, and so on. However, that type of comment is usually better coded as a JavaDoc comment, as described in the next section.
Warning |
You may be tempted to temporarily comment out a range of lines by placing /* in front of the first line in the range and */ after the last line in the range. However, that can get you in trouble if the range of lines you try to comment out includes a traditional comment. That's because traditional comments can't be nested. For example, the following code won't compile: |
/* int x, y, z; y = 10; z = 5; x = (y + /* a strange place for a comment */ 5) / z; */
Here I tried to comment out a range of lines that already included a traditional comment. Unfortunately, the */ sequence near the end of the fifth line is interpreted as the end of the traditional comment that begins in the first line. Then, when the compiler encounters the */ sequence in line 6, it generates an error message.
JavaDoc comments are actually a special type of traditional comment that you can use to create Web-based documentation for your programs-automatically. Because you'll have a better appreciation of JavaDoc comments when you know more about object-oriented programming, I devote a section in Book III, Chapter 8 to creating and using JavaDoc comments.
Having presented some of the most basic elements of the Java programming language, most Java books would next turn to the important topics of variables and data types. However, because Java is an inherently object-oriented programming language, and classes are the heart of object-oriented programming, I look next at classes to explore the important role they play in creating objects. I get to variables and data types first thing in the next chapter.
As I've already mentioned, a class is code that defines the behavior of a Java programming element called an object. An object is an entity that has both state and behavior. The state of an object consists of any data that the object might be keeping track of, and the behavior consists of actions that the object can perform. The behaviors are represented in the class by one or more methods that can be called upon to perform actions.
The difference between a class and an object is similar to the difference between a blueprint and a house. A blueprint is a plan for a house. A house is an implementation of a blueprint. One set of blueprints can be used to build many houses. Likewise, a class is a plan for an object, and an object is-in Java terms-an instance of a class. You can use a single class to create more than one object.
When an object is created, Java sets aside an area of computer memory that's sufficient to hold all the data that's stored by the object. As a result, each instance of a class has its own data, independent of the data used by other instances of the same class.
You don't necessarily have to create an instance of a class to use the methods of the class. If a method is declared with the static keyword, the method can be called without first creating an instance of the class. That's because static methods are called from classes, not from objects.
The main method of a Java application must be declared with the static keyword. That's because when you start a Java program by using the java command from a command prompt, Java doesn't create an instance of the application class. Instead, it simply calls the program's static main method.
The difference between static and non-static methods will become more apparent when you look at object-oriented programming in more depth in Book III. But for now, consider this analogy. The blueprints for a house include the details about systems that actually perform work in a finished house, such as electrical and plumbing systems. In order to use those systems, you have to actually build a house. In other words, you can't turn on the hot water by using the blueprint alone; you have to have an actual house with an actual device to heat the water.
However, the blueprints do include detailed measurements of the dimensions of the house. As a result, you can use the blueprints to determine the square footage of the living room. Now imagine that the blueprints actually had a built-in calculator that would display the size of the living room if you pushed the "Living Room" button. That button would be like a static method in a class: You don't actually have to build a house to use the button; you can activate it from the blueprints alone.
Many Java programs-in fact, many of the programs in the rest of Book II-are entirely made up of static methods. However, most realistic programs require that you create one or more objects that the program uses as it executes. As a result, learning how to create simple classes and how to create objects from those classes are basic skills in Java programming.
In Java, you can create an object from a class in several ways. But the most straightforward is to create a variable that provides a name you can use to refer to the object, use the new keyword to create an instance of the class, and then assign the resulting object to the variable. The general form of a statement that does that bit of magic looks like this:
ClassName variableName = new ClassName();
For example, to create an object instance of a class named Class1 and assign it to a variable named myClass1Object, you would write a statement like this:
Class1 myClass1Object = new Class1();
Why do you have to list the class name twice? The first time, you're providing a type for the variable. In other words, you're saying that the variable you're creating here can be used to hold objects created from the Class1 class. The second time you list the class name, you're creating an object from the class. The new keyword tells Java to create an object, and the class name provides the name of the class to use to create the object.
The equal sign (=) is an assignment operator. It simply says to take the object created by the new keyword and assign it to the variable. Thus, this statement actually does three things:
To give you an early look at what object-oriented programming really looks like, Listings 1-2 and 1-3 show another version of the HelloApp application-this time using two classes, one of which is actually made into an object when the program is run. The first class, named HelloApp2, is shown in Listing 1-2. This class is similar to the HelloApp class shown in Listing 1-1. However, it uses an object created from the second class, named Greeter, to actually display the “Hello, World!” message on the console. The Greeter class is shown in Listing 1-3. It defines a method named sayHello that displays the message.
REMEMBER |
Both the HelloApp and the Greeter classes are public classes. Java requires that each public class be stored in a separate file, with the same name as the class and the extension .java. As a result, the HelloApp2 class is stored in a file named HelloApp2.java, and the Greeter class is stored in a file named Greeter.java. |
The HelloApp2 class
The HelloApp2 class is shown in Listing 1-2.
Listing 1-2: The HelloApp2 Class
// This application displays a hello message on → 1 // the console by creating an instance of the // Greeter class, then calling the Greeter // object's sayHello method. public class HelloApp2 → 6 { public static void main(String[] args) → 8 { Greeter myGreeterObject = new Greeter(); → 10 myGreeterObject.sayHello(); → 11 } }
The following paragraphs describe the key points:
→ 1 |
This class begins with a series of comment lines that identify the function of the program. For these comments, I used simple end-of-line comments rather than traditional comments. (For more on commenting, see the "Crafting Comments" section, earlier in this chapter.) |
→ 6 |
The HelloApp2 class begins on line 6 with the public class declaration. Because the public keyword is used, a file named HelloApp2.java must contain this class. |
→ 8 |
The main method is declared using the same form as the main method in the first version of this program (Listing 1-1). Get used to this form because all Java applications must include a main method that's declared in this way. |
→ 10 |
The first line in the body of the main method creates a variable named myGreeterObject that can hold objects created from the Greeter class. Then it creates a new object using the Greeter class and assigns this object to the myGreeterObject variable. |
→ 11 |
The second line in the body of the main method calls the myGreeterObject object's sayHello method. As you'll see in a moment, this method simply displays the message “Hello, World!” on the console. |
Open table as spreadsheet
The Greeter class
The Greeter class is shown in Listing 1-3.
Listing 1-3: The Greeter Class
// This class creates a Greeter object → 1 // that displays a hello message on // the console. public class Greeter → 5 { public void sayHello() → 7 { System.out.println("Hello, World!"); → 9 } }
The following paragraphs describe the key points:
→ 1 |
This class also begins with a series of comment lines that identify the function of the program. |
→ 5 |
The class declaration begins on this line. The class is declared as public so other classes can use it. This declaration is required so that the HelloApp2 class can access the Greeter class. |
→ 7 |
The sayHello method is declared using the public keyword so that it's available to other classes that use the Greeter class. The void keyword indicates that this method doesn't provide any data back to the class that calls it, and sayHello simply provides the name of the method. |
→ 9 |
The body of this method consists of just one line of code that displays the “Hello, World!” message on the console. |
Open table as spreadsheet
You might notice that the only line that actually does any real work in the HelloApp2 program is line 9 in the Greeter class (Listing 1-3), and this line happens to be identical to line 5 in the original HelloApp class (Listing 1-1). Other than the fact that the second version requires roughly twice as much code as the first version, what really is the difference between these two applications?
Simply put, the first version is procedural, and the second is object-oriented. In the first version of the program, the main method of the application class does all the work of the application by itself: It just says hello. The second version defines a class that knows how to say hello to the world, and then creates an object from that class and asks that object to say hello. The application itself doesn't know (or even care) exactly how the Greeter object says hello. It doesn't know exactly what the greeting will be, what language the greeting will be in, or even how the greeting will be displayed.
To illustrate this point, consider what would happen if you used the Greeter class shown in Listing 1-4 rather than the one shown in Listing 1-3. This version of the Greeter class uses a Java library class called JOptionPane to display a message in a dialog box rather than in a console window. (I won't bother explaining how this code works, but you can find out more about it in the next chapter.) If you were to run the HelloApp2 application using this version of the Greeter class, you'd get the dialog box shown in Figure 1-1.
Figure 1-1: The class in Listing 1-4 displays this dialog box.
Listing 1-4: Another Version of the Greeter Class
// This class creates a Greeter object // that displays a hello message // in a dialog box. import javax. swing. JOptionPane; → 5 public class Greeter { public void sayHello() { JOptionPane.showMessageDialog(null, → 11 "Hello, World!", "Greeter", JOptionPane.INFORMATION_MESSAGE); } }
The important point to realize here is that the HelloApp2 class doesn't have to be changed to use this new version of the Greeter class. Instead, all you have to do is replace the old Greeter class with the new one, and the HelloApp2 class won't know the difference. That's one of the main benefits of object-oriented programming.
You may have noticed that the Greeter class in Listing 1-4 includes this statement:
import javax.swing.JOptionPane;
The purpose of the import statement is to let the compiler know that the program is using a class that's defined by the Java API called JOptionPane.
Because the Java API contains literally thousands of classes, some form of organization is needed to make the classes easier to access. Java does this by grouping classes into manageable groups called packages. In the previous example, the package that contains the JOptionPane class is named javax.swing.
Strictly speaking, import statements are never required. But if you don't use import statements to import the API classes your program uses, you must fully qualify the names of the classes when you use them by listing the package name in front of the class name. So, if the class in Listing 1-4 didn't include the import statement in line 5, you'd have to code line 11 like this:
javax.swing.JOptionPane.showMessageDialog(null, "Hello, World!", "Greeter", javax.swing.JOptionPane.INFORMATION_MESSAGE);
In other words, you'd have to specify javax.swing.JOptionPane instead of just JOptionPane whenever you referred to this class.
Tip |
Here are some additional rules for working with import statements:
|
Book I - Java Basics
Book II - Programming Basics
Book III - Object-Oriented Programming
Book IV - Strings, Arrays, and Collections
Book V - Programming Techniques
Book VI - Swing
Book VII - Web Programming
Book VIII - Files and Databases
Book IX - Fun and Games