Showing posts with label java 5 tutorial. Show all posts
Showing posts with label java 5 tutorial. Show all posts

Wednesday, 22 August 2012

How to format String in Java – printf Example


String format and printf Example
How to format String in Java is most common problem developer encounter because classic System.out.println() doesn’t support formatting oString while printing on console. For those who doesn’t  know What is formatted String ? here is a simple definition,  Formatted String is a String which not only display contents but also display it in a format which is widely accepted like including comma while displaying large numbers e.g. 100,000,000 etc. Displaying formatted String is one of need for modern GUI application and thankfully Java has good support for formatting String and all other types like IntegersDouble and DateHow to format a String in Java is never as easy as it has been since Java 1.5 which along-with front line features like GenericsEnumAutoboxing and Varargs also introduces several utility method to support rich formatting of String in Java. prior to Java 5 java programmer relies java.text API for all there formatting need but with Java 5 we have now two more convenient way to format String in Java. JDK 1.5 has added format() method in java.lang.String class and provided a printf() method in PrintStream class for printing formatted output in console. printf() method is similar to C programming language printf()method and allows programmer to print formatting string directly to console, which makes System.out.printf() better alternative of System.out.println() method. Both format() and printf()  are overloaded method to support Locale specific formatting.

By the way this is the third article about formatting in Java , earlier we have seeDecimal Format examples and DateFormat examples for formatting numbers and dates in Java.

How String.format() or printf() works in Java

Java String format Example printf String.format() and System.out.printf() both works similarly and if you see the signature of both method they also accepvariable arguments . Both take minimum two parameters, first of them is formatting instruction and other was actual String or anything which needs to be formatted. Java formatting instructions are both powerful and flexible and allows you to generate formatted String on many different format. Its worth to understand format of "formatting instruction" to take full benefit of String.format() method because this is the only tricky part of String formatting specially if you have not used printf() in past. I have seen developer struggle to understand the formatting behavior because of lack of knowledge of different formatting options available in Java.This is how we specify formatting instruction in Java :

String.format "%[argument number] [flags] [width] [.precision] type"

Now let's see what is meaning of each part of formatting instruction. "%" is a special character in formatted String and it denotes start of formatting instruction. String.format() can support multiple formatting instruction with multiple occurrence of "%" character in formatting instruction.

"argument number" is used to specify correct argument in case multiple arguments are available for formatting. "flags" is another special formatting instruction which is used to print String in some specific format for example you can use flag as "," to print comma on output. "width" formatting option denotes minimum number or character will be used in output but in case if number is larger than width then full number will be displayed but if its smaller in length then it will be be padded with zero. "precision" is using for print floating point formatted String, by using precision you can specify till how many decimal a floating point number will be displayed in formatted String. "type" is the only mandatory formatting option and must always comes last in format String also input String which needs to be formatted must be with same type specified in "type" parameter. for example you can not input a floating point number if you have specified "type" as decimal integer "%d", that will result in error. Now let's see an example of String format() method to understand these formatting option better:

format ( "%,6.2f"124.000)

In above example of  String.format() method flag is comma "," , width is 6 and precision is upto 2 decimal point and type is float.

String format Example in Java
In this section we will see different examples to format String in Java. We will see how we can format numbers and dates. Introduce decimal points and aligning number left or right etc. One of the common application of format() is to print leading zero in a number as shown in this Java program example:

/**
 * Java program to demonstrate How to format String in Java by using
 * format() method of String class and printf() method of OutputStream in Java.
 * String.format() is very powerful and not only can format String but numbers
 * and Date in Java
 *
 * @author Javin
 */

public class StringFormatExample{

