Previous Page
Next Page

Assignments and Comparisons

When you put a value into a variable, you are assigning that value to the variable, and you use an assignment operator to do the job. For example, you use the equals operator to make an assignment, such as hisName="Tom". There are a whole set of assignment operators as listed in Table 1.4.

Table 1.4. Assignments

Assignment

What It Does

x = y

Sets x to the value of y

x += y

Same as x = x + y

x -= y

Same as x = x - y

x *= y

Same as x = x * y

x /= y

Same as x = x / y

x %= y

Same as x = x % y


Other than the equals sign, the other assignment operators serve as shortcuts for modifying the value of variables. For example, a shorter way to say x=x+5 is to say x+=5. For the most part, we've used the longer version in this book for clarity's sake.

Comparisons

You'll often want to compare the value of one variable with another, or the value of a variable against a literal value (i.e., a value typed into the expression). For example, you might want to compare the value of the day of the week to "Tuesday", and you can do this by checking if todaysDate=="Tuesday". A complete list of comparisons is in Table 1.5.

Table 1.5. Comparisons

Comparison

What It Does

x == y

Returns true if x and y are equal

x != y

Returns true if x and y are not equal

x > y

Returns true if x is greater than y

x > = y

Returns true if x is greater than or equal to y

x < y

Returns true if x is less than y

x <= y

Returns true if x is less than or equal to y

x && y

Returns true if both x and y are true

x || y

Returns true if either x or y is true

!x

Returns true if x is false


Tip

  • If you are comparing strings, be aware that "a" is greater than "A" and that "abracadabra" is less than "be".



Previous Page
Next Page