OPERATORS IN JAVA

arithmetic assignment relational logical strings Exercises

Early in your schooling, you learned about the "+" symbol that represents the operation of addition. The + symbol is known as an operator. Of course, the symbol alone doesn't do anything-- you have to have two numbers to add, such as 5 + 3. In that expression, the + symbol is the operator, while the 5 and the 3 are known as "operands." The operation of addition takes those two operands and does something in order to produce a result. All operations produce a result. Sometimes that result is a number and sometimes it's a response like true or false.

Arithmetic Operators

+ - * / %
addition subtraction multiplication division modulo

Doing arithmetic in Java is very simple. You can use the arithmetic operators in the same way that you use them in math class. Here is an example of the addition operation used to initialize the value of a variable:

int y = x + 5;

Subtraction would work the same way:

int profit = revenue - cost;

For multiplication, you must use the * symbol:

int revenue = numberSold * unitPrice;

Be careful that you don't try something like this:

int y = 3x + 17;     --won't work!

because the "3x" will not be recognized as multiplication. Nor will it work to do something like this:

int y = 3(x + 4);     --don't do!

You must use the * symbol in every place that you want to have multiplication. This would be fine:

int y = 3 * (x + 4);

and the parentheses still have the same meaning as they do in ordinary arithmetic.

Division is represented by a slash:

float ratio = height/width;

Be careful with division, however. Its results can surprise you. In the example above, if the variables height and width were both declared as integers, then the value of the quotient would come out as an integer--whether that's the "real" answer or not! Look at this:

int height = 17;

int width = 5;

float ratio = height/width;

17 divided by 5 is actually 3.4, but in this situation the value of the variable named ratio would be 3. The same thing can happen when you are using integer literals in your quotient:

float oneFifth = 1/5;

In this case, the value of oneFifth will come out as 0. Probably not what you intended, and you don't get any error message to warn you about it. In general, if you do an operation with two integers, you will get another integer as a result. This is true of all of the data types-- an operation with two floats gives a float. If you mix the types, you will end up with a result of the more complicated type. For example, an integer divided by a double will give a double as a result.

The modulo operator works the same way that the keyword MOD does in BASIC. If you wanted the expression:

n MOD 5

you would write it this way in Java:

n % 5

It has nothing to do with percent, by the way, even though that symbol is used for the operator. If you need a refresher on how mods work, go here.


The Assignment Operator

You learned about the assignment operator in your basic programming class, and we have seen it already in the reading on variables. It simply assigns a value to a variable:

switchOn = true;

It sure looks like the equal sign, doesn't it? It's very hard not to think of it that way, but for computer science, you really need to think in terms of assignment. That variable named "switchOn" is assigned a value of true.

Notice that the variable name is on the left hand side of the assignment operator. This is mandatory. The variable you are assigning always goes on the left hand side. The right hand side will contain whatever expression you want to use to give the variable its value. That right-hand expression may be simply a number, or it may contain some operations, or it might be a call to a class constructor or to some method. Here are some examples:

pointsGained = level * 1000;

messageLabel = new Label();

currentGraphics = theApplet.getGraphics();

fraction = numerator/denominator;

luckyNumber = Math.random()* 100;

This is another way in which the assignment operator differs from the ordinary equal sign you are accustomed to. The assignment operator is not symmetrical. It definitely matters whether you place something on the left side or the right side.

You can also use the assignment operator to update the value of a variable:

n = n + 1;

You did this kind of incrementing in your basic class, too. Read that statement carefully, though. A variable named n is equal to itself plus 1? No number equals itself plus 1! But, of course, that is not the equal sign, so it's not saying that they're equal. It's the assignment operator and it's saying that n is now assigned to have a value one greater than it used to be.

That style of incrementing happens so often that there is a shortcut symbol for it. If you write:

n++;

it means exactly the same thing as:

n = n + 1;

Similarly, you can use n-- to decrease the value by one. There are other shortcut operators, which offer a variety of ways to be lazy when you are updating the value of a variable. We won't be using them, but you can find these in the tutorial if you are curious. I find they make the code harder to read, but if you like them, you may incorporate them in your own code.


Relational Operators

< < = > > = == !=
less than less than or equal to greater than greater than or equal to equal to not equal to

This set of operators allows you to compare two numbers to determine their relationship. Perhaps the two numbers are equal, or perhaps one is greater than the other. Often, you use these operators in the context of an "if" statement, because you are trying to find out if a certain relationship exists or not. For example, you might want to promote a game player to level two when the score exceeds 1000 points. That could be determined by this statement:

if (score > 1000)

Relational expressions always return a boolean response. It is either true or false that the score is greater than 1000.

The double equal sign (==), known as the equality operator, is very different from the single equal sign (=). The single equal sign is used to assign values to variables, while the double equal sign checks to see if two things really are equal to each other. As with other relational operators, the == operator will return a boolean response. Either the two things are equal or they're not. The == operator is used in the same way as the greater than and less than operators:

