Chapter 4

Java Basics


CONTENTS


On Days 1 and 3, you learned about Java programming in very broad terms-what a Java program and an executable look like, and how to create simple classes. On Day 2 you learned about the Café desktop. For the remainder of this week, you're going to get down to details and deal with the specifics of what the Java language looks like and how you can use Café to make understanding Java easier.

Today, you won't define any classes or objects or worry about how any of them communicate inside a Java program. Rather, you'll draw closer and examine simple Java statements-the basic things you can do in Java within a method definition such as main().

Today you'll learn about the following:

Technical Note
Java looks a lot like C++, and-by extension-like C. Much of the syntax will be very familiar to you if you are used to working in these languages. If you are an experienced C or C++ programmer, you might want to pay special attention to the Technical Notes (such as this one), because they will provide information about the specific differences between these and other traditional languages and Java.

Statements and Expressions

A statement is the simplest thing you can do in Java; a statement forms a single Java operation. All of the following are simple Java statements:

int i = 1;
import java.awt.Font;
System.out.println("This motorcycle is a "
    + color + " " + make);
m.engineState = true;

Statements sometimes return values-for example, when you add two numbers together or test to see whether one value is equal to another. These kind of statements are called expressions. We'll discuss them later on today.

The most important thing to remember about Java statements is that each one ends with a semicolon. Forget the semicolon and you will get an error when you compile your Java program.

Java also has compound statements, or blocks, that can be placed wherever a single state-
ment can. Block statements are surrounded by braces ({}). You'll learn more about blocks on Day 6.

Variables and Data Types

Variables are locations in memory in which values can be stored. They have a name, a type, and a value. Before you can use a variable, you have to declare it. After it is declared, you then can assign values to it.

Java actually has three kinds of variables: instance variables, class variables, and local variables.

Instance variables, as you learned yesterday, are used to define attributes or the state for a particular object. Class variables are similar to instance variables, except that their values apply to all of that class's instances (and to the class itself) rather than having different values for each object.

Local variables are declared and used inside method definitions-for example, for index counters in loops, as temporary variables, or to hold values that you need only inside the method definition itself. They also can be used inside blocks ({}), which you'll learn about later this week. Once the method (or block) finishes executing, the variable definition and its value cease to exist. Use local variables to store information needed by a single method and instance variables to store information needed by multiple methods in the object.

Although all three kinds of variables are declared in much the same way, class and instance variables are accessed and assigned in slightly different ways from local variables. Today, you'll focus on variables as used within method definitions; tomorrow, you'll learn how to deal with instance and class variables.

Note
Unlike other languages, Java does not have global variables-that is, variables that are global to all parts of a program. Instance and class variables can be used to communicate global information between and among objects. Remember, Java is an object-oriented language, so you should think in terms of objects and how they interact, rather than in terms of programs.

Declaring Variables

To use any variable in a Java program, you must first declare it. Variable declarations consist of a type and a variable name:

int myAge;
String myName;
boolean isTired;

Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java statement can go), although they are most commonly declared at the beginning of the definition before they are used:

public static void main (String args[]) {
    int count;
    String title;
    boolean isAsleep;
...
}

You can string together variable names with the same type:

int x, y, z;
String firstName, LastName;

You also can give each variable an initial value when you declare it:

int myAge, mySize, numShoes = 28;
String myName = "Laura";
boolean isTired = true;
int a = 4, b = 5, c = 6;

If there are multiple variables on the same line with only one initializer (as in the first of the previous examples), the initial value applies to only the last variable in a declaration. You also can group individual variables and initializers on the same line using commas, as with the last example, above.

Note
Always assign a value to a local variable in your Java programs.

Local variables must be given values before they can be used. (Your Java program will not compile if you try to use an unassigned local variable.) For this reason, it's a good idea to always give local variables initial values. Instance and class variable definitions do not have this restriction (their initial value depends on the type of the variable: null for instances of classes, 0 for numeric variables, '\0' for characters, and false for booleans).

Notes on Variable Names

Variable names in Java can start with a letter, an underscore (_), or a dollar sign ($). They cannot start with a number. After the first character, your variable names can include any letter or number. Symbols, such as %, *, @, and so on, often are reserved for operators in Java, so be careful when using symbols in variable names. A good programming practice is to not use symbols in variable names-unless there is a very good reason to.

