About Ryan Wang

Top 10 Questions of Java Strings

The following are top 10 frequently asked questions about Java Strings.

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

In brief, “==” tests if references are equal and equals() tests if values are equal. Unless you want to check if two strings are the same object, you should always use equals().

It would be better if you know the concept of string interning.

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

Strings are immutable, which means once they are created, they will stay unchanged until Garbage Collector kicks in. With an array, you can explicitly change its elements. In this way, security sensitive information(e.g. password) will not be present anywhere in the system.

3. Can we use string for switch statement?

Yes to version 7. From JDK 7, we can use string as switch condition. Before version 6, we can not use string as switch condition.

// 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");

Simple, but so frequently used and sometimes ignored.

5. How to split a string with white space characters?

We can simple do split using regular expression. “\s” stands for white space characters such as ” “, “\t”, “\r”, “\n”.

String[] strArray = aString.split("\\s+");

6. Does substring() method create a new string?

The answer is no. The substring() method gives a window to an array of chars which represents the existing String, but do not create a new one. To create a new string, you can do add an empty string like the following:

str.substring(m, n) + ""

This will create a new string. The above approach sometimes can make your code faster, because Garbage Collector can collect the unused large string and keep only the sub string.

In Oracle JDK 7, substring() creates a new string. Check out the diagram for showing substring() difference between JDK 6 and JDK 7.

7. String vs StringBuilder vs StringBuffer

String vs StringBuilder: StringBuilder is mutable, which means you can modify it after its creation.
StringBuilder vs StringBuffer: StringBuffer is synchronized, which means it is thread-safe but slower than StringBuilder.

8. How to repeat a string?

In Python, we can just multiple a number to repeat a string. In Java, we can use the repeat() method of StringUtils from Apache Commons Lang package.

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?

Use StringUtils from apache commons lang.

int n = StringUtils.countMatches("11112222", "1");
System.out.println(n);

One more
Do you know How to detect if a string contains only uppercase letter?

Related Articles:

Reference: Top 10 FAQs of Java Strings from our JCG partner Ryan Wang at the Programcreek blog.
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

5 Responses to "Top 10 Questions of Java Strings"

  1. Jaromir Hamala says:

    The point no. 6 is no longer true. The Oracle JDK 7+ does not reuse the char[] from the original String, but it create a new one.

Leave a Reply


5 + = eight



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books