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 Russian nesting matryoshka dolls. Every one of those dolls seems to have a smaller doll inside it, as intricate and detailed as its larger companion.
Today’s lesson 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 primitive data types
Constants
Comments
Literals
Arithmetic
Comparisons
Logical operators
All tasks that you want to accomplish in a Java program can be broken down into a series of statements. In a programming language, a statement is a simple command that causes something to happen.
Statements represent a single action taken in a Java program. All the following are simple Java statements:
int weight = 225; 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. This kind of statement is called an expression.
An expression is a statement that produces a value. 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 when two numbers are added together or multiplied. Others produce a Boolean value—true
or false
—or even can produce a Java object. They are discussed later today.
Although many Java programs contain 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 brace ({
) and closing brace (}
). A group of statements organized between these characters is called a block or block statement, and you learn more about them during Day 4, “Lists, Logic, and Loops.”
In the VolcanoRobot
application you created during Day 1, “Getting Started with Java,” you used variables to keep track of information. A variable is a place where information can be stored while a program is running. The value can be changed at any point in the program—hence the name.
To create a variable, you must give it a name and identify what type of information it will store. You also can give a variable an initial value at the same time you create it.
There are three kinds of variables in Java: instance variables, class variables, and local variables.
Instance variables, as you learned yesterday, are used to define an object’s attributes.
Class variables define the attributes of an entire class of objects and apply to all instances of it.
Local variables are used inside method definitions or even smaller blocks of statements within a method. You can use them only while the method or block is being executed by the Java interpreter. They cease to exist afterward.
Although all three kinds of variables are created in much the same way, class and instance variables are used in a different manner than local variables. You will learn about local variables today and explore instance and class variables during Day 3, “Working with Objects.”
Unlike other languages, Java does not have global variables, variables that can be used in all parts of a program. Instance and class variables communicate information from one object to another, so they replace the need for global variables.
Before you can use a variable in a Java program, you must create the variable by declaring its name and the type of information it will store. The type of information is listed first, followed by the name of the variable. The following are all examples of variable declarations:
int loanLength; String message; boolean gameOver;
You learn about variable data types later today. In these examples, the int
type represents integers, String
is an object that holds text, and boolean
is used for Boolean true/false values.
Local variables can be declared at any place inside a method, just like any other Java statement, but they must be declared before they can be used. The normal place for variable declarations is immediately after the statement that names and identifies the method.
In the following example, three variables are declared at the top of a program’s main()
method:
public static void main(String[] arguments) { int total; String reportTitle; boolean active; }
If you are creating several variables of the same type, you can declare all of them in the same statement by separating the variable names with commas. The following statement creates three String
variables named street
, city
, and state:
String street, city, state;
Variables can be assigned a value when they are created by using an equal sign (=
) followed by the value. The following statements create new variables and give them initial values:
int zipCode = 90210; int box = 350; boolean pbs = true; String name = "Zoom", city = "Boston", state = "MA";
As the last statement indicates, you can assign values to multiple variables of the same type by using commas to separate them.
You must give values to local variables before you use them in a program or the program won’t compile successfully. For this reason, it is good practice to give initial values to all local variables.
Instance and class variable definitions are given an initial value depending on the type of information they hold, as in the following:
Numeric variables: 0
Characters: ' '
Booleans: false
Objects: null
Variable names in Java must start with a letter, an underscore character (“_”), or a dollar sign (“$”). They cannot start with a number. After the first character, variable names can include any combination of letters or numbers.
In addition, the Java language uses the Unicode character set, which includes thousands of character sets to represent international alphabets. Accented characters and other symbols can be used in variable names as long as they have a Unicode character number.
When naming a variable and using it in a program, it’s important to remember that Java is case sensitive—the capitalization of letters must be consistent. Because of this, a program can have a variable named X
and another named x
(and Rose
is not a rose
is not a ROSE
).
In programs in this book and elsewhere, Java variables are given meaningful names that include several words joined together. To make it easier to spot the words, the following rule of thumb is used:
The first letter of the variable name is lowercase.
Each successive word in the variable name begins with a capital letter.
All other letters are lowercase.
The following variable declarations follow this rule of naming:
Button loadFile; int localAreaCode; boolean quitGame;
In addition to a name, a variable declaration must include the data type of information being stored. The type can be any of the following:
One of the primitive data types
The name of a class or interface
An array
You learn how to declare and use array variables on Day 4. Today’s lesson focuses on the other variable types.
There are eight basic data types for the storage of integers, floating-point numbers, characters, and Boolean values. These often are called primitive types because they are built-in parts of the Java language rather than objects, which makes them more efficient to use. These data types have the same size and characteristics no matter what operating system and platform you’re on, unlike some data types in other programming languages.
There are four data types you can use to store integers. Which one you use depends on the size of the integer, as indicated in Table 2.1.
All these types are signed, which means that they can hold either positive or negative numbers. The type used for a variable depends on the range of values it might need to hold. None of these integer variables can reliably store a value that is too large or too small for its designated variable type, so take care when designating the type.
Another type of number that can be stored is a floating-point number, which has the type float
or double
. Floating-point numbers are numbers with a decimal point. The float
type should be sufficient for most uses because it can handle any number from 1.4E-45
to 3.4E+38
. If not, the double
type can be used for more precise numbers ranging from 4.9E-324
to 1.7E+308
.
The char
type is used for individual characters, such as letters, numbers, punctuation, and other symbols.
The last of the eight primitive data types is boolean
. As you have learned, this data type holds either true
or false
in Java.
All these variable types are listed in lowercase, and you must use them as such in programs. There are classes with the same names as some of these data types but with different capitalization—for example, Boolean
and Char
. These have different functionality in a Java program, so you can’t use them interchangeably. Tomorrow you will see how to use these special classes.
In addition to the primitive data types, a variable can have a class as its type, as in the following examples:
String lastName = "Hopper"; Color hair; VolcanoRobot vr;
When a variable has a class as its type, the variable refers to an object of that class or one of its subclasses.
The last statement in the preceding list—VolcanoRobot vr;
—creates a variable named vr
that is reserved for a VolcanoRobot
object. You’ll learn more tomorrow about how to associate objects with variables.
Referring to a superclass as a variable type is useful when the variable might be one of several different subclasses. For example, consider a class hierarchy with a CommandButton
superclass and three subclasses: RadioButton
, CheckboxButton
, and ClickButton
. If you create a CommandButton
variable called widget
, it could refer to a RadioButton
, CheckboxButton
, or ClickButton
object.
Declaring a variable of type Object
means that it can be associated with any kind of object.
After a variable has been declared, a value can be assigned to it with the assignment operator, which is an equal sign (“=”). The following are examples of assignment statements:
idCode = 8675309; accountOverdrawn = false;
Variables are useful when you need to store information that can be changed as a program runs.
If the value should never change during a program’s runtime, you can use a type of variable called a constant. A constant, which also is called a constant variable, is a variable with a value that never changes. This might seem like an oxymoron, given the meaning of the word “variable.”
Constants are useful in defining shared values for the use of all methods of an object. In Java, you can create constants for all kinds of variables: instance, class, and local.
To declare a constant, use the final
keyword before the variable declaration and include an initial value for that variable, as in the following:
final float PI = 3.141592; final boolean DEBUG = false; final int PENALTY = 25;
In the preceding statements, the names of the constants are capitalized: PI
, DEBUG
, and PENALTY
. This is a convention adopted by many Java programmers that makes it clear you’re using a constant instead of a variable.
Constants can be handy for naming various states of an object and then testing for those states. Suppose you have a program that takes directional input from the numeric keypad on the keyboard—push 8 to go up, 4 to go left, and so on. You can define those values as constant integers:
final int LEFT = 4; final int RIGHT = 6; final int UP = 8; final int DOWN = 2;
Constants often make a program easier to understand. To illustrate this point, consider which of the following two statements is more informative as to its function:
guide.direction = 4; guide.direction = LEFT;
Today’s first project is a Java application that creates several variables, assigns them initial values, and displays two of them as output. The full source code is in Listing 2.1.
Example 2.1. The Full Text of Variables.java
1: public class Variables { 2: 3: public static void main(String[] arguments) { 4: final char UP = 'U'; 5: byte initialLevel = 12; 6: short location = 13250; 7: int score = 3500100; 8: boolean newGame = true; 9: 10: System.out.println("Level: " + initialLevel); 11: System.out.println("Up: " + UP); 12: } 13: }
Compile this application and run the class file Variables.class
. This program produces the following output:
Level: 12 Up: U
This class uses four local variables and one constant, making use of System.out.println()
in lines 10–11 to produce output.
System.out.println()
is a method called to display strings and other information to the standard output device, which usually is the screen.
System.out.println()
takes a single argument within its parentheses: a string. To present more than one variable or literal as the argument to println()
, you can use the “+” operator to combine these elements into a single string, which will be described later today.
There’s also a System.out.print()
method, which displays a string without terminating it with a newline character. You can call print()
instead of println()
to display several strings on the same line.
One of the most important ways to improve the readability of your program is to use comments. Comments are information included in a program strictly for the benefit of humans trying to figure out what’s going on in the program. The Java compiler ignores comments entirely when preparing a runnable version of a Java source file.
There are three different kinds of comments you can use in Java programs, and you can use each of them at your discretion.
The first way to add a comment to a program is to precede it with two slash characters (“//”). Everything from the slashes to the end of the line is considered a comment and is disregarded by a Java compiler, as in the following statement:
int creditHours = 3; // set up credit hours for course
If you need to make a comment that takes up more than one line, you can begin it with the text “/*” and end it with the text “*/”. Everything between these two delimiters is considered a comment, as in the following:
/* This program occasionally deletes all files on your hard drive and renders it completely unusable when you press the Save button. */
The final type of comment is meant to be computer-readable as well as human-readable. If you begin a comment with the text “/**” (instead of “/*”) and end it with “*/”, the comment is interpreted to be official documentation on how the class and its methods work.
This kind of comment then can be read by utilities such as the javadoc
tool included with the JDK. The javadoc
program uses official comments to create a set of Hypertext Markup Language (HTML) records that document the program, its class hierarchy, and its methods. More information is available on javadoc
in Appendix B, “Programming with the Java Development Kit.”
All the official documentation on Java’s class library comes from javadoc
-style comments. You can view current Java documentation on the Web at http://java.sun.com/javase/6/docs/api.
In addition to variables, you can work with values as literals in a Java statement. A literal is any number, text, or other information that directly represents a value.
The following assignment statement uses a literal:
int year = 2007;
The literal is 2007 because it directly represents the integer value 2007. Numbers, characters, and strings all are examples of literals.
Although the meaning and usage of literals is intuitive most of the time, Java has some special types of literals that represent different kinds of numbers, characters, strings, and Boolean values.
Java has several integer literals. The number 4, for example, is an integer literal of the int
variable type. It also can be assigned to byte
and short
variables because the number is small enough to fit into those integer types. An integer literal larger than an int
can hold is automatically considered to be of the type long
. You also can indicate that a literal should be a long
integer by adding the letter L (upper- or lowercase) to the number. For example, the following statement treats the value 4
as a long
integer:
pennyTotal = pennyTotal + 4L;
To represent a negative number as a literal, prepend a minus sign (“-”) to the literal—for example, -45.
Java also supports numeric literals that use octal and hexadecimal numbering.
Octal numbers are a base-8 numbering system, which means that they can represent only the values 0 through 7 as a single digit. The eighth number in octal is 10 (or 010 as a Java literal).
Hexadecimal is a base-16 numbering system that can represent each of 16 numbers as a single digit. The letters A through F represent the last six digits, so the first 16 numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
The octal and hexadecimal systems are better suited for certain tasks in programming than the normal decimal system. If you have ever used HTML to set a web page’s background color, you might have used hexadecimal numbers.
If you need to use a literal integer with octal numbering, prepend a 0 to the number. For example, the octal number 777 would be the literal 0777. Hexadecimal integers are used as literals by prepending the number with 0x, as in 0x12 or 0xFF.
Floating-point literals use a period character (“.”) for the decimal point, as you would expect. The following statement uses a literal to set up a double
variable:
double myGPA = 2.25;
All floating-point literals are considered to be of the double
variable type instead of float
. To specify a literal of float
, add the letter F (upper- or lowercase) to the literal, as in the following example:
float piValue = 3.1415927F;
You can use exponents in floating-point literals by using the letter e or E followed by the exponent, which can be a negative number. The following statements use exponential notation:
double x = 12e22; double y = 19E-95;
The Boolean literals true
and false
are the only two values you can use when assigning a value to a boolean
variable type or using a Boolean in a statement.
The following statement sets a boolean
variable:
boolean chosen = true;
If you have programmed in other languages, you might expect that a value of 1
is equivalent to true and 0
is equivalent to false. This isn’t the case in Java; you must use the values true
or false
to represent Boolean values.
Note that the literal true
does not have quotation marks around it. If it did, the Java compiler would assume that it was a string.
Character literals are expressed by a single character surrounded by single quotation marks, such as ‘a’, ‘#’, and ‘3’. You might be familiar with the ASCII character set, which includes 128 characters, including letters, numerals, punctuation, and other characters useful in computing. Java supports thousands of additional characters through the 16-bit Unicode standard.
Some character literals represent characters that are not readily printable or accessible through a keyboard. Table 2.2 lists the special codes that can represent these special characters as well as characters from the Unicode character set. In Table 2.2, the letter d
in the octal, hex, and Unicode escape codes represents a number or a hexadecimal digit (a–f or A–F).
The final literal that you can use in a Java program represents strings of characters. A string in Java is an object rather than a primitive data type. Strings are not stored in arrays as they are in languages such as C.
Because string objects are real objects in Java, methods are available to combine strings, modify strings, and determine whether two strings have the same value.
String literals consist of a series of characters inside double quotation marks, as in the following statements:
String quitMsg = "Are you sure you want to quit?"; String password = "swordfish";
Strings can include the character escape codes listed previously in Table 2.2, as shown here:
String example = "Socrates asked, "Hemlock is poison?""; System.out.println("Sincerely, Millard Fillmore "); String title = "Sams Teach Yourself Ruby on Rails While You Sleepu2122"
In the last of the preceding examples, the Unicode code sequence u2122
produces a ™ symbol on systems that have been configured to support Unicode.
Although Java supports the transmission of Unicode characters, the user’s system also must support it for the characters to be displayed. Unicode support provides a way to encode its characters for systems that support the standard. Java supports the display of any Unicode character that can be represented by a host font.
For more information about Unicode, visit the Unicode Consortium website at http://www.unicode.org.
Although string literals are used in a manner similar to other literals in a program, they are handled differently behind the scenes.
With a string literal, Java stores that value as a String
object. You don’t have to explicitly create a new object, as you must when working with other objects, so they are as easy to work with as primitive data types. Strings are unusual in this respect—none of the basic types are stored as an object when used. You learn more about strings and the String
class later today and tomorrow.
An expression is a statement that can convey a value. Some of the most common expressions are mathematical, such as in the following example:
int x = 3; int y = x; int z = x * y;
All three of these statements can be considered expressions; they convey values that can be assigned to variables. The first assigns the literal 3 to the variable x
. The second assigns the value of the variable x
to the variable y
. In the third expression, the multiplication operator * is used to multiply the x
and y
integers, and the result is stored in the z
integer.
An expression can be any combination of variables, literals, and operators. They also can be method calls because methods can send back a value to the object or class that called the method.
The value conveyed by an expression is called a return value. This value can be assigned to a variable and used in many other ways in your Java programs.
Most of the expressions in Java use operators such as “*”. Operators are special symbols used for mathematical functions, some types of assignment statements, and logical comparisons.
Five operators are used to accomplish basic arithmetic in Java, as shown in Table 2.3.
Each operator takes two operands, one on either side of the operator. The subtraction operator also can be used to negate a single operand, which is equivalent to multiplying that operand by 1.
One thing to be mindful of when performing division is the kind of numbers being used. If you store a division operation into an integer, the result will be truncated to the next lower whole number because the int
data type can’t handle floating-point numbers. As an example, the expression 31 / 9
results in 3 if stored as an integer.
Modulus division, which uses the %
operator, produces the remainder of a division operation. The expression 31 % 9
results in 4 because 31 divided by 9, with the whole number result of 3, leaves a remainder of 4.
Note that many arithmetic operations involving integers produce an int
regardless of the original type of the operands. If you’re working with other numbers, such as floating-point numbers or long
integers, you should make sure that the operands have the same type you’re trying to end up with.
Listing 2.2 contains a class that demonstrates simple arithmetic in Java.
Example 2.2. The Full Text of Weather.java
1: public class Weather { 2: public static void main(String[] arguments) { 3: float fah = 86; 4: System.out.println(fah + " degrees Fahrenheit is ..."); 5: // To convert Fahrenheit into Celsius 6: // Begin by subtracting 32 7: fah = fah - 32; 8: // Divide the answer by 9 9: fah = fah / 9; 10: // Multiply that answer by 5 11: fah = fah * 5; 12: System.out.println(fah + " degrees Celsius "); 13: 14: float cel = 33; 15: System.out.println(cel + " degrees Celsius is ..."); 16: // To convert Fahrenheit into Celsius 17: // Begin by subtracting 9 18: cel = cel * 9; 19: // Divide the answer by 5 20: cel = cel / 5; 21: // Add 32 to the answer 22: cel = cel + 32; 23: System.out.println(cel + " degrees Fahrenheit"); 24: } 25: }
When you compile and run this Java application, it produces the following output:
86.0 degrees Fahrenheit is ... 30.0 degrees Celsius 33.0 degrees Celsius is ... 91.4 degrees Fahrenheit
In lines 3–12 of this Java application, a temperature in Fahrenheit is converted to Celsius using the arithmetic operators:
Line 3—. The floating-point variable fah
is created with a value of 86
.
Line 4—. The current value of fah
is displayed.
Line 5—. The first of several comments explain what the program is doing. The Java compiler ignores these comments.
Line 7—. fah
is set to its current value minus 32.
Line 9—. fah
is set to its current value divided by 9.
Line 11—. fah
is set to its current value multiplied by 5.
Line 12—. Now that fah
has been converted to a Celsius value, fah
is displayed again.
A similar thing happens in lines 14–23 but in the reverse direction—a temperature in Celsius is converted to Fahrenheit.
Assigning a value to a variable is an expression because it produces a value. Because of this feature, you can string assignment statements together the following way:
x = y = z = 7;
In this statement, all three variables end up with the value of 7
.
The right side of an assignment expression always is calculated before the assignment takes place. This makes it possible to use an expression statement as in the following code:
int x = 5; x = x + 2;
In the expression x = x + 2
, the first thing that happens is that x + 2
is calculated. The result of this calculation, 7, is then assigned to x
.
Using an expression to change a variable’s value is a common task in programming. Several operators are used strictly in these cases.
Table 2.4 shows these assignment operators and the expressions they are functionally equivalent to.
These shorthand assignment operators are functionally equivalent to the longer assignment statements for which they substitute. If either side of your assignment statement is part of a complex expression, however, there are cases where the operators are not equivalent. For example, if x
equals 20
and y
equals 5
, the following two statements do not produce the same value:
x = x / y + 5; x /= y + 5;
When in doubt, simplify an expression by using multiple assignment statements and don’t use the shorthand operators.
Another common task required in programming is to add or subtract 1 from an integer variable. There are special operators for these expressions, which are called increment and decrement operations. Incrementing a variable means to add 1 to its value, and decrementing a variable means to subtract 1 from its value.
The increment operator is ++
, and the decrement operator is --
. These operators are placed immediately after or immediately before a variable name, as in the following code example:
int x = 7; x = x++;
In this example, the statement x = x++
increments the x
variable from 7 to 8.
These increment and decrement operators can be placed before or after a variable name, and this affects the value of expressions that involve these operators.
Increment and decrement operators are called prefix operators if listed before a variable name and postfix operators if listed after a name.
In a simple expression such as standards--;
, using a prefix or postfix operator produces the same result, making the operators interchangeable. When increment and decrement operations are part of a larger expression, however, the choice between prefix and postfix operators is important.
Consider the following code:
int x, y, z; x = 42; y = x++; z = ++x;
The three expressions in this code yield very different results because of the difference between prefix and postfix operations.
When you use postfix operators, as in y = x++
, y
receives the value of x
before it is incremented by one. When using prefix operators, as in z = ++x
, x
is incremented by one before the value is assigned to z
. The end result of this example is that y
equals 42
, z
equals 44
, and x
equals 44
.
If you’re still having some trouble figuring this out, here’s the example again with comments describing each step:
int x, y, z; // x, y, and z are all declared x = 42; // x is given the value of 42 y = x++; // y is given x's value (42) before it is incremented // and x is then incremented to 43 z = ++x; // x is incremented to 44, and z is given x's value
As with shorthand operators, increment and decrement operators in extremely complex expressions can produce results you might not have expected.
The concept of “assigning x
to y
before x
is incremented” isn’t precisely right because Java evaluates everything on the right side of an expression before assigning its value to the left side.
Java stores some values before handling an expression to make postfix work the way it has been described in this section.
When you’re not getting the results you expect from a complex expression that includes prefix and postfix operators, try to break the expression into multiple statements to simplify it.
Java has several operators for making comparisons among variables, variables and literals, or other types of information in a program.
These operators are used in expressions that return Boolean values of true
or false
, depending on whether the comparison being made is true or not. Table 2.5 shows the comparison operators.
The following example shows a comparison operator in use:
boolean hip; int age = 36; hip = age < 25;
The expression age < 25
produces a result of either true
or false
, depending on the value of the integer age
. Because age
is 36 in this example (which is not less than 25), hip
is given the Boolean value false
.
Expressions that result in Boolean values, such as comparison operations, can be combined to form more complex expressions. This is handled through logical operators, which are used for the logical combinations AND
, OR
, XOR
, and logical NOT
.
For AND
combinations, the &
or &&
logical operators are used. When two Boolean expressions are linked by the &
or &&
operators, the combined expression returns a true
value only if both Boolean expressions are true.
Consider this example:
boolean extraLife = (score > 75000) & (playerLives < 10);
This expression combines two comparison expressions: score > 75000
and playerLives < 10
. If both of these expressions are true, the value true
is assigned to the variable extraLife
. In any other circumstance, the value false
is assigned to the variable.
The difference between “&” and “&&” lies in how much work Java does on the combined expression. If “&” is used, the expressions on either side of the “&” are evaluated no matter what. If “&&” is used and the left side of the “&&” is false, the expression on the right side of the “&&” never is evaluated.
For OR
combinations, the “|” or “||” logical operators are used. These combined expressions return a true
value if either Boolean expression is true.
Consider this example:
boolean extralife = (score > 75000) || (playerLevel == 0);
This expression combines two comparison expressions: score > 75000
and playerLevel = 0
. If either of these expressions is true, the value true
is assigned to the variable extraLife
. Only if both of these expressions are false will the value false
be assigned to extraLife
.
Note the use of “||” instead of “|”. Because of this usage, if score > 75000
is true, extraLife
is set to true
, and the second expression is never evaluated.
The XOR
combination has one logical operator, “^”. This results in a true
value only if both Boolean expressions it combines have opposite values. If both are true or both are false, the “^” operator produces a false
value.
The NOT
combination uses the “!” logical operator followed by a single expression. It reverses the value of a Boolean expression the same way that a minus symbol reverses the positive or negative sign on a number.
For example, if age < 30
returns a true
value, !(age < 30)
returns a false
value.
The logical operators can seem completely illogical when encountered for the first time. You get plenty of chances to work with them for the rest of this week, especially on Day 5, “Creating Classes and Methods.”
When more than one operator is used in an expression, Java has an established precedence hierarchy to determine the order in which operators are evaluated. In many cases, this precedence determines the overall value of the expression.
For example, consider the following expression:
y = 6 + 4 / 2;
The y
variable receives the value 5
or the value 8
, depending on which arithmetic operation is handled first. If the 6 + 4
expression comes first, y
has the value of 5
. Otherwise, y
equals 8
.
In general, the order of evaluation from first to last is the following:
Increment and decrement operations
Arithmetic operations
Comparisons
Logical operations
Assignment expressions
If two operations have the same precedence, the one on the left in the actual expression is handled before the one on the right. Table 2.6 shows the specific precedence of the various operators in Java. Operators farther up the table are evaluated first.
Table 2.6. Operator Precedence
Notes | |
---|---|
| Parentheses (“()”) are used to group expressions; a period (“.”) is used for access to methods and variables within objects and classes (discussed tomorrow); square brackets (“[]”) are used for arrays. (This operator is discussed later in the week.) |
| The |
| The |
| Multiplication, division, modulus. |
| Addition, subtraction. |
| Bitwise left and right shift. |
| Relational comparison tests. |
| Equality. |
| AND |
| XOR |
| OR |
| Logical |
| Logical |
| Shorthand for |
| Various assignments. |
| More assignments. |
Returning to the expression y = 6 + 4 / 2
, Table 2.6 shows that division is evaluated before addition, so the value of y
will be 8
.
To change the order in which expressions are evaluated, place parentheses around the expressions that should be evaluated first. You can nest one set of parentheses inside another to make sure that expressions are evaluated in the desired order; the innermost parenthetic expression is evaluated first.
The following expression results in a value of 5
:
y = (6 + 4) / 2
The value of 5
is the result because 6 + 4
is calculated first, and then the result, 10, is divided by 2.
Parentheses also can improve the readability of an expression. If the precedence of an expression isn’t immediately clear to you, adding parentheses to impose the desired precedence can make the statement easier to understand.
As stated earlier today, the +
operator has a double life outside the world of mathematics. It can concatenate two or more strings. Concatenate means to link two things together. For reasons unknown, it is the verb of choice when describing the act of combining two strings—winning out over paste, glue, affix, combine, link, and conjoin.
In several examples, you have seen statements that look something like this:
String firstName = "Raymond"; System.out.println("Everybody loves " + firstName);
These two lines result in the display of the following text:
Everybody loves Raymond
The +
operator combines strings, other objects, and variables to form a single string. In the preceding example, the literal “Everybody loves” is concatenated to the value of the String
object firstName
.
Working with the concatenation operator is easy in Java because of the way the operator can handle any variable type and object value as if it were a string. If any part of a concatenation operation is a String
or a string literal, all elements of the operation will be treated as if they were strings:
System.out.println(4 + " score and " + 7 + " years ago");
This produces the output text 4 score and 7 years ago
, as if the integer literals 4 and 7 were strings.
There is also a shorthand +=
operator to add something to the end of a string. For example, consider the following expression:
myName += " Jr.";
This expression is equivalent to the following:
myName = myName + " Jr.";
In this example, it changes the value of myName
, which might be something like “Efrem Zimbalist”, by adding “Jr.” at the end to form the string “Efrem Zimbalist Jr.”
Anyone who pops open a set of matryoshka dolls has to be a bit disappointed to reach the smallest doll in the group. Advances in microengineering enable Russian artisans to create ever smaller and smaller dolls, until someone reaches the subatomic threshold and is declared the winner.
You have reached Java’s smallest nesting doll today. Using statements and expressions enables you to begin building effective methods, which make effective objects and classes possible.
Today, you learned about creating variables and assigning values to them. You also used literals to represent numeric, character, and string values and worked with operators. Tomorrow, you put these skills to use developing classes.
To summarize today’s material, Table 2.7 lists the operators you learned about. Be a doll and look them over carefully.
Table 2.7. Operator Summary
Operator | Meaning |
---|---|
| Addition |
| Subtraction |
| Multiplication |
| Division |
| Modulus |
| Less than |
| Greater than |
| Less than or equal to |
| Greater than or equal to |
| Equal |
| Not equal |
| Logical |
| Logical |
| Logical |
|
|
|
|
|
|
| Assignment |
| Increment |
Decrement | |
| Add and assign |
| Subtract and assign |
| Multiply and assign |
| Divide and assign |
| Modulus and assign |
Review today’s material by taking this three-question quiz.
The following question is the kind of thing you could expect to be asked on a Java programming certification test. Answer it without looking at today’s material.
Which of the following data types can hold the number 3,000,000,000 (three billion)?
|
The answer is available on the book’s website at http://www.java21days.com. Visit the Day 2 page and click the Certification Practice link.
To extend your knowledge of the subjects covered today, try the following exercises:
Create a program that calculates how much a $14,000 investment would be worth if it increased in value by 40% during the first year, lost $1,500 in value the second year, and increased 12% in the third year.
Write a program that displays two numbers and uses the /
and %
operators to display the result and remainder after they are divided. Use the
character escape code to separate the result and remainder in your output.
Where applicable, exercise solutions are offered on the book’s website at http://www.java21days.com.