Web solution, Websites help, Java help, C & C# Language help

Tuesday, January 8, 2008

Java Help, Java Tutorials, Java Programming, Java Tricks



Java Help, Java Tutorials, Java Programming, Java Tricks

Lesson Three

Java Basics






CONTENTS



Statements and Expressions



Variables and Data Types

Declaring Variables

Notes on Variable Names

Variable Types

Assigning Values to Variables



Comments



Literals

Number Literals

Boolean Literals

Character Literals

String Literals



Expressions and Operators

Arithmetic

More About Assignment

Incrementing and Decrementing

Comparisons

Logical Operators

Bitwise Operators

Operator Precedence



String Arithmetic

Summary

Q&A



Already this week you've learned about Java programming in very broad terms-what
a Java program andan 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:

Java statements and expressions

Variables and data types

Comments

Literals

Arithmetic

Comparisons

Logical operators

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 provide information about the specific differences

between these and other traditional languages and Java.

Statements and Expressions

A statement indicates the simplest tasks you can accomplish 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. You'll learn about

these later today.



White space in Java statements, as with C, is unimportant. A statement can be
contained on a single line

or on multiple lines, and the Java compiler will be able to read it just fine.
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
on Day 5, "Arrays,

Conditionals, and Loops."



Variables and Data Types

Variables are locations in memory in which values can be stored. Each one has 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 (you can also declare and assign a value to a variable at the same
time, as you'll learn in this

section).



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

Instance variables, as you learned yesterday, are used to define the attributes
of 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 on Day 5. 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 that 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 on one line:

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.

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
includes several thousand 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.

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:

One of the eight primitive data types

The name of a class or interface

An array

You'll learn about how to declare and use array variables on Day 5; this lesson
focuses on the primitive

and class types.

Primitive Types

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.

Table 3.1. Integer types.

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

Note that all the primitive types are in lowercase. Be careful when you use them
in your programs that

you do use the lowercase, because there are also classes with the same names
(and an initial capital

letter) that have different behavior-so, for example, the primitive type boolean
is different from the

Boolean class. You'll learn more about these special classes and what they're
used for on Day 4,

"Working with Objects."

Class Types

In addition to the eight primitive 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 hold instances of the named class or of any of its
subclasses. The latter is

useful when you want a variable to be able to hold different instances of
related classes. For example,

let's say you had a set of fruit classes-Apple, Pear, Strawberry, and so on- all
of which inherited

from the general class Fruit. By declaring a variable of type Fruit, that
variable can then hold

instances of any of the Fruit classes. Declaring a variable of type Object means
that variable can

hold any object.



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 =, like this:

size = 14;

tooMuchCaffiene = true;



Comments

Java has three kinds of comments: two for regular comments in source code and
one for the special

documentation system javadoc.

The symbols /* 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 identically to the first
type of comment.

javadoc is used to generate API documentation from the code. You'll learn more
about javadoc on

Day 22, "Java Programming Tools."

Literals

Literal is a programming language term that 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 are used to indicate simple
values in your Java

programs.



New Term

A literal is a simple value where "what you type is what you get."

Numbers, characters, and strings are all examples of literals.

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.77777. A floating-point literal results in a floating-point number of type
double, regardless of the

precision of the 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).

Table 3.2. Character escape codes.

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

simply 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 Unicode

characters for systems that support Unicode.

Java 1.1 will provide better capabilities for the display of Unicode

characters and for handling international character sets.

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 data 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: All

expressions, when evaluated, return a value (other statements don't necessarily
do so). 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.

Most of the expressions in Java use operators. Operators are special symbols for
things like arithmetic,

various forms of assignment, increment and decrement, and logical operations.

New Term

Expressions are statements that return a value.

New Term

Operators are special symbols that are commonly used in expressions.

Arithmetic

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

Table 3.3. Arithmetic operators.

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 the result type of most arithmetic operations involving integers is an
int regardless of the

original type of the operands (shorts and bytes are both automatically converted
to int). 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 on Sun's official Java Web site at http://java.sun.com/;
that's more

detail than I want to cover here.)

Listing 3.1 is an example of simple arithmetic in Java.

Listing 3.1. 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: }

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



Analysis

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. The System.out.println() method takes a
single

argument-a string-but you can use + to concatenate multiple values into a single
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.

Table 3.4. 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

Technically, the shorthand assignment and longhand expressions are

not exactly equivalent, particularly in cases where x or y may

themselves be complicated expressions and your code relies on side

effects of those expressions. In most instances, however, they are

functionally equivalent. 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
variable's 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 yield 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.

Listing 3.2. Test of prefix and postfix increment operators.

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: }

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

Table 3.5. 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 && operators. The entire expression
will be true only if both

expressions on either side of the operator 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 is assumed to be false (the value of the right side
doesn't matter), so the expression

returns false, and the right side of the expression is never evaluated. (This is
often called a

"short-circuited" expression.)

For OR expressions, use either | or ||. OR expressions result in true if either
or both of the expressions

on either side is also true; if both expression operands are false, the
expression is false. As with & and

&&, the single | evaluates both sides of the expression regardless of the
outcome; and || is

short-circuited: 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. Most of these
expressions 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 3.6

summarizes the bitwise operators.

Table 3.6. 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.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.

Table 3.7. Operator precedence.

Operator Notes

. [] () Parentheses (()) are used to group expressions; dot

(.) is used for access to methods and variables

within objects and classes (discussed tomorrow);

square brackets ([]) are used for arrays (this is

discussed later on in the week)

++ -- ! ~

instanceof

The instanceof operator returns true or

false based on whether the object is an instance

of the named class or any of that class's subclasses

(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

&= |= <<= >>= >>>= More 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 parenthetic 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 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 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 print 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 have 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 have 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 have
learned about today so that

you can refer back to them.

Table 3.8. 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: 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 any of the primitive 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.

Q: You covered simple math in this section using operators. I'm assuming that
Java has ways

of doing more complex math operations?

A: You assume correctly. A special class in the java.lang package, called
java.lang.Math,

has a number of methods for exponential, trigonometric, and other basic math
operations. In fact,

because you call these methods using the Math class itself, these are prime
examples of class

methods. You'll learn more about this tomorrow.

No comments: