Tuesday, December 16, 2014

Java: formatting text

Nowadays everybody says learn PHP, Python as first language. I beg to disagree. Don't forget C and Java! I even heard people write forget C and go C++ first. This guy is completely cluless.

C's printf is so useful in text-based things, and it is still needed today... to insert your variables in text. Sure, just add them and it works just fine. Then some guy will say dude Java String is immutable please append with use StringBuffer, and then another guy will say dude, use StringBuilder. Yes, this has to do synchronized or not, like that classic interview question that make some even seasoned java developer wet their pant during interview: Vector vs ArrayList. But it is still clumsy... and printf is nicer, especially if your text to display is some constant. The original Java did NOT have printf... but it got added later a long while ago. And there is this MessageFormat thing that works similarly too.

import java.text.MessageFormat;

public class Test {

 public static void main(String[] arg) {
  int a = 10;
  String name = "John";

  Object[] testArgs = { new Integer(a), name };

  MessageFormat form = new MessageFormat(
    "1. My brother {1} is {0} years old.");

  System.out.println(form.format(testArgs));

  String result = String.format("2. My brother %s is %d years old.",
    name, a);
  System.out.println(result);

  System.out.printf("3. My brother %s is %d years old.\n", name, a);

 }

}

No comments: