Expressions

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

What does the following assignment statement statement do:

sum = 2*sum ;

Answer:

  1. Evaluate the expression: get the value in sum and multiply it by two.
  2. Then, put that value into sum.

Normally you would say:

The statement doubles sum.

However, this is a little sloppy.

Expressions

Sometimes you need to think carefully about the two steps of an assignment statement. The first step is to evaluate the expression on the right of the assignment operator.

An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value.

This (slighly incomplete) definition needs some explanation:

  • literal — characters that directly give you a value, like: 3.456
  • operator — a symbol like plus + or times * that asks for an arithmetic operation.
  • variable — a section of memory containing a value.
  • parentheses — ( and ).

This might sound awful. Actually, this is stuff that you know from algebra, like:

(32 - y) / ( x + 5 )

In the above, the character / means division. Not just any mess of symbols will work. The following

32 - y) / ( x  5 + )

is not a syntactically correct expression. There are rules for this, but the best rule is that an expression must look OK as algebra. However, multiplication must always be shown by using a * operator. You can't multiply two variables by placing them next to each other. So, although xy might be correct in algebra, you must use x*y in Java.

QUESTION 19:

Which of the following expressions are correct? (Assume that the variables have been properly declared elsewhere.)

Expression 5312 - 3)x + 34*z   99 sum + value
Correct or Not?