Elements of Programming
24
Program 2.1.1 Hello, World
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println(Hello, World);
}
}
This code is a complete Java program
that accomplishes a simple task
(printing a message on the terminal
window). It is traditionally a beginning programmers first program .
% javac HelloWorld
% java HelloWorld
Hello, World
cuted, one by one, when the method is invoked. One type of statement is a
method name with, in parentheses, zero or more arguments. When we write
a such a statement, we are simply saying that we want to run that method
(and to provide it with some information, in the arguments). This process is
known as invoking or calling the method. In HelloWorld, the main method
consists of a single statement that calls the Java library method System.out.println(). The name of the method is println(); the name of
the library is System.out. You will be writing programs that use calls to many
different Java library methods, and you refer to each of them in just this way.
In Program 2.1.1, System.out.println() takes the message Hello, World
as its argument and prints it to the terminal. We do not need to know the
details of how System.out.println() accomplishes this taskwe can simply rely on it to do so. The method main() itself takes an argument, which we
will discuss soon as the focus of Program 2.1.2.
At first, accomplishing the task of printing something out in a terminal window might not seem very interesting; upon reflection, you will see
that one of the most basic capabilities that we need from a program is for it to
be able to tell us what it is doing.
For the time being, all our program code will be just like
Program 2.1.1, except with a different sequence of statements in main(). We
AN INTRODUCTION TO COMPUTER SCIENCE
Your First Program
will develop a more detailed understand of everything in HelloWorld.java
in due time: for the moment, you do not need to start with a blank page to
write a program, because you can
copy HelloWorld.java into a new file whose name is a new program
name of your choice, followed by .java
replace HelloWorld with the program name on the first line
replace the System.out.println() statement by a sequence of statements (each ending with a semicolon).
Each Java program must reside in a file whose name matches the name after
the word class on the first line and has a .java extension. In the next two
sections, you will learn all kinds of different statements that you can put
together to make a program; for the moment, we will just use System.out.println() and its cousin System.out.print() (which does the
same thing except without starting a new line after printing the message).
Errors. In modern interactive systems like Java, we sometimes blur the
distinction among editing, compiling, and executing programs, but it is
worthwhile to keep them separate in your mind when you are learning to
program. The main reason to do so is to understand the effects of the errors
that inevitably crop up. Several examples of errors are discussed in the Q&A
and the exercises at the end of this section. Most errors are easily fixed by
carefully examining the program as we create it, in just the same way as we fix
spelling and grammatical errors when we type an e-mail message. Some other
errors are caught when we compile the program, because they prevent the
compiler from doing the translation (so it issues an error message that tries to
explain why). Many other errors, called bugs, do not show up until we execute
the program. Errors are the bane of a programmers existence: the compilers
error messages can be confusing or misleading, and bugs can be very hard to
find. One of the very first skills that you will learn is to identify errors; one of
the next will be to be sufficiently careful when coding to avoid many of them.
Program 2.1.2 uses three statements to accomplish a more complicated task than simply printing a message. Whenever this program is executed, it reads the command-line argument that you type after the program
name and prints it back out to the terminal as part of the message. The result
of executing this program depends on what we type after the program name.
25
Elements of Programming
26
Program 2.1.2 Using a command-line argument
public class Hi
{
public static void main(String[] args)
{
System.out.print(Hi, );
System.out.print(args[0]);
System.out.println(. How are you?);
}
}
This program shows the way in which
we can control the actions of our programs: by providing an argument on
the command line. Doing so allows us
to tailor the behavior of our programs.
% javac Hi.java
% java Hi Alice
Hi, Alice. How are you?
% java Hi Bob
Hi, Bob. How are you?
After compiling the program once, we can run it for different command-line
arguments and get different results.
As with your first program, we will discuss in more detail the mechanism that we use to pass arguments to our programs later, in Section X. In
the meantime, you can do so by using args[0] to represent the argument,
just as in Program 2.1.2.
Again, accomplishing the task of getting a program to write back out
what we type in to it may not seem interesting at first, but upon reflection you
will see that another basic capability that we need from a program is for it to
be able to respond to basic information from the user to control what it does.
The simple model that Program 2.1.2 represents will suffice to allow us to
consider Javas basic programming mechanism and to address all sorts of
interesting computational problems. Later, we will consider refinements to
this simple model that incorporate more sophisticated mechanisms for program input and output.
AN INTRODUCTION TO COMPUTER SCIENCE
Your First Program
Stepping back, we can see that
Program 2.1.2 does no more nor no less
than implement a function that maps a
string of characters (the argument) into
another string of characters (the message
printed back to the terminal). When using
black box
it, we might think of our Java program as a
black box that converts our input string to
some output string. This model is attractive because it is very simple, but also sufHi, Alice.
output string ficiently general to allow completion of
How are you?
any computational task. For example, the
A birds-eye view of a Java program Java compiler itself is nothing more than a
program that takes one string of characters as input (a .java file) and produces another string of characters as output (the corresponding .class file). While we stop short of programs quite
that complicated, we will be able to consider and to write programs that
accomplish a variety of interesting tasks.
Alice
input string
Q&A
Q Why Java?
A The programs that we are writing are very similar to their counterparts in
several other languages, so our choice of language is not crucial.. We use Java
because it is widely available, embraces a full set of modern abstractions, and
has a variety of automatic checks for mistakes in programs, so it is suitable for
learning to program. There is no perfect language, and you certainly will find
yourself programming in other languages in the future.
Q What are Javas rules regarding tabs, spaces and newline characters?
A There are not many. Java translators treat them all to be equivalent. For
example, we could also write Program 2.1.1 as follows:
public class HelloWorld { public static void main (String[]
args) {System.out.println(Hello, World);}}
27
Elements of Programming
28
But we do normally adhere to spacing and indenting conventions when we
write Java programs, just as we always indent paragraphs and lines consistently when we write prose or poetry.
Q What are the rules regarding quotation marks?
A Material inside quotation marks is an exception to the rule of the previous
question: things within quotes have to be taken literally so that you can
precisely specify what gets printed out. If you put any number of successive
spaces within the quotes, you get that number of spaces in the output. If you
accidentally omit a quotation mark, the compiler may get very confused,
because it needs that mark to know the difference between characters in the
string you are defining and you program itself.
Q How do I print out a quotation mark, a newline, or a tab?
A Use \, \n, or \t, respectively, within the quotation marks.
Q What happens when you omit a brace or misspell one of the words, like
public or static or main?
A It depends upon precisely what you do. Such errors are called syntax errors
and are usually caught by the compiler. But the compiler may not be able to
tell you exactly what mistake you made (for a profound reason that we will
discuss in Chapter 8), so it might print an error message that is hard to
understand. For example, if you make a program Bad.java that is exactly the
same as Program 2.1.1 except that you omit the first left brace (and change
the program name from HelloWorld to Bad), you get the following helpful
message:
% javac Bad.java
Bad.java:1: '{' expected
public class Bad
^
1 error
From this message, you might correctly surmise that you need to insert a left
brace. But if you omit only the second left brace, you get a less helpful
sequence of messages:
AN INTRODUCTION TO COMPUTER SCIENCE
Your First Program
29
Bad.java:3: ';' expected
public static void main(String[] args)
^
Bad.java:6: 'class' or 'interface' expected
}
^
Bad.java:7: 'class' or 'interface' expected
^
Bad.java:3: missing method body, or declare abstract
public static void main(String[] args)
^
4 errors
One way to get used to such messages is to intentionally introduce mistakes
into a simple program, then see what happens. Whatever the error message
says, you should treat the compiler as a friend, for it is just trying to tell you
that something is wrong with your program.
Q Can a program use more than one command-line argument?
A Yes, you can put several, though we normally use only a few. You refer to
the second one as args[1], the third one as args[2], and so forth.
Q Do I really have to type in the programs in the book to try them out?
A No, you can find them on the web site
http://www.cs.princeton.edu/IntroCS
which we refer to as the booksite. This site also has information about installing and running Java on your computer, answers to some exercises, web
links, and other extra information that you might find useful or interesting.
For example, the booksite describes how to annotate code with comments, by
enclosing the comment in between /* and */ or by putting the comment at
the end of any line after //. We do not use comments in the book because the
text describes the code.
Elements of Programming
30
Exercises
2.1.1 Write a program that prints the Hello,
World message 10 times.
2.1.2 Describe what happens if, in HelloWorld.java, you omit
a
public
static
void
args
2.1.3 Describe what happens if, in
HelloWorld.java,
you misspell (by,
say, omitting the second letter)
a
public
static
void
args
2.1.4 Describe what happens if you try to execute Program 2.1.2 with
a
java Hi
java Hi @!&^%
java Hi 1234
java Hi.class Bob
java Hi.java Bob
java Hi Alice Bob
2.1.5 Modify Hi.java to make a program HiThree.java that takes three
names and prints out a proper sentence with the names in the reverse of
the order given, so that, for example, java HiThree Alice Bob Carol
gives Hi Carol, Bob, and Alice.
AN INTRODUCTION TO COMPUTER SCIENCE
Primitive Types of Data
2.1
Primitive Types of Data
A data type is a set of values and a set of operations defined on them. For
example, we are familiar with numbers and with operations defined on them
such as addition and multiplication. In mathematics, we are accustomed to
thinking of the set of numbers as being infinite; in computer programs we have
to work with a finite number of possibilities. In Java, you must always be
aware of the type of the data that your program is processing.
There are eight different built-in types of data (called primitive types)
in Java, mostly for different kinds of numbers. Of the eight primitive types,
we most often use three: int for integers; double for real numbers; and
boolean for true-false values. There are other types of data (called system
types) available in Java libraries: for example, the only type used in the programs in Section 2.1 is the system type String for strings of characters. We
consider the String type in this section because its usage for input and output is essential. Accordingly, it shares some characteristics of the primitive
types: for example, some of its operations are built in to the Java language.
Beyond primitive types and system types, we can build our own data types:
indeed, programming in Java is often centered around doing so, as we shall
see in Chapter 3.
After defining some basic terms, we will consider several sample programs that illustrate use of different types of data. These programs still do not
do much real computing, but understanding types is an essential step in
beginning to program and sets the stage for us to begin working with more
intricate programs in the next section.
Basic definitions. To talk about data types, we need to define a number of
terms, which are illustrated in the following simple four-statement Java program fragment:
int
a =
b =
c =
a, b, c;
1234;
99;
a + b;
The first statement is a declaration that declares three variables with the identifiers a, b, and c to be of type int. The next three statements are assignment
21
22
statements that change the values of the variables, using the literals 1234 and
99, with the end result that c has the value 1243.
Identifiers. We use identifiers to name variables (and many other things) in
Java. An identifier is a sequence of letters, digits, _ and $, the first of which is
not a digit. The sequences of characters abc, Ab$, abc123, and a_b are all
legal Java identifiers, but Ab*, 1abc, and a+b are not.
Literals. For each of the primitive data types, Java defines ways to specify its
values. To specify an integer, we use a string of digits like 1234 or 99 to define
int literal values. To specify a real number, we add a decimal point as in
3.14159 or 2.71828 to define double literal values. To specify a boolean
value, we use the keywords true or false. We will consider other literals as
we consider each type in more detail.
Variables. A variable is an instance of a data type. We create one by declaring
its type and giving it a name; we compute with it by using the name in an
expression that uses operations defined for its type. Each variable has one of
the data-type values.
Declarations. We always use declarations to specify the names and types of
variables in our programs. By doing so, we are being explicit about any computation that we are specifying. The Java compiler checks for consistency (for
example, it does not make sense to multiply a String by a double) and translates to the appropriate machine code.
Assignment statements. When we write a = b + c in Java, we are not expressing mathematical equality, but are instead expressing an action: set the value
of the variable a to be the value of b plus the value of c. It is true that a is
mathematically equal to b + c after the assignment statement has been executed, but the point of the statement is to change the value of a (if necessary).
The left-hand side of an assignment statement must be a single variable
(identifier); the right-hand side can be an arbitrary expression that uses operators defined for the type. For example, we can say discriminant = b*b 4*a*c in Java, but we do not say a + b = b + a or 1 = a , and a = b is
certainly not the same as b = a.
AN INTRODUCTION TO COMPUTER SCIENCE
Primitive Types of Data
Expressions. We can use parentheses to specify compound operations to
compute a value just as in mathematical formulas. For example, we can write
(x + 1) * (x + 1) or x*x + 2*x + 1 on the right-hand side of an assignment statement and the compiler will understand what we mean. An expression is shorthand for specifying a sequence of computations: in what order
should they be performed? Java has natural and well-defined precedence rules
(see Appendix X) that fully specify this order. For arithmetic operations,
multiplication and division are performed before addition and subtraction.
When the precedence rules do not lead to the computation that you want,
you can use parentheses.
Functions. Some methods implement functionsthey use their arguments to
compute a value of a specified type. Besides variables and literals, we can use
method names (with arguments) in expressions, when we do so, we are
expecting that method to compute a value of the appropriate type. Method
arguments may also be expressions. Many familiar functions are implemented in Javas Math libarary (see Appendix X). Thus, we can write expressions like Math.sin(x)*Math.cos(y) and so on.
For economy, we can combine a declaration with an assignment
statement to provide an initial value for the variable (otherwise, the value is
undefined). Declarations can appear anywhere in a program before a variable
is usedmost often, we put them at the point of first use, as in this version of
the program fragment that we started with.
int a = 1234;
int b = 99;
int c = a + b;
In older programming languages, it was required that all declarations appear
at the beginning of a piece of code, and it is legal to do so in Java. We sometimes use this convention in small programs with multiple variables (for an
example, see Program 2.1.2), but most often we put declarations at the point
of first use.
To understand how to use a primitive data type, you need to know its
defined set of values, which operations you can perform, and how to specify
literals. Next, we consider these details for characters, strings, integers, float-
23
24
ing point numbers, and truefalse values, along with sample programs that
illustrate their use.
Characters and Strings. A char is an alphanumeric character or symbol,
16
like the ones that you type. There are 2 different possible character values,
but we usually restrict attention to the ones that represent letters, numbers,
symbols, and white-space characters like tab and newline. To specify a character as a char literal, we enclose it in single quotes: 'a' represents the
letter a. For tab, newline, single quote and double quote, we use the special
escape sequences \t, \n, \', and \", respectively. The characters are encoded
as 16-bit integers using an encoding scheme known as Unicode, and there are
escape sequences for specifying any special character (see Appendix X). We
usually do not perform any operations on characters other than assigning
values to variables and using the comparison functions defined later in this
section, so we move immediately on to other data types.
A String is a sequence of characters. A literal String is a sequence
of characters within double quotes, like "Hello, World". The String data
type is not a primitive type, but Jave sometimes treats it like one. For example,
one of the most common operations that we perform on Strings is built in
to the Java language. That operation is known as concatenation: given two
strings, chain them together to make a new string. The symbol for concatenating strings in Java is + (the same symbol that we use for adding numbers).
For example, the following Java code fragment is like the one that we considered at the beginning of this section, but it uses Strings instead of ints:
String a, b, c;
a = "1234";
b = "99";
c = a + b;
As before, the first statement declares three variables to be of type String and
the next three assign values to them. In this case, the end result that c has the
value "123499".
We use the concatenation operation frequently to put together
results of computation in output. For example we could make Program 2.1.2
much simpler by replacing its three statements by this single statement:
AN INTRODUCTION TO COMPUTER SCIENCE