Tuesday, April 5, 2011

Java 5 Feature : Simple Example: printf vs. println

• General idea
– Each %s entry in formatting string is replaced by next argument in argument list. %n means newline.
• Example
public static void printSomeStrings() {
        String firstName = "Rohit";
        String lastName = "Sharma";
        int numPets = 7;
        String petType = "dogs";
        System.out.printf("%s %s has %s %s.%n", firstName, lastName, numPets, petType);
        //here in above printf statement first '%s' replaced by firstName, second '%s' by lastName likewise '%s' replaced by other variables.
        System.out.println(firstName + " " + lastName +" has " + numPets + " " +petType + ".");
}
• Result:
Rohit Sharma has 7 dogs.
Rohit Sharma has 7 dogs.

No comments:

Post a Comment