In addition, the Java language uses the Unicode character set. Unicode is a character set definition that not only offers characters in the standard ASCII character set, but also several million other characters for representing most international alphabets. This means that you can use accented characters and other glyphs as legal characters in variable names, as long as they have a Unicode character number above 00C0.

Warning
The Unicode specification is a two-volume set of lists of thousands of characters. If you don't understand Unicode, or don't think you have a use for it, it's safest just to use plain numbers and letters in your variable names. You'll learn a little more about Unicode later on.

Finally, note that the Java language is case-sensitive, which means that uppercase letters are different than lowercase letters. This means that the variable X is different from the variable x, and a rose is not a Rose is not a ROSE. Keep this in mind as you write your own Java programs and as you read Java code other people have written.

By convention, Java variables have meaningful names, often made up of several words combined. The first word is lowercase, but all following words have an initial uppercase letter:

Button theButton;
long reallyBigNumber;
boolean currentWeatherStateOfPlanetXShortVersion;

Variable Types

In addition to the variable name, each variable declaration must have a type, which defines what values that variable can hold. The variable type can be one of three things:

You'll learn about how to declare and use array variables on Day 6.

The eight primitive data types handle common types for integers, floating-point numbers, characters, and boolean values (true or false). They're called primitive because they're built into the system and are not actual objects, which makes them more efficient to use. Note that these data types are machine-independent, which means that you can rely on their sizes and characteristics to be consistent across your Java programs.

There are four Java integer types, each with a different range of values (as listed in Table 4.1). All are signed, which means they can hold either positive or negative numbers. The type you choose for your variables depends on the range of values you expect that variable to hold; if a value becomes too big for the variable type, it silently is truncated.

Table 4.1. Integer types.
TypeSize Range
byte 8 bits-128 to 127
short 16 bits-32,768 to 32,767
int 32 bits-2,147,483,648 to 2,147,483,647
long 64 bits-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Floating-point numbers are used for numbers with a decimal part. Java floating-point numbers are compliant with IEEE 754 (an international standard for defining floating-point numbers and arithmetic). There are two floating-point types: float (32 bits, single-precision) and double (64 bits, double-precision).

The char type is used for individual characters. Because Java uses the Unicode character set, the char type has 16 bits of precision, unsigned.

Finally, the boolean type can have one of two values, true or false. Note that unlike in other C-like languages, boolean is not a number, nor can it be treated as one. All tests of boolean variables should test for true or false.

In addition to the eight basic data types, variables in Java also can be declared to hold an instance of a particular class:

String LastName;
Font basicFont;
OvalShape myOval;

Each of these variables then can hold only instances of the given class. As you create new classes, you can declare variables to hold instances of those classes (and their subclasses) as well.

Technical Note
Java does not have a typedef statement (as in C and C++). To declare new types in Java, you declare a new class; then variables can be declared to be of that class's type.

Assigning Values to Variables

Once a variable has been declared, you can assign a value to that variable by using the assignment operator =:

size = 14;
tooMuchCaffiene = true;

Comments

Java has three kinds of comments. /* and */ surround multiline comments, as in C or C++. All text between the two delimiters is ignored:

/* I don't know how I wrote this next part; I was working
    really late one night and it just sort of appeared. I
    suspect the code elves did it for me. It might be wise
    not to try and change it.
*/

These comments cannot be nested; that is, you cannot have a comment inside a comment.

