Operators

Course Home

Operators are symbols that tell the compiler or an interpreter to provide specific logic operations or mathematical calculations.

Operators are tyically consistent across languages, so once you learn them in one language, the knowledge will transfer to others if you are using them on the same/equivalent types.

Arithmetic

Mostly used for math, but I see people use ‘+’ frequently with strings to combine them together.

Sample usage      In English          Result
a + b a plus b If the types were numbers, 1 + 2 would give you 3.
If they were strings, “richard” + “tester” would give you “richardtester”
a - b a minus b If the types were numbers, 5 -1 would give you 4
a * b a times b If the types were numbers, 2 * 2 would give you 4
a / b a divide b If the types were numbers, 8 / 2 would give you 4
a % b a mod b It returns the remainder of the division. So 8 % 5 would give you 3

Logical

Mostly used in control flow to help us control the flow of our code.

Sample usage      In English          Result
a & b Evaluate all values and returns logical conjunction (AND) If these are boolean, ‘true & false’ would return false.
a && b Evaluates all values, but stops if first value returns false So false && true would return false and not evaluate or run b.
a || b Evaluates all values and returns the logical disjunction (OR) Used in Control Flow to see if a or b is true and carry on
!a Basically means NOT This tends to only work on boolean types. !true if the expression is not true, carry on

Relational

Used for type comparisons. A lot of this logic is what a test framework like JUnit is doing under the hood.

Sample usage      In English          Result
a == b a is equal to b If a was “richard” and b was “richard” it would return true
a != b a is not equal to b If a was “richard” and b was “sarah” it would return true
a < b a is less than b 6 < 15 would return true
a > b a is greater than b 15 > 6 would return true
a <= b a is less than or equal to b 15 <= 15 would be true. 6 <= 15 would also return true
a >= b a is greater than or equal to b 15 >= 15 would be true. 25 >= 15 would also return true

Assigment

Sample usage      In English          Result
a = b make a the value of b if a was 7 and b was 10, after this code a would be assigned the value of 10
new object make a new instance of an object If we had a class called Person, Person richard = new Person() would make a new instance of Person called richard


Next Lesson ➔


References

Wikibooks - Operators

Richard Bradshaw's photo
Author

Richard Bradshaw

@FriendlyTester

Software Tester, speaker and trainer at Friendly Testing. BossBoss at Ministry of Testing. Whiteboard Testing creator. Striving to improve the testing craft.

Comments