2013-05-16 16 views
8

क्या समान डेटा स्वरूपण के इन चार तरीकों में कोई अंतर है?उसी डेटा को प्रारूपित करने के कई तरीके

// Solution 1 
    System.out.printf("%.1\n",10.99f); 

    // Solution 2 
    System.out.format("%.1\n",10.99f); 

    // Solution 3 
    System.out.print(String.format("%.1\n",10.99f)); 

    // Solution 4 
    Formatter formatter = new Formatter(); 
    System.out.print(formatter.format("%.1\n",10.99f)); 
    formatter.close(); 

उत्तर

1

System.out एक PrintStream विस्तार के लिए इस लिंक का अनुसरण है: Details about various format

प्रपत्र की इस पद्धति का एक मंगलाचरण मंगलाचरण के रूप में बिल्कुल उसी तरह

out.printf(Locale l, String format,Object... args)

बर्ताव

out.format(Locale l,String format,Object... args)

तो 1 & 2 वही हैं, उनमें कोई अंतर नहीं है। और 3 & 4 लगभग एक ही केवल संकलन समय अंतर नहीं हो सकता है अगर 1 & 2.

0

को ध्यान में लेते हुए कि String.format() कॉल new Formatter().format() और PrintWriter.printf() कॉल लगभग एक ही वहाँ नहीं कोई फर्क होना चाहिए की तुलना में कर रहे हैं।

0

System.out.printf(), System.out.format()PrintStream के तरीके हैं। वे समकक्ष हैं।

printf() बस नए प्रारूपित स्ट्रिंग को System.out पर प्रदर्शित करता है, जबकि format() आपको एक नया स्वरूपित स्ट्रिंग देता है।

2

पहले दो वास्तव में, एक ही हैं, क्योंकि printf के रूप में (source)

public PrintStream printf(String format, Object ... args) { 
    return format(format, args); 
} 

कार्यान्वित किया जाता है बाद के दो भी बिल्कुल वैसा ही कर रहे हैं, String.format के बाद के रूप में (source)

public static String format(String format, Object ... args) { 
    return new Formatter().format(format, args).toString(); 
} 
कार्यान्वित किया जाता है

अंत में, दूसरा और चौथाई उतना ही कम है, जैसा कि PrintStream.format (source) के कार्यान्वयन से देखा जा सकता है। हुड के तहत, यह एक नया Formatter (यदि आवश्यक हो) बनाता है और उस Formatter पर format पर कॉल करता है।

public PrintStream format(String format, Object ... args) { 
    try { 
     synchronized (this) { 
      ensureOpen(); 
      if ((formatter == null) 
       || (formatter.locale() != Locale.getDefault())) 
       formatter = new Formatter((Appendable) this); 
      formatter.format(Locale.getDefault(), format, args); 
     } 
    } catch (InterruptedIOException x) { 
     Thread.currentThread().interrupt(); 
    } catch (IOException x) { 
     trouble = true; 
    } 
    return this; 
} 
संबंधित मुद्दे