if (score == 1000)

This expression is either true or false. The equality operator can also be used to compare the value of two integer variables, like this:

if (score == bonusLevel)

and it will return true when those two variables have the same numerical value. That type of comparison will work with any type of primitive variable, including characters:

if (nextLetter == 'h')

Remember that you must use single quotation marks for a character literal.

You may also use the equality operator to compare two objects, like this:

if (clickedButton == okayButton)

This is a little trickier. When I ask it to compare two integers, it just checks to see if each integer has the same value. When it compares two buttons, what does it mean for them to be equal? It doesn't actually look at the buttons at all. Instead it checks to see if each variable refers to the same location in memory. If so, it returns true. This is especially important when comparing strings, as seen below.


Logical Operators

In your Basic Programming class, you used the keywords AND, OR and NOT. In Java, these keywords are replaced by symbols:

&& means "and"

|| means "or"

! means "not"

To use a conditional operator, be sure that each of the operands is a boolean expression:

if (x < 5 && y > 17)

The first operand, x < 5, is a boolean expression and y > 17 is another boolean expression. If both of those boolean expressions return true, then the entire conditional expression will return true and the "if" condition will be satisfied. On the other hand, if either one of them is false, the conditional expression will also be false. As it turns out, if the first operand is false, the second one will never even be evaluated. No point, since they both need to be true. That's known as "short-circuit" evaluation, since it saves some time.

The "or" operator will return true if either or both booleans are true:

if (responseLetter == 'y' || bonusLevel == 5)

With the || operator, the first operand will be evaluated and if it's true, the condition is already true and the second one will never be evaluated. If the first operand is false, the second one will be checked. The || operator comes back false only if both operands are false. By the way, the key for that vertical line is located just under the backspace key on your keyboard.

Read more about operators: Sun Java tutorial.
Skip section on Shift and Logical Operators
David Eck's textbook.

Operations with Strings

In general, Java operators are used only with primitives. An exception is made for strings. Even though string variables are not primitives, you can use the addition symbol with strings. This operation:

String combo = "stir "+ "fry";

will produce the string "stirfry" as its result and assign it to the variable named combo.

This addition of strings works not only with literals, but also with reference to other string variables:

String fullName = firstName + lastName;

The resulting string will actually combine the two into a single string. You can even put together variable names with string literals and the addition symbol will still work. This process of combining strings together is known as "concatenation." The subtraction symbol does not work with strings, however. To get part of a string, you need to use the substring method found in class String.

Java also allows you to use the equality operator (==) with strings. So you can type something like this:

if (guess == correctWord)

with two string variables and you won't get an error from the compiler. The problem is that strings are not primitives, so the equality operator won't be checking to see if guess and correctWord are actually the same text. Instead, it will check to see if they refer to the same location in memory. Depending on how the values of those variables were assigned, they may be the same text, but stored in different locations. So the answer could come back false, even though you think it should be true. A safer way to compare two strings is to use the equals method found in class String:

if (guess.equals(correctWord))

This will return true if the two string variables contain the same text, no matter where they are stored in memory. You can also use the "not" operator (!) to check for the opposite situation:

if (!guess.equals(correctWord))

Simply put the operator just inside the parentheses containing the boolean expression .


Exercises

  1. Confusing the assignment operator (=) and the equality operator (==) is perhaps the most common mistake in coding Java. It's hard to remember to use the double equal sign, especially because in your basic programming class, you used the same symbol in both situations. Use this short application to see what kind of error message you get when you make the mistake:

    public class Test{

    public static void main(String[] args){

    int favoriteNumber = 4;

    int uglyNumber = 23;

    if (favoriteNumber = uglyNumber - 19){

    System.out.println("it's true");

    }

    }

    }

    Write down that error message and keep it nearby when you are coding, so that you will be able to fix that problem on your own.


  2. Write up a short application and insert this statement in your code:

    2 + 3 = 5;

    Compiler doesn't like it, does it? What kind of error message do you get?


  3. 2 + 3 = 5 would be a fine statement to make in math class, but that is not an appropriate use of the assignment operator in a computer program. Try it this way:

    5 = 2 + 3;

    Do you get the same error message? Why can't you say that 5 is assigned to equal 2 plus 3?


  4. See what you need to change in the statement 5 = 2 + 3 to get the program to compile.


  5. Write an application to experiment with changing the values of these numbers and see what the integer quotient comes out to be.

    int height = 17;

    int width = 5;

    float ratio = height/width;

    Does the rounding work in the way you would expect it to?


  6. Take this code statement:

    String fullName = firstName + lastName;

    and alter it so that the resulting fullName string will have a space between the firstName string and the lastName string.


  7. What's wrong with this code statement?

    int x < = 20;



  8. Fix this line of code so that the value of oneFifth is .2 instead of 0:

    float oneFifth = 1/5;

    Put it in an application and test it with a System.out.println statement.

Previous Topic Java Home Page Syntax Sheet Next Topic