Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

The String class is one of the most widely used classes in Java, which prompted language designers to treat it specially. This special behavior makes it one of the hottest topics in Java interviews.

In this tutorial, we'll go through some of the most common interview questions about String.

2. String Fundamentals

This section consists of questions that concern the String internal structure and memory.

Q1. What Is a String in Java?

In Java, a String is represented internally by an array of byte values (or char values before JDK 9).

In versions up to and including Java 8, a String was composed of an immutable array of Unicode characters. However, most characters require only 8 bits (1 byte) to represent them instead of 16 bits (char size).

To improve memory consumption and performance, Java 9 introduced compact Strings. This means that if a String contains only 1-byte characters, it will be represented using Latin-1 encoding. If a String contains at least 1 multi-byte character, it will be represented as 2 bytes per character using UTF-16 encoding.

In C and C++, String is also an array of characters, but in Java, it's a separate object with its own API.

Q2. How Can We Create a String Object in Java?

java.lang.String defines 13 different ways to create a String. Generally, though, there are two:

  • Through a String literal:
    String s = "abc";
  • Through the new keyword:
    String s = new String("abc");

All String literals in Java are instances of the String class.

Q3. Is String a Primitive or a Derived Type?

A String is a derived type since it has state and behavior. For example, it has methods like substring(), indexOf(), and equals(), which primitives cannot have.

But, since we all use it so often, it has some special characteristics that make it feel like a primitive:

  • While strings are not stored on the call stack like primitives are, they are stored in a special memory region called the string pool
  • Like primitives, we can use the operator on strings
  • And again, like primitives, we can create an instance of a String without the new keyword

Q4. What Are the Benefits of Strings Being Immutable?

According to an interview by James Gosling, strings are immutable to improve performance and security.

And actually, we see several benefits to having immutable strings:

  • The string pool is only possible if the strings, once created, are never changed, as they are supposed to be reused
  • The code can safely pass a string to another method, knowing that it can't be altered by that method
  • Immutably automatically makes this class thread-safe
  • Since this class is thread-safe, there is no need to synchronize common data, which in turn improves performance
  • Since they are guaranteed to not change, their hashcode can be easily cached

Q5. How Is a String Stored in Memory?

According to the JVM Specification, String literals are stored in a runtime constant pool, which is allocated from the JVM's method area.

Although the method area is logically part of the heap memory, the specification does not dictate the location, memory size, or garbage collection policies. It can be implementation-specific.

This runtime constant pool for a class or interface is constructed when the class or interface is created by the JVM.

Q6. Are Interned Strings Eligible for Garbage Collection in Java?

Yes, all Strings in the string pool are eligible for garbage collection if there are no references from the program.

Q7. What Is the String Constant Pool?

The string pool, also known as the String constant pool or the String intern pool, is a special memory region where the JVM stores String instances.

It optimizes application performance by reducing how often and how many strings are allocated:

  • The JVM stores only one copy of a particular String in the pool
  • When creating a new String, the JVM searches in the pool for a String having the same value
  • If found, the JVM returns the reference to that String without allocating any additional memory
  • If not found, then the JVM adds it to the pool (interns it) and returns its reference

Q8. Is String Thread-Safe? How?

Strings are indeed completely thread-safe because they are immutable. Any class which is immutable automatically qualifies for thread-safety because its immutability guarantees that its instances won't be changed across multiple threads.

For example, if a thread changes a string's value, a new String gets created instead of modifying the existing one.

Q9. For Which String Operations Is It Important to Supply a Locale?

The Locale class allows us to differentiate between cultural locales as well as to format our content appropriately.

When it comes to the String class, we need it when rendering strings in format or when lower- or upper-casing strings.

In fact, if we forget to do this, we can run into problems with portability, security, and usability.

Q10. What Is the Underlying Character Encoding for Strings?

According to String's Javadocs for versions up to and including Java 8, Strings are stored in the UTF-16 format internally.

The char data type and java.lang.Character objects are also based on the original Unicode specification, which defined characters as fixed-width 16-bit entities.

Starting with JDK 9, Strings that contain only 1-byte characters use Latin-1 encoding, while Strings with at least 1 multi-byte character use UTF-16 encoding.

3. The String API

In this section, we'll discuss some questions related to the String API.

Q11. How Can We Compare Two Strings in Java? What’s the Difference Between str1 == str2 and str1.Equals(str2)?

We can compare strings in two different ways: by using equal to operator ( == ) and by using the equals() method.

