There is a cool new way to create String templates in java and use the String.format() static method to substitute values dynamically.
For example the code snippet
The output is:
> Hello Jane Doe
---
This gives you an idea of how to create string templates and replace them by using printf like syntax. Here is the sun link that will give you more on this style of formatting. http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html in our project we are using this on the message properties and substituting values for more meaningfull validation messages.
Here is one more example with multiple indexes.
The index "2" in the line number 1 refers to the second array element in the string array that is passed to the format utility in line number 4.
Much more complicated example are available in the sun link. I tried the above examples in Java 1.5.
For example the code snippet
- String message="Hello %1$s";
- message = message.format(message,"Jane Doe");
- System.out.println(message);
The output is:
> Hello Jane Doe
---
This gives you an idea of how to create string templates and replace them by using printf like syntax. Here is the sun link that will give you more on this style of formatting. http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html in our project we are using this on the message properties and substituting values for more meaningfull validation messages.
Here is one more example with multiple indexes.
- String x = "test who let the stars out '%2$s' ";
- String y = "me";
- String z = "you";
- String message = String.format(x,new String[]{y,z});
- System.out.println(message);
The index "2" in the line number 1 refers to the second array element in the string array that is passed to the format utility in line number 4.
Much more complicated example are available in the sun link. I tried the above examples in Java 1.5.
No comments:
Post a Comment