The most common uses for variables and data are in expressions. Expressions are combinations of literal values, variables, operators, and expressions. Operators are the symbols used in expressions to manipulate operands. Operands are the variables and literals used in the expression. For example:
employee_number = 21456;
The variable employee_number and the integer value 21456 are the operands. The (=) equals sign is the assignment operator that assigns the value 21456 to employee_number.
Variables | var x, y, returnValue; | |
---|---|---|
Addition Operator | x = 60;
y = 20; returnValue = x + y; |
returnValue is 80 |
Subtraction Operator | x = 60;
y = 20; returnValue = x - y; |
returnValue is 40 |
Multiplication Operator | x = 60;
y = 20; returnValue = x * y; |
returnValue is 1200 |
Division Operator | x = 60;
y = 20; returnValue = x / y; |
returnValue is 3 |
Modulus Operator | x = 60;
y = 20; returnValue = x % y; |
returnValue is 0 |
Two other types of operators that are commonly used are the prefix operator and the postfix operator. These are the (++) increment and (--) decrement operators that can be placed before and after a variable. To show, ++number is returned after it has been incremented by one, while number++ is returned before it has been incremented by one.
Assignment operators are the (=) equals sign and any arithmetic operator adjoined in front of it. For example, x = x + y is the same as x += y. You can combine two strings in the same manner.
You can also combine the equals sign with other symbols to create comparison operators. Comparison operators include (==) is equal to, (!=) not equal to, (>) greater than, (<) less than, (>=) greater than or equal to, and (<=) less than or equal to. Using these with variables creates Boolean expressions. Other Boolean operators are (&&) and, (||) or, and (!) not. These are considered logical operators. These are most often used in conditional and looping statements that we will get to in later lessons.
Another operator that can be used to combine two strings is called a concatenation operator, which uses the (+) plus sign to join two strings. Say you had a form that asked for the user's first name on one line and their last name on the second line. If you wanted to display them together, this is how you'd write the script:
document.write(firstName + lastName);
Question: This seems like a bunch of mumble-jumble. You say what these things are used for. Are we going to see how to use these operators?
Answer: Although it may seem like mumble-jumble, this lesson was only meant to be informative. Yes, you will find out how to use these as we explore decision making with if, if...else, and switch statements.
Return to : Java
Programming Hints and Tips