Java Chapter 2 Flashcards

(280 cards)

1
Q

questions

A

answers

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

What are Java operators?

A

Special symbols that operate on variables, values, or literals and return a result.

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

What are operands?

A

The values or variables being operated on by an operator.

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

What is the result of an operation?

A

The value produced after applying an operator to operands.

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

What are the three types of Java operators?

A

Unary, binary, and ternary.

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

How many operands does a unary operator work on? Give an example.

A

One operand (e.g., -a, ++a).

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

How many operands does a binary operator work on? Give an example.

A

Two operands (e.g., a + b, x > y).

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

How many operands does the ternary operator work on? Write its syntax.

A

Three operands (e.g., condition ? trueVal : falseVal).

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

Is ++x a unary or binary operator?

A

Unary (only operates on x).

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

Is a * b a unary or binary operator?

A

Binary (operates on a and b).

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

What symbol represents the ternary operator in Java?

A

? : (e.g., x > 5 ? “Yes” : “No”).
Let me know if you’d like more questions or refinements!

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

What is the output of this code?

```java
int cookies = 4;
double reward = 3 + 2 * –cookies;
System.out.println(“Zoo animal receives: “ + reward + “ reward points”);
~~~

A

“Zoo animal receives: 9.0 reward points”(Explanation: –cookies decrements first (3), then 2 * 3 = 6, then 3 + 6 = 9.)

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

What determines the order of evaluation in Java expressions?

A

Operator precedence (higher precedence operators are evaluated first).

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

How does Java handle operators with the same precedence?

A

They are evaluated left to right (except for assignment operators, which are right-associative).

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

How can you override default operator precedence?

A

Use parentheses () to force evaluation order (e.g., (3 + 2) * cookies).

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

What does the bitwise negation operator (~) do?

A

Flips all bits of an integer (e.g., ~70 becomes -71).

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

What is the output of this code?

```java
int number = 70;
System.out.println(~number);
~~~

A

-71

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

Can ~ be used on boolean values?

A

❌ No, it only works on integers.

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

Why does this code fail?

```java
int pelican = !5;
~~~

A

! is a logical operator and cannot be applied to numbers (only booleans).

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

Why does this code fail?

```java
boolean penguin = -true;
~~~

A

The - operator cannot be used on booleans (only numbers).

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

Why does this code fail?

```java
boolean peacock = 10;
~~~

A

Java does not allow assigning integers (10) to booleans (true/false).
Q: What is the difference between ++x and x++?A:
Pre-increment (++x): Updates x before using its value.
Post-increment (x++): Uses the current value of x, then increments it.
Q: What is the value of x and y after this code?

```java
int x = 5;
int y = x++ * 2;
~~~

A:
x = 6 (post-increment)
y = 10 (original x value 5 * 2)
Let me know if you’d like more questions or clarifications!

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

What are binary operators in Java?

A

Operators that work with two operands (values/variables) to perform math, logic, or assignments.

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

Give an example of a binary operator.

A

3 + 5 (+ is the binary operator, 3 and 5 are operands).

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

What three tasks do binary operators perform?

A

