These newer classes are seemingly often under-used, but pretty straight forward...
Take a scenario where we need to format a year value into HTML, underlining the last digit. E.g: 2005 becomes: 2005. In this example, the first snippet of code initialises two variables that describe the split year: the centuryAndDecade and yearDigit:
String year = "2005";
int length = year.length();
String centuryAndDecade = year.substring(0, length - 1);
char yearDigit = year.charAt(length - 1);
Using the old fashion StringBuffer, you can create our desired output like this:
StringBuffer sb = new StringBuffer(" ");
sb.append(centuryAndDecade);
sb.append("<u>");
sb.append(yearDigit);
sb.append("</u>");
System.out.println("Result: " + sb.toString());
But, you can use the StringBuilder and Formatter classes to do the same thing:
StringBuilder sb1 = new StringBuilder();
Formatter f = new Formatter(sb1);
f.format(" %3s<u>%c</u>", centuryAndDecade, yearDigit);
System.out.println(sb1.toString());
Or, you can use printf(...) method to simplify your code even further:
System.out.printf(" %3s<u>%c</u>", centuryAndDecade, yearDigit);
No comments:
Post a comment