Home » Java Basics » 02 - Java Concepts
2

Operators

The use of operators to manipulate variables

Operators are used to manipulate variables. In the last section, we saw how the equality operator was used. Following is a table that contains common operators, descriptions, and examples of how it is used.

Operator Description Example Explanation
= Simple Assignment x = y Sets y equal to the value of x
Arithmetic Operators
+ additive operator(also used for String concatenation) z = x+y Adds y to x
- Subtraction operator z = x-y Subtracts y from x
* Multiplication operator z = x*y computes x times y
/ Division operator z = x/y divides x by y
% Modulus operator z = x%y returns remainder after x is divided by y (7%3 returns 2)
Unary Operators
+ Unary plus operator; indicates positive value +x converts x to a positive value
- Unary minus operator; negates an expression -x converts x to a negative value
++ Increment operator ++ i increments value in i by 1
-- Decrement operator -- i decrements value in i by 1
! Logical complement operator !someCondition inverts the value of someCondition
Equality Operators
== equal to a == b returns true if value in a equals value in b
!= not equal to y != z returns true if value in y does not equal value in z
greater than x > y returns true if x is greater than y
>= greater than or equal to x >= y returns true if x is greater than or equal to y
less than x < y returns true if x is less than y
<= less than or equal to x <= y returns true if x is less than or equal to y
Conditional Operators
&& Conditional AND x && y returns true only if both x and y are true
|| Conditional OR x || y returns true if either x or y or both are true
?: If-then Shorthand >condition?(x = y):(x = z) if 'condition' is true, x equals y; otherwise x equals z
Type Comparison Operator
instanceof Tests Object Type x instanceof String returns true if x is of the same type/class as String
  1. Arithmetic operators may be combined with '=' to create compound assignments. For example, i += 1; and i = i+1; both increment the value of x by 1.
  2. The + operator can also be used for combining or concatenating two strings ("also " + "combine" will equal "also combine")
  3. Difference between prefixed and suffixed increment/decrement - 'i++' and 'i--' increment/decrement after the rest of the line of code is executed (the line on which they occur uses the initial value) while '++i' and '--i' increment/decrement before the rest of the line of code is executed (the line on which they occur use the increment/decrement value)If i contains 5, j+(i++) evaluates to j+5 and i is incremented afterwards while j+(++i) evaluates to j+6.
  4. The Java programming language also provides operators that perform bitwise and bit shift operations on integers represented as sequences of 0s and 1s. These operators shift the sequence of bits to the left, right and so on and are rarely used.