Both are quite different from each other:

  • The operator (str1 == str2checks for referential equality
  • The method (str1.equals(str2)checks for lexical equality

Though, it's true that if two strings are lexically equal, then str1.intern() == str2.intern() is also true.

Typically, for comparing two Strings for their content, we should always use String.equals.

Q12. How Can We Split a String in Java?

The String class itself provides us with the String#split method, which accepts a regular expression delimiter. It returns us a String[] array:

String[] parts = "john,peter,mary".split(",");
assertEquals(new String[] { "john", "peter", "mary" }, parts);

One tricky thing about split is that when splitting an empty string, we may get a non-empty array:

assertEquals(new String[] { "" }, "".split(","));

Of course, split is just one of many ways to split a Java String.

Q13. What Is Stringjoiner?

StringJoiner is a class introduced in Java 8 for joining separate strings into one, like taking a list of colors and returning them as a comma-delimited string. We can supply a delimiter as well as a prefix and suffix:

StringJoiner joiner = new StringJoiner(",", "[", "]");
joiner.add("Red")
  .add("Green")
  .add("Blue");

assertEquals("[Red,Green,Blue]", joiner.toString());

Q14. Difference Between String, Stringbuffer and Stringbuilder?

Strings are immutable. This means that if we try to change or alter its values, then Java creates an absolutely new String

For example, if we add to a string str1 after it has been created:

String str1 = "abc";
str1 = str1 + "def";

Then the JVM, instead of modifying str1, creates an entirely new String.

However, for most of the simple cases, the compiler internally uses StringBuilder and optimizes the above code.

But, for more complex code like loops, it will create an entirely new String, deteriorating performance. This is where StringBuilder and StringBuffer are useful.

Both StringBuilder and StringBuffer in Java create objects that hold a mutable sequence of characters. StringBuffer is synchronized and therefore thread-safe whereas StringBuilder is not.

Since the extra synchronization in StringBuffer is typically unnecessary, we can often get a performance boost by selecting StringBuilder.

Q15. Why Is It Safer to Store Passwords in a Char[] Array Rather Than a String?

Since strings are immutable, they don't allow modification. This behavior keeps us from overwriting, modifying, or zeroing out its contents, making Strings unsuitable for storing sensitive information.

We have to rely on the garbage collector to remove a string's contents. Moreover, in Java versions 6 and below, strings were stored in PermGen, meaning that once a String was created, it was never garbage collected.

By using a char[] array, we have complete control over that information. We can modify it or wipe it completely without even relying on the garbage collector.

Using char[] over String doesn't completely secure the information; it's just an extra measure that reduces an opportunity for the malicious user to gain access to sensitive information.

Q16. What Does String’s Intern() Method Do?

The method intern() creates an exact copy of a String object in the heap and stores it in the String constant pool, which the JVM maintains.

Java automatically interns all strings created using string literals, but if we create a String using the new operator, for example, String str = new String(“abc”), then Java adds it to the heap, just like any other object.

We can call the intern() method to tell the JVM to add it to the string pool if it doesn't already exist there, and return a reference of that interned string:

String s1 = "Baeldung";
String s2 = new String("Baeldung");
String s3 = new String("Baeldung").intern();

assertThat(s1 == s2).isFalse();
assertThat(s1 == s3).isTrue();

Q17. How Can We Convert String to Integer and Integer to String in Java?

The most straightforward approach to convert a String to an Integer is by using Integer#parseInt:

int num = Integer.parseInt("22");

To do the reverse, we can use Integer#toString:

String s = Integer.toString(num);

Q18. What Is String.Format() and How Can We Use It?

String#format returns a formatted string using the specified format string and arguments.

String title = "Baeldung"; 
String formatted = String.format("Title is %s", title);
assertEquals("Title is Baeldung", formatted);

We also need to remember to specify the user's Locale, unless we are okay with simply accepting the operating system default:

Locale usersLocale = Locale.ITALY;
assertEquals("1.024",
  String.format(usersLocale, "There are %,d shirts to choose from. Good luck.", 1024))

Q19. How Can We Convert a String to Uppercase and Lowercase?

String implicitly provides String#toUpperCase to change the casing to uppercase.

Though, the Javadocs remind us that we need to specify the user's Locale to ensure correctness:

String s = "Welcome to Baeldung!";
assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase(Locale.US));

Similarly, to convert to lowercase, we have String#toLowerCase:

String s = "Welcome to Baeldung!";
assertEquals("welcome to baeldung!", s.toLowerCase(Locale.UK));

Q20. How Can We Get a Character Array from String?

String provides toCharArray, which returns a copy of its internal char array pre-JDK9 (and converts the String to a new char array in JDK9+):

char[] hello = "hello".toCharArray();
assertArrayEquals(new String[] { 'h', 'e', 'l', 'l', 'o' }, hello);

Q21. How Would We Convert a Java String into a Byte Array?

By default, the method String#getBytes() encodes a String into a byte array using the platform’s default charset.

And while the API doesn't require that we specify a charset, we should in order to ensure security and portability:

byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII);
byte[] byteArray3 = "ijkl".getBytes("UTF-8");

4. String-Based Algorithms

In this section, we'll discuss some programming questions related to Strings.

Q22. How Can We Check If Two Strings Are Anagrams in Java?

An anagram is a word formed by rearranging the letters of another given word, for example, “car” and “arc”.

To begin, we first check whether both the Strings are of equal length or not.

Then we convert them to char[] array, sort them, and then check for equality.

Q23. How Can We Count the Number of Occurrences of a Given Character in a String?

Java 8 really simplifies aggregation tasks like these:

long count = "hello".chars().filter(ch -> (char)ch == 'l').count();
assertEquals(2, count);

And, there are several other great ways to count the l's, too, including loops, recursion, regular expressions, and external libraries.

Q24. How Can We Reverse a String in Java?

There can be many ways to do this, the most straightforward approach being to use the reverse method from StringBuilder (or StringBuffer):

String reversed = new StringBuilder("baeldung").reverse().toString();
assertEquals("gnudleab", reversed);

Q25. How Can We Check If a String Is a Palindrome or Not?

A palindrome is any sequence of characters that reads the same backward as forward, such as “madam”, “radar” or “level”.

To check if a string is a palindrome, we can start iterating the given string forward and backward in a single loop, one character at a time. The loop exits at the first mismatch.

5. Conclusion

In this article, we went through some of the most prevalent String interview questions.

All the code samples used here are available on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!