Double slashes (//) can be used for a single line of comment. All the text up to the end of the line is ignored:

int vices = 7; // are there really only 7 vices?

The final type of comment begins with /** and ends with */.

Literals

Literals are used to indicate simple values in your Java programs.

Literal is a programming language term, which essentially means that what you type is what you get. For example, if you type 4 in a Java program, you automatically get an integer with the value 4. If you type 'a', you get a character with the value a.

Literals might seem intuitive most of the time, but there are some special cases of literals in Java for different kinds of numbers, characters, strings, and boolean values.

Number Literals

There are several integer literals. 4, for example, is a decimal integer literal of type int (although you can assign it to a variable of type byte or short because it's small enough to fit into those types). A decimal integer literal larger than an int is automatically of type long. You also can force a smaller number to a long by appending an L or l to that number (for example, 4L is a long integer of value 4). Negative integers are preceded by a minus sign-for example, -45.

Integers also can be expressed as octal or hexadecimal: a leading 0 indicates that a number is octal-for example, 0777 or 0004. A leading 0x (or 0X) means that it is in hex (0xFF, 0XAf45). Hexadecimal numbers can contain regular digits (0-9) or upper- or lowercase hex digits (a-f or A-F).

Note
Octal and hexadecimal are numbering systems. Octal is base 8 and hexadecimal is base 16. That means that in the octal set there are only 8 digits (0, 1, 2, 3, 4, 5, 6, 7) and in the hexadecimal set there are 16 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, A, B, C, D, E, F). Both of these numbering systems are used in programs and by programmers to represent various binary values.

Floating-point literals usually have two parts: the integer part and the decimal part-for example, 5.677777. Floating-point literals result in a floating-point number of type double, regardless of the precision of that number. You can force the number to the type float by appending the letter f (or F) to that number-for example, 2.56F.

You can use exponents in floating-point literals using the letter e or E followed by the exponent (which can be a negative number): 10e45 or .36E-2.

Boolean Literals

Boolean literals consist of the keywords true and false. These keywords can be used anywhere you need a test or as the only possible values for boolean variables.

Character Literals

Character literals are expressed by a single character surrounded by single quotes: 'a', '#', '3', and so on. Characters are stored as 16-bit Unicode characters. Table 4.2 lists the special codes that can represent nonprintable characters, as well as characters from the Unicode character set. The letter d in the octal, hex, and Unicode escapes represents a number or a hexadecimal digit (a-f or A-F).

Table 4.2. Character escape codes.
EscapeMeaning
\n Newline
\t Tab
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
\' Single quote
\" Double quote
\ddd Octal
\xdd Hexadecimal
\udddd Unicode character

Technical Note
C and C++ programmers should note that Java does not include character codes for \a (bell) or \v (vertical tab).

String Literals

A combination of characters is a string. Strings in Java are instances of the class String. Strings are not simple arrays of characters as they are in C or C++, although they do have many array-like characteristics (for example, you can test their length and access and change individual characters). Because string objects are real objects in Java, they have methods that enable you to combine, test, and modify strings very easily.

String literals consist of a series of characters inside double quotes:

"Hi, I'm a string literal."
"" //an empty string

Strings can contain character constants such as newline, tab, and Unicode characters:

"A string with a \t tab in it"
"Nested strings are \"strings inside of\" other strings"
"This string brought to you by Java\u2122"

In the last example, the Unicode code sequence for \u2122 produces a trademark symbol (™).

Note
Just because you can represent a character using a Unicode escape does not mean your computer can display that character-the computer or operating system you are running might not support Unicode, or the font you're using might not have a glyph (picture) for that character. Windows 95 and Windows NT do not support Unicode externally. That means that if you are attempting to use Unicode escapes in Symantec Café, you will most likely experience problems. All that Unicode escapes in Java provide is a way to encode special characters for systems that support Unicode.

When you use a string literal in your Java program, Java automatically creates an instance of the class String for you with the value you give it. Strings are unusual in this respect; the other literals do not behave in this way (none of the primitive base types are actual objects), and usually creating a new object involves explicitly creating a new instance of a class. You'll learn more about strings, the String class, and the things you can do with strings later today and tomorrow.

Expressions and Operators

Expressions are the simplest form of statement in Java that actually accomplishes something.

Expressions are statements that return a value.

Operators are special symbols that commonly are used in expressions.

Arithmetic and tests for equality and magnitude are common examples of expressions. Because they return a value, you can assign that result to a variable or test that value in other Java statements.

Operators in Java include arithmetic, various forms of assignment, increment and decrement, and logical operations. This section describes all of these things.

Arithmetic

Java has five operators for basic arithmetic (see Table 4.3).

Table 4.3. Arithmetic operators.
Operator
Meaning
Example
Result
+
Addition
3 + 4
7
-
Subtraction
5 - 7
-2
*
Multiplication
5 * 5
25
/
Division
14 / 7
2
%
Modulus
20 % 7
6

Each operator takes two operands, one on either side of the operator. The subtraction operator (-) also can be used to negate a single operand.

Integer division results in an integer. Because integers don't have decimal fractions, any remainder is ignored. The expression 31 / 9, for example, results in 3 (9 goes into 31 only 3 times).

Modulus (%) gives the remainder once the operands have been evenly divided. For example, 31 % 9 results in 4 because 9 goes into 31 three times, with 4 left over.

When dealing with integers in binary arithmetic (arithmetic operations involving two operands and one operator), if either operand is of type long then the other operand will automatically be promoted to long and the resulting value will be a long. This is also true if either operand is type float. If, on the other hand, you are using the short or byte integer data type as one of your operands, they will automatically be promoted to type int-as will the result. Note that all of the promotions described in binary arithmetic increase the bit width of the data type, thus there is no potential for data loss except in the case of floats where there is a potential for rounding. The next several paragraphs will be a runnable example of arithmetic.

Create a new project called Arithmetic.prj using Table 4.4 to input to the ProjectExpress wizard.

Table 4.4. Table of information for the ProjectExpress to create the project Arithmetic.
StepActions needed
1. Name projectProject name: Arithmetic.prj Directory:   \Cafe\Projects
2. Set project typeCheck option Release
Change Target Type to Application
3. Add files to projectNo changes
4. Initial settingsNo changes

After this is done, open a new Source window text editor and input the code from Listing 4.1 into it.


Listing 4.1. The code for Arithmetic.java.
1: class ArithmeticTest {
2: public static void main (String args[]) {
3:     short x = 6;
4:     int y = 4;
5:     float a = 12.5f;
6:     float b = 7f;
7:
8:     System.out.println("x is " + x + ", y is " + y);
9:     System.out.println("x + y = " + (x + y));
10:     System.out.println("x - y = " + (x - y));
11:     System.out.println("x / y = " + (x / y));
12:     System.out.println("x % y = " + (x % y));
13:
14:     System.out.println("a is " + a + ", b is " + b);
15:     System.out.println("a / b = " + (a / b));
16: }
17:
18: }

Once you have finished copying the code from Listing 4.1 into the Source window text editor, save it as ArithmeticTest.java in the ..\Cafe\Projects directory and add it to the project Arithmetic. Once you have completed that, go ahead and mark ArithmeticTest.java as Main. Your Project window then should look something like Figure 4.1.

Figure 4.1 : Project Window for Arithmetic.prj.

Now you are ready to compile the project by clicking Project and Rebuild All.

When you run the Java application, you should see the following:

x is 6, y is 4
x + y = 10
x - y = 2
x / y = 1
x % y = 2
a is 12.5, b is 7
a / b = 1.78571

In this simple Java application (note the main() method), you initially define four variables in lines 3 through 6: x and y, which are integers (type int), and a and b, which are floating-point numbers (type float). Keep in mind that the default type for floating-point literals (such as 12.5) is double, so to make sure that these are numbers of type float, you have to use an f after each one (lines 5 and 6).

The remainder of the program merely does some math with integers and floating-point numbers and prints out the results.

There is one other thing to mention about this program: the method System.out.println(). You've seen this method on previous days, but you haven't really learned exactly what it does. The System.out.println() method merely prints a message to the standard output of your system-to the screen, to a special window, or maybe just to a special log file, depending on your system and the development environment you're running (Sun's JDK prints it to the screen). The System.out.println() method takes a single argument-a string-but you can use + to concatenate values into a string, as you'll learn later today.

