Sunday, December 11, 2011

Java's character and assorted string classes support text-processing - 11


  • public String concat(String str) creates a new String containing the current String's characters followed by the str-referenced String's characters. A reference to the new String returns. However, if str contains no characters, a reference to the current String returns. Example: String s = "Hello,"; System.out.println (s.concat (" World")); (output: Hello, World). Although you can choose concat(String str), the string concatenation operator (+) produces more compact source code. For example, String t = "a"; String s = t + "b"; is more compact than String t = "a"; String s = t.concat ("b");. However, because the compiler converts String t = "a"; String s = t + "b"; to String t = "a"; String s = new StringBuffer ().append (t).append ("b").toString ();, using concat(String str) might seem cheaper. However, their execution times prove similar.
  •  
Caution
Do not use either concat(String str) or the string concatenation operator in a loop that executes repeatedly; that can affect your program's performance. (Each approach creates several objects—which can increase garbage collections—and several methods are called behind the scenes.)
  •  
  • public static String copyValueOf(char [] data) creates a new String containing a copy of all characters in the data array and returns the new String's reference. Example: char [] yesNo = { 'y', 'n', 'Y', 'N' }; String s = String.copyValueOf (yesNo); System.out.println (s); (output: ynYN).
  • public boolean equalsIgnoreCase(String anotherString) performs a case-insensitive comparison of the current String's characters with anotherString's characters. If those characters match (from a case-insensitive perspective), this method returns true. But if either the characters do not match or if anotherString contains a null reference, this method returns false. Example: System.out.println ("Abc".equalsIgnoreCase ("aBC")); (output: true).

No comments: