Expressions and Assignment Statements
Expressions and Assignment Statements
Expressions
-
An expression is any combination of variables, literals, method invocations, operators, and parentheses constructed according to the syntax of the language. Expressions will compute a value.
-
Expressions can be simple or complex. An example of a simple expression is
5 + 2
. A complex expression might involve multiple operations:5 + 2 * 3
. -
The order of operations in Java follows the standard mathematical rules, often encapsulated by the acronym BIDMAS or PEMDAS: Brackets/parentheses, indices/exponents, division and multiplication (from left to right), and addition and subtraction (from left to right).
-
Java features a range of operators that can be used to construct expressions, including arithmetic operators (
+
,-
,*
,/
,%
), assignment operators (=
,+=
,-=
,*=
,/=
,%=
, etc.), and comparison operators (>
,<
,==
,!=
,>=
,<=
).
Assignment Statements
-
An assignment statement gives a variable a new value. This is done using the
=
operator. For example,int a = 5;
ora = 3;
The variable on the left side of the=
takes the value of the expression on the right side. -
It’s important to match the type of the variable on the left side of the assignment with the potential result of the expression on the right side. So you shouldn’t try to assign a
String
result to anint
variable, for instance. -
Compound assignment operators are a shortcut for performing an operation and assignment at the same time. For example,
a += 3;
is equivalent toa = a + 3;
. -
Increment (
++
) and decrement (--
) operators are a shorthand way of increasing or decreasing a variable’s value by one.a++
is equivalent toa = a + 1;
. Similarly,a--
is equivalent toa = a - 1;
. -
Be aware of the difference between pre-increment/pre-decrement (where the operation is performed before the variable’s value is used in an expression) and post-increment/post-decrement (where the operation is performed after the value is used). So, if
a
equals 5, thenint b = a++;
setsb
equal to 5 anda
becomes 6, whereasint c = ++a;
setsc
to 6 whilea
becomes 6 as well. -
Assignment statements can be used within more complex expressions, but keep in mind that the assignment itself has a value–the value being assigned. This means you can chain assignments, such as
a = b = c = 5;
, which sets all three variables to 5.
Boolean Expressions
-
A Boolean expression is a Java expression that, when computed, returns a Boolean value: true or false.
-
Relational operators (
<
,<=
,>
,>=
,==
,!=
) are typically used in Boolean expressions. They compare two values and return a Boolean result. -
Logical operators (
&&
,||
,!
) can also be used in Boolean expressions. These take one or more Boolean values and return a Boolean result.&&
returns true if both operands are true,||
returns true if either operand (or both) are true, and!
returns the opposite of the following Boolean value.