Sunday, April 13, 2014

Example for String.format


import java.util.*;

public class replaceQuestionMarkwithValues {

       static String query = "select * from table where col1 = ?, col2= ?, col3=? ";
    
       public static void main(String[] args) {

         replaceQuestionMarkwithValues re = new replaceQuestionMarkwithValues();
         List list = new ArrayList();
         list.add("1");
         list.add("2");
         list.add("3");
         list.add("4");
     System.out.println("The Output Is " + extracted(re, list));

       }

private static String extracted(replaceQuestionMarkwithValues re, List list) {
     return re.formatQuery(query, list);
}

        public static String formatQuery(String query, List params){
         Object[] args=params.toArray();
         System.out.println("Total values present are " + args.length);
     return String.format(query.replaceAll("\\?", "%s"), args);
}

}

Result Is : 
--------------
Total values present are 4
The Output Is select * from table where col1 = 1, col2= 2, col3=3 

No comments:

Post a Comment