Number Manipulation
Basic Arithmetic Operations
Java provides comprehensive methods for number manipulation:
public class BasicArithmeticDemo {
public static void main(String[] args) {
// Basic operations
int a = 10, b = 3;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Modulus: " + (a % b));
}
}
Mathematical Operations
Math Class Utilities
graph TD
A[Math Class] --> B[Basic Operations]
A --> C[Advanced Functions]
B --> D[abs()]
B --> E[max()]
B --> F[min()]
C --> G[pow()]
C --> H[sqrt()]
C --> I[round()]
Code Example
public class MathOperationsDemo {
public static void main(String[] args) {
// Math class methods
double x = -5.6;
System.out.println("Absolute Value: " + Math.abs(x));
System.out.println("Ceiling: " + Math.ceil(x));
System.out.println("Floor: " + Math.floor(x));
System.out.println("Power: " + Math.pow(2, 3));
System.out.println("Square Root: " + Math.sqrt(16));
}
}
Operation |
Method |
Example |
Rounding |
Math.round() |
Math.round(3.7) = 4 |
Decimal Formatting |
DecimalFormat |
new DecimalFormat("#.##").format(3.14159) |
Scientific Notation |
String.format() |
String.format("%e", 1234.5678) |
Advanced Manipulation Techniques
BigDecimal for Precise Calculations
import java.math.BigDecimal;
import java.math.RoundingMode;
public class PreciseCalculationsDemo {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("0.1");
BigDecimal num2 = new BigDecimal("0.2");
// Precise addition
BigDecimal result = num1.add(num2);
System.out.println("Precise Sum: " + result);
// Rounding and scaling
BigDecimal scaledResult = result.setScale(2, RoundingMode.HALF_UP);
System.out.println("Scaled Result: " + scaledResult);
}
}
Bitwise Operations
public class BitwiseOperationsDemo {
public static void main(String[] args) {
int a = 60; // 0011 1100
int b = 13; // 0000 1101
System.out.println("Bitwise AND: " + (a & b));
System.out.println("Bitwise OR: " + (a | b));
System.out.println("Bitwise XOR: " + (a ^ b));
}
}
Best Practices
- Use
BigDecimal
for financial calculations
- Be cautious with floating-point precision
- Utilize
Math
class for complex mathematical operations
- Understand rounding modes and their implications
LabEx recommends practicing these techniques to master number manipulation in Java.