More About Assignment

Variable assignment is a form of expression; in fact, because one assignment expression results in a value, you can string them together like this:

x = y = z = 0;

In this example, all three variables now have the value 0.

The right side of an assignment expression always is evaluated before the assignment takes place. This means that expressions such as x = x + 2 do the right thing; 2 is added to the value of x, and then that new value is reassigned to x. In fact, this sort of operation is so common that Java has several operators to do a shorthand version of this, borrowed from C and C++. Table 4.5 shows these shorthand assignment operators.

Table 4.5. Assignment operators.
Operator
Expression
Meaning
+=
x += y
x = x + y
-=
x -= y
x = x - y
*=
x *= y
x = x * y
/=
x /= y
x = x / y

Technical Note
If you rely on complicated side effects of sub-expressions on either side of these assignments, the shorthand expressions might not be entirely equivalent to their longhand equivalents. For more information about very complicated expressions, evaluation order, and side effects, you might want to consult the Java Language Specification.

Incrementing and Decrementing

As in C and C++, the ++ and -- operators are used to increment or decrement a value by 1. For example, x++ increments the value of x by 1 just as if you had used the expression x = x + 1. Similarly x-- decrements the value of x by 1. (Unlike C and C++, Java allows x to be floating point.)

These increment and decrement operators can be prefixed or postfixed; that is, the ++ or
-- can appear before or after the value it increments or decrements. For simple increment or decrement expressions, the one you use isn't overly important. In complex assignments, where you are assigning the result of an increment or decrement expression, the one you use makes a difference.

Take, for example, the following two expressions:

y = x++;
y = ++x;

These two expressions give very different results because of the difference between prefix and postfix. When you use postfix operators (x++ or x--), y gets the value of x before x is changed; using prefix, the value of x is assigned to y after the change has occurred. Our next project will show how all of this works.

Create a new project called Operators.prj using Table 4.6 to input to the ProjectExpress wizard.

Table 4.6. Table of information for the ProjectExpress to create the project Operators.
StepActions needed
1. Name projectProject name: Operators.prj
Directory:   \Cafe\Projects
2. Set project typeCheck option Release
Change Target Type to Application
3. Add files to projectNo changes
4. Initial settingsNo changes

After this is done, open a new Source window text editor and input the code from Listing 4.2 into it.


Listing 4.2. The code for Operators.java.
1: class Operators {
2:
3:    public static void main (String args[]) {
4:        int x = 0;
5:        int y = 0;
6:
7:        System.out.println("x and y are " + x + " and " + y );
8:        x++;
9:        System.out.println("x++ results in " + x);
10:       ++x;
11:       System.out.println("++x results in " + x);
12:       System.out.println("Resetting x back to 0.");
13:       x = 0;
14:       System.out.println("------");
15:       y = x++;
16:       System.out.println("y = x++ (postfix) results in:");
17:       System.out.println("x is " + x);
18:       System.out.println("y is " + y);
19:       System.out.println("------");
20:
21:       y = ++x;
22:       System.out.println("y = ++x (prefix) results in:");
23:       System.out.println("x is " + x);
24:       System.out.println("y is " + y);
25:       System.out.println("------");
26:
27:    }
28:
29: }

Once you have finished copying the code from Listing 4.2 into the Source window text editor, save it as Operators.java in the ..\Cafe\Projects directory and then add it to the project Operators. Once you have completed that, mark Operators.java as Main. Now you are ready to compile this new project by clicking Project and Rebuild All. Run it using the interpreter to see the following output:

x and y are 0 and 0
x++ results in 1
++x results in 2
Resetting x back to 0.
------------
y = x++ (postfix) results in:
x is 1
y is 0
------------
y = ++x (prefix) results in:
x is 2
y is 2
------------

In the first part of this example, you increment x alone using both prefix and postfix increment operators. In each, x is incremented by 1 each time. In this simple form, using either prefix or postfix works the same way.

In the second part of this example, you use the expression y = x++, in which the postfix increment operator is used. In this result, the value of x is incremented after that value is assigned to y. Hence the result: y is assigned the original value of x (0), and then x is incremented by 1.

In the third part, you use the prefix expression y = ++x. Here, the reverse occurs: x is incremented before its value is assigned to y. Because x is 1 from the previous step, its value is incremented (to 2), and then that value is assigned to y. Both x and y end up being 2.

Technical Note
Technically, this description is not entirely correct. In reality, Java always completely evaluates all expressions on the right of an expression before assigning that value to a variable, so the concept of "assigning x to y before x is incremented" isn't precisely right. Instead, Java takes the value of x and "remembers" it, evaluates (increments) x, and then assigns the original value of x to y. Although in most simple cases this distinction might not be important, for more complex expressions with side effects it might change the behavior of the expression overall. See the Language Specification for many more details about the details of expression evaluation in Java.

Comparisons

Java has several expressions for testing equality and magnitude. All of these expressions return a boolean value (that is, true or false). Table 4.7 shows the comparison operators:

