<div class="core-java-notes">
<h1>Introduction to Java Operators and Expressions</h1>
<p><strong>Course:</strong> Core Java Training</p>
<p><strong>Topic:</strong> Introduction to Java Operators and Expressions</p>
<p><strong>Course Link:</strong> <a href="https://www.justacademy.co/course-detail/core-java-training" target="_blank" rel="noopener noreferrer">Core Java Training Course</a></p>
<p><strong>Demo Link:</strong> <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for a Course Demo</a></p>
<p><strong>JustAcademy Website:</strong> <a href="https://www.justacademy.co/" target="_blank" rel="noopener noreferrer">Visit JustAcademy</a></p>
<hr>
<h2>1. Introduction to Java Operators and Expressions</h2>
<p>Operators and expressions are fundamental parts of Java programming. They allow developers to perform calculations, compare values, assign data, check conditions, manipulate bits, and control how values are processed in a program.</p>
<p>An <strong>operator</strong> is a symbol or token that performs an operation on one or more values. An <strong>expression</strong> is a combination of values, variables, method calls, and operators that is evaluated to produce a result.</p>
<p>For example:</p>
<pre><code>int a = 10;
int b = 5;
int sum = a + b;</code></pre>
<p>In this example, <code>+</code> is an operator, and <code>a + b</code> is an expression. The expression evaluates to <code>15</code>, which is assigned to the variable <code>sum</code>.</p>
<p>Understanding operators and expressions is essential for writing programs that calculate results, validate user input, implement business rules, and make decisions.</p>
<h2>2. Learning Objectives</h2>
<p>After studying this topic, you should be able to:</p>
<ul>
<li>Define operators and expressions in Java.</li>
<li>Understand operands and how operators work with them.</li>
<li>Use arithmetic operators for mathematical calculations.</li>
<li>Apply assignment and compound assignment operators.</li>
<li>Compare values using relational and equality operators.</li>
<li>Build logical expressions using boolean operators.</li>
<li>Use unary, increment, decrement, and conditional operators.</li>
<li>Understand bitwise and shift operators.</li>
<li>Apply operator precedence and associativity.</li>
<li>Recognize type conversion, integer division, and short-circuit evaluation.</li>
<li>Identify common operator-related errors and follow coding best practices.</li>
</ul>
<h2>3. What Is an Operator?</h2>
<p>An operator is a symbol or token that instructs Java to perform an operation on one or more operands. Operands are the values or expressions on which an operator acts.</p>
<h3>Example</h3>
<pre><code>int result = 12 + 8;</code></pre>
<ul>
<li><code>12</code> is an operand.</li>
<li><code>8</code> is an operand.</li>
<li><code>+</code> is the operator.</li>
<li><code>12 + 8</code> is the expression.</li>
<li><code>result</code> is the variable that receives the computed value.</li>
</ul>
<h3>Operators Based on Number of Operands</h3>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Type</th><th>Description</th><th>Example</th></tr>
</thead>
<tbody>
<tr><td>Unary</td><td>Works with one operand.</td><td><code>-number</code></td></tr>
<tr><td>Binary</td><td>Works with two operands.</td><td><code>a + b</code></td></tr>
<tr><td>Ternary</td><td>Uses three operands in a conditional expression.</td><td><code>age >= 18 ? "Adult" : "Minor"</code></td></tr>
</tbody>
</table>
<h2>4. What Is an Expression?</h2>
<p>An expression is a valid combination of operands, operators, and sometimes method calls that produces a value. Expressions can be simple or complex.</p>
<h3>Simple Expression</h3>
<pre><code>int total = 10 + 20;</code></pre>
<p>The expression <code>10 + 20</code> produces the value <code>30</code>.</p>
<h3>Expression Using Variables</h3>
<pre><code>int price = 500;
int quantity = 3;
int totalCost = price * quantity;</code></pre>
<p>The expression <code>price * quantity</code> multiplies the price by the quantity, producing <code>1500</code>.</p>
<h3>Expression Using Comparison</h3>
<pre><code>int marks = 75;
boolean passed = marks >= 40;</code></pre>
<p>The expression <code>marks >= 40</code> evaluates to <code>true</code>, so <code>passed</code> receives the boolean value <code>true</code>.</p>
<h3>Expression Using Multiple Operators</h3>
<pre><code>int result = 10 + 5 * 2;</code></pre>
<p>The multiplication operator has higher precedence than addition, so Java evaluates <code>5 * 2</code> first. The final result is <code>20</code>, not <code>30</code>.</p>
<h2>5. Categories of Java Operators</h2>
<p>Java provides several operator categories, each designed for a particular type of operation.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Category</th><th>Operators</th><th>Purpose</th></tr>
</thead>
<tbody>
<tr><td>Arithmetic</td><td><code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code></td><td>Perform mathematical calculations.</td></tr>
<tr><td>Unary</td><td><code>+</code>, <code>-</code>, <code>++</code>, <code>--</code>, <code>!</code>, <code>~</code></td><td>Operate on a single operand.</td></tr>
<tr><td>Relational</td><td><code><</code>, <code>></code>, <code><=</code>, <code>>=</code></td><td>Compare numeric values or compatible values.</td></tr>
<tr><td>Equality</td><td><code>==</code>, <code>!=</code></td><td>Test equality or inequality.</td></tr>
<tr><td>Logical</td><td><code>&&</code>, <code>||</code>, <code>!</code></td><td>Combine or reverse boolean conditions.</td></tr>
<tr><td>Bitwise</td><td><code>&</code>, <code>|</code>, <code>^</code>, <code>~</code></td><td>Operate on individual bits.</td></tr>
<tr><td>Shift</td><td><code><<</code>, <code>>></code>, <code>>>></code></td><td>Shift bits left or right.</td></tr>
<tr><td>Assignment</td><td><code>=</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>, <code>%=</code></td><td>Assign or update variable values.</td></tr>
<tr><td>Conditional</td><td><code>? :</code></td><td>Select one of two expressions based on a condition.</td></tr>
<tr><td>Type comparison</td><td><code>instanceof</code></td><td>Check whether an object is compatible with a specified type.</td></tr>
</tbody>
</table>
<h2>6. Arithmetic Operators</h2>
<p>Arithmetic operators perform mathematical calculations on numeric values. They are commonly used in billing systems, marks calculations, financial applications, unit conversions, and data processing.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Operator</th><th>Name</th><th>Example</th><th>Result</th></tr>
</thead>
<tbody>
<tr><td><code>+</code></td><td>Addition</td><td><code>10 + 5</code></td><td><code>15</code></td></tr>
<tr><td><code>-</code></td><td>Subtraction</td><td><code>10 - 5</code></td><td><code>5</code></td></tr>
<tr><td><code>*</code></td><td>Multiplication</td><td><code>10 * 5</code></td><td><code>50</code></td></tr>
<tr><td><code>/</code></td><td>Division</td><td><code>10 / 5</code></td><td><code>2</code></td></tr>
<tr><td><code>%</code></td><td>Remainder</td><td><code>10 % 3</code></td><td><code>1</code></td></tr>
</tbody>
</table>
<h3>6.1 Addition Operator (+)</h3>
<p>The addition operator adds two numeric values. When one operand is a string, <code>+</code> can instead concatenate text.</p>
<pre><code>int a = 15;
int b = 10;
System.out.println(a + b);
System.out.println("Java " + "Programming");</code></pre>
<p><strong>Output:</strong></p>
<pre><code>25
Java Programming</code></pre>
<h3>6.2 Subtraction Operator (-)</h3>
<p>The subtraction operator calculates the difference between two numeric values.</p>
<pre><code>int totalMarks = 100;
int obtainedMarks = 82;
int remainingMarks = totalMarks - obtainedMarks;
System.out.println(remainingMarks);</code></pre>
<p><strong>Output:</strong> <code>18</code></p>
<h3>6.3 Multiplication Operator (*)</h3>
<p>The multiplication operator multiplies two numeric operands.</p>
<pre><code>int price = 250;
int quantity = 4;
int totalPrice = price * quantity;
System.out.println(totalPrice);</code></pre>
<p><strong>Output:</strong> <code>1000</code></p>
<h3>6.4 Division Operator (/)</h3>
<p>The division operator divides one numeric value by another. The result depends on the operand types.</p>
<pre><code>int a = 10;
int b = 3;
System.out.println(a / b);
System.out.println(10.0 / 3);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>3
3.3333333333333335</code></pre>
<p>When both operands are integers, Java performs integer division and discards the fractional part of the result. If at least one operand is floating-point, the operation uses floating-point arithmetic.</p>
<h3>6.5 Remainder Operator (%)</h3>
<p>The remainder operator returns the remainder after division. It is useful for checking even and odd numbers and for working with repeating cycles.</p>
<pre><code>int number = 17;
System.out.println(number % 5);
System.out.println(10 % 2);
System.out.println(11 % 2);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>2
0
1</code></pre>
<p>A remainder of zero when dividing an integer by two indicates that the number is even.</p>
<h3>Important Arithmetic Considerations</h3>
<ul>
<li>Integer division truncates toward zero.</li>
<li>Integer division or remainder by zero throws <code>ArithmeticException</code>.</li>
<li>Floating-point calculations may contain rounding errors.</li>
<li>Integer arithmetic can overflow when the result exceeds the representable range.</li>
<li>For accurate monetary calculations, consider using <code>BigDecimal</code> with a suitable rounding policy instead of relying on binary floating-point values.</li>
</ul>
<h2>7. Unary Operators</h2>
<p>Unary operators act on one operand. They can change a value's sign, increment or decrement a variable, or reverse a boolean value.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Operator</th><th>Purpose</th><th>Example</th></tr>
</thead>
<tbody>
<tr><td><code>+</code></td><td>Unary plus; indicates a positive value.</td><td><code>+number</code></td></tr>
<tr><td><code>-</code></td><td>Unary minus; negates a numeric value.</td><td><code>-number</code></td></tr>
<tr><td><code>++</code></td><td>Increments a variable by one.</td><td><code>count++</code></td></tr>
<tr><td><code>--</code></td><td>Decrements a variable by one.</td><td><code>count--</code></td></tr>
<tr><td><code>!</code></td><td>Reverses a boolean value.</td><td><code>!isActive</code></td></tr>
<tr><td><code>~</code></td><td>Inverts the bits of an integral value.</td><td><code>~number</code></td></tr>
</tbody>
</table>
<h3>7.1 Unary Plus and Minus</h3>
<pre><code>int number = 10;
System.out.println(+number);
System.out.println(-number);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>10
-10</code></pre>
<h3>7.2 Increment Operator (++ )</h3>
<p>The increment operator increases a variable's value by one.</p>
<pre><code>int count = 5;
count++;
System.out.println(count);</code></pre>
<p><strong>Output:</strong> <code>6</code></p>
<h3>7.3 Decrement Operator (-- )</h3>
<p>The decrement operator decreases a variable's value by one.</p>
<pre><code>int count = 5;
count--;
System.out.println(count);</code></pre>
<p><strong>Output:</strong> <code>4</code></p>
<h3>7.4 Logical NOT Operator (!)</h3>
<p>The logical NOT operator reverses a boolean value: <code>true</code> becomes <code>false</code>, and <code>false</code> becomes <code>true</code>.</p>
<pre><code>boolean isLoggedIn = true;
System.out.println(!isLoggedIn);</code></pre>
<p><strong>Output:</strong> <code>false</code></p>
<h2>8. Prefix and Postfix Increment and Decrement</h2>
<p>Increment and decrement operators can be placed before or after a variable. The difference matters when the expression's value is used as part of a larger expression.</p>
<ul>
<li><strong>Prefix:</strong> The variable is updated first, and the expression produces the updated value.</li>
<li><strong>Postfix:</strong> The expression produces the original value, and the variable is then updated.</li>
</ul>
<h3>Prefix Example</h3>
<pre><code>int a = 5;
int result = ++a;
System.out.println(a);
System.out.println(result);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>6
6</code></pre>
<h3>Postfix Example</h3>
<pre><code>int a = 5;
int result = a++;
System.out.println(a);
System.out.println(result);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>6
5</code></pre>
<p>In both cases, <code>a</code> becomes <code>6</code>. However, the value assigned to <code>result</code> differs because prefix and postfix expressions produce different values.</p>
<h2>9. Relational Operators</h2>
<p>Relational operators compare numeric values and produce a boolean result. They are frequently used in <code>if</code> statements, loops, and validation logic.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Operator</th><th>Meaning</th><th>Example</th><th>Result</th></tr>
</thead>
<tbody>
<tr><td><code><</code></td><td>Less than</td><td><code>5 < 10</code></td><td><code>true</code></td></tr>
<tr><td><code>></code></td><td>Greater than</td><td><code>15 > 10</code></td><td><code>true</code></td></tr>
<tr><td><code><=</code></td><td>Less than or equal to</td><td><code>10 <= 10</code></td><td><code>true</code></td></tr>
<tr><td><code>>=</code></td><td>Greater than or equal to</td><td><code>8 >= 10</code></td><td><code>false</code></td></tr>
</tbody>
</table>
<h3>Example</h3>
<pre><code>int age = 21;
System.out.println(age >= 18);
System.out.println(age < 18);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>true
false</code></pre>
<h2>10. Equality Operators</h2>
<p>Java uses <code>==</code> to test equality and <code>!=</code> to test inequality. Their behavior depends on the types being compared.</p>
<pre><code>int a = 10;
int b = 10;
int c = 20;
System.out.println(a == b);
System.out.println(a != c);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>true
true</code></pre>
<h3>Comparing Objects</h3>
<p>For reference types, <code>==</code> checks whether two references point to the same object, not whether two different objects contain equal data.</p>
<pre><code>String first = new String("Java");
String second = new String("Java");
System.out.println(first == second);
System.out.println(first.equals(second));</code></pre>
<p><strong>Output:</strong></p>
<pre><code>false
true</code></pre>
<p>The references refer to distinct objects, so <code>==</code> returns <code>false</code>. The <code>equals()</code> method on <code>String</code> compares the character content, so it returns <code>true</code>.</p>
<h2>11. Logical Operators</h2>
<p>Logical operators combine or reverse boolean expressions. They are essential for implementing conditions involving multiple requirements.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Operator</th><th>Name</th><th>Behavior</th></tr>
</thead>
<tbody>
<tr><td><code>&&</code></td><td>Logical AND</td><td>True only when both operands are true; skips the right operand if the left is false.</td></tr>
<tr><td><code>||</code></td><td>Logical OR</td><td>True when at least one operand is true; skips the right operand if the left is true.</td></tr>
<tr><td><code>!</code></td><td>Logical NOT</td><td>Reverses a boolean value.</td></tr>
</tbody>
</table>
<h3>11.1 Logical AND (&&)</h3>
<pre><code>int age = 25;
boolean hasLicense = true;
System.out.println(age >= 18 && hasLicense);</code></pre>
<p><strong>Output:</strong> <code>true</code></p>
<p>Both conditions must be true for the entire expression to evaluate to true.</p>
<h3>11.2 Logical OR (||)</h3>
<pre><code>boolean isWeekend = false;
boolean isHoliday = true;
System.out.println(isWeekend || isHoliday);</code></pre>
<p><strong>Output:</strong> <code>true</code></p>
<p>Only one of the conditions needs to be true for the expression to evaluate to true.</p>
<h3>11.3 Logical NOT (!)</h3>
<pre><code>boolean isAvailable = false;
System.out.println(!isAvailable);</code></pre>
<p><strong>Output:</strong> <code>true</code></p>
<h2>12. Short-Circuit Evaluation</h2>
<p>Java's conditional logical operators <code>&&</code> and <code>||</code> use short-circuit evaluation. This means Java evaluates the right operand only when it is necessary to determine the result.</p>
<h3>Example Using AND</h3>
<pre><code>int number = 0;
if (number != 0 && 10 / number > 1) {
System.out.println("Condition is true");
} else {
System.out.println("Condition is false");
}</code></pre>
<p><strong>Output:</strong> <code>Condition is false</code></p>
<p>Because <code>number != 0</code> is false, Java does not evaluate <code>10 / number</code>. This prevents division by zero in the second operand.</p>
<h3>Example Using OR</h3>
<pre><code>boolean isAdmin = true;
if (isAdmin || checkPermission()) {
System.out.println("Access granted");
}</code></pre>
<p>If <code>isAdmin</code> is true, Java does not call <code>checkPermission()</code> because the overall OR expression is already true. The method must be defined if this example is used in a complete program.</p>
<h3>Logical Operators Versus Boolean Bitwise Operators</h3>
<p>The operators <code>&</code> and <code>|</code> can also operate on boolean operands. Unlike <code>&&</code> and <code>||</code>, they evaluate both operands. Prefer the conditional operators for ordinary boolean conditions unless evaluating both operands is intentional.</p>
<h2>13. Assignment Operators</h2>
<p>The assignment operator stores a value in a variable. Compound assignment operators combine an operation with assignment.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Operator</th><th>Equivalent Form</th><th>Example</th></tr>
</thead>
<tbody>
<tr><td><code>=</code></td><td>Assign a value</td><td><code>x = 10;</code></td></tr>
<tr><td><code>+=</code></td><td><code>x = x + value;</code></td><td><code>x += 5;</code></td></tr>
<tr><td><code>-=</code></td><td><code>x = x - value;</code></td><td><code>x -= 3;</code></td></tr>
<tr><td><code>*=</code></td><td><code>x = x * value;</code></td><td><code>x *= 2;</code></td></tr>
<tr><td><code>/=</code></td><td><code>x = x / value;</code></td><td><code>x /= 4;</code></td></tr>
<tr><td><code>%=</code></td><td><code>x = x % value;</code></td><td><code>x %= 3;</code></td></tr>
</tbody>
</table>
<h3>Example</h3>
<pre><code>int balance = 100;
balance += 50;
System.out.println(balance);
balance -= 20;
System.out.println(balance);
balance *= 2;
System.out.println(balance);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>150
130
260</code></pre>
<p>Compound assignments can include implicit narrowing conversions that an equivalent expanded assignment would not allow. For example, <code>byte b = 5; b += 2;</code> is valid, while <code>b = b + 2;</code> requires an explicit cast because <code>b + 2</code> is evaluated as an <code>int</code>.</p>
<h2>14. Conditional (Ternary) Operator</h2>
<p>The conditional operator <code>? :</code> selects one of two expressions based on a boolean condition. It provides a compact alternative to some simple <code>if-else</code> statements.</p>
<h3>Syntax</h3>
<pre><code>condition ? expressionIfTrue : expressionIfFalse;</code></pre>
<h3>Example</h3>
<pre><code>int age = 20;
String category = age >= 18 ? "Adult" : "Minor";
System.out.println(category);</code></pre>
<p><strong>Output:</strong> <code>Adult</code></p>
<h3>Equivalent if-else Statement</h3>
<pre><code>int age = 20;
String category;
if (age >= 18) {
category = "Adult";
} else {
category = "Minor";
}</code></pre>
<p>Use the ternary operator for short, clear choices. Deeply nested ternary expressions can make code difficult to read, so use ordinary conditional statements when the logic becomes complex.</p>
```html
<h2>15. Bitwise Operators</h2>
<p>Bitwise operators work on the individual bits of integral numeric values such as <code>byte</code>, <code>short</code>, <code>int</code>, and <code>long</code>. They are useful in low-level programming, flags, permissions, and certain data-processing tasks.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Operator</th><th>Name</th><th>Purpose</th></tr>
</thead>
<tbody>
<tr><td><code>&</code></td><td>Bitwise AND</td><td>Sets a result bit to 1 when both corresponding bits are 1.</td></tr>
<tr><td><code>|</code></td><td>Bitwise OR</td><td>Sets a result bit to 1 when either corresponding bit is 1.</td></tr>
<tr><td><code>^</code></td><td>Bitwise XOR</td><td>Sets a result bit to 1 when the corresponding bits differ.</td></tr>
<tr><td><code>~</code></td><td>Bitwise complement</td><td>Inverts every bit of an integral value.</td></tr>
</tbody>
</table>
<h3>15.1 Bitwise AND (&)</h3>
<pre><code>int a = 6; // Binary: 0110
int b = 3; // Binary: 0011
System.out.println(a & b);</code></pre>
<p><strong>Output:</strong> <code>2</code></p>
<p>Only the second bit from the right is 1 in both operands, so the result is binary <code>0010</code>, which equals decimal 2.</p>
<h3>15.2 Bitwise OR (|)</h3>
<pre><code>int a = 6; // Binary: 0110
int b = 3; // Binary: 0011
System.out.println(a | b);</code></pre>
<p><strong>Output:</strong> <code>7</code></p>
<p>The result is binary <code>0111</code>, which equals decimal 7.</p>
<h3>15.3 Bitwise XOR (^)</h3>
<pre><code>int a = 6; // Binary: 0110
int b = 3; // Binary: 0011
System.out.println(a ^ b);</code></pre>
<p><strong>Output:</strong> <code>5</code></p>
<p>The result is binary <code>0101</code>, which equals decimal 5. XOR produces 1 when the corresponding bits differ.</p>
<h3>15.4 Bitwise Complement (~)</h3>
<pre><code>int number = 5;
System.out.println(~number);</code></pre>
<p><strong>Output:</strong> <code>-6</code></p>
<p>For Java's signed two's-complement integer representation, the bitwise complement of an integer <code>x</code> equals <code>-x - 1</code>.</p>
<h2>16. Shift Operators</h2>
<p>Shift operators move the bits of an integral value to the left or right. They are often used in bit manipulation, masks, and performance-sensitive algorithms where their behavior is appropriate.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Operator</th><th>Name</th><th>Behavior</th></tr>
</thead>
<tbody>
<tr><td><code><<</code></td><td>Left shift</td><td>Shifts bits to the left and fills the rightmost positions with zeros.</td></tr>
<tr><td><code>>></code></td><td>Signed right shift</td><td>Shifts bits to the right and preserves the sign bit.</td></tr>
<tr><td><code>>>></code></td><td>Unsigned right shift</td><td>Shifts bits to the right and fills the leftmost positions with zeros.</td></tr>
</tbody>
</table>
<h3>16.1 Left Shift</h3>
<pre><code>int number = 5;
System.out.println(number << 1);
System.out.println(number << 2);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>10
20</code></pre>
<p>For this example, shifting 5 left by one position produces 10, and shifting it left by two positions produces 20. However, overflow and the fixed width of integer types mean that left shifts should not always be treated as ordinary multiplication.</p>
<h3>16.2 Signed Right Shift</h3>
<pre><code>int number = 16;
System.out.println(number >> 2);</code></pre>
<p><strong>Output:</strong> <code>4</code></p>
<p>For this positive value, shifting right by two positions produces 4. For negative numbers, signed right shift preserves the sign bit.</p>
<h3>16.3 Unsigned Right Shift</h3>
<pre><code>int number = -8;
System.out.println(number >> 1);
System.out.println(number >>> 1);</code></pre>
<p>The two results differ because <code>>></code> preserves the sign bit, whereas <code>>>></code> fills the leftmost bits with zeros. The unsigned-shift result for an <code>int</code> is a nonnegative value representing the shifted 32-bit pattern.</p>
<h2>17. The instanceof Operator</h2>
<p>The <code>instanceof</code> operator checks whether an object reference is compatible with a specified type. It commonly appears in inheritance, object-oriented programming, and runtime type checks.</p>
<h3>Example</h3>
<pre><code>Object value = "Hello Java";
System.out.println(value instanceof String);
System.out.println(value instanceof Integer);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>true
false</code></pre>
<p>The object referred to by <code>value</code> is a <code>String</code>, so the first expression is true. It is not an <code>Integer</code>, so the second expression is false.</p>
<p>In modern Java versions, pattern matching can also combine a type check with a variable declaration:</p>
<pre><code>Object value = "Hello Java";
if (value instanceof String text) {
System.out.println(text.length());
}</code></pre>
<p><strong>Output:</strong> <code>10</code></p>
<p>The variable <code>text</code> is available in the appropriate scope when the pattern match succeeds.</p>
<h2>18. Operator Precedence and Associativity</h2>
<p>Operator precedence determines which operators are grouped first in an expression. Associativity determines how operators of the same precedence are grouped when parentheses do not specify otherwise.</p>
<h3>Example of Precedence</h3>
<pre><code>int result = 10 + 5 * 2;
System.out.println(result);</code></pre>
<p><strong>Output:</strong> <code>20</code></p>
<p>Multiplication has higher precedence than addition, so Java groups the expression as <code>10 + (5 * 2)</code>.</p>
<h3>Using Parentheses</h3>
<pre><code>int result = (10 + 5) * 2;
System.out.println(result);</code></pre>
<p><strong>Output:</strong> <code>30</code></p>
<p>Parentheses explicitly control the grouping and make expressions easier to understand.</p>
<h3>Common Operator Precedence Order</h3>
<p>The table below shows a simplified precedence order, from higher precedence to lower precedence. Operators on the same row generally have the same precedence.</p>
<table border="1" cellpadding="8" cellspacing="0">
<thead>
<tr><th>Precedence</th><th>Operators</th><th>Associativity or Notes</th></tr>
</thead>
<tbody>
<tr><td>Highest</td><td>Parentheses <code>()</code>, array access, member access, method invocation</td><td>Parentheses explicitly group expressions.</td></tr>
<tr><td>Unary</td><td><code>++</code>, <code>--</code>, unary <code>+</code>, unary <code>-</code>, <code>!</code>, <code>~</code>, casts</td><td>Unary operators group according to their syntax.</td></tr>
<tr><td>Multiplicative</td><td><code>*</code>, <code>/</code>, <code>%</code></td><td>Left to right.</td></tr>
<tr><td>Additive</td><td><code>+</code>, <code>-</code></td><td>Left to right.</td></tr>
<tr><td>Shift</td><td><code><<</code>, <code>>></code>, <code>>>></code></td><td>Left to right.</td></tr>
<tr><td>Relational</td><td><code><</code>, <code>></code>, <code><=</code>, <code>>=</code>, <code>instanceof</code></td><td>Left to right; relational expressions cannot be chained like mathematical inequalities.</td></tr>
<tr><td>Equality</td><td><code>==</code>, <code>!=</code></td><td>Left to right.</td></tr>
<tr><td>Bitwise AND</td><td><code>&</code></td><td>Higher than bitwise XOR and OR.</td></tr>
<tr><td>Bitwise XOR</td><td><code>^</code></td><td>Higher than bitwise OR.</td></tr>
<tr><td>Bitwise OR</td><td><code>|</code></td><td>Higher than conditional logical AND.</td></tr>
<tr><td>Logical AND</td><td><code>&&</code></td><td>Higher than logical OR.</td></tr>
<tr><td>Logical OR</td><td><code>||</code></td><td>Higher than the conditional operator.</td></tr>
<tr><td>Conditional</td><td><code>? :</code></td><td>Groups from right to left.</td></tr>
<tr><td>Assignment</td><td><code>=</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>, <code>%=</code>, and other assignment operators</td><td>Groups from right to left.</td></tr>
<tr><td>Lowest among those listed</td><td>Lambda arrow <code>-></code> in relevant expression grammar</td><td>Has its own syntax and context rules.</td></tr>
</tbody>
</table>
<p>This is a learning summary, not a complete grammar specification. When expressions become complex, use parentheses instead of relying on memorized precedence.</p>
<h3>Associativity Example</h3>
<pre><code>int result = 20 - 5 - 3;
System.out.println(result);</code></pre>
<p><strong>Output:</strong> <code>12</code></p>
<p>Subtraction groups from left to right: <code>(20 - 5) - 3</code>.</p>
<h3>Assignment Associativity Example</h3>
<pre><code>int a, b, c;
a = b = c = 10;
System.out.println(a);
System.out.println(b);
System.out.println(c);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>10
10
10</code></pre>
<p>Assignment groups from right to left, so <code>c</code> receives 10 first, then <code>b</code>, then <code>a</code>.</p>
<h2>19. Type Conversion and Numeric Promotion</h2>
<p>Java sometimes converts operand types automatically before performing an operation. Understanding these conversions helps prevent unexpected results and compilation errors.</p>
<h3>19.1 Integer Division</h3>
<pre><code>int a = 7;
int b = 2;
System.out.println(a / b);
System.out.println((double) a / b);</code></pre>
<p><strong>Output:</strong></p>
<pre><code>3
3.5</code></pre>
<p>The first expression uses integer division. The second converts <code>a</code> to <code>double</code> before division.</p>
<h3>19.2 Numeric Promotion</h3>
<p>For many arithmetic operations, Java promotes smaller integral types such as <code>byte</code>, <code>short</code>, and <code>char</code> to <code>int</code>. If an expression includes a <code>long</code>, <code>float</code>, or <code>double</code> operand, the operation may use the corresponding wider type.</p>
<pre><code>byte a = 10;
byte b = 20;
int result = a + b;
System.out.println(result);</code></pre>
<p><strong>Output:</strong> <code>30</code></p>
<p>The addition expression is evaluated as an <code>int</code>, so assigning it to an <code>int</code> variable is valid.</p>
<h3>19.3 Explicit Casting</h3>
<pre><code>double price = 99.95;
int roundedDown = (int) price;
System.out.println(roundedDown);</code></pre>
<p><strong>Output:</strong> <code>99</code></p>
<p>Casting a floating-point value to an integer type discards the fractional part toward zero. It does not perform conventional rounding.</p>
<h2>20. Common Mistakes When Using Operators</h2>
<h3>Mistake 1: Confusing Assignment and Equality</h3>
<pre><code>int number = 10; // Assignment
System.out.println(number == 10); // Equality comparison</code></pre>
<p><strong>Explanation:</strong> <code>=</code> assigns a value, whereas <code>==</code> compares values or references, depending on their types.</p>
<h3>Mistake 2: Expecting Decimal Division from Integers</h3>
<pre><code>System.out.println(5 / 2);</code></pre>
<p><strong>Output:</strong> <code>2</code></p>
<p><strong>Correction:</strong> Use a floating-point operand when a fractional result is required, for example <code>5.0 / 2</code>.</p>
<h3>Mistake 3: Using == to Compare String Content</h3>
<pre><code>String first = new String("Java");
String second = new String("Java");
System.out.println(first == second);</code></pre>
<p><strong>Explanation:</strong> The expression compares object references, not string content. Use <code>first.equals(second)</code> to compare string content when both references are non-null.</p>
<h3>Mistake 4: Ignoring Operator Precedence</h3>
<pre><code>int result = 2 + 3 * 4;</code></pre>
<p>The result is <code>14</code>, not <code>20</code>, because multiplication is evaluated before addition.</p>
<p><strong>Correction:</strong> Write <code>(2 + 3) * 4</code> if the intended result is 20.</p>
<h3>Mistake 5: Dividing an Integer by Zero</h3>
<pre><code>int a = 10;
int b = 0;
// int result = a / b; // Throws ArithmeticException</code></pre>
<p><strong>Correction:</strong> Validate the divisor before performing integer division.</p>
<h3>Mistake 6: Confusing Logical and Bitwise Operators</h3>
<p><code>&&</code> and <code>||</code> perform conditional logical evaluation with short-circuiting. The operators <code>&</code> and <code>|</code> can operate on boolean operands without short-circuiting, or on integral operands bit by bit.</p>
<h3>Mistake 7: Using Increment Operators in Complicated Expressions</h3>
<pre><code>int a = 5;
int result = a++ + ++a;
System.out.println(result);</code></pre>
<p>Although Java defines the evaluation rules, mixing several side effects in one expression makes code harder to read and maintain. Prefer separate statements when possible.</p>
<h2>21. Practical Example: Student Marks Calculator</h2>
<p>This example combines arithmetic, comparison, logical, and assignment operators to calculate a student's average and determine whether the student has passed.</p>
<pre><code>public class MarksCalculator {
public static void main(String[] args) {
int subject1 = 80;
int subject2 = 75;
int subject3 = 90;
int total = subject1 + subject2 + subject3;
double average = total / 3.0;
boolean passedAllSubjects =
subject1 >= 40 &&
subject2 >= 40 &&
subject3 >= 40;
String result = passedAllSubjects
? "Pass"
: "Fail";
System.out.println("Total: " + total);
System.out.println("Average: " + average);
System.out.println("Result: " + result);
}
}</code></pre>
<h3>Output</h3>
<pre><code>Total: 245
Average: 81.66666666666667
Result: Pass</code></pre>
<h3>Operators Used</h3>
<ul>
<li><code>+</code> calculates the total marks.</li>
<li><code>/</code> calculates the average using floating-point division.</li>
<li><code>>=</code> compares each subject mark with the passing threshold.</li>
<li><code>&&</code> requires every subject condition to be true.</li>
<li><code>? :</code> selects the result text based on the boolean condition.</li>
<li><code>=</code> assigns calculated values to variables.</li>
</ul>
<h2>22. Practical Example: Shopping Bill Calculator</h2>
<p>This program demonstrates multiplication, addition, compound assignment, and conditional expressions in a basic shopping scenario.</p>
<pre><code>public class ShoppingBill {
public static void main(String[] args) {
final double TAX_RATE = 0.18;
double itemPrice = 500.0;
int quantity = 3;
double subtotal = itemPrice * quantity;
double tax = subtotal * TAX_RATE;
double total = subtotal;
total += tax;
String message = total >= 1500
? "High-value purchase"
: "Regular purchase";
System.out.println("Subtotal: " + subtotal);
System.out.println("Tax: " + tax);
System.out.println("Total: " + total);
System.out.println(message);
}
}</code></pre>
<h3>Output</h3>
<pre><code>Subtotal: 1500.0
Tax: 270.0
Total: 1770.0
High-value purchase</code></pre>
<p><strong>Note:</strong> This example demonstrates operator usage. Production billing systems should use appropriate decimal arithmetic and apply the correct tax, rounding, and currency rules for their requirements.</p>
<h2>23. Best Practices for Working with Operators and Expressions</h2>
<ul>
<li>Use descriptive variable names so expressions are easier to understand.</li>
<li>Add parentheses when they make the intended evaluation order clearer.</li>
<li>Avoid combining multiple increments, assignments, or method side effects in one complex expression.</li>
<li>Use <code>&&</code> and <code>||</code> for normal conditional logic when short-circuiting is desired.</li>
<li>Use <code>equals()</code> or an appropriate comparison method when comparing object content.</li>
<li>Check for zero before integer division or remainder operations.</li>
<li>Be aware of integer overflow and floating-point precision limitations.</li>
<li>Use explicit casting when a conversion is intended and safe.</li>
<li>Prefer readable conditional statements over deeply nested ternary expressions.</li>
<li>Use appropriate numeric types for the problem, especially when dealing with financial calculations.</li>
<li>Test boundary conditions, such as zero, negative numbers, maximum values, and empty input.</li>
<li>Consult the <a href="https://docs.oracle.com/javase/specs/jls/se26/html/" target="_blank" rel="noopener noreferrer">Java Language Specification</a> for the formal rules governing operators, expressions, precedence, and evaluation.</li>
</ul>
<h2>24. Practical Exercises</h2>
<h3>Exercise 1: Arithmetic Operators</h3>
<p>Create a program with two integer variables and display their sum, difference, product, quotient, and remainder.</p>
<h3>Exercise 2: Even or Odd</h3>
<p>Use the remainder operator to determine whether a given integer is even or odd.</p>
<h3>Exercise 3: Comparison Operators</h3>
<p>Declare two numbers and print the results of <code><</code>, <code>></code>, <code><=</code>, <code>>=</code>, <code>==</code>, and <code>!=</code>.</p>
<h3>Exercise 4: Logical Conditions</h3>
<p>Create a program that checks whether a person is at least 18 years old and has a valid identification document. Use <code>&&</code> to combine the conditions.</p>
<h3>Exercise 5: Prefix and Postfix</h3>
<p>Initialize an integer to 10 and demonstrate the difference between <code>++number</code> and <code>number++</code>. Print the expression results and the variable values.</p>
<h3>Exercise 6: Ternary Operator</h3>
<p>Write a program that uses the conditional operator to display <code>Pass</code> when marks are at least 40 and <code>Fail</code> otherwise.</p>
<h3>Exercise 7: Operator Precedence</h3>
<p>Evaluate the following expressions manually, then verify them using Java:</p>
<pre><code>int a = 10 + 2 * 5;
int b = (10 + 2) * 5;
int c = 20 - 5 - 3;
int d = 18 / 4;</code></pre>
<h3>Exercise 8: Shopping Calculator</h3>
<p>Calculate a bill from item price and quantity, add a tax amount, and use a comparison operator to check whether the total exceeds a chosen threshold.</p>
<h2>25. Interview Questions and Answers</h2>
<h3>Q1. What is an operator in Java?</h3>
<p><strong>Answer:</strong> An operator is a symbol or token that performs an operation on one or more operands, such as addition, comparison, assignment, or logical evaluation.</p>
<h3>Q2. What is an expression?</h3>
<p><strong>Answer:</strong> An expression is a combination of operands, operators, and possibly method calls that evaluates to a value or produces a result.</p>
<h3>Q3. What is the difference between = and ==?</h3>
<p><strong>Answer:</strong> The <code>=</code> operator assigns a value, whereas <code>==</code> checks equality. For object references, <code>==</code> tests reference identity.</p>
<h3>Q4. What is the difference between / and %?</h3>
<p><strong>Answer:</strong> The division operator <code>/</code> calculates a quotient, while the remainder operator <code>%</code> returns the remainder from division.</p>
<h3>Q5. What is the difference between prefix and postfix increment?</h3>
<p><strong>Answer:</strong> Prefix increment updates the variable before the expression produces its value. Postfix increment produces the original value and then updates the variable.</p>
<h3>Q6. What is short-circuit evaluation?</h3>
<p><strong>Answer:</strong> Short-circuit evaluation means Java skips evaluating the right operand of <code>&&</code> when the left operand is false and skips the right operand of <code>||</code> when the left operand is true.</p>
<h3>Q7. What is operator precedence?</h3>
<p><strong>Answer:</strong> Operator precedence determines how operators are grouped in an expression when parentheses do not explicitly determine the grouping.</p>
<h3>Q8. What is operator associativity?</h3>
<p><strong>Answer:</strong> Associativity determines how operators of the same precedence are grouped. For example, subtraction groups from left to right, while assignment groups from right to left.</p>
<h3>Q9. What is the ternary operator?</h3>
<p><strong>Answer:</strong> The ternary operator <code>? :</code> selects one of two expressions based on a boolean condition.</p>
<h3>Q10. What is the difference between && and &?</h3>
<p><strong>Answer:</strong> <code>&&</code> performs conditional logical AND with short-circuit evaluation. <code>&</code> can perform bitwise AND on integral values or non-short-circuit logical AND on boolean values.</p>
<h3>Q11. What happens when an integer is divided by zero?</h3>
<p><strong>Answer:</strong> Integer division by zero throws an <code>ArithmeticException</code>.</p>
<h3>Q12. Why does 5 / 2 produce 2 in Java?</h3>
<p><strong>Answer:</strong> Both operands are integers, so Java performs integer division and discards the fractional part toward zero.</p>
<h3>Q13. How do you compare the contents of two strings?</h3>
<p><strong>Answer:</strong> Use <code>equals()</code> to compare string content. The <code>==</code> operator checks whether two references refer to the same object.</p>
<h3>Q14. What are bitwise operators used for?</h3>
<p><strong>Answer:</strong> Bitwise operators manipulate individual bits of integral values and are useful for flags, masks, and low-level data processing.</p>
<h3>Q15. What is the instanceof operator?</h3>
<p><strong>Answer:</strong> The <code>instanceof</code> operator checks whether an object is compatible with a specified type.</p>
<h2>26. Quick Revision Checklist</h2>
<ul>
<li>An operator performs an operation on one or more operands.</li>
<li>An expression combines operands and operators to produce a result.</li>
<li>Arithmetic operators include <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, and <code>%</code>.</li>
<li>Relational and equality operators produce boolean results.</li>
<li>Logical operators combine or reverse boolean conditions.</li>
<li>Assignment operators assign or update values.</li>
<li>Prefix and postfix increment differ in the value produced by the expression.</li>
<li>Bitwise operators manipulate individual bits.</li>
<li>Shift operators move bits left or right.</li>
<li>The ternary operator provides a compact conditional expression.</li>
<li>Operator precedence and associativity determine expression grouping.</li>
<li>Integer division discards the fractional part toward zero.</li>
<li>Short-circuit operators can skip evaluating the right operand.</li>
<li>Parentheses improve clarity and help express intended grouping.</li>
</ul>
<h2>27. Conclusion</h2>
<p>Java operators and expressions are essential for performing calculations, comparing data, assigning values, manipulating bits, and implementing decision-making logic. Understanding each operator category helps you write accurate and readable programs, while knowledge of precedence, associativity, type conversion, and short-circuit evaluation helps prevent common programming mistakes.</p>
<p>Continue practicing with small Java programs before combining multiple operators into larger applications. As your skills develop, apply these concepts to calculations, validation, loops, conditional statements, object-oriented programming, and real-world business logic.</p>
<p>To continue your learning journey, explore the <a href="https://www.justacademy.co/course-detail/core-java-training" target="_blank" rel="noopener noreferrer">Core Java Training Course</a>, register through the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">JustAcademy course demo page</a>, or visit the <a href="https://www.justacademy.co/" target="_blank" rel="noopener noreferrer">JustAcademy website</a>.</p>
</div>
``】【。