Binary operators typically perform three types of tasks:
1. Arithmetic operations
• Examples: +, -, *, /, %
• Task: Perform mathematical calculations.
2. Relational/comparison operations
• Examples: ==, !=, <, >, <=, >=
• Task: Compare two values and return a boolean.
3. Logical operations
• Examples: &&, ||, ^
• Task: Combine boolean expressions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Which operators are evaluated after parentheses?
Unary operators (e.g., -a, ++x, !true).
26
What comes after unary operators in precedence?
Multiplicative operators (*, /, %).
27
What operators follow multiplicative ones?
Additive operators (+, -).
28
Which operators are used to compare values?
Relational operators (<, <=, >, >=).
29
How does Java check for equality?
With equality operators (==, !=).
30
What is the difference between && and ||?
• && (logical AND): Returns true only if both conditions are true • || (logical OR): Returns true if at least one condition is true
31
What is the result of 5 + 3 * 2?
11 (* has higher precedence than +).
32
How would parentheses change 5 + 3 * 2 to get 16?
(5 + 3) * 2 (forces addition first).
33
Why does boolean flag = 1; cause an error?
Java does not allow numbers (1) to be assigned to booleans (true/false).
34
What is the output of this code? ```java int x = 5; System.out.println(x++ + ++x); ```
12 (Post-increment x++ uses 5, then pre-increment ++x makes x 7 before addition: 5 + 7).
35
What does x += 3 mean?
Shortcut for x = x + 3.
36
Write the equivalent of y = y * 4 using a compound operator.
y *= 4.
37
What does z %= 2 do?
Stores the remainder of z / 2 back into z (e.g., if z=5, result is 1).
38
What is the golden rule of operator precedence?
Higher precedence operators are evaluated first. Use () to override.
39
Can relational operators (>, <) be used with booleans?
❌ No, they only work with numbers.
40
Is == the same as =?
No! == checks equality, = assigns a value. Let me know if you'd like more examples or a deeper dive into any section!
41
Which operators have the highest precedence?
Postfix operators (expr++, expr--).
42
What does x++ do?
Uses the current value of x, then increments it (post-increment). Example: ```java int x = 5; System.out.println(x++); // Output? ``` A: 5 (value used first, then incremented to 6).
43
Which unary operators are part of the prefix operator group in Java, and what do they do?
These are unary prefix operators in Java, applied before the operand: • ++expr → Pre-increment: Increments expr before using its value • --expr → Pre-decrement: Decrements expr before using its value • +expr → Unary plus: Indicates a positive value (rarely used) • -expr → Unary minus: Negates a value • !expr → Logical NOT: Inverts a boolean (true becomes false) • ~expr → Bitwise complement: Flips each bit (only for integers)
44
What is the output? ```java int y = 3; System.out.println(--y); ```
2 (pre-decrement: decrements before use).
45
What does ~0b1 (bitwise negation of binary 1) return?
-2 (flips all bits: 0b1 → 0b111...1110 in two's complement).
46
List the multiplicative operators.
*, /, %.
47
What is 5 % 2?
1 (remainder of division).
48
Which operators are additive?
+, -. Example: ```java System.out.println(3 + 2 * 4); ``` A: 11 (* has higher precedence than +).
49
What does x << 2 do?
Shifts bits of x left by 2 (equivalent to multiplying by 4). Example: ```java System.out.println(1 << 2); ``` A: 4 (binary 01 → 0100).
50
What does instanceof do?
Checks if an object is an instance of a class (e.g., obj instanceof String).
51
Is 5 <= 5 true or false?
true (less than or equal).
52
What is the difference between == and !=?
== checks if two values are equal. != checks if two values are not equal.
53
What is the output? ```java System.out.println(5 & 3); // 0101 & 0011 ```
1 (bitwise AND: 0001).
54
What does ^ (XOR) do?
Returns true if operands are different (e.g., true ^ false → true).
55
Why is && preferred over & for booleans?
&& short-circuits (stops if first operand is false). Example: ```java false && (x++ > 0); // Does `x++` execute? ``` A: ❌ No (short-circuiting avoids unnecessary evaluation).
56
Rewrite this using if-else: ```java int max = (a > b) ? a : b; ```
int max; if (a > b) { max = a; } else { max = b; } x = x + 5. Example: ```java int x = 2; x *= 3 + 2; // What is `x`? ``` A: 10 (x = 2 * (3 + 2) due to precedence).
57
How to remember precedence?
PEMDAS + extras: Parentheses Exponents (not in Java, but Math.pow) Multiplicative (*, /, %) Additive (+, -) Shift/Relational/Equality/Bitwise/Logical/Ternary/Assignment.
58
What is the safest way to override precedence?
Use parentheses () to explicitly group operations. Let me know if you'd like more examples or a deeper dive into bitwise operations!
59
Do ++, --, +, -, !, or ~ promote byte/short/char to int?
❌ No. They operate directly on the original type. Example: ```java short s = 5; s++; // What type is `s` now? ``` A: Still short (remains 5 if printed after increment).
60
Does b += 5 promote byte b to int?
❌ No. It implicitly casts back to the original type: ```java byte b = 10; b += 5; // Equivalent to: b = (byte)(b + 5); ```
61
What happens if the result overflows?
Silent truncation (e.g., byte b = 127; b += 1; → -128).
62
Does char c == 65 promote c to int?
❌ No. Java compares the numeric value directly (char ↔ int allowed).
63
Can you compare boolean with ==?
✅ Yes, but only with other booleans (e.g., true == false → false).
64
What is the result type of byte b1 = 5, b2 = 10; b1 + b2?
int (even though both operands are byte). Example: ```java byte b = 5; short s = 10; var result = b + s; // Type? ``` A: int (promoted before the operation).
65
Does byte b = true ? 1 : 2; compile?
✅ Yes (literal values within byte range are allowed).
66
What if the values are variables? ```java byte b1 = 1, b2 = 2; byte result = true ? b1 : b2; // Compile? ```
✅ Yes (both sides are byte).
67
What if one side is int? ```java byte b = 1; int i = 2; var result = true ? b : i; // Type? ```
int (promoted to the larger type).
68
What is the result type of 5.0 + 3?
double (promoted to the wider type).
69
What is the result of 'A' + 1.5f in Java, and why?
✅ Answer: The result is a float value: 66.5. Explanation: • 'A' is a char, which has the Unicode value 65. • 1.5f is a float. • In the expression 'A' + 1.5f, the char is first promoted to int (65), then to float, due to type promotion rules. • So: 65 (int) + 1.5 (float) = 66.5 (float)
70
Why does this fail? ```java byte b = 5; b = b + 2; // Error? ```
❌ b + 2 is int (can’t assign back to byte without casting).
71
So, how would you go about fixing, you know, B is equal to 5 plus 2? How would you go about fixing that? Or, B is equal to B plus 2, that's what I meant to say.
Use += or explicit cast: ```java b += 2; // OR b = (byte)(b + 2); ```
72
What’s the output? ```java System.out.println(5 / 2); ```
2 (integer division). Use 5.0 / 2 for 2.5. Final Tip: "Small" types (byte, short, char) are promoted to int in most operations. +=/-= are safe (auto-cast back). For mixed types, think "widest type wins." Need a mnemonic? "Be Safe, Cast Intentionally" (BSCI: byte, short, char → int). Let me know if you’d like practice questions!
73
What happens when you add two byte variables?
Both are promoted to int, and the result is int. ```java byte b1 = 10, b2 = 20; int result = b1 + b2; // Requires int (compile error if assigned to byte). ```
74
Why does this fail? ```java byte b = 5; b = b + 2; // Error? ```
b + 2 is int (can’t assign back to byte without casting). Fix: Use += or explicit cast: ```java b += 2; // OR b = (byte)(b + 2); ```
75
What is the type of ~b if b is a byte?
int (promoted before bitwise operation). ```java byte b = 0b1010; int r = ~b; // ~00001010 → 11110101 (as int, value -11). ```
76
Can you do bitwise ops on float/double?
❌ No (only int, long, char, byte, short).
77
What is the type of s << 2 if s is a short?
int (left operand promoted). ```java short s = 5; int r = s << 2; // 5 (00000101) → 20 (00010100). ```
78
What if the left operand is long?
Stays long (no promotion needed). ```java long l = 10L; long r = l << 2; // 40L. ```
79
What happens when comparing short and int?
short promoted to int first. ```java short s = 10; if (s < 20) { ... } // s converted to int. ```
80
Can you compare boolean with
❌ No (only numeric types).
81
What is the type of true ? 5 : 10.5?
double (promoted to the wider type). Example: ```java int a = 5; double b = 10.5; double r = (true) ? a : b; // a promoted to double. ```
82
What if both branches are byte? ```java byte b1 = 1, b2 = 2; byte r = (true) ? b1 : b2; // Compiles? ```
✅ Yes (no promotion if both are byte). "Small" types (byte, short, char) promote to int in arithmetic/bitwise/shift ops. Mixed types: Promote to the widest type (e.g., int + double → double). Ternary operator: Resolves to the most general type of the two branches. Mnemonic: "Be Safe, Cast Intentionally" (BSCI: byte, short, char → int). Q1: What is the type of 'A' + 1L?A: long (char promoted to long). Q2: Why does byte b = (true) ? 1 : 2; compile but byte b = (true) ? 1 : 128; fail?A: Literals within byte range (-128 to 127) are allowed; 128 is too large. Q3: What is the result of 5 / 2 vs. 5 / 2.0?A: 2 (integer division) vs. 2.5 (floating-point division). Need more examples? Ask for specific scenarios!
83
Do long, float, or double ever get promoted further?
❌ No - they're the "dominant" types in mixed operations.
84
Can boolean participate in type promotion?
❌ Never! Only works with logical operators (&&, ||, !). Example: ```java boolean flag = true; int x = flag + 5; // Compile error? ``` A: ✅ Yes! boolean can't be used in arithmetic.
85
What type results from short s = 5; s++;?
Still short (Postfix/Unary: ❌ No promotion).
86
What happens in byte b = 10; b += 5;?
Stays byte (Assignment: ❌ No promotion, auto-casts back).
87
What's the type of byte b = 1; short s = 2; b + s?
int (Arithmetic: ✅ Always promotes).
88
Why does 5 / 2 give 2 but 5 / 2.0 gives 2.5?
First is int division (truncates), second promotes to double.
89
Why does Java promote small types to int?
Unintended truncation: ```java byte b = (byte) (128 + 128); // -256 (overflow)! ``` Memorize:🔹 "Unary/assignment never promote"🔹 "Arithmetic/bitwise always do" Visual Cue: ```java Small types (byte/short/char) → int → long/float/double ↑ ↑ No promotion here Always promotes here ``` Q1: What's the output? ```java byte b = 100; b = b + b; // Compiles? ``` A: ❌ No! b + b is int (can't assign to byte without cast). Q2: What type is 'A' + 1.5f + 100L?A: float (promotion chain: char→float→long → float wins). Q3: Which operator never causes promotion?A) + B) += C) <
90
How does Java evaluate 3 - 2 + 5?
Left-to-right → (3 - 2) + 5 = 6 (same precedence level).
91
What about 3 / 2 * 4?
Left-to-right → (3 / 2) * 4 = 4 (integer division first: 3/2=1). Key Rule: "Same-level operators go left → right, unless parentheses override."
92
Can you do true * false?
❌ No! Booleans only work with &&, ||, !.
93
Which operator works on String?
+ (concatenation): ```java String s = "Hi " + 5; // "Hi 5" (int auto-converted to String) ``` Pitfall: ```java System.out.println("5" * 2); // ❌ Compile error (no `*` for Strings) ```
94
What is 9 / 2 in Java?
4 (drops decimal, not rounding).
95
How get 4.5 instead?
Use a double: ```java System.out.println(9.0 / 2); // 4.5 ```
96
What is 9 % 2?
1 (remainder after division).
97
What about 10 % 3?
1 (10 ÷ 3 = 3 with remainder 1). Pro Tip: *"Modulus is clock math: 7 % 12 = 7 (like 7:00 on a 12-hour clock)."* Q1: What is 10 / 3 / 2?A: 1 → Evaluates left-to-right: (10 / 3) / 2 → 3 / 2 = 1. Q2: What is "5" + 2 * 3?A: "56" → * first: 2 * 3 = 6, then "5" + 6 → string concatenation. Q3: Why is 5 / 0 a runtime error but 5.0 / 0 gives Infinity?A: Integer division by zero → ArithmeticException. Floating-point division by zero → Infinity (IEEE 754 rule). 🔹 "Division chops, modulus wraps, Strings only add." Need practice? Try: ```java System.out.println(11 % 3 * 2); // What’s the output? ``` Answer: 4 (11 % 3 = 2 → 2 * 2 = 4). Ask for more puzzles! 🧩
98
What happens when the divisor (right-hand number) is negative?
Java ignores the negative sign! ```java System.out.println(7 % -5); // Output? → 2 (same as 7 % 5) ```
99
What if the dividend (left-hand number) is negative?
The result keeps the negative sign. ```java System.out.println(-7 % 5); // Output? → -2 ``` Mnemonic: "Divisor's sign? Forget it! Dividend's sign? Keep it!" Positive Dividend: ```java System.out.println(2 % 5); // ? → 2 System.out.println(7 % -5); // ? → 2 ``` A: Both output 2 (divisor's sign ignored). Negative Dividend: ```java System.out.println(-2 % 5); // ? → -2 System.out.println(-7 % -5); // ? → -2 ``` A: Both output -2 (dividend's sign preserved).
100
How is the % operator in Java different from how we normally calculate remainders in regular math?
Java uses truncated division (rounds toward zero), not floor division. Compare: Python: -7 % 5 → 3 (math-style remainder) Java: -7 % 5 → -2 (truncated toward zero).
101
What is -10 % -3?
-1 (dividend negative → result negative; divisor sign ignored). Breakdown: Ignore divisor sign: -10 % 3 10 / 3 = 3 with remainder 1 → -10 % 3 = -1 Remember: ```java a % b = a - (a / b) * b ``` Where / is integer division (truncates). Example: ```java -7 % 5 = -7 - (-7 / 5 * 5) = -7 - (-1 * 5) = -2 ``` Need practice? Try: ```java System.out.println(-12 % 5); // ? → -2 ``` Ask for more edge cases! 🚀
102
What is numeric promotion?
Java automatically converts smaller numeric types to larger ones when mixed in operations.
103
Why does Java do this?
To prevent data loss and ensure consistent results. Key Metaphor: "Like pouring a small cup (short) into a bigger bucket (int) – no spills!" Memorize This Order:byte → short → int → long → float → double Mnemonic:"Bring Sugar In Large Fluffy Doses"
104
What happens in int + double?
int promotes to double → result is double. ```java int a = 5; double b = 3.2; System.out.println(a + b); // 8.2 (double) ```
105
What type is ++myByte if myByte is a byte?
Still byte (unary ops don't promote).
106
Does short s = 5; s += 2; promote?
❌ No – compound assignment auto-casts back. Example 1: ```java short x = 10; int y = 20; var result = x + y; // Type? ``` A: int (smaller short promotes to int). Example 2: ```java float f = 1.5f; long l = 10L; var result = f * l; // Type? ``` A: float (long promotes to float).
107
What about char? does it promote to int with arithmetic ops
Promotes to int in arithmetic ops: ```java char c = 'A'; System.out.println(c + 1); // 66 (int) ```
108
Can boolean be promoted?
❌ Never! boolean stays boolean. Trap 1: Integer Division ```java double d = 5 / 2; // Result? ``` A: 2.0 (division happens first as int, THEN assigned to double). Fix: ```java double d = 5.0 / 2; // 2.5 ``` Trap 2: Overflow ```java byte b = 100 + 28; // Compile error? ``` A: ✅ Yes! 100 + 28 is int (can't assign to byte without cast). Remember: "Smaller type always yields to bigger type" "int is Java's favorite – small types promote to it first!" "Floating-point dominates over integer" Final Check: ```java System.out.println('A' + 1.5f + 100L); // Type? → float ``` Why? Promotion chain: char→float→long → float wins! Need practice? Ask for custom examples! 🎯
109
What happens in int a = 5; double b = 3.2; a + b?
int promotes to double → result is double (8.2). Key Concept: "When types differ, the smaller one grows to match the larger." Visual Aid: ```java byte → short → int → long → float → double (Small) --------------------------> (Big) ```
110
Why does 3 + 2.5 give 5.5?
Java promotes 3 (int) to 3.0 (double) first. Tricky Example: ```java System.out.println(5 / 2.0); // Output? ``` A: 2.5 (int 5 → double 5.0 before division). Common Mistake: ```java double d = 5 / 2; // Result? → 2.0 (integer division first!) ```
111
What type is byte b = 1; short s = 2; b + s?
int (both promoted to int first). Why? "Java's CPU loves working with int – it's the native size!" Example: ```java char c = 'A'; System.out.println(c + 1); // Output? → 66 (char → int) ```
112
What type is 2.5f * 3.0f?
float (both operands are float).
113
What about 100L - 50L?
long (both long → result stays long). Critical Exception: ```java int big = 2_000_000_000; System.out.println(big * 2); // Output? → Overflow! (-294967296) ``` Even with same types, watch for overflow! Spot the Trap: ```java short s1 = 5, s2 = 10; short sum = s1 + s2; // Compile error! (result is int) ``` Fix It: ```java short sum = (short)(s1 + s2); // Explicit cast ``` Remember: / with integers → truncates + with String → concatenation boolean never promotes "Be Smart, Ints Love Floating Doubles"(Byte → Short → Int → Long → Float → Double) Practice Question: ```java System.out.println('A' + 1.5f + 100L); // Final type? ``` Answer: float (promotion chain: char→float→long → float wins). Need more? Ask for real-world coding scenarios! 🚀
114
115
Do unary operators (++, --) promote byte, short, or char to int?
No, unary operators preserve the original type (no promotion).
116
On which primitive types do unary operators (++, --) work?
All numeric types: byte, short, char, int, long, float, double.
117
What is the result type if one operand is a double?
double (highest precedence).
118
What is the result type if one operand is a float (but no double)?
float.
119
What is the result type if one operand is a long (but no double or float)?
long.
120
What happens to byte, short, or char operands in arithmetic operations?
They are promoted to int (if no double, float, or long is present).
121
Does short s = 5; s++; require casting?
No, because ++ is a unary operator (no promotion to int).
122
What is the result type of byte b1 = 2; byte b2 = 3; byte sum = b1 + b2;?
Compilation error—arithmetic operations promote byte to int, so int must be cast back to byte.
123
What is the result type of 5 / 2?
int (both operands are int).
124
What is the result type of 5.0 + 2?
double (because of the double operand). Let me know if you'd like any modifications or additional questions!
125
Do compound assignment operators (+=, -=, etc.) promote byte, short, or char to int?
No, they implicitly cast the result back to the original type (no promotion).
126
Will byte b = 5; b += 3; compile? What about b = b + 3;?
Yes, the first promotes to int (like arithmetic operators). but not the second
127
What is the result type of byte b1 = 0b1010; byte b2 = 0b0101; b1 & b2;?
int (bitwise operations promote byte to int).
128
What is the result type of double + int?
double (follows the widest type).
129
What is the result type of float + long?
float (float > long in hierarchy).
130
What is the result type of short + char?
int (both promoted to int before operation).
131
Does short s = 1; s++; require promotion?
No (unary ++ preserves short).
132
Does byte b = 1; b = b * 2; compile?
❌ No—* promotes byte to int; needs casting: b = (byte)(b * 2);.
133
Does char c = 'A'; c += 1; compile?
✅ Yes (compound assignment handles casting).
134
What is the result of 5 / 2.0?
2.5 (double due to 2.0).
135
What is the type of ~0b1010 (where 0b1010 is a byte)?
int (bitwise ~ promotes byte to int).
136
Why does float f = 10.0 + 5L; compile without casting?
10.0 is double → 5L is promoted to double, then implicitly narrowed to float. Let me know if you’d like more questions or adjustments! This covers all the edge cases from your notes.
137
What is Java's widening order for primitive numeric types?
byte → short → char → int → long → float → double
138
What is the result type if one operand is a double?
double (highest precedence).
139
What is the result type if one operand is a float (but no double)?
float.
140
What happens to byte, short, or char in arithmetic operations (e.g., +, *)?
They are promoted to int (if no double, float, or long is present).
141
Will this compile? ```java double x = 39.21; float y = 2.1; // missing 'f' suffix var z = x + y; ```
❌ No! 2.1 is treated as a double literal (default for decimals). Java won’t implicitly narrow double to float.
142
How do you fix it?
Declare y as float y = 2.1f;. Then: y is promoted to double. z becomes double.
143
What is the type of z here? ```java short x = 10, y = 3; var z = x * y; ```
int (Rule 3: short → int before multiplication).
144
Why does this fail? ```java short z = x * y; ```
Compile error! Result is int, which can’t be stored in short without casting: ```java short z = (short)(x * y); ```
145
What is the type of 10 / 3?
int (both operands are int → result is truncated to 3).
146
What is the type of 10L + 5.0f?
float (float > long in hierarchy).
147
What is wrong here? ```java byte b = 100; b = b + 1; ```
❌ b + 1 promotes byte to int → needs casting: ```java b = (byte)(b + 1); ``` Bonus: Why does b++ work? Unary ++ doesn’t promote (original type preserved). Let me know if you’d like more examples or refinements! This covers all the nuances from your notes.
148
What is the step-by-step promotion for short w = 14; float x = 13; double y = 30; var z = w * x / y;?
Absolutely — let’s walk through the correct step-by-step type promotion for this Java expression: ⸻ 💻 Code: short w = 14; float x = 13; double y = 30; var z = w * x / y; ⸻ 🔍 Step-by-Step Promotion: 1. w * x → short * float • short is automatically promoted to float • Result: float * float → float 2. (w * x) / y → float / double • float is promoted to double • Result: double / double → double 3. var z → inferred from the final result • Result is double • So z is a double ⸻ ✅ Final Types Involved: short → float → double So this is: double z = (double)((float)w * x) / y; ⸻ ✅ Summary: Step Promotion Result Type w * x short → float float (w * x) / y float → double double var z inferred as double Let me know if you want a cheat sheet for all binary promotion rules — from byte to double — in arithmetic expressions!
149
What happens when assigning an int to a short?
❌ Compile error (risk of data loss). Requires explicit cast: ```java int b = 1000; short a = (short) b; // Narrowing ```
150
What is widening? Give an example.
Automatic conversion to a larger type (e.g., int → double). Safe, no cast: ```java double d = 100; // int → double ```
151
What is narrowing? Why does it require a cast?
Manual conversion to a smaller type (e.g., double → int). Risky (data loss possible): ```java int i = (int) 3.14; // Truncates to 3 ```
152
Will this compile? ```java byte b = 50; b = b * 2; ```
❌ No! b * 2 promotes to int. Requires cast: ```java b = (byte)(b * 2); ```
153
What is the result type here? ```java char c = 'A'; var r = c + 1L; ```
long (char → int → int + long → long).
154
Why does this work? ```java float f = 10; // int → float ```
Widening is implicit (safe). Need more examples or adjustments? Let me know! This covers all your new cases with clarity.
155
Why does this fail? ```java float egg = 2.0 / 9; ```
❌ 2.0 is a double → result is double. Can't store double in float without casting: ```java float egg = (float)(2.0 / 9); // Fixed! ```
156
Why does this fail? ```java int tadpole = (int)5 * 2L; ```
❌ Cast applies only to 5 → (int)5 * 2L is long (can't store long in int). Fix: ```java int tadpole = (int)(5 * 2L); // Cast the final result. ```
157
Why does this fail? ```java short frog = 3 - 2.0; ```
❌ 3 - 2.0 is double (due to 2.0) → can't store in short. Fix: ```java short frog = (short)(3 - 2.0); // Explicit cast. ```
158
Why does int fish = 1.0; fail?
❌ 1.0 is double → narrowing to int requires cast: ```java int fish = (int)1.0; ```
159
Why does short bird = 1921222; fail?
❌ 1921222 exceeds short’s max value (32,767).
160
Why does int mammal = 9f; fail?
❌ 9f is float → narrowing to int needs cast: ```java int mammal = (int)9f; ```
161
Why does long reptile = 192_301_398_193_810_323; fail?
❌ Java treats literals as int by default → number too large for int. Fix: ```java long reptile = 192301398193810323L; // Add 'L' suffix. ```
162
Why does long reptile = (long)192301398193810323; still fail?
❌ The literal itself is invalid (too large for int before casting). Must use L suffix. Literal Types: 5 → int, 5.0 → double, 5f → float, 5L → long. Assignment: Widening (auto): int → long, float → double. Narrowing (manual cast): double → int, long → short. Arithmetic Promotions: byte/short/char → int in arithmetic ops. Mixed types follow hierarchy: double > float > long > int.
163
Correct this statement: ```java double snake = 10 / 4; ```
To get 2.5: ```java double snake = 10.0 / 4; // Promote to double. ```
164
Correct this: ```java byte bat = (byte)128; ```
-128 (byte range: -128 to 127). Need more examples or clarifications? This covers all the edge cases from your notes!
165
What is overflow in Java?
When a number exceeds the maximum value a data type can hold, causing it to "wrap around" to the minimum value (like a clock going from 12 to 1).
166
What happens here? ```java short bird = (short)1921222; ```
❌ Overflow! short range: -32,768 to 32,767. Wraps around to 20678 (due to modulo arithmetic).
167
What is underflow?
When a number goes below the minimum value of a type (e.g., Integer.MIN_VALUE - 1 → Integer.MAX_VALUE).
168
Why does this fail? ```java short mouse = 10; short hamster = 3; short capybara = mouse * hamster; ```
❌ Compile Error! mouse and hamster are promoted to int before multiplication (Rule 3). Result is int, which can't be stored in short without casting: ```java short capybara = (short)(mouse * hamster); ```
169
What’s the risk even after casting?
Potential overflow if the result exceeds short’s range (e.g., (short)32768 → -32768).
170
What is the value of byte b = (byte)128;?
-128 (byte range: -128 to 127).
171
What does this print? ```java int max = Integer.MAX_VALUE; System.out.println(max + 1); ```
-2147483648 (wraps to Integer.MIN_VALUE). Promotion in Arithmetic: byte, short, char → int (even if both operands are small). Assignment: Narrowing requires explicit casting (risk of overflow/underflow). Literal Limits: short: -32,768 to 32,767 byte: -128 to 127
172
How can you safely multiply two short values?
Use int for the result: ```java int result = mouse * hamster; // No casting needed. ```
173
What’s the safest way to handle large numbers?
Use long or BigInteger for extreme cases.
174
Will this compile? What’s the value? ```java byte bat = (byte)255; ```
✅ Yes, but value = -1 (255 wraps around in byte’s range). Need more examples? This covers the critical edge cases from your scenario!
175
What does the += operator do?
Performs addition and assignment in one step.Example: a += 5 → equivalent to a = a + 5.
176
Name the 4 main compound assignment operators.
✅ Answer: The 4 main compound assignment operators are: 1. += (addition assignment) 2. -= (subtraction assignment) 3. *= (multiplication assignment) 4. /= (division assignment)
177
Why does this work without an explicit cast? ```java byte b = 10; b += 2; // ✅ ```
+= implicitly casts the result (int → byte), unlike b = b + 2 which would fail.
178
Fix this using a compound operator: ```java int x = 3; x = x * 2.5; // ❌ (lossy double → int) ```
-56 (overflow wraps around due to implicit cast).
179
Does this compile? ```java short s = 1; s = s + 1; ```
❌ No! s + 1 promotes to int. Fix: ```java s += 1; // ✅ OR s = (short)(s + 1); ```
180
What’s the difference between these? ```java long l = 10; int i = 5; i *= l; // ✅ i = i * l; // ❌ ```
When precision loss is critical (e.g., financial calculations). Example: ```java double account = 100.50; account *= 1.05; // Safe (uses double). ```
181
What’s a common pitfall with *=?
Silent overflow: ```java byte b = 100; b *= 2; // No error, but value = -56! ``` Need more edge cases? This covers the core concepts with practical examples!
182
What does the expression (x = 5) evaluate to?
The assigned value 5 (assignment operators return the value they assign).
183
What will this code print? ```java int wolf; long coyote = (wolf = 3); System.out.println(wolf); // ? System.out.println(coyote); // ? ```
Chain assignments or embed them in expressions: ```java int a, b, c; a = b = c = 10; // All variables get 10 ```
184
What’s the result of this? ```java int x; System.out.println(x = 15); // ? ```
Prints 15 (the assignment returns the value).
185
Does this compile? What’s the value of y? ```java boolean y; if (y = true) { ... } // ❓ ```
✅ Yes, but risky! y = true assigns true to y and returns true. Likely a bug (meant to use == for comparison).
186
What’s the output? ```java int z; double d = (z = 20) / 5.0; System.out.println(d); // ? ```
4.0 (assignment returns 20, then division occurs). All assignments return a value: =, +=, -=, etc., return the assigned value. Use Cases: Chain assignments: a = b = 0; Embed in conditions (but avoid confusion with ==). Watch Out: Accidental assignments in conditions (if (x = 5) vs if (x == 5)).
187
What does this do? ```java int m, n; m = n = 10 * (5 + 2); ```
In conditions where clarity is critical: ```java // Unclear: while (line = readNextLine()) { ... } // Better: while ((line = readNextLine()) != null) { ... } ``` Need more examples? This covers the sneaky-but-useful behavior of assignment returns!
188
How does == work with primitives (e.g., int, double)?
Checks if values are identical: ```java int a = 5, b = 5; System.out.println(a == b); // true ```
189
How does == work with objects (e.g., String)?
Checks if memory references are the same (not content!): ```java String s1 = new String("Hi"); String s2 = new String("Hi"); System.out.println(s1 == s2); // false (different objects) ```
190
How to compare object content?
Use .equals(): ```java System.out.println(s1.equals(s2)); // true (same content) ```
191
Why does boolean monkey = true == 3; fail?
❌ Incompatible types (boolean vs. int).
192
Why does boolean ape = false != "Grape"; fail?
❌ Cannot compare boolean with String.
193
What’s wrong with 10.2 == "Koko"?
❌ double and String are incomparable. Key Rule: Both sides of ==/!= must be compatible types (primitives with primitives, objects with objects).
194
Does this compile? ```java char c = 'A'; int i = 65; System.out.println(c == i); // ? ```
✅ Yes! char is promoted to int (value 65 → prints true).
195
What about this? ```java Integer x = 10; Double y = 10.0; System.out.println(x == y); // ? ```
❌ Fails (Integer and Double are incompatible object types).
196
What’s the output? ```java String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // ? ```
true (due to string pooling, but never rely on this—use .equals()!).
197
Why is this dangerous? ```java if (isReady = true) { ... } // ❓ ```
Accidentally assigns true instead of checking (==). Always do: ```java if (isReady) { ... } ``` Need more examples? This covers the critical exam traps and real-world usage!
198
What does == compare when used with objects?
Checks if both variables reference the same memory location (not content). Example: ```java File monday = new File("schedule.txt"); File tuesday = new File("schedule.txt"); System.out.println(monday == tuesday); // false (different objects) ```
199
How can two variables evaluate to true with ==?
If they point to the same object: ```java File wednesday = tuesday; System.out.println(tuesday == wednesday); // true ```
200
Why is == unreliable for comparing object content?
It only checks memory addresses. Use .equals() for content comparison: ```java String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 == s2); // false System.out.println(s1.equals(s2)); // true ```
201
When does == return true for String objects?
Only if they reference the same object (or due to string pooling): ```java String a = "Hi"; String b = "Hi"; System.out.println(a == b); // true (string pool optimization) ```
202
Can == compare different numeric types (e.g., int and double)?
✅ Yes! Java promotes the smaller type first: ```java int x = 5; double y = 5.0; System.out.println(x == y); // true (x promoted to double) ```
203
What happens here? ```java Integer i = 10; Double d = 10.0; System.out.println(i == d); // ? ```
❌ Compile error (incompatible object types).
204
What’s wrong with this code? ```java if (userInput == "exit") { ... } // ❓ ```
Uses == instead of .equals() → fails for new String objects. Fix: ```java if ("exit".equals(userInput)) { ... } ```
205
Why does this behave unexpectedly? ```java File f1 = new File("data.txt"); File f2 = new File("data.txt"); System.out.println(f1 == f2); // false ```
#ERROR!
206
What’s the output? ```java String s1 = new String("Java"); String s2 = "Java"; System.out.println(s1 == s2); // ? ```
false (new forces a new object, breaking string pooling).
207
How to safely compare File objects?
Compare paths or use .equals() (if overridden): ```java file1.getAbsolutePath().equals(file2.getAbsolutePath()); ``` Need more examples? This covers the core pitfalls and best practices for object comparison!
208
What does the instanceof operator do?
Checks if an object is an instance of a specific class/interface.Example: ```java String name = "Ralph"; System.out.println(name instanceof String); // true ```
209
Can instanceof be used with primitives (e.g., int, double)?
❌ No! Only for objects and classes/interfaces.
210
What does null instanceof Object return? Why?
false — null isn’t an instance of any class (it’s the absence of an object).
211
What’s the output here? ```java String noObjectHere = null; System.out.println(noObjectHere instanceof String); ```
false (variable is null, not a String instance).
212
Why does null instanceof null fail to compile?
❌ Right side of instanceof must be a class/interface, not a value.
213
What’s the key requirement for a instanceof B to compile?
B must be a class/interface name, and a must be a reference type (not primitive).
214
Does this compile? ```java Integer x = 10; System.out.println(x instanceof Number); ```
✅ Yes (Integer is a subclass of Number).
215
What happens here? ```java Object obj = "Hello"; System.out.println(obj instanceof Integer); ```
false (runtime check: obj is a String, not Integer).
216
Why does this compile but return false? ```java String s = null; System.out.println(s instanceof Object); ```
Compiles because s is a reference type, but evaluates to false (null isn’t an object).
217
How is instanceof used in practice?
To safely cast after type checking: ```java if (animal instanceof Dog) { Dog dog = (Dog) animal; // Safe! } ```
218
What’s the output? ```java List list = new ArrayList<>(); System.out.println(list instanceof ArrayList); ```
true (ArrayList is the concrete class).
219
What if list were declared as List list = null;?
false (null fails all instanceof checks). Need more edge cases? This covers the core behavior and common gotchas!
220
What does the & (AND) operator do?
Returns true only if both operands are true.Truth Table: Example: ```java boolean sunny = true, warm = false; System.out.println(sunny & warm); // false ```
221
What does the | (OR) operator do?
Returns true if at least one operand is true.Truth Table:| A | B | A | B ||-----|-----|-------|| T | T | T || T | F | T || F | T | T || F | F | F | Example: ```java boolean rainy = true, windy = false; System.out.println(rainy | windy); // true ```
222
What’s unique about the ^ (XOR) operator?
Returns true only if operands differ (one true, one false).Truth Table: Example: ```java boolean cat = true, dog = true; System.out.println(cat ^ dog); // false ```
223
How do && and || differ from & and |?
They skip evaluating the right operand if the result is already determined.Example: ```java if (false && riskyOperation()) { ... } // `riskyOperation()` never runs! ```
224
What’s coming in Chapter 3 about instanceof?
Pattern matching simplifies type checks and casts: ```java if (obj instanceof String s) { // Directly use `s` as String System.out.println(s.length()); } ```
225
How will Chapter 7 expand on this?
Records and polymorphism will show instanceof with advanced object hierarchies. & vs &&: & always evaluates both sides. && stops if the left is false. ^ is rare but useful for toggle logic. instanceof evolution: Pattern matching (Java 16+). Integration with sealed classes (Java 17+).
226
What’s the output? ```java boolean a = true, b = false, c = true; System.out.println(a ^ b ^ c); ```
false (Equivalent to (a ^ b) ^ c → true ^ true → false). Need more examples? This covers both foundational logic and future Java features!
227
What are the two main conditional (short-circuit) operators in Java and their symbols?
Conditional AND (&&) and Conditional OR (||)
228
How does the Conditional AND (&&) operator behave?
If the left side (a) is false, the right side (b) is not evaluated at all
229
What's the key difference between logical & and conditional && operators?
& always evaluates both sides, while && stops if the left side is false
230
Why is short-circuiting more efficient?
It avoids unnecessary computations by skipping evaluation when the result is already determined
231
Show an example where short-circuiting prevents a NullPointerException
if (duck != null && duck.getAge() < 5) - if duck is null, getAge() won't be called
232
What would happen in this code without short-circuiting: if (duck != null & duck.getAge() < 5)?
It could throw a NullPointerException because both sides are evaluated regardless
233
In boolean zooOpen = true || (hour < 4), will (hour < 4) ever be evaluated?
No, because the left side is true so the OR condition is already satisfied
234
When should you use short-circuit operators instead of logical operators?
When you want to: 1) Avoid unnecessary computations, or 2) Prevent potential errors from evaluating the right side
235
Can you give another example where short-circuiting would be beneficial?
Checking array bounds before access: if (index < array.length && array[index] == 5)
236
Why might you sometimes want to use logical & or | instead of short-circuit operators?
When you specifically need both sides to be evaluated, such as when both operations have required side effects
237
How can short-circuit operators help with null checks?
if (obj != null && obj.isValid()) safely checks validity only if obj exists
238
Why should you put cheaper operations first in a conditional statement?
To potentially skip expensive operations (e.g., if (fastCheck() && expensiveCheck()))
239
What's a common use of short-circuiting in other languages like JavaScript?
Setting default values (e.g., name = user.getName() || "Anonymous")
240
Why doesn't the default value pattern (||) work directly in Java?
Java requires boolean operands for ||, unlike JavaScript which accepts truthy/falsy values
241
Why is order important in conditions involving division?
if (x != 0 && 100/x > 10) is safe, but reversing it could cause division by zero
242
What happens if you write if (100/x > 10 && x != 0) when x is 0?
It throws ArithmeticException before checking x != 0
243
Why should you avoid side effects in the right operand of short-circuit operators?
Because they might not execute (e.g., if (true || counter++) never increments counter)
244
What's the danger of writing if (false && initializeSystem())?
The initialization will never occur because the right side is skipped
245
How can short-circuit operators help with array or list access?
if (index >= 0 && index < array.length) prevents ArrayIndexOutOfBoundsException
246
Why might if (config != null && config.isDebugEnabled()) be better than a nested if?
It's more concise while maintaining safety against null references
247
In what scenario would you want to avoid short-circuit evaluation?
When both operations must execute regardless of the first result (e.g., for required side effects)
248
How does short-circuit evaluation affect performance in complex conditionals?
It can significantly improve performance by skipping unnecessary expensive operations
249
What's wrong with if (initialized || initialize()) when you need to ensure initialization?
If initialized is true, the initialize() call will be skipped, which might be undesirable
250
Why is if (file.exists() && file.canRead()) better than two separate if statements?
It combines checks concisely and avoids the second check if the file doesn't exist
251
What is the basic syntax of a ternary operator?
variable = condition ? valueIfTrue : valueIfFalse;
252
How does a ternary operator differ from an if-else statement in terms of what it can return?
Ternary must return a value, while if-else can execute arbitrary code blocks
253
When is using a ternary operator most appropriate?
For simple conditional assignments like default values or min/max checks
254
Show an example of a good ternary usage for finding the minimum of two numbers
int min = (a < b) ? a : b;
255
When should you avoid using ternary operators?
For complex logic or when nested ternaries would make code hard to read
256
What's wrong with this nested ternary: String result = x > 0 ? "Positive" : x < 0 ? "Negative" : "Zero"?
It becomes confusing and hard to read with multiple nested conditions
257
How do ternary operators handle side effects compared to short-circuit operators?
Ternary always evaluates one side, while &&/|| may skip evaluation
258
What will this code output: int x=1; int y=true?x++:x--; System.out.println(y);?
It will output 1 (the original value before post-increment)
259
What type requirement must ternary operator branches satisfy?
Both possible return values must be of compatible types
260
Why does "int num = true ? 1 : "two";" fail to compile?
Because the types (int and String) are incompatible
261
How can you use a ternary operator for safe null checking?
String name = (user != null) ? user.getName() : "Guest";
262
How can you make nested ternaries more readable?
By adding parentheses like: (owl < 4 ? ((owl > 2) ? 3 : 4) : 5)
263
What's one advantage of if-else statements over ternary operators?
They're clearer for complex logic and multi-step operations
264
Why might you choose a ternary over if-else in some cases?
When you want more concise code for simple conditional assignments
265
What happens if you try to put statements (rather than expressions) in a ternary?
It won't compile - ternaries only work with expressions that return values
266
What's the most important principle when deciding whether to use a ternary operator?
Always prioritize clarity over cleverness - make sure the code remains readable
267
How can you improve readability of nested ternary operators?
By using parentheses to explicitly group conditions, like: (a > b) ? ((c < d) ? 1 : 2) : 3
268
When should you definitely avoid using ternary operators?
For deeply nested logic where if-else statements would be much clearer
269
What type requirement must both sides of a ternary operator satisfy?
Both possible result values must be of the same compatible type
270
Show an example of proper type matching in a ternary operator
String msg = (score > 90) ? "A" : "B"; (both results are Strings)
271
Why is it dangerous to put side effects inside ternary operators?
Because it can lead to unexpected behavior and make code harder to debug
272
How should you handle operations with side effects when using ternaries?
Isolate them outside the ternary, like:int value = computeValue();int result = (flag) ? value : 0;
273
What's the benefit of putting the side effect computation before the ternary?
It makes the code's behavior more predictable and easier to understand
274
Why might String output = (x > 0) ? "Positive" : 42; fail to compile?
Because the two possible return types (String and int) are incompatible
275
What should you do if your ternary operator starts spanning multiple lines?
Consider refactoring it into an if-else statement for better readability
276
How can ternary operators actually improve code readability when used properly?
By concisely expressing simple conditional assignments in a single line
277
What's one situation where ternaries are particularly well-suited?
When assigning default values or implementing simple conditional logic
278
Why should you avoid complex expressions within ternary branches?
Because it can make the code harder to understand at a glance
279
What's a good rule of thumb for deciding ternary vs if-else?
If you can't understand it immediately, use if-else instead
280
How does proper use of ternaries affect code maintenance?
When used appropriately, they can make code more maintainable by reducing verbosity