1. Assignment Operations
The fundamental assignment operator is =. When assigning values to variables, type compatibility matters. If the source and target types differ, implicit casting occurs when safe, or explicit casting must be applied.
Extension Assignment: These operators perform an operation folllowed by assignment:
| Operator | Functionality |
|---|---|
+= |
Adds right operand to left variable |
-= |
Subtracts right operand from left variable |
*= |
Multiplies left variable by right operand |
/= |
Divides left variable by right operand |
%= |
Assigns remainder of division to left variable |
Important: Extension assignments do not alter the original data type of the variable on the left side automatically.
public class AssignmentLogicDemo {
public static void main(String[] args) {
char initial = 'A';
// Automatic unboxing happens for extended assignment
initial += 32;
System.out.println("Converted char: " + initial);
int value = 100;
System.out.println("Initial: " + value);
value *= 5;
System.out.println("Scaled: " + value);
int quotient = 45;
quotient %= 7;
System.out.println("Remainder: " + quotient);
}
}
2. Comparison Logic
Comparison operations yield a boolean result (true or false).
- Numeric/Char:
>,<,>=,<= - Equality:
==(equals),!=(not equals) - References:
==compares memory addresses, while.equals()compares content (for Objects).
Note that == and = behave differently. = assigns a value; == checks equality.
public class ComparisonCheck {
public static void main(String[] args) {
int x = 10;
int y = 20;
System.out.println(x == y); // false
System.out.println(x != y); // true
boolean flagA = false;
boolean flagB = true;
// Correct usage of assignment in condition is risky if accidental
if (flagA = flagB) {
System.out.println("Condition met");
}
}
}
3. Boolean Operators
These operators work exclusively with boolean values.
| Symbol | Name | Behavior |
|---|---|---|
& |
AND | Both operands must be true |
&& |
Short-circuit AND | Evaluates right side only if left is true |
| ` | ` | OR |
| ` | ` | |
^ |
XOR | True if operands differ |
! |
NOT | Inverts the boolean state |
Short-circuiting Difference:
With && or ||, if the outcome is determined by the first operand, the second is skipped. This prevents unnecessary computation or runtime errors.
public class BooleanOperationsDemo {
public static void main(String[] args) {
boolean t1 = true, f1 = false;
System.out.println(t1 && f1); // false
System.out.println(t1 || f1); // true
System.out.println(t1 ^ f1); // true
System.out.println(!t1); // false
// Demonstrating short-circuit effect
int counter = 0;
boolean res = (counter++ < 5) || (++counter > 10);
// counter increased twice here because || short-circuits only if left is true
// Here left is true (0<5), so right side skipped? No, wait.
// Left is true, so || returns true immediately. Right skipped.
System.out.println("Counter: " + counter);
}
}
4. Bitwise Manipulation
Bitwise operations act on binary representations (two's complement) of numbers.
- Left Shift (
<<): Equivalent to multiplication by 2 raised to the shift count. - Right Shift (
>>): Equivalent to integer division by 2 raised to the shift count (preserves sign). - Unsigned Right Shift (
>>>): Fills left bits with zero regardless of sign. - And (
&), Or (|), Xor (^): Standard bit-level operations. - Not (
~): Flips all bits.
public class BinaryProcessingDemo {
public static void main(String[] args) {
System.out.println(8 << 2); // 32 (8 * 4)
System.out.println(64 >> 3); // 8 (64 / 8)
System.out.println(-1 >>> 1); // Large positive number due to unsigned fill
System.out.println(10 & 7); // 2
System.out.println(10 | 7); // 15
System.out.println(10 ^ 7); // 13
System.out.println(~5); // -6
}
}
5. Ternary Conditional Operator
A compact way to handle simple if-else logic.
Syntax: (Condition) ? ExpressionTrue : ExpressionFalse
Both expressions following the colon must return compatible types.
public class TernaryExpressionTest {
public static void main(String[] args) {
int score = 85;
String grade = score >= 60 ? "Pass" : "Fail";
// Finding max of two
int num1 = 50, num2 = 90;
int max = (num1 > num2) ? num1 : num2;
// Complex nesting for multiple conditions
String status = (score >= 90) ? "Excellent"
: (score >= 80) ? "Good"
: (score >= 60) ? "Average"
: "Poor";
System.out.println(status);
}
}
6. Handling User Input (Scanner)
The Scanner class facilitates console input.
import java.util.Scanner;
public class InputProcessor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int age = scanner.nextInt();
System.out.print("Enter text: ");
String message = scanner.next(); // Stops at whitespace
System.out.print("Enter full line: ");
scanner.nextLine(); // Clear buffer after nextInt
String paragraph = scanner.nextLine();
System.out.println("Processed: " + age + " - " + paragraph);
} catch (Exception e) {
System.out.println("Invalid input provided.");
} finally {
if (scanner != null) {
scanner.close();
}
}
}
}
Key Notes:
nextInt()skips whitespace but does not consume the newline character.nextLine()reads until the end of the line.- Char input must be extracted from a String using
charAt(), as there is nonextChar()method.
7. Random Number Generation
To generate integers within a specific range [min, max]:
int rand = (int)(Math.random() * (max - min + 1)) + min;
This yields a value between min and max inclusive.
8. Control Structures
Execution flow is managed via conditional blocks.
Single Branch (if)
Executes code only if the boolean expression evaluates to true.
Double Branch (if-else)
Provides alternative execution paths.
Multi Branch (if-else if-else)
Evaluates multiple sequential conditions.
public class DecisionFlowExercises {
public static void main(String[] args) {
int year = 2024;
// Leap Year Logic
boolean isLeap = (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
if (isLeap) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
// Score Grading Example
int level = 88;
String result;
if (level >= 90) {
result = "Grade A";
} else if (level >= 80) {
result = "Grade B";
} else if (level >= 70) {
result = "Grade C";
} else {
result = "Grade D";
}
System.out.println("Score Level: " + result);
// Eligibility Simulation
double height = 175.5;
int wealth = 50000;
boolean isHandsome = true;
// Criteria Check
if (height > 180 && wealth > 1000000 && isHandsome) {
System.out.println("Eligible for Premium Status!");
} else if (height > 180 || wealth > 1000000 || isHandsome) {
System.out.println("Qualified for Basic Status");
} else {
System.out.println("Application Declined");
}
}
}