Table 4.7. Comparison operators.
Operator
Meaning
Example
==
Equal
x == 3
!=
Not equal
x != 3
<
Less than
x < 3
>
Greater than
x > 3
<=
Less than or equal to
x <= 3
>=
Greater than or equal to
x >= 3

Logical Operators

Expressions that result in boolean values (for example, the comparison operators) can be combined by using logical operators that represent the logical combinations AND, OR, XOR, and logical NOT.

For AND combinations, use either the & or &&. The expression will be true only if both expressions also are true; if either expression is false, the entire expression is false. The difference between the two operators is in expression evaluation. Using &, both sides of the expression are evaluated regardless of the outcome. Using &&, if the left side of the expression is false, the entire expression returns false, and the right side of the expression never is evaluated.

For OR expressions, use either | or ||. OR expressions result in true if either or both of the operands is also true; if both operands are false, the expression is false. As with & and &&, the single | evaluates both sides of the expression regardless of the outcome; with ||, if the left expression is true, the expression returns true and the right side is never evaluated.

In addition, there is the XOR operator ^, which returns true only if its operands are different (one true and one false, or vice versa) and false otherwise (even if both are true).

In general, only the && and || are commonly used as actual logical combinations. &, |, and ^ are more commonly used for bitwise logical operations.

For NOT, use the ! operator with a single expression argument. The value of the NOT expression is the negation of the expression; if x is true, !x is false.

Bitwise Operators

Finally, here's a short summary of the bitwise operators in Java. These all are inherited from C and C++ and are used to perform operations on individual bits in integers. This book does not go into bitwise operations; it's an advanced topic covered better in books on C or C++. Table 4.8 summarizes the bitwise operators.

Table 4.8. Bitwise operators.
Operator
Meaning
&
Bitwise AND
|
Bitwise OR
^
Bitwise XOR
<<
Left shift
>>
Right shift
>>>
Zero fill right shift
~
Bitwise complement
<<=
Left shift assignment (x = x << y)
>>=
Right shift assignment (x = x >> y)
>>>=
Zero fill right shift assignment (x = x >>> y)
x&=y
AND assignment (x = x & y)
x|=y
OR assignment (x + x | y)
x^=y
XOR assignment (x = x ^ y)

Operator Precedence

Operator precedence determines the order in which expressions are evaluated. This, in some cases, can determine the overall value of the expression. For example, take the following expression:

y = 6 + 4 / 2

Depending on whether the 6 + 4 expression or the 4 / 2 expression is evaluated first, the value of y can end up being 5 or 8. Operator precedence determines the order in which expressions are evaluated, so you can predict the outcome of an expression. In general, increment and decrement are evaluated before arithmetic, arithmetic expressions are evaluated before comparisons, and comparisons are evaluated before logical expressions. Assignment expressions are evaluated last.

Table 4.9 shows the specific precedence of the various operators in Java. Operators further up in the table are evaluated first; operators on the same line have the same precedence and are evaluated left to right based on how they appear in the expression itself. For example, given that same expression y = 6 + 4 / 2, you now know, according to this table, that division is evaluated before addition, so the value of y will be 8.

