Web Article - Questions about Java Strings

1. How to compare strings? Use “==” or use equals()?

2. Why is char[] preferred over String for security sensitive information?

3. Can we use string for switch statement?

// java 7 only!
switch (str.toLowerCase()) {
      case "a":
           value = 1;
           break;
      case "b":
           value = 2;
           break;
}

4. How to convert string to int?
int n = Integer.parseInt("10");

5. How to split a string with white space characters?
String[] strArray = aString.split("\\s+");

6. Does substring() method create a new string?
str.substring(m, n) + ""

7. String vs StringBuilder vs StringBuffer 

8. How to repeat a string?
String str = "abcd";
String repeated = StringUtils.repeat(str,3);
//abcdabcdabcd

9. How to convert string to date?
String str = "Sep 17, 2013";
Date date = new SimpleDateFormat("MMMM d, yy", Locale.ENGLISH).parse(str);
System.out.println(date);
//Tue Sep 17 00:00:00 EDT 2013

10. How to count # of occurrences of a character in a string?
int n = StringUtils.countMatches("11112222", "1");
System.out.println(n);

A method to detect if string contains only uppercase letter in Java
public static boolean testAllUpperCase(String str){
  for(int i=0; i < str.length(); i++){
   char c = str.charAt(i);
   if(c >= 97 && c <= 122) {
    return false;
   }
  }
  //str.charAt(index)
  return true;
 }
Source: http://www.programcreek.com/

0 Respostas em "Web Article - Questions about Java Strings"

Powered by Blogger