Previous Page TOC Index Next Page Home


Day 3

Java Basics

by Laura Lemay

On Days 1 and 2, you learned about Java programming in very broad terms—what a Java program and an executable look like, and how to create simple classes. 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.

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 may 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 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 these later on today.

The most important thing to remember about Java statements is that each one ends with a semicolon. Forget the semicolon and your Java program won't compile.

Java also has compound statements, or blocks, which can be placed wherever a single statement can. Block statements are surrounded by braces ({}). You'll learn more about blocks in Chapter 5, "Arrays, Conditionals, and Loops."

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 can then 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 their values apply to all 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 can also 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 ways, 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 can also 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 can also group individual variables and initializers on the same line using commas, as with the last example, above.

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 always to 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, are often reserved for operators in Java, so be careful when using symbols in variable names.

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.


Caution: 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 from 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 in Chapter 5.

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 3.1). All are signed, which means they can hold either positive or negative numbers. Which 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 is silently truncated.

Type

Size

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

—9223372036854775808 to 9223372036854775807

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 can also be declared to hold an instance of a particular class:

String LastName;
Font basicFont;
OvalShape myOval;

Each of these variables can then 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 */. The contents of these special comments are used by the javadoc system, but are otherwise used indentically to the first type of comment. Javadoc is used to generate API documentation from the code. You won't learn about javadoc in this book; you can find out more information from the documentation that came with Sun's Java Developer's Kit or from Sun's Java home page (<A HREF="http://java.sun.com"> http://java.sun.com</A>).

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 may 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 can also 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).

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 3.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).

Escape

Meaning

\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 may not support Unicode, or the font you're using may not have a glyph (picture) for that character. 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 are commonly 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 these things.

Arithmetic

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

Operator

Meaning

Example

+

Addition

3 + 4

Subtraction

5 — 7

*

Multiplication

5 * 5

/

Division

14 / 7

%

Modulus

20 % 7

Each operator takes two operands, one on either side of the operator. The subtraction operator (—) can also 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.

Note that, for integers, the result type of most operations is an int regardless of the original type of the operands. If either or both operands is of type long, the result is of type long. If one operand is an integer and another is a floating point number, the result is a floating point. (If you're interested in the details of how Java promotes and converts numeric types from one type to another, you may want to check out the Java Language Specification at Sun's official Java Web site; that's more detail than I want to cover here.)

Listing 3.1 is an example of simple arithmetic.

 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: }
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 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 is always 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 3.4 shows these shorthand assignment operators.

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 subexpressions on either side of these assignments, the shorthand expressions may not be entirely equivalent to their longhand equivalents. For more information about very complicated expressions, evaluation order, and side effects, you may 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, which one you use isn't overly important. In complex assignments, where you are assigning the result of an increment or decrement expression, which 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. Listing 3.2 is a Java example of how all this works.

 1: class PrePostFixTest {
 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: }
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 may not be important, for more complex expressions with side effects it may 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 3.5 shows the 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 are also 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 is never 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 are all 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 3.6 summarizes the 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 3.8 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, give 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.

Operator

Notes

. [] ()

Parentheses () group expressions; dot (.) is used for access to methods and variables within objects and classes (discussed tomorrow); [] 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 and right shift

< > <= >=

Relational comparison tests

== !=

Equality

&

AND

^

XOR

|

OR

&&

Logical AND

||

Logical OR

? :

Shorthand for if...then...else (discussed on Day 5)

= += —= *= /= %= ^= &= |= <<= >>= >>>=

Various assignments

You can always 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 expressions evaluate in the order you want them to (the innermost parenthetical expression is evaluated first). The following expression 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:

y = (6 + 4) / 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.


Technical 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 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 this:

myName = myName + " Jr.";

just as it would be 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 3.8 is a list of all the operators you learned about today so that you can refer back to them.

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: I didn't see any way to define constants.

A: You can't create local constants in Java; you can create only 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 toward zero again.

Because this can result in some very confusing (and wrong) results, make sure that you declare the right integer type for all 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 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.

Previous Page TOC Index Next Page Home