Java 7 for Absolute Beginners

(nextflipdebug5) #1

C H A P T E R 2


15

Java Syntax


The syntax of any language is the rules that any speaker of the language follows so that other speakers of
that language can understand. In other words, syntax is a set of rules that all the speakers of a language
agree to follow so that they can communicate. If you violate the rules, people listening to you are either
going to ask, “Huh? What?” or think you're being silly (which might be appropriate in some settings but
will often cause a problem).
Computer languages work in much the same way, except that they're never spoken (though I won't
be surprised to see, or should I say hear, oral programming languages someday). If you decide to do your
own thing, don't be surprised when your computer doesn't do what you had in mind. If you fail to code
clearly and follow the rules of your programming language, all you'll get is confusion, though your
computer will generate error messages rather than say, “Huh? What?”
Java gets most of its syntax from another language called C++. C++ in turn gets most of its syntax
from C. And C was influenced by other languages. The people who created Java chose C++ as the basis
for Java's syntax because C++ was one of the most widely used languages at the time, and that gave many
developers some familiarity with Java syntax. Java's success (it's now widely used) depends on many
factors, but adopting an already widely known syntax certainly didn't hurt.

An Example


I created two classes and an interface that together demonstrate almost all of Java's syntax. We learned
in Chapter 1 that a class is a bit of code that contains other bits of code (which we get to later in this
chapter). An interface is basically a contract; a class that uses an interface must do all the things
specified by the interface. (In proper Java terms, a class that implements an interface must implement
all the methods specified by the interface)I might have missed some obscure bits, but understanding this
much syntax serves you well for a long time. We refer to these three listings throughout the rest of the
chapter. If the listings seem long, don't let that bother you. For now, just read through them. As we work
through this chapter, come back to these three listings and things should become clearer. Let's start with
an interface, as shown in Listing 2-1.

Listing 2-1. The Average interface

package com.apress.java7forabsolutebeginners.syntaxExample;

public interface Average {

public int[] getInts();

Java 7 for Absolute Beginners
© Jay Bryant 2012


J. Bryant,

Free download pdf