The ABCs of Java
A Java program is made up of classes and objects, which in turn are made up of methods and variables. Methods are made up of statements and expressions, which are made up of operators.
At this point, you might be afraid that Java is like the Russian nesting dolls called matryoshka. Every one of those dolls seems to have a smaller doll inside it, which is as intricate and detailed as its larger companion.
This chapter clears away the big dolls to reveal the smallest elements of Java programming. You'll leave classes, objects, and methods alone for a day and examine the basic things you can do in a single line of Java code.
The following subjects are covered:
Java statements and expressions
Variables and data types
Constants
Comments
Literals
Arithmetic
Comparisons
Logical operators
NOTE
Because of Java's ties to C and C++, much of the material in this chapter will look familiar to programmers who are well versed in those languages.
Statements and Expressions
All tasks that you want to accomplish in a Java program can be broken down into a series of statements.
New Term
A statement is a simple command written in a programming language that causes something to happen.
Statements represent a single action that is taken in a Java program. All of the following are simple Java statements:
int weight = 295; System.out.println("Free the bound periodicals!"); song.duration = 230;
Some statements can convey a value, such as when you add two numbers together in a program or evaluate whether two variables are equal to each other. These kinds of statements are called expressions.
New Term
An expression is a statement that results in a value being produced. The value can be stored for later use in the program, used immediately in another statement, or disregarded. The value produced by a statement is called its return value.
Some expressions produce a numerical return value, as in the example of adding two numbers together. Others produce a Boolean value—true or false—or can even produce a Java object. They are discussed later today.
Although many Java programs list one statement per line, this is a formatting decision that does not determine where one statement ends and another one begins. Each statement in Java is terminated with a semicolon character (;). A programmer can put more than one statement on a line and it will compile successfully, as in the following example:
dante.speed = 2; dante.temperature = 510;
Statements in Java are grouped using the opening curly brace ({) and closing curly brace (}). A group of statements organized between these characters is called a block or block statement, and you learn more about them during Day 5, "Lists, Logic, and Loops."