String.format(args, args) Java

+1 Prolific Alias · February 1, 2016
When Bucky was explaining how to do the time in military, he used the String.format method. I'm really confused with that and I was trying to find help online and it just confused me more. Does anyone know a place I could learn how that works and more of the possibilities? Thanks

Post a Reply


Oldest  Newest  Rating
0 Linguist Llama · February 1, 2016
Do you know what a string is?
0 Gary Whitney · February 1, 2016
String.format is above all else a method,. Which means it can do logic. Specifically it can parse the string you pass it and apply the code in the method to return a formatted string.

The % is a flag that says what follows is a regular expression so decode the expression and apply it to the argument and insert the result into the return string.

You can insert a variable into a string with concatenation. e.g. String response = "The Title of the book is: " + title +"."
if title = "Threat Vector"
response =  "The Title of the book is: Threat Vector."

You can achieve the same result with the %s flag. e.g. response = String.format("The Title of the book is: %s." , title);
Here the %s flag simply says "get the first argument and plug it in here."

Now try to wrap your head around this.
The % flag is like a call to a subroutine that decodes the expression that follows the flag and inserts arguments formatted according to the expression. Regular expressions are a language all there own.
The syntax is %[argument number][flags][width][precision]type
So you see there is a lot of formatting you can do with the [optional parameters]

The bare minimum is %type
Note: If you are familiar with the printf() method, it  works the same way.
Here are some examples using the printf() method
   printf("%2d", 1); would print 1 with a width of 2 characters
     printf("%.2f",2.333333 ); would print 2.33
     The f  stands for floating point and .2 limits the precision to 2 places after the decimal point.
     %,d ,1000000000 would print 1,000,000,000 Notice the coma flag between the % symbol and the d.
     If you have multiple formatting instructions and multiple arguments,, the arguments are taken in order, and inserted in the instructions in the order they appear. Printf(“The sum of %d and %d is %d.”, a, b, c);
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator