-1

this an example to get mac address form my machine but i can't understand the syntax of sting.format function here is the example.

public String getMACIdentifier(NetworkInterface network)
{
    StringBuilder identifier = new StringBuilder();
    try {
        byte[] macBuffer = network.getHardwareAddress();
        if (macBuffer != null) {
            for (int i = 0; i < macBuffer.length; i++) {
                identifier.append(
                    String.format("%02X%s",macBuffer[i],
                    (i < macBuffer.length - 1) ? "-" : ""));
            }
        } else {
            return "---";
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }

    return identifier.toString();
}
Trevor Keller
  • 510
  • 2
  • 10
Unknown
  • 1
  • 1
  • Possible duplicate of [Format specifier %02x](https://stackoverflow.com/questions/18438946/format-specifier-02x) – Jay May 30 '19 at 21:59
  • 1
    Did you **read the documentation** on [`String.format()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-), leading you to the full description of the [**format string**](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax)? – Andreas May 30 '19 at 22:18

2 Answers2

2

Formatted strings are a common feature of programming languages. I would recommend reading up on how they work in Java.

In your specific example, the format string "%02X%s" will print a hexadecimal number (represented by %02X) next to a string (represented by "%s"). The hex number will be printed using at least 2 characters; if the number is representable with just one character, then the empty space will be "padded" with a '0' character. This is coded "%02X". The string character will be either "-" or "" (empty), depending on the result of the ternary operator (test ? true_value : false_value).

Trevor Keller
  • 510
  • 2
  • 10
  • 1
    *"using **up to** 2 characters"* is wrong, it means *at least* 2 characters. --- Also, `""` is not *null*, it's an *empty* string. Null is something entirely different. – Andreas May 30 '19 at 22:19
0

Have you try it?

public static void main(String[] args) {
    StringBuilder identifier = new StringBuilder();
    byte[] macBuffer = new byte[5];

    macBuffer[0] = 0x10;
    macBuffer[1] = 0x1;
    macBuffer[2] = 0x02;
    macBuffer[3] = 0x30;

    for (int i = 0; i < macBuffer.length; i++) {
        identifier.append(
                String.format("%02X%s", macBuffer[i],
                        (i < macBuffer.length - 1) ? "-" : ""));
    }

    System.out.println(identifier.toString());
}

Output

10-01-02-30-00

"%02X%s"

  • %02X this is for hexadecimal format and the 02 refer to the minimum number of chars (0x1 is printed as 0x01)
  • %s this is for string format
Butiri Dan
  • 1,759
  • 5
  • 12
  • 18