    public static void main(String args[]){          
   
        //simple example of formatted string in Java
        //%d is used to format decimals like integers
        //position of argument is the order in which they appear in source String
          e.g here 40021 will replace first %d and 3000 will replace second %d.

        String formattedString = String.format("Order with OrdId : %d and Amount: %d is missing"400213000);       

      
 System.out.println(formattedString); 

 
        System.out.printf("Order with OrdId : %d  and Amount: %d is missing \n"400213000);
   
        //%s is used to denote String arguments in formatted String
        String str = String.format("Hello %s""Raj");
        System.out.println(str);
   
        //if argument is not convertible into specified data type than
 //Formatter will throw following java.util.IllegalFormatConversionException

        //e.g. specifying %d and passing 3.0
   
        //str = String.format("Number %d", 3.0);
   
//        Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double
//      at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999)
//      at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2709)
//      at java.util.Formatter$FormatSpecifier.print(Formatter.java:2661)
//      at java.util.Formatter.format(Formatter.java:2433)
//      at java.util.Formatter.format(Formatter.java:2367)
//      at java.lang.String.format(String.java:2769)
   
        //common meta characters used in String.format() and
 //System.out.printf() method: %s - String , %d - decimal integer

        // %f - float  %tD - date as MM/dd/yy while %td is day %tm is month
 // and %ty is 2 digit year while %tY is four digit year

   
        //Formatting date in String format method - date in MM/dd/yy
        str = String.format("Today is %tD"new Date());
        System.out.println(str);
   
        Date today = new Date();
        System.out.printf("Date in dd/mm/yy format %td/%tm/%ty %n", today,today,today );
   
        // date as July 25, 2012, difference between %td and %te is that
 // %td use leading zero while %te doesn't
        System.out.printf("Today is %tB %te, %tY %n", today,today,today,today);
   
        //adding leading zero in numbers using String format,
 //%d is for decimal, 8 specify formatted number should be 8 digit and 0 specify use
        //leading zero, default is space, so if you don't specify leading
 // character space will be used.
        System.out.printf("Amount : %08d %n" , 221);
   
        //printing positive and negative number using String format
 //+ sign for positive, - for negative and %n is for new line

        System.out.printf("positive number : +%d %n"1534632142);
        System.out.printf("negative number : -%d %n"989899);
   
        //printing floating point number with System.format()
        System.out.printf("%f %n"Math.E);
   
        //3 digit after decimal point
        System.out.printf("%.3f %n"Math.E);
   
        //8 charcter in width and 3 digit after decimal point
        System.out.printf("%8.3f %n"Math.E);
   
        //adding comma into long numbers
        System.out.printf("Total %,d messages processed today"10000000);
    }


}

Output:
Order with OrdId : 40021  and Amount: 3000 is missing
Order with OrdId : 40021  and Amount: 3000 is missing
Hello Raj
Today is 07/25/12
Date in dd/mm/yy format 25/07/12
Today is July 252012
Amount : 00000221
positive number : +1534632142
negative number : -989899n
2.718282
2.718
   2.718
Total 10,000,000 messages processed today


Difference between the printf and format methods in Java

printf() and format()both methods are used to format String in Java and more or less similar. printf()is more close to C programming language because of identical name used in  C programming language, Anyone who has work in C previously can easily start with this printf() method also its look more as a replacement of System.out.println(). if you don't want to print just want a formatted string for any other purpose String format() method is a way to go. In summary you can say that printf()writes on stdout while format() return you a formatted string.

We have already seen String format examples with both format and printf method. In short formatting is easier in Java and it provides several classes like DateFormat, NumberFormat etc which can also be used to format Date and numbers.

How to write parametrized class and method in Java – Generics Example


Parametrized class and method in Java
Writing Generic parametrized class and method in Java is easy and should be used as much as possible. Generic in Java was introduced in version 1.5  along with Autoboxing, Enum, varargs and static import. Most of the new code development in Java uses type-safe Generic collection i.e. HashSet in place of HashSet but still Generic is underused in terms of writing own parametrized classes and method. I agree that most Java programmers has started using Generic while working with the Java collection framework but they are still not sure how Generic can allow you to write Template kind of classes which can work with any Type just like the parametrized ArrayList in Java which can store any Type of element. In the last couple of article  about Generics we have seen How Generic works in Java and  explored wild cards of Generic in Java and In this part of Java Generic example we will see How to write parametrized Generic Class and method in Java.


