Last Updated:

TOP-10 questions on strings in Java

Below are the 10 most frequently asked questions about Java Strings.

10. How do I compare strings? Use "==" or equals()?


Simply put, "==" is used if the references are equal, and equals() is used if the values are equal. If you want to check if two rows are the same object, then you should always use equals().
Why is that? Here's a good example and a good explanation of what a string pool is in Java.

9. Why is char[] preferable to string for the security of confidential information?


Strings are immutable, which means that once created, they do not change until the garbage collector destroys it. And using an array, you can explicitly change its elements. Thus, the security of confidential information (for example, a password) will not be present anywhere in the system.

8. Can I use string in a switch statement?

Yes. However, this feature appeared in Java only with JDK 7. Before that, we couldn't use string in a switch statement.

7. How to convert String to int?


Simple, but often forgotten.

6. How do I split a string into spaces?

And here everything is simple:

As you can see, here the split method is used with a parameter in the form of a regular expression.

5. What does the method actually do?substring()

In JDK 6, the method returns an array of characters from an existing string, but does not create a new one. To create a new line, you had to use a small trick - add an empty line to the end:


Running this code creates a new array of characters and converts it to a new string. The approach described above can make your program faster, because the garbage collector will collect only an unused string, and will save only the substring.

Starting with JDK 7, the substring() method creates a new character array without using an input string.

4. String vs StringBuilder vs StringBuffer


String vs StringBuilder: The StringBuilder is mutable, which means you can change it after you create it.

StringBuilder vs StringBuffer: The StringBuffer is synchronizable, which means that it is thread-safe, but runs slower than StringBuilder.

3. How do I duplicate/repeat a string in Java?


In Java, we can use the method from the StringUtils of the Apache Commons Lang package.


2. How do I convert a string to a date?

Let's show it all with an example:


1. How to calculate the number of occurrences of a character in a string?


We want our program to work quickly and without errors, right? Then let's use the method from the StringUtils of the Apache Commons Lang package.


That's where our TOP-10 ends. Follow the updates in the Blog and the release of new articles.