Integer Operations
Basic Arithmetic Operations
public class IntegerArithmetic {
public static void main(String[] args) {
int a = 10, b = 3;
// Basic arithmetic operations
System.out.println("Addition: " + (a + b)); // 13
System.out.println("Subtraction: " + (a - b)); // 7
System.out.println("Multiplication: " + (a * b)); // 30
System.out.println("Division: " + (a / b)); // 3
System.out.println("Modulus: " + (a % b)); // 1
}
}
Bitwise Operations
graph TD
A[Bitwise Operations] --> B[AND &]
A --> C[OR |]
A --> D[XOR ^]
A --> E[NOT ~]
A --> F[Left Shift <<]
A --> G[Right Shift >>]
public class BitwiseOperations {
public static void main(String[] args) {
int x = 5; // 0101 in binary
int y = 3; // 0011 in binary
System.out.println("AND: " + (x & y)); // 1
System.out.println("OR: " + (x | y)); // 7
System.out.println("XOR: " + (x ^ y)); // 6
System.out.println("Left Shift: " + (x << 1)); // 10
System.out.println("Right Shift: " + (x >> 1)); // 2
}
}
Comparison Operations
Operator |
Description |
Example |
== |
Equal to |
a == b |
!= |
Not equal |
a != b |
> |
Greater than |
a > b |
< |
Less than |
a < b |
>= |
Greater or equal |
a >= b |
<= |
Less or equal |
a <= b |
Advanced Integer Methods
public class IntegerMethods {
public static void main(String[] args) {
// Integer class methods
System.out.println("Max Value: " + Integer.max(5, 10));
System.out.println("Min Value: " + Integer.min(5, 10));
System.out.println("Sum: " + Integer.sum(5, 10));
// Parsing and conversion
String numStr = "123";
int parsedNum = Integer.parseInt(numStr);
System.out.println("Parsed Number: " + parsedNum);
// Bit counting
int num = 42;
System.out.println("Number of Set Bits: " + Integer.bitCount(num));
}
}
Overflow and Underflow Handling
public class OverflowHandling {
public static void main(String[] args) {
int maxInt = Integer.MAX_VALUE;
try {
int result = Math.addExact(maxInt, 1);
} catch (ArithmeticException e) {
System.out.println("Overflow detected!");
}
}
}
- Use primitive types for performance
- Avoid unnecessary boxing/unboxing
- Be cautious with complex calculations
LabEx Tip
Explore integer operations interactively with LabEx's coding environments to master these concepts practically.
Best Practices
- Use appropriate data types
- Handle potential overflow
- Understand bitwise operations
- Prefer built-in methods for complex calculations