Chapter 3 Operators Flashcards

1
Q

Operation

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Operand

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

TYPES OF OPERATORS

A
  1. Unary
  2. Binary
  3. Ternary
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Java operators are not necessarily evaluated from left-to-right order

A
double reward = 3 + 2 * --cookies;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Order of operator precedence

A
  1. Post-unary operators
    expression++, expression--
  2. Pre-unary operators
    ++expression, --expression
  3. Other unary operators
    -, !, ~, +, (type)
  4. Multiplication/division/modulus
    *, /, %
  5. Addition/subtraction
    +, -
  6. Shift operators
    <<, >>, >>>
  7. Relational operators
    <, >, <=, >=, instanceof
  8. Equal to/not equal to
    ==, !=
  9. Logical operators
    &, ^, |
  10. Short-circuit logical operators
    &&, ||
  11. Ternary operators
    boolean expression ? expression1 :expression2
  12. Assignment operators
    =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Unary operators

A

By definition, a unary operator is one that requires exactly one operand, or variable, to function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Unary operators

A
  1. Inverts a boolean’s logical value
    !
  2. Indicates a number is positive, although numbers are assumed to be positive in Java unless accompanied by a negative unary operator
+
  1. Indicates a literal number is negative or negates an expression
-
  1. Increments a value by 1
++
  1. Decrements a value by 1
--
  1. Casts a value to a specific type.
(type)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

LOGICAL COMPLEMENT

A

The logical complement operator (!) flips the value of a boolean expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

NEGATION OPERATORS

A

negation operator, -, reverses the sign of a numeric expression

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
int pelican = !5; 
boolean penguin = -true; 
boolean peacock = !0;
A
  • will not compile because in Java you cannot perform a logical inversion (!) of a numeric value.
int pelican = !5; // DOES NOT COMPILE
  • does not compile because you cannot numerically negate a boolean value; you need to use the logical inverse operator.
boolean penguin = -true; // DOES NOT COMPILE
  • does not compile because you cannot take the logical complement of a numeric value, nor can you assign an integer to a boolean variable.
boolean peacock = !0; // DOES NOT COMPILE
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

in Java, 1 and true are not related in any way, just as 0 and false are not related.

A

in Java, 1 and true are not related in any way, just as 0 and false are not related.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

INCREMENT AND DECREMENT OPERATORS

A
  1. ++
  2. --
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

pre-increment operator

A

If the operator is placed before the operand, referred to as the pre-increment operator and the pre-decrement operator, then the operator is applied first and the value returned is the new value of the expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

post-increment operator

A

if the operator is placed after the operand, referred to as the post-increment operator and the post-decrement operator, then the original value of the expression is returned, with operator applied after the value is returned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Binary arithmetic operators

A
  1. +, Adds two numeric values
  2. -, Subtracts two numeric values
  3. *, Multiplies two numeric values
  4. /, Divides one numeric value by another
  5. %, Modulus operator returns the remainder after division of one numeric value by another
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

ARITHMETIC OPERATORS

A

Arithmetic operators are often encountered in early mathematics and include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).

Arithmetic operators also include the unary operators, ++ and –, which we covered already.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

All of the arithmetic operators may be applied to any Java primitives, with the exception of boolean.

only the addition operators + and += may be applied to String values, which results in String concatenation.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Adding Parentheses

A

you can change the order of operation explicitly by wrapping parentheses around the sections you want evaluated first.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Changing the Order of Operation

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Verifying Parentheses Syntax

A

When working with parentheses, you need to make sure they are always valid and balanced.

  • does not compile because the parentheses are not
    balanced. There is a left-parenthesis with no matching right-parenthesis.
