Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^42) | Java Syntax and Semantics, Classes, and Objects


2.1 The Elements of Java Programs


In this section we examine in turn each of the components that are needed to write a pro-
gram that can perform simple actions, including input and output. In Section 2.2 we see how
to assemble these components into a complete program.

Syntax and Semantics


A programming language is a set of rules, symbols, and special words used to construct a pro-
gram. Rules apply to both syntax(grammar) and semantics(meaning).
Syntax is a formal set of rules that defines exactly which combinations of let-
ters, numbers, and symbols can be used in a programming language. The syntax
of a programming language leaves no room for ambiguity because the computer
can’t think; it doesn’t “know what we mean.” To avoid ambiguity, syntax rules
themselves must be written in a very simple, precise, formal language called a
metalanguage.
Learning to read a metalanguage is like learning to read the playbook for a
sport. Once you understand the notation, you can learn the plays that give a team
its competitive edge. It’s true that many people learn a sport simply by watching
others play, but what they learn is usually just enough to allow them to take part
in casual games. You could learn Java by following the examples in this book, but
a serious programmer, like a serious athlete, must take the time to read and un-
derstand the rules and to recognize how they are applied.
Syntax rules are the blueprints we use to “build” instructions in a program.They
allow us to take the elements of a programming language—the basic building blocks
of the language—and assemble them intoconstructs, or syntactically correct structures. If our code
violates any of the rules of the language—by misspelling a crucial word or leaving out an im-
portant comma, for instance—the program is said to havesyntax errorsand cannot compile cor-
rectly until we fix them.

Syntax Templates


The following Theoretical Foundations feature describes notations (called metalanguages)
that have long been used to define the syntax of programming languages. In this book we
write the syntax rules for Java using a metalanguage called a syntax template. A syntax tem-
plate is a generic example of the Java construct being defined. Graphic conventions show
which portions are optional and which can be repeated. A colorword or symbol is written
in the Java construct just as it is in the template. A black word can be replaced by another tem-
plate. A square bracket indicates a set of items from which you can choose.

Syntax The formal rules gov-
erning how valid instructions are
written in a programming
language
Semantics The set of rules that
determines the meaning of in-
structions written in a program-
ming language
Metalanguage A language
that is used to write the syntax
rules for another language
Free download pdf