How to write parametrized class and method in Java - Example tutorialIn this Generic tutorial we will write a parametrized class called Wrapper which can contain any Type specified while creating instance just like any collection e.g. Hashtable in Java. This generic class will contain two parametrized method T getItem () and setItem(T) whose Type will be determined at the time of instantiation. We will also see the old version of the same class which is written without using Generic to demonstrate concrete benefit offered by Generic type-safety in terms of coding and development.

Guideline of writing parametrized Generic class:

1) Use type parameter  in Class declaration e.g. class Wrapper where T is a Generic type parameter stands for Type, you can also use which stands for Element and much suitable for collection kind of data structure which stores elements.

2) Now use this T in all places where you need to use actual Type e.g. While declaring the method argument, while writing return type of method etc.

/**
 * Java program to demonstrate How to write parametrized class in Java and type-safety
 * provided by parametrized class. Program also compares non parametrized to
 * parametrized class to highlight issue with non generic classes in Java.
 *
 * @author Javin Paul
 */

public class GenericTest {

    
public static void main(String args[]) {
       
        //string wrapper
        Wrapper
<String> stringWrapper = new Wrapper<String>();
        stringWrapper.
setItem("Test");
        System.
out.println(stringWrapper.getItem());
     
        
//compilation error, type checking at compile time
        
//stringWrapper.setItem(new StringBuffer("")); 
   
        Wrapper
<Integer> integerWrapper = new Wrapper<Integer>();
        integerWrapper.
setItem(123);
     
        
//compilation error, type safety checking
        
//integerWrapper.setItem("123"); 
        System.
out.println(integerWrapper.getItem());
   
   
        
// Now let's see how to write generic wrapper without using
        
// JDK1.5 generic and what problem it poses
   
        OldWrapper oldStringWrapper = 
new OldWrapper();
   
        
//no compilation error i.e. no type checking at compile time
        oldStringWrapper.
setItem(123);

        
//will throw ClassCastException at runtime  
        
((String)oldStringWrapper.getItem()).toUpperCase();
    
}
}
/*
 * wrapper can wrap any item
 * Generic parametrized form of Wrapper, offers compile time type checking
 */

class Wrapper<T> {
    
private T item;

    
public T getItem(){
        
return item;
    
}

    
public void setItem(T item){
        
this.item = item;
    
}
}
/*
 * Object form of Wrapper fragile and error prone
 */

class OldWrapper{
    
private Object item;

    
public Object getItem(){
        
return item;
    
}

    
public void setItem(Object item){
        
this.item = item;
    
}
}


If you look at above example and compare both parametrized versions of class and non parametrized or raw version of same class,  You can derive two substantial benefits of using generic parametrized class and method :

1) Parametrized classes offer compile time type verification. Which is not present in non Generic or non parametrized version of the class.

2) If you use Generic parametrized method or class you don't need to cast into a specific type
3) Generic methods don't throw ClassCastException as Type verification was already done at compile time.


How to write parametrized method in Java Generics:
What is parametrized method in Java? is a popular Java Generics interview question and followed by question like how to write parametrized method using Generics.  Parametrized method in Java are those method writing using Generics feature of Java which accept method argument as type and/or return type instead of any particular type like StringDouble or Float. Parametrized method prevents duplication of code and provides type-safety at compile time. Any static utility method which operate on Object type is good candidate of making parametrized or Generic method in Java. Here is a code example of How to write Generic Parametrized method in Java:

/**
 * Java program to demonstrate how to write parametrized method in Java
 * parametrized method needs a type parameter declaration before return
 * type, here is a type parameter
 * @author Javin
 */

class ItemUtils{
 
    public static <T> T wrap(T item){
        //code for wrapping item
        return item;
    }
 
}

In Summary use Generic parametrized version of class and method in place of using Object as generic type. If you have a code which is on Java 5 and doesn’t use Generic, consider refactoring that code to use Generic to enjoy benefits provided by Generics like type-safety, no ClassCastException and no need of casting.

That's all on this Java Generic Example of  how to create parametrized class and method using Generic. Just remember that Generic is only available from Java 1.5 onwards and you can not write parametrized class and method in Java 1.4 or lower version.