long pigeon = 1 + ((3 * 5) / 3; // DOES NOT COMPILE
  • has an equal number of left and right parentheses, but they are not balanced properly. When reading from left to right, a new right-parenthesis must match a previous left-parenthesis. Likewise, all left-parentheses must be closed by right-parentheses before the end of the expression.
int blueJay = (9 + 2) + 3) / (2 * 4; // DOES NOT COMPILE
  • does not compile because Java, unlike some
    other programming languages, does not allow brackets, [], to be used in place of parentheses.
short robin = 3 + [(4 * 2) + 4]; // DOES NOT COMPILE
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

modulus operator

A

The modulus operator, often called the remainder operator, is simply the remainder when two numbers are divided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q
  • The modulus operation is not limited to positive integer values in Java;
  • it may also be applied to negative integers and floating-point numbers.
  • For example, if the divisor is 5, then the modulus value of a negative number is between -4 and 0.
  • For the exam, though, you are not required to be able to take the modulus of a negative integer or a floating-point number.
A
  • The modulus operation is not limited to positive integer values in Java;
  • it may also be applied to negative integers and floating-point numbers.
  • For example, if the divisor is 5, then the modulus value of a negative number is between -4 and 0.
  • For the exam, though, you are not required to be able to take the modulus of a negative integer or a floating-point number.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Division and Modulus Operators

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

floor value, it just means the value
without anything after the decimal point. For example, the floor value is 4
for each of the values 4.0, 4.5, and 4.9999999.

A

floor value, it just means the value without anything after the decimal point.

For example, the floor value is 4 for each of the values 4.0, 4.5, and 4.9999999.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
NUMERIC PROMOTION
26
primitive numeric promotion
27
**Numeric Promotion Rules**
**Numeric Promotion Rules:** 1. **If two values have different data types, Java will automatically promote one of the values to the larger of the two data types.** 2. **If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type.** 3. **Smaller data types, namely, byte, short, and char**, are **first promoted to *int* any time they’re used with a Java binary arithmetic operator**, even if neither of the operands is int. 4. **After all promotion has occurred and the operands have the same data type, the resulting value will have the same data type as its promoted operands.**
28
**applying ++ to a short value results in a short value.**
29
**What is the data type of x * y?** ``` int x = 1; long y = 33; var z = x * y; ```
If we follow the first rule, since one of the values is long and the other is int and since long is larger than int, then the int value is promoted to a long, and the resulting value is **long**.
30
**What is the data type of x + y?** ``` double x = 39.21; float y = 2.1; var z = x + y; ```
This is actually a trick question, as this **code will not compile!** As you may remember from Chapter 2, **floating-point literals are assumed to be double**, **unless postfixed with an f, as in 2.1f**. If the value of y was set properly to 2.1f, then the promotion would be similar to the previous example, with both operands being promoted to a double, and the result would be a double value.
31
**What is the data type of x * y?** ``` short x = 10; short y = 3; var z = x * y; ```
On the last line, we must apply the third rule, namely, that x and y will both be **promoted to int** before the binary multiplication operation, resulting in an output of type int. If you were to try to assign the value to a short variable without casting, the code would not compile. Pay close attention to the fact that the resulting output is not a short, as we’ll come back to this example in the upcoming “Assigning Values” section.
31
**What is the data type of w * x / y?** ``` short w = 14; float x = 13; double y = 30; var z = w * x / y; ```
In this case, we must apply all of the rules. First, will automatically be promoted to int solely because it is a short and it is being used in an arithmetic binary operation. The promoted w value will then be automatically promoted to a float so that it can be multiplied with x. The result of w * x will then be automatically promoted to a double so that it can be divided by y, **resulting in a double value.**
32
**As The Java Language Specification (JLS 3.10.2) states:** A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.
33
**Assigning Values**
An **assignment operator** is a binary operator that modifies, or assigns, the variable on the left side of the operator, with the result of the value on the right side of the equation. The simplest assignment operator is the **=**assignment
34
**=**
**Assigns the value on the *right* to the variable on the *left***
35
Java will automatically promote from smaller to larger data types, as you saw in the previous section on arithmetic operators, but it will throw a compiler exception if it detects that you are trying to convert from larger to smaller data types without casting.
**Java will automatically promote from smaller to larger data types,** as you saw in the previous section on arithmetic operators, but **it will throw a compiler exception if it detects that you are trying to convert from larger to smaller data types without casting.**
36
**CASTING VALUES**
**Casting is a unary operation** where one data type is explicitly interpreted as another data type. **Casting is optional and unnecessary when converting to a larger or widening data type**, but **it is required when converting to a smaller or narrowing data type.** Without casting, the **compiler will generate an error when trying to put a larger data type inside a smaller one.**
37
**Examples of casting:**
``` int fur = (int)5; int hair = (short) 2; //Spaces between the cast and the value are optional String type = (String) "Bird"; short tail = (short)(4 + 10); long feathers = 10(long); // DOES NOT COMPILE ```
38
``` float egg = 2.0 / 9; // DOES NOT COMPILE int tadpole = (int)5 * 2L; // DOES NOT COMPILE short frog = 3 - 2.0; // DOES NOT COMPILE ```
``` float egg = 2.0f / 9; int tadpole = (int)(5 * 2L); int tadpole2 = (int)5 * 2; short frog = (short)(3 - 2.0); ```
39
`int fish = 1.0; // DOES NOT COMPILE`
does not compile because you are trying to **assign a double 1.0 to an integer value**. Even though the value is a mathematic integer, by adding .0, you’re instructing the compiler to treat it as a double.
40
`short bird = 1921222; // DOES NOT COMPILE`
does not compile because the **literal value 1921222 is outside the range of short** and the compiler detects this.
41
`int mammal = 9f; // DOES NOT COMPILE`
does not compile because of the f added to the end of the number that instructs the compiler to treat the number as a floating-point value, but the assignment is to an int.
42
`long reptile = 192301398193810323; // DOES NOT COMPILE`
does not compile because **Java interprets the literal as an int and notices that the value is larger than int allows.** **The literal would need a postfix *L* or l to be considered a long.**
43
**Spaces between the cast and the value are optional.**
Spaces between the cast and the value are optional. ``` int hair = (short) 2; String type = (String) "Bird"; ```
44
`long feathers = 10(long); // DOES NOT COMPILE`
does not compile because **the type is on the wrong side of the value**.
45
**Primitive Assignments** `int fish = 1.0; // DOES NOT COMPILE`
does not compile because you are trying to **assign a double 1.0 to an integer value.** Even though the value is a mathematic integer, **by adding .0, you’re instructing the compiler to treat it as a double.**
46
``` int fish = 1.0; // DOES NOT COMPILE short bird = 1921222; // DOES NOT COMPILE int mammal = 9f; // DOES NOT COMPILE long reptile = 192301398193810323; // DOES NOT COMPILE ```
``` int trainer = (int)1.0; short ticketTaker = (short)1921222; // Stored as 20678 int usher = (int)9f; long manager = 192301398193810323L; ```
47
OVERFLOW AND UNDERFLOW
48
``` short ticketTaker = (short)1921222; // stored as 20678 ```
1,921,222, is too large to be stored as a short, so numeric overflow occurs and it becomes 20,678.
49
**Overflow**
**Overflow** is when a **number is so large that it will no longer fit within the data type**, so the system “wraps around” to the lowest negative value and counts up from there, similar to how modulus arithmetic works.
50
**underflow**
**underflow**, when the **number is too low to fit in the data type, such as storing -200 in a byte field.**
51
``` System.out.print(2147483647+1); // -2147483648 ```
**Since 2147483647 is the maximum int value, adding any strictly positive value to it will cause it to wrap to the smallest negative number.**
52
``` short mouse = 10; short hamster = 3; short capybara = mouse * hamster; // DOES NOT COMPILE ```
**short values are automatically promoted to int when applying any arithmetic operator,** with the resulting value being of type int. Trying to assign a short variable with an int value results in a compiler error, as Java thinks you are trying to implicitly convert from a larger data type to a smaller one.
53
``` short mouse = 10; short hamster = 3; short capybara = mouse * hamster; // DOES NOT COMPILE ```
``` short mouse = 10; short hamster = 3; short capybara = (short)(mouse * hamster); //fix ```
54
``` short mouse = 10; short hamster = 3; short capybara = (short)mouse * hamster; // DOES NOT COMPILE ```
**casting was a unary operation**, cast only applied to mouse, and mouse alone. After the cast is complete, both operands are promoted to int since they are used with the binary multiplication operator (*), making the result an int and causing a compiler error.
55
``` short mouse = 10; short hamster = 3; short gerbil = 1 + (short)(mouse * hamster); // DOES NOT COMPILE ```
casting is performed successfully, but the resulting value is automatically promoted to int because it is used with the binary arithmetic operator (+).
56
**COMPOUND ASSIGNMENT OPERATORS**
1. **+=** Adds the value on the right to the variable on the left and assigns the sum to the variable 2. **-=** Subtracts the value on the right from the variable on the left and assigns the difference to the variable 3. ***=** Multiplies the value on the right with the variable on the left and assigns the product to the variable 4. **/=** Divides the variable on the left by the value on the right and assigns the quotient to the variable
57
``` int camel = 2, giraffe = 3; camel = camel * giraffe; // Simple assignment operator camel *= giraffe; // Compound assignment operator ```
if camel were not already defined, then the expression camel *= giraffe would not compile.
58
**Compound operators**
1. **shorthand** 2. save us from having to explicitly cast a value, compiler will automatically cast the resulting value to the data type of the value on the left side of the compound operator. ``` long goat = 10; int sheep = 5; sheep = sheep * goat; // cannot assign long to int //fix sheep = (int)(sheep * goat); //fix sheep *= goat; ```
59
**ASSIGNMENT OPERATOR RETURN VALUE**
the result of an assignment is an expression in and of itself, equal to the value of the assignment.
60
the result of an assignment is an expression in and of itself, equal to the value of the assignment.
``` long wolf = 5; long coyote = (wolf=3); System.out.println(wolf); // 3 System.out.println(coyote); // 3 ```
61
``` long wolf = 5; long coyote = (wolf=3); System.out.println(wolf); // 3 System.out.println(coyote); // 3 ```
The key here is that (wolf=3) does two things. First, it sets the value of the variable wolf to be 3. Second, it returns a value of the assignment, which is also 3.
62
``` boolean healthy = false; if(healthy = true) System.out.print("Good!"); ```
The result of the assignment is the value of the assignment, which is true, resulting in this snippet printing Good!.
63
Comparing Values
used to check if two values are the same, check if one numeric value is less than or greater than another, and perform boolean arithmetic.
64
**EQUALITY OPERATORS**
**==** * **Primitive**: Returns **true** if the two values represent the **same value**. * **Object**: Returns **true** if the two values **reference the same object**. **!=** * **Primitive**: Returns **true** if the two values represent **different values**. * **Object**: Returns **true** if the two values do **not reference the same object**
65
**The equality operators are used in one of three scenarios:**
* **Comparing two *numeric* or character primitive types.** If the numeric values are of different data types, the values are **automatically promoted.** For example, 5 == 5.00 returns true since the left side is promoted to a double. * **Comparing two *boolean* values** * **Comparing two *objects*, including *null* and *String* values**
66
``` boolean monkey = true == 3; // DOES NOT COMPILE boolean ape = false != "Grape"; // DOES NOT COMPILE boolean gorilla = 10.2 == "Koko"; // DOES NOT COMPILE ```
``` boolean monkey = true == 3; // incomparable types: boolean and int boolean ape = false != "Grape"; // bad operand types for != boolean and String boolean gorilla = 10.2 == "Koko"; // bad operand types for == double and String ```
67
``` boolean bear = false; boolean polar = (bear = true); System.out.println(polar); // true ```
the expression is **assigning the value of true to bear** **the assignment itself has the value of the assignment.** Therefore, **polar is also assigned a value of true**, and the output is **true**.
68
**object comparison**
**For object comparison, the equality operator is applied to the *references* to the objects**, not the objects they point to. **Two references are equal if and only if they point to the same object or both point to *null*.**
69
``` File monday = new File("schedule.txt"); File tuesday = new File("schedule.txt"); File wednesday = tuesday; System.out.println(monday == tuesday); // false System.out.println(tuesday == wednesday); // true ```
Even though all of the variables point to the same file information, only two references, tuesday and wednesday, are equal in terms of == since they point to the same object.
70
In some languages, comparing null with any other value is always false, although this is not the case in Java. System.out.print(null == null); // true
**Java comparing null will always *true*.**
71
**RELATIONAL OPERATORS**
**compare two expressions and return a boolean value.**
72
**Relational operators**
1. **<** Returns true if the value on the left is strictly less than the value on the right 2. <= Returns true if the value on the left is less than or equal to the value on the right 3. **>** Returns true if the value on the left is strictly greater than the value on the right 4. **\>\=** Returns true if the value on the left is greater than or equal to the value on the right 5. **a instanceof b**, Returns true if the reference that a points to is an instance of a class, subclass, or class that implements a particular interface, as named in b
73
**Numeric Comparison Operators**
1. **<** Returns true if the value on the left is strictly less than the value on the right 2. <= Returns true if the value on the left is less than or equal to the value on the right 3. **>** Returns true if the value on the left is strictly greater than the value on the right 4. **>=** Returns true if the value on the left is greater than or equal to the value on the right
74
**instanceof Operator**
It is useful for determining whether an arbitrary **object** is a member of a particular **class** or **interface** at runtime.
75
It is common to use casting and instanceof together when working with objects that can be various different types, since it can give you access to fields available only in the more specific classes. It is considered a **good coding practice** to **use the instanceof operator prior to casting** from one object to a narrower type.
76
**Invalid instanceof**
``` public static void openZoo(Number time) { if(time instanceof String) // DOES NOT COMPILE ``` **Number cannot possibly hold a String value, so the following would cause a compilation error:** **rule applies to classes, but not interfaces.**
77
**null and the instanceof operator**
**calling *instanceof* on *the* null literal or a null reference always returns *false*.** ``` System.out.print(null instanceof Object); //false Object noObjectHere = null; System.out.print(noObjectHere instanceof String); //false ``` **does not compile, since null is used on the right side of the instanceof operator:** ``` System.out.print(null instanceof null); // DOES NOT COMPILE ```
78
**LOGICAL OPERATORS**
The **logical operators**, **(&), (|), and (^)**, may be applied to both **numeric** and **boolean** data types; When they’re applied to **boolean** data types, they’re referred to as **logical operators**. Alternatively, when they’re applied to **numeric** data types, they’re referred to as **bitwise operators**, as they perform bitwise comparisons of the bits that compose the number. **For the exam, though, you don’t need to know anything about numeric bitwise comparisons**
79
**Logical operators**
1. **& Logical AND** is true only if both values are true. 2. **| Inclusive OR** is true if at least one of the values is true. 3. **^ Exclusive XOR** is true only if one value is true and the other is false.
80
**Logical operator tips**
1. AND is only true if both operands are true. 2. Inclusive OR is only false if both operands are false. 3. Exclusive OR is only true if the operands are different.
81
**SHORT-CIRCUIT OPERATORS**
The short-circuit operators are nearly identical to the logical operators, & and |, except that the ***right* side of the expression may never be evaluated if the final result can be determined by the *left* side of the expression.**
82
**SHORT-CIRCUIT OPERATORS**
1. **&& Short-circuit AND** is true only if both values are true. If the left side is false, then the right side will not be evaluated. 2. **|| Short-circuit OR** is true if at least one of the values is true. If the left side is true, then the right side will not be evaluated.
83
**Avoiding a NullPointerException**
A more common example of where **short-circuit operators are used is checking for null objects before performing an operation.** ``` if(duck!=null & duck.getAge()<5) { // Could throw a NullPointerException // Do something } ``` ``` if(duck!=null && duck.getAge()<5) { // Do something } ```
84
**Checking for Unperformed Side Effects**
Because rabbit >= 6 is true, the increment operator on the right side of the expression is never evaluated, so the output is 6. ``` int rabbit = 6; boolean bunny = (rabbit >= 6) || (++rabbit <= 7); System.out.println(rabbit); ```
85
**Making Decisions with the Ternary Operator**
It is notable in that it is the **only operator that takes *three* operands.** The ternary operator has the following form: ``` booleanExpression ? expression1 : expression2 ``` The **first operand must be a boolean expression**, and the **second and third operands can be any expression that returns a value.** The ternary operation is really a condensed form of a combined if and else statement that returns a value.
86
``` int owl = 5; int food; if(owl < 2) { food = 3; } else { food = 4; } System.out.println(food); // 4 ```
``` int owl = 5; int food = owl < 2 ? 3 : 4; System.out.println(food); // 4 ``` Note that it is often helpful for **readability** to add **parentheses** around the expressions in ternary operations, although it is certainly **not required**. ```int food = (owl < 2) ? 3 : 4;```
87
For the exam, you should know that there is **no requirement** that **second and third expressions** in ternary operations have the **same data types**, although it does come into play when combined with the assignment operator.
``` int stripes = 7; System.out.print((stripes > 5) ? 21 : "Zebra"); int animal = (stripes < 9) ? 3 : "Horse"; // DOES NOT COMPILE ```
88
``` int stripes = 7; System.out.print((stripes > 5) ? 21 : "Zebra"); int animal = (stripes < 9) ? 3 : "Horse"; // DOES NOT COMPILE ```
89
**TERNARY EXPRESSION AND UNPERFORMED SIDE EFFECTS**
``` int sheep = 1; int zzz = 1; int sleep = zzz<10 ? sheep++ : zzz++; System.out.print(sheep+","+zzz); // 2,1 ``` Notice that since the left-hand boolean expression was true, only sheep was incremented.
90
int sheep = 1; int zzz = 1; int sleep = sheep>=10 ? sheep++ : zzz++; System.out.print(sheep+","+zzz); // 1,2
``` int sheep = 1; int zzz = 1; int sleep = sheep>=10 ? sheep++ : zzz++; System.out.print(sheep+","+zzz); // 1,2 ``` left-hand boolean expression evaluates to false, only zzz was incremented.
91
TERNARY EXPRESSION AND UNPERFORMED SIDE EFFECTS
For the exam, be wary of any question that includes a ternary expression in which a variable is modified in one of the right-hand side expressions.