Table 4.9. Operator precedence.
OperatorNotes
. [] () Parentheses () are used to group expressions; a dot (.) is used for access to methods and variables within objects and classes (discussed tomorrow); and [] is used for arrays (discussed later on in the week)
++ -- ! ~ instanceof Returns true or false based on whether the object is an instance of the named class or any of that class's superclasses (discussed tomorrow)
new (type)expression The new operator is used for creating new instances of classes; () in this case is for casting a value to another type (you'll learn about both of these tomorrow)
* / % Multiplication, division, modulus
+ - Addition, subtraction
<< >> >>> Bitwise left, right shift, and the zero fill right shift
< > <= >= Relational comparison tests
== != Equality
& AND
^ XOR
| OR
&& Logical AND
|| Logical OR
? : Shorthand for if…then…else (discussed on Day 6)
= += -= *= /= %= ^= Various assignments
&= |= <<= >>= >>>=  

You always can change the order in which expressions are evaluated by using parentheses around the expressions you want to evaluate first. You can nest parentheses to make sure that expressions evaluate in the order you want them to (the innermost parenthetical expression is evaluated first). Consider the following expression:

y = (6 + 4) / 2

This results in a value of 5, because the 6 + 4 expression is evaluated first, and then the result of that expression (10) is divided by 2.

Parentheses also can be useful in cases where the precedence of an expression isn't immediately clear-in other words, they can make your code easier to read. Adding parentheses doesn't hurt, so if they help you figure out how expressions are evaluated, go ahead and use them.

String Arithmetic

One special expression in Java is the use of the addition operator (+) to create and concatenate strings. In most of the previous examples shown today and in earlier lessons, you've seen lots of lines that looked something like this:

System.out.println(name + " is a " + color " beetle");

The output of that line (to the standard output) is a single string, with the values of the variables (here, name and color), inserted in the appropriate spots in the string. So what's going on here?

The + operator, when used with strings and other objects, creates a single string that contains the concatenation of all its operands. If any of the operands in string concatenation is not a string, it is automatically converted to a string, making it easy to create these sorts of output lines.

Note
An object or type can be converted to a string if you implement the method toString(). All objects have a default string representation, but most classes override toString() to provide a more meaningful printable representation.

String concatenation makes lines such as the previous one especially easy to construct. To create a string, just add all of the parts together-the descriptions plus the variables-and output it to the standard output, to the screen, to an applet, or anywhere.

The += operator, which you learned about earlier, also works for strings. For example, take the following expression:

myName += " Jr.";

This expression is equivalent to the following:

myName = myName + " Jr.";

This works the same as it would for numbers. In this case, it changes the value of myName (which might be something like John Smith) to have a Jr. at the end (John Smith Jr.).

Summary

As you learned in the last two lessons, a Java program is made up primarily of classes and objects. Classes and objects, in turn, are made up of methods and variables, and methods are made up of statements and expressions. It is those last two things that you've learned about today; the basic building blocks that enable you to create classes and methods and build them up to a full-fledged Java program.

Today, you learned about variables, how to declare them and assign values to them; literals for easily creating numbers, characters, and strings; and operators for arithmetic, tests, and other simple operations. With this basic syntax, you can move on tomorrow to learning about working with objects and building simple useful Java programs.

To finish up this summary, Table 4.10 is a list of all the operators you learned about today so that you can refer back to them.

Table 4.10. 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 AND
||
Logical OR
!
Logical NOT
&
AND
|
OR
^
XOR
<<
Left shift
>>
Right shift
>>>
Zero fill right shift
~
Complement
=
Assignment
++
Increment
--
Decrement
+=
Add and assign
-=
Subtract and assign
*=
Multiply and assign
/=
Divide and assign
%=
Modulus and assign
&=
AND and assign
|=
OR and assign
<<=
Left shift and assign
^=
XOR and assign
>>=
Right shift and assign
>>>=
Zero fill right shift and assign

Q&A

Q
Is there any way to define constants?
A
You can't create local constants in Java; you only can create constant instance and class variables. You'll learn how to do this tomorrow.
Q
What happens if you assign an integer value to a variable that is too large for that variable to hold?
A
Logically, you would think that the variable is just converted to the next larger type, but this isn't what happens. What does happen is called overflow. This means that if a number becomes too big for its variable, that number wraps around to the smallest possible negative number for that type and starts counting upward to zero again.
Because this can result in some very confusing (and wrong) results, make sure that you declare the right integer type for all of your numbers. If there's a chance a number will overflow its type, use the next larger type instead.
Q
How can you find out the type of a given variable?
A
If you're using the base types (int, float, boolean), and so on, you can't. If you care about the type, you can convert the value to some other type by using casting (you'll learn about this tomorrow).

If you're using class types, you can use the instanceof operator, which you'll learn more about tomorrow.

Q
Why does Java have all of these shorthand operators for arithmetic and assignment? It's really hard to read that way.
A
The syntax of Java is based on C++, and therefore on C. One of C's implicit goals is the capability of doing very powerful things with a minimum of typing. Because of this, shorthand operators, such as the wide array of assignments, are common.

There's no rule that says you have to use these operators in your own programs, however. If you find your code to be more readable using the long form, no one will come to your house and make you change it.