Coding Practical Examples
Real-World Scenarios of Numeric Prefixes
Bitwise Operations and Flags
public class BitFlagExample {
// Using binary literals for flag definitions
public static final int READ_PERMISSION = 0b0001;
public static final int WRITE_PERMISSION = 0b0010;
public static final int EXECUTE_PERMISSION = 0b0100;
public static void main(String[] args) {
int userPermissions = READ_PERMISSION | WRITE_PERMISSION;
System.out.println("Binary Representation: " +
Integer.toBinaryString(userPermissions));
}
}
Color Representation in Hexadecimal
public class ColorCodeExample {
public static void main(String[] args) {
// Hexadecimal color codes
int red = 0xFF0000; // Pure Red
int green = 0x00FF00; // Pure Green
int blue = 0x0000FF; // Pure Blue
System.out.println("Red Color Code: " + Integer.toHexString(red));
System.out.println("Green Color Code: " + Integer.toHexString(green));
System.out.println("Blue Color Code: " + Integer.toHexString(blue));
}
}
Network Address Manipulation
public class NetworkAddressExample {
public static void main(String[] args) {
// Subnet mask in binary and hexadecimal
int subnetMask = 0b11111111_11111111_11111111_00000000; // 255.255.255.0
int hexSubnet = 0xFFFFFF00;
System.out.println("Subnet Mask (Binary): " +
Integer.toBinaryString(subnetMask));
System.out.println("Subnet Mask (Hex): " +
Integer.toHexString(hexSubnet));
}
}
Numeric Prefix Conversion Strategies
graph TD
A[Numeric Input] --> B{Conversion Method}
B --> |Integer.parseInt()| C[Decimal Conversion]
B --> |Integer.decode()| D[Flexible Prefix Parsing]
B --> |Custom Logic| E[Advanced Parsing]
Conversion Techniques Comparison
Method |
Prefix Support |
Flexibility |
Performance |
Integer.parseInt() |
Limited |
Low |
High |
Integer.decode() |
Comprehensive |
Medium |
Medium |
Custom Parsing |
Unlimited |
High |
Variable |
Advanced Parsing Example
public class NumericParsingExample {
public static int parseFlexibleNumeric(String input) {
try {
// Supports multiple prefix formats
if (input.startsWith("0b") || input.startsWith("0B")) {
return Integer.parseInt(input.substring(2), 2);
}
if (input.startsWith("0x") || input.startsWith("0X")) {
return Integer.parseInt(input.substring(2), 16);
}
if (input.startsWith("0")) {
return Integer.parseInt(input.substring(1), 8);
}
return Integer.parseInt(input);
} catch (NumberFormatException e) {
System.err.println("Invalid numeric format");
return 0;
}
}
public static void main(String[] args) {
System.out.println(parseFlexibleNumeric("0b1010")); // Binary
System.out.println(parseFlexibleNumeric("0x2A")); // Hexadecimal
System.out.println(parseFlexibleNumeric("052")); // Octal
}
}
Best Practices
- Use appropriate numeric prefixes for clarity
- Understand conversion mechanisms
- Handle potential parsing exceptions
- Consider performance implications
Enhance your numeric manipulation skills with LabEx's interactive Java programming environments, exploring these practical examples and techniques.