Search code examples
javastringformatting

Sprintf equivalent in Java


Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this?


Solution

  • // Store the formatted string in 'result'
    String result = String.format("%4d", i * j);
    
    // Write the result to standard output
    System.out.println(result);
    

    See format and its syntax