In the last three days you learned about Java programming in very broad termswhat a Java program and an executable look like, and how to create simple classes. You also learned (again in broad terms) Microsoft Developer Studio. For the remainder
of this week, you're going to get down to details, and learn the specifics of what the Java language looks like by using Microsoft Developer Studio.
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 statementsthe basic things you can do in Java within a method definition such as
main().
Today you'll learn about the following:
Java looks a lot like C++, andby extensionlike 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.
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 iTemp = 1; import java.awt.Font; System.out.println("This motorcycle is a " + color + " " + make); m.engineState = true;
Statements sometimes return valuesfor 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 today.
The most important thing to remember about Java statements is that each one ends with a semicolon. If you forget a semicolon, errors will display and your Java program won't compile. Often, a single missed semicolon will generate an error on each line
following the forgotten semicolon, so be careful: one missed semicolon can generate many errors.
Java also has compound statements; called blocks. Wherever a single statement can be used, blocks can be used. Block statements are surrounded by braces { }. Microsoft Developer Studio automatically indents and matches { } to help make your code easier
to read. You'll learn more about blocks in Chapter 6, "Arrays, Conditionals, and Loops."
Variables are locations in memory where 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 assign values to it. The following are a few examples of
variables.
String sTemp = "Judith" \\set variable sTemp to hold the data "Judith" int iTemp; iTemp = 2 + 5; \\set variable iTemp to hold the sum of 2 + 5
Java actually has three kinds of variables: data members, class variables, and local variables.
Data members, as you learned yesterday, are used to define attributes, or the state of a particular object. Class variables are similar to data members, except their values apply to all of that class's instances (and to the class itself) rather than
having different values for each object.
For example, local variables are declared and used inside method definitions. They can be used 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. You'll use local variables to store information needed by a single method and data members to store
information needed by multiple methods in the object.
Although all three kinds of variables are declared in much the same way, class variables and data members 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 work with data members and class variables.
Unlike other languages, Java does not have global variablesthat is, variables that are accessible to all parts of a program. Instead, data members 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 and communicate with one another, rather than in terms of a single program containing subroutines accessing public memory variables.
To use any variable in a Java program, you must first declare it. Variable declarations consist of a variable type and a variable name:
int iMyAge; String sMyName; boolean bIsTired;
Variable definitions can be placed 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 in which they are being used:
public static void main (String args[]) { int iCount; String sTitle; boolean bIsAsleep; ... }
You can string together variable names with the same type:
int iX, iY, iZ; String sFirstName, sLastName;
You can also give each variable an initial value when you declare it:
int iNumDollars, iNumCentury, iNumCranes = 100; String sBigCityName = "New York"; boolean bIsTired = true; int iA= 4, iB = 5, iC = 6;
If there are multiple variables on the same line with only one initializer (as in the first line of the previous example), the value (100) applies to only the last variable (iNumCranes) in the declaration. You can also group individual variables and
initializers on the same line by using commas, so that each is initialized, as in the preceding example.
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. Data member and class
variable definitions do not have this restriction. (Their initial value depends on the variable type: null for instances of classes, 0 for numeric variables, '\0' for characters, and false for Booleans.)
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.
It is very important to understand that the preceding naming convention applies to all identifiers, which includes variables (int, String, and so on) and to method names (MyMethod(), YourMethod()).
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, which is ASCII character 130.
The Unicode specification is a two volume set that lists 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.
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 btnTheButton; long lReallyBigNumber; boolean bCurrentWeatherStateOfPlanetXShortVersion;
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, regardless of the computer on which your Java program is running.
There are four Java integer types, each with a different range of values. (See Table 4.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. Be careful though when declaring integers: if a value becomes too big for the variable type, the value is truncated without warning, and more than likely producing runtime errors in your program. This doesn't mean though to declare
all your integers as long!
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 neither evaluated to the numbers 0 and 1, nor is it treated as one. All tests of Boolean variables should test for true or
false.
To anyone not familiar with object-oriented programming, this next little piece might seem quite confusing. After reading it, you might even turn back a page or two and say, "Hey, didn't I declare String sLastName as type String; how can String be a class too? How does Java know which is which?" On Day 5 we'll go deeply into objects and classes. You might want to re-read this little piece a few times and mark it, so after Day 5, you can refer to it.
In addition to the eight basic data types, variables in Java can also be declared to hold an instance of a particular class:
String sLastName; Font fntBasicFont; OvalShape ovlMyOval;
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.
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' type.
Once a variable has been declared, you can assign a value to that variable by using the assignment operator =:
iSize = 14; bTooMuchCaffiene = true;
As all good programmers know (or eventually find out), one of the most important aspects to writing good code is to use a naming convention for your variables. Naming your variables using some meaningful convention makes your code easier to read and,
most importantly, easier to maintain.
There are many theories and concepts for defining a standard naming convention. One widely used naming convention is the Hungarian convention that is most often found in C or C++ programs. When using strict Hungarian naming convention, you can look at
any variable and know everything about the variable: where the variable was initiated, its data type, what data the variable holds, and so on. Some development environments, on the other hand, suggest their own take-off from strict Hungarian: Visual Basic
being one example.
In order to stick with the "spirit" of Java, we suggest using a rather simple naming convention. It states:
That's it (except for a few more suggestions later on). By following a few simple principles, you will most likely find your code easy to read and maintain, but also very easy to write, because you don't have to remember a complicated naming
convention.
Below are some examples of naming conventions for the primitive data types, as well as for three of the Java class libraries that you'll find used in this book:
Type | Prefix | Definition | Notes |
byte | si | byte siCount; | Similar to C++ Short Int |
short | w | short wCount; | Similar to C++ WORD |
int | i | int iCount; | |
long | l | long lCount; | |
float | f | float fCount; | |
double | d | double dCount; | |
char | c | char cItem; | |
Font | fnt | Font fntBasic; | |
OvalShape | ovl | OvalShape ovlMyShape; | |
String | s | String sName; |
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 that is also borrowed from C++. All the text up to the end of the line is ignored:
int iVices = 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 identically 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 about it from the documentation that came with Sun's Java Developer's Kit or from Sun's Java home page (http://java.sun.com).
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 literals in Java that are used for different kinds of numbers, characters, strings, and Boolean values.
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 signfor example, -45.
Integers can also be expressed as octal or hexadecimal: a leading 0 indicates that a number is octalfor example, 0777 or 0004. A leading 0x (or 0X) means that it is in hex (0xFF, 0XAF45). Hexadecimal numbers can contain regular digits (09)
or uppercase or lowercase hex digits (af or AF).
Octal is base 8, meaning the only valid digits are 0-7.
Hexadecimal is base 16, which uses all the digits 0-9 and the letters A-F to represent values.
Floating-point literals usually have two parts: the integer part and the decimal partfor example, .5677777. 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 consist of the keywords true and false. These keywords can be used anywhere you need to test a positive or negative state, or to declare the only possible value for a Boolean variable, for example, bYes=true.
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 non-printable 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 (af or AF).
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 |
C and C++ programmers should note that Java does not include character codes for \a (bell) or \v (vertical tab).
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." "I like Visual J++" ""
Note that the last string listed in the preceding code is an empty string. This is a perfectly legal string in Visual J++.
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.
Just because you can represent a character using a Unicode escape sequence in your program, doesn't mean your computer can display that character. The computer or operating system you or someone else is running might not support Unicode, or the font you're using might not have a glyph (picture) for that character. Unicode escape code support in Java provides only the means to encode special characters. The system your program runs on must provide the support for 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 are the simplest form of statement in Java that actually accomplish 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.
Java has five operators for basic arithmetic. (See Table 4.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 might want to check out the Java Language Specification at Sun's official Java Web site; we're not
going to cover that much detail here.)
Listing 4.1 is an example of simple arithmetic.
Listing 4.1. Simple arithmetic.
1: class ArithmeticTest 2: { 3: public static void main (String args[]) 4: { 5: short siX = 6; 6: int iY = 4; 7: float fA = 12.5f; 8: float fB = 7f; 9: 10: System.out.println("x is " + siX + ", y is " + iY); 11: System.out.println("x + y = " + (siX + iY)); 12: System.out.println("x - y = " + (siX - iY)); 13: System.out.println("x / y = " + (siX / iY)); 14: System.out.println("x % y = " + (siX % iY)); 15: 16: System.out.println("a is " + fA + ", b is " + fB; 17: System.out.println("a / b = " + (fA / fB)); 18: } 19: 20: }
The following is a listing of the output that you would receive if you ran the preceding program using JVIEW.
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: siX and iY, which are integers (type int), and fA and fB, 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 systemto 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. The System.out.println() method takes a single argumenta
stringbut you can use + to concatenate values into a string, as you'll learn later today.
Variable assignment is a form of expression; in fact, because one assignment expression results in a value, you can string them together like this:
iX = iY = iZ = 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 4.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 |
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 does make 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 4.2 is a Java example of how all this works.
Listing 4.2. Test of prefix and postfix increment operators.
1: class PrePostFixTest 2: { 3: 4: public static void main (String args[]) 5: { 6: int ix = 0; 7: int iy = 0; 8: 9: System.out.println("x and y are " + ix + " and " + iy ); 10: ix++; 11: System.out.println("x++ results in " + ix); 12: ++x; 13: System.out.println("++x results in " + ix); 14: System.out.println("Resetting x back to 0."); 15: ix = 0; 16: System.out.println(""); 17: iy = ix++; 18: System.out.println("y = x++ (postfix) results in:"); 19: System.out.println("x is " + ix); 20: System.out.println("y is " + iy); 21: System.out.println(""); 22: 23: y = ++x; 24: System.out.println("y = ++x (prefix) results in:"); 25: System.out.println("x is " + ix); 26: System.out.println("y is " + iy); 27: System.out.println(""); 28: 29: } 30: 31: }
The following is the output from the preceding program.
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 ix alone using both prefix and postfix increment operators. In each, ix 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 iy = ix++, in which the postfix increment operator is used. In this result, the value of ix is incremented after that value is assigned to iy. Hence the result: iy is assigned the
original value of ix (0), and then ix is incremented by 1.
In the third part, you use the prefix expression iy = ++ix. Here, the reverse occurs: ix is incremented before its value is assigned to iy. Because ix is 1 from the previous step, its value is incremented (to 2), and then that value is assigned to iy.
Both ix and iy end up being 2.
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 ix to iy before ix is incremented" isn't precisely right. Instead, Java takes the value of ix and "remembers" it, evaluates (increments) ix, and then assigns the original value of ix to iy. 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 more detailed information for expression evaluation in Java.
Java has several expressions for testing equality and magnitude. All of these expressions return a Boolean value, either true or false. Table 4.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 |
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.
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 4.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 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.7 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.
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' 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, but
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.
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 (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 a string concatenation is not a string, it is automatically converted to a string, making
it easy to create these sorts of output lines.
An object or type can be converted to a String object 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 togetherthe descriptions plus the variablesand 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:
sMyName += " Jr.";
This expression is equivalent to this:
sMyName = sMyName + " Jr.";
just as it would be for numbers. In this case, it changes the value of sMyName, which might be something like John Smith having a Jr. at the endJohn Smith Jr.
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.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: I didn't see any way to define constants.
A: You can't create local constants in Java; you can create constant instance and class variables only. 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.