Java String Interview Questions With Answers for Java 25

Java String interview questions with answers and runnable code. Immutability, string pool, == vs equals, StringBuilder, and coding tasks for Java 25.

Diagram with four statements on the left. The variables a and b, created from the literal java, and d, created by c.intern(), point to one pooled java object inside the string pool area of the heap. The variable c, created with new String, points to a separate java object outside the pool.

Java String interview questions check how well we know the String class, such as its immutability, the string pool, equality checks and the difference from StringBuilder. Almost every Java interview has a few of them, because every app works with text and small mistakes with strings cause real bugs.

We use these questions to prepare for Java developer interviews, from the first job to mid-level roles, and as a quick refresher on how strings behave in current Java versions such as Java 25.

The following example answers the most common questions in a few lines, with the result of each line as a comment.

String a = "java";
String b = "java";
String c = new String("java");
boolean samePooled = a == b;                                  // true (one pooled object)
boolean sameObject = a == c;                                  // false (c is a new object)
boolean sameText = a.equals(c);                               // true
boolean afterIntern = a == c.intern();                        // true
String upper = a.toUpperCase();                               // "JAVA" (a stays "java")
String reversed = new StringBuilder(a).reverse().toString();  // "avaj"

Notice that == compares object references and equals() compares characters, which is the root of many interview questions. The questions are grouped by topic, from the basics and the pool to the classic coding exercises, and each answer shows the code that proves it.

1. String Basics

Interviewers often start with what a String is and why it never changes. These answers changed a little in recent Java versions, so we give the Java 25 view.

1.1. Is String a Keyword or a Primitive Type?

Neither. The String class is a final class in the java.lang package, and Java has only eight primitive types. Because String is not one of the reserved keywords, it is even a legal variable name.

int String = 10;                                  // 10 (compiles, but never do this)
boolean isFinal = java.lang.reflect.Modifier.isFinal(java.lang.String.class.getModifiers());   // true

The class is final, so nobody can write a subclass that changes how strings behave. It implements CharSequence, Comparable<String> and Serializable.

1.2. Why Is String Immutable?

An immutable object cannot change its state after it is created. Every String method that looks like a change, such as toUpperCase() or concat(), returns a new String and leaves the original alone.

String city = "pune";
String upperCity = city.toUpperCase();      // "PUNE"
String full = city.concat(", India");       // "pune, India"
boolean unchanged = city.equals("pune");    // true

Java designs String this way for four reasons, and naming them is the answer interviewers expect.

  • The string pool can share one object between many variables, because no variable can change it for the others.
  • The hash code is calculated once and cached, so a String works fast as a HashMap key.
  • Security checks stay valid, because a file path or a class name cannot change after the check.
  • Strings are safe to share between threads without locks.

For example, a web app stores user sessions in a HashMap keyed by the session ID. If the ID string could change after put(), the map would look in the wrong bucket and never find the session again. The full reasoning is in why strings are immutable, and the general recipe is in making a class immutable.

1.3. How Does String Store Its Characters Since Java 9?

Older answers say that a String wraps a char[] with offset and count fields. That has been wrong for years. The offset and count fields were removed in Java 7 update 6, and since Java 9 a String stores its characters in a byte[] plus a coder flag. This change is called compact strings (JEP 254).

TextCoderBytes per character
Only Latin-1 characters, such as “java”LATIN11
Any other character, such as Hindi or emojiUTF162

Compact strings halve the memory for the characters of most strings, because most text in an app is Latin-1. The change is internal, so length() and charAt() still count UTF-16 code units, and our code does not change.

1.4. Is String Thread-Safe?

Yes. A String has no method that changes its characters, and the field that holds them is final, so several threads can read the same String at the same time without locks. A variable that holds a String is a different matter, because assigning a new string to a shared field still needs the usual concurrency rules such as volatile or synchronization.

2. String Pool and Memory

The pool questions check whether we understand where string objects live and why == sometimes returns true for two variables.

2.1. Where Do String Literals Live in Memory?

The string pool is a table inside the JVM that holds one shared String object for each string literal. Every literal with the same text resolves to the same pooled object, in every class of the app. Since Java 7, the pooled strings live in the normal heap, not in PermGen, so the garbage collector removes pooled strings that nothing references any more.

Diagram with four statements on the left. The variables a and b, created from the literal java, and d, created by c.intern(), point to one pooled java object inside the string pool area of the heap. The variable c, created with new String, points to a separate java object outside the pool.
Literals and intern() return the pooled object, whereas new String() always creates a separate one

For example, an app reads a CSV file with a million rows, and every row has a country column with one of 20 values. Each split() call creates new strings, so the heap holds a million copies of “India”. Calling intern() on the column value keeps one copy per country.

2.2. How Many Objects Does new String(“java”) Create?

One or two. The literal “java” creates a pooled object the first time the JVM resolves it, unless the pool already has one. The new keyword always creates a second object at run time.

String s1 = "java";
String s2 = "java";
String s3 = new String("java");
boolean s1s2 = s1 == s2;          // true (both use the pooled object)
boolean s1s3 = s1 == s3;          // false (s3 is a new object)

So the three lines create two String objects in total, the pooled one and the one from new. The constructor new String(String) is almost never needed in real code, because strings are immutable and a copy gives us nothing.

2.3. What Does intern() Do?

The method intern() returns the pooled String with the same characters. If the pool has no such string yet, the JVM adds the current one to the pool and returns it. The method does not move or change the object we call it on, so we must use the return value.

String fromInput = new String("india");
String pooled = fromInput.intern();
boolean sameAsLiteral = pooled == "india";       // true
boolean original = fromInput == "india";         // false (fromInput is unchanged)

For any two strings, s.intern() == t.intern() is true only when s.equals(t) is true.

2.4. Does Concatenation at Run Time Use the Pool?

No. The compiler joins constant expressions, such as two literals or final variables with constant values, and puts the result in the pool. Concatenation with a normal variable happens at run time and creates a new object.

String full = "howto" + "doinjava";
boolean compileTime = full == "howtodoinjava";       // true (constant expression)

String part = "howto";
String joined = part + "doinjava";
boolean runTime = joined == "howtodoinjava";         // false (built at run time)

final String constPart = "howto";
String joinedConst = constPart + "doinjava";
boolean finalConst = joinedConst == "howtodoinjava";  // true (constPart is a constant)

Only constant expressions are pooled for us. Tricky questions of this kind test whether we know that == on strings depends on how the strings were created.

3. String Equality and Ordering

Equality questions come up in nearly every interview, because comparing strings with == is one of the most common bugs in Java code.

3.1. What Is the Difference Between == and equals()?

The == operator compares references, so it returns true only when both variables point to the same object. The method equals() compares the characters, so it returns true for two different objects with the same text.

Say a login service compares the role from the database with role == “ADMIN”. The check passes in a unit test that uses a literal, but in production the role comes from a JDBC result set as a new String, so the admin is refused.

String fromDb = new String("ADMIN");
boolean byReference = fromDb == "ADMIN";               // false
boolean byValue = fromDb.equals("ADMIN");              // true
boolean nullSafe = "ADMIN".equals(null);               // false (no NullPointerException)
boolean bothNull = Objects.equals(null, null);         // true

We always compare strings with equals(), and we call it on the literal or use Objects.equals() when the variable can be null.

3.2. How Do compareTo() and equalsIgnoreCase() Work?

The method compareTo() compares two strings character by character, which is what sorting needs. It returns 0 for equal strings, a negative number when the first string comes first, and a positive number otherwise. The number is the difference of the first characters that differ, or the difference of the lengths.

int before = "apple".compareTo("banana");               // -1 ('a' - 'b')
int same = "apple".compareTo("apple");                  // 0
int upperFirst = "Apple".compareTo("apple");            // -32 ('A' - 'a')
int shorter = "app".compareTo("apple");                 // -2 (length 3 - 5)
int ignoreCase = "Apple".compareToIgnoreCase("apple");  // 0
boolean equalText = "Apple".equalsIgnoreCase("APPLE");  // true

Notice that uppercase letters sort before lowercase letters, because compareTo() uses the character codes. For sorting names the way people expect in a given language, we use a java.text.Collator.

3.3. Why Is String a Good HashMap Key?

A HashMap finds an entry by the key’s hash code first and by equals() second. The String class overrides both methods by its characters, as the hashCode() and equals() contract requires, and its immutability means the hash code never changes after put().

Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 5);
int found = stock.get(new String("apple"));    // 5 (equal text, different object)
int hash = "apple".hashCode();                 // 93029210

The String class also caches the hash code in a field after the first call, so later lookups with the same key object skip the calculation.

4. String, StringBuilder and StringBuffer

The builder question is the most asked String question for developers with a few years of experience, and the answer is a short comparison.

4.1. What Is the Difference Between Them?

A String cannot change, whereas StringBuilder and StringBuffer hold a changeable sequence of characters. The two builders have the same methods, and they differ only in synchronization.

StringStringBuilderStringBuffer
Can changenoyesyes
Thread-safeyes (immutable)noyes (synchronized methods)
Speed for many appendsslow, creates new objectsfastestslower because of locks
SinceJava 1.0Java 5Java 1.0
Use forvalues, keys, constantsbuilding text in one threadlegacy code shared by threads

In current code, we use StringBuilder almost always. A builder is rarely shared between threads, and when it is, the code needs higher-level locking anyway, so StringBuffer is mostly found in old APIs.

StringBuilder sb = new StringBuilder("java");
sb.append(" 25").insert(0, "Hello ").replace(0, 5, "Hi");
String text = sb.toString();                    // "Hi java 25"
int size = sb.length();                         // 10

4.2. Should We Use + or StringBuilder for Concatenation?

For a single expression, we use +. Since Java 9, the compiler turns + into an invokedynamic call to StringConcatFactory (JEP 280), which sizes the result once, so a StringBuilder is not faster there.

Inside a loop, += creates a new string on every pass and copies all previous characters, so the work grows with the square of the number of items. For example, an export job that builds a CSV line for 10,000 orders with += copies millions of characters, whereas a StringBuilder appends to one buffer.

List<String> names = List.of("Lokesh", "Alex", "Maria");

StringBuilder line = new StringBuilder();
for (String name : names) {
  line.append(name).append(';');
}
String built = line.toString();                 // "Lokesh;Alex;Maria;"
String joined = String.join(", ", names);       // "Lokesh, Alex, Maria"

When the items are already in a collection, String.join() or a StringJoiner is the shortest choice. The measured differences are in string concatenation performance.

5. Questions About Common String Methods

Interviewers like method questions with a trap, such as a regex that matches more than expected or an empty string that is not blank.

5.1. What Is the Difference Between replace() and replaceAll()?

Both methods replace every match, not only the first one. The method replace() takes plain text, whereas replaceAll() takes a regular expression, so characters such as the dot have a special meaning there.

String version = "25.0.1";
String plain = version.replace(".", "_");              // "25_0_1"
String regex = version.replaceAll(".", "_");           // "______" (dot matches any character)
String escaped = version.replaceAll("\\.", "_");       // "25_0_1"
String first = version.replaceFirst("\\.", "_");       // "25_0.1"
String removed = "java".replace("a", "");              // "jv"

To remove characters, we replace them with an empty string, as the last line shows.

5.2. Why Does split() Drop Empty Values?

The method split() also takes a regex, and by default it removes empty strings at the end of the result. A CSV line with empty last columns loses those columns unless we pass a negative limit.

String row = "Lokesh,37,,";
int dropped = row.split(",").length;            // 2 (trailing empty values removed)
int kept = row.split(",", -1).length;           // 4
int wrongDot = "a.b.c".split(".").length;       // 0 (every character is a separator)
int rightDot = "a.b.c".split("\\.").length;     // 3

More options, such as limits and multiple separators, are in the String.split() guide.

5.3. Is an Empty String the Same as a Blank String?

The method isEmpty() returns true only for a string of length 0. The method isBlank(), added in Java 11, also returns true for a string that contains only whitespace. The matching pair for removing whitespace is trim() and strip(), which we compare in removing leading and trailing whitespace.

boolean emptyCheck = "  ".isEmpty();           // false
boolean blankCheck = "  ".isBlank();           // true
boolean bothEmpty = "".isEmpty();              // true
String stripped = "  java  ".strip();          // "java"

5.4. Can We Use a String in a switch?

Yes, since Java 7. The switch compares the value with equals(), after a quick check of the hash code, and it throws a NullPointerException when the value is null. Since Java 14, a switch expression with arrow labels returns a value.

String size = "M";
String label = switch (size) {
  case "S" -> "Small";
  case "M" -> "Medium";
  case "L" -> "Large";
  default -> "Unknown";
};
boolean medium = label.equals("Medium");        // true

6. String Coding Questions

Most interviews include one short coding task on strings. Interviewers also check how the code treats null, case and empty input, so we mention these cases while we write the solution.

6.1. How Do We Reverse a String?

The shortest answer is new StringBuilder(text).reverse().toString(). When the interviewer asks for a solution without a builder, we swap characters in a char[] from both ends.

static String reverse(String text) {
  if (text == null) {
    return null;
  }
  char[] chars = text.toCharArray();
  for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
    char tmp = chars[i];
    chars[i] = chars[j];
    chars[j] = tmp;
  }
  return new String(chars);
}

Both ways give the same result for normal text.

String byBuilder = new StringBuilder("howtodoinjava").reverse().toString();   // "avajniodotwoh"
String byLoop = reverse("howtodoinjava");                                     // "avajniodotwoh"

A recursive version is a common follow-up question, and it is covered in reversing a string with recursion.

6.2. How Do We Check a Palindrome?

A palindrome reads the same in both directions, such as “level”. Instead of building a reversed copy, we compare characters from both ends and stop at the first difference, so the method needs no extra memory.

static boolean isPalindrome(String text) {
  String s = text.toLowerCase();
  for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
    if (s.charAt(i) != s.charAt(j)) {
      return false;
    }
  }
  return true;
}

The method ignores case, so “Madam” counts as a palindrome.

boolean level = isPalindrome("level");      // true
boolean madam = isPalindrome("Madam");      // true
boolean java = isPalindrome("java");        // false

Variants that ignore spaces and punctuation are in checking a palindrome string.

6.3. How Do We Check if Two Strings Are Anagrams?

Two strings are anagrams when they contain the same characters the same number of times, such as “listen” and “silent”. We sort the characters of both strings and compare the arrays.

static boolean isAnagram(String first, String second) {
  char[] a = first.toLowerCase().toCharArray();
  char[] b = second.toLowerCase().toCharArray();
  Arrays.sort(a);
  Arrays.sort(b);
  return Arrays.equals(a, b);
}

Sorting costs O(n log n). An int[26] counter array works in O(n) for the letters a to z, which is a typical follow-up question.

boolean anagram = isAnagram("Listen", "Silent");   // true
boolean notAnagram = isAnagram("java", "jav");     // false

6.4. How Do We Count Each Character in a String?

We put each character into a map with its count. A TreeMap keeps the keys sorted, so the output is stable, and merge() adds 1 to the existing count or starts it at 1.

Map<Character, Integer> counts = new TreeMap<>();
for (char ch : "banana".toCharArray()) {
  counts.merge(ch, 1, Integer::sum);
}
String result = counts.toString();             // "{a=3, b=1, n=2}"

A Stream version with Collectors.groupingBy() and the related task of finding repeated characters are in finding duplicate characters.

6.5. How Do We Find the First Non-Repeated Character?

We count the characters in a LinkedHashMap, which keeps the insertion order, and return the first character with a count of 1. The method returns an Optional, because a string such as “aabb” has no such character.

static Optional<Character> firstUnique(String text) {
  Map<Character, Long> counts = text.chars()
      .mapToObj(c -> (char) c)
      .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
  return counts.entrySet().stream()
      .filter(e -> e.getValue() == 1)
      .map(Map.Entry::getKey)
      .findFirst();
}

For “swiss”, the letters s repeat, so the first unique letter is w.

Optional<Character> unique = firstUnique("swiss");   // Optional[w]
Optional<Character> none = firstUnique("aabb");       // Optional.empty

6.6. How Do We Print All Permutations of a String?

A permutation is one ordering of all the characters, and a string of length N has N! permutations. The recursive solution fixes each character in turn as the first one and permutes the rest.

static void permute(String prefix, String rest, List<String> result) {
  if (rest.isEmpty()) {
    result.add(prefix);
    return;
  }
  for (int i = 0; i < rest.length(); i++) {
    permute(prefix + rest.charAt(i), rest.substring(0, i) + rest.substring(i + 1), result);
  }
}

For “abc”, the method finds 3! = 6 permutations in order. With repeated characters, such as in “aab”, we collect into a Set to remove the duplicates.

List<String> perms = new ArrayList<>();
permute("", "abc", perms);
String all = perms.toString();                 // "[abc, acb, bac, bca, cab, cba]"

6.7. How Do We Reverse Each Word in a Sentence?

We split the sentence on spaces, reverse each word with a StringBuilder, and join the words again. The word order stays the same.

String sentence = "how to do in java";
String reversedWords = Arrays.stream(sentence.split(" "))
    .map(word -> new StringBuilder(word).reverse().toString())
    .collect(Collectors.joining(" "));          // "woh ot od ni avaj"

More exercises of this kind are in the interview puzzles and coding exercises collection.

7. Passwords and Encoding

Two questions about security and bytes round off the list, and both have answers that changed with newer Java versions.

7.1. Why Is char[] Preferred Over String for Passwords?

We can overwrite a char[] after use, but we cannot change a String. A password in a String stays in memory until the garbage collector removes it, and that can take a long time, so a heap dump or a memory-reading attack can find it. This is why Console.readPassword() and JPasswordField.getPassword() return a char[].

Many older answers clear the array with a for-each loop, which does not work, because the loop variable is a copy of each element. We clear the array with Arrays.fill().

char[] pin = {'1', '2', '3', '4'};
for (char ch : pin) {
  ch = '0';
}
String stillThere = new String(pin);                                    // "1234" (the loop changed only copies)
Arrays.fill(pin, '\0');
long remaining = new String(pin).chars().filter(ch -> ch != 0).count(); // 0

Clearing the array limits how long the password stays in memory, but it is not encryption. We still store passwords only as a salted hash, as shown in password hashing in Java.

7.2. How Do We Convert a String to Bytes?

We call getBytes() with an explicit charset. Since Java 18, the default charset is UTF-8 on every operating system (JEP 400), but passing StandardCharsets.UTF_8 keeps the code clear and safe on older versions.

String word = "caf\u00e9";
int chars = word.length();                                        // 4
int utf8Bytes = word.getBytes(StandardCharsets.UTF_8).length;     // 5 (the accented e needs 2 bytes)
int latin1Bytes = word.getBytes(StandardCharsets.ISO_8859_1).length;   // 4
String back = new String(word.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);   // "caf\u00e9"

The number of characters and the number of bytes differ for any text outside ASCII. A length check on bytes, such as a database column limit, must therefore count the encoded bytes, not length().

8. String Interview Preparation FAQs

Candidates who prepare for a String round often ask the same few questions about the interview itself.

8.1. Which String Questions Are Asked Most Often?

The top five are == vs equals(), why String is immutable, the string pool and intern(), String vs StringBuilder vs StringBuffer, and one coding task such as reversing a string or checking a palindrome. The intro snippet of this page covers the first four in a few lines.

8.2. Do the Answers Differ Between Java 8 and Java 25?

Yes, in a few places, and interviewers for current projects notice old answers.

TopicJava 8 answerJava 25 answer
Internal storagechar[]byte[] plus a coder flag (compact strings, Java 9)
+ in one expressioncompiled to StringBuilderinvokedynamic with StringConcatFactory (Java 9)
Default charset of getBytes()platform-dependentUTF-8 (Java 18)
Newer String methodstrim(), isEmpty()strip(), isBlank(), lines(), repeat() (Java 11)
Multiline textconcatenated literalstext blocks (Java 15)
switch on a Stringstatement onlyswitch expressions with arrow labels (Java 14)

8.3. Is a Text Block Also a String?

Yes. A text block, written between triple quotes since Java 15, is only another way to write a string literal. The result is a normal String that goes into the pool like any other literal, as shown in multiline strings in Java.

8.4. Where Can I Practice More Java Interview Questions?

The core Java interview questions cover the language as a whole, and the Java String guide explains every method of the class with examples.

9. Conclusion

Most String interview questions come back to two facts. A String never changes, and == compares references while equals() compares characters. The pool, intern(), the HashMap key question and the thread-safety question all follow from them.

For the comparison questions, we know when to pick StringBuilder, why replaceAll() and split() treat the dot as a regex, and how isBlank() differs from isEmpty(). For the coding round, short methods that handle case, null and empty input make a better impression than clever one-liners.

Answers based on Java 8 still circulate, so we mention compact strings, the UTF-8 default and text blocks where they fit.

10. References

Happy Learning !!

Source Code on Github

Leave a Comment

  1. “`
    char[] passwordChars = new char[4]; //Get password from some system such as database

    //use password

    for(char c : passwordChars) {
    c = ‘ ‘;
    }
    “`
    You have copy of the original char in variable `c`, thus this code does not change `passwordChars `.

  2. How many objects will be created and where those will be stored in below scenario:

    String s1 = “ABC”;
    String s2 = “XYZ”;
    s1.concat(s2);
    system.out.println(s1 + s2);

  3. String str = new String(“how_to_do_in_java”);

    As you mentioned above the above line will create two object one in heap and other in String Constant Pool(Perm are of heap).

    str.intern() method will check if SCP(String Constant Pool)) has this char if not then it will return that else it will create a object with this char.

    My question is why will there be a possibilty that this character wont exist in SCP because when we create with new literal definetly it will be created in SCP

    • It is in general that a String is checked for availability in String Constant Pool (SCP).
      When we create String str = new String(“how_to_do_in_java”), definitely a reference is created in SCP. But, reference of the object in heap memory is returned. Intern method is implemented in such a way that it would check for a reference in SCP. In our case when we create a String object using new operator, we are sure that it will create one reference in SCP.

  4. Really appreciate for this blog!!

    Sir please rectify as I have a small doubt.

     
    
    String s1=new String("abc"); //1st line
    String s2="abc";                           //2nd line
    Sytem.out.println(s1==s2); // false
    
    

    As per my understanding, 1st line will create two objects(1 heap+1 pool) and 2nd line will not create any object as “abc” is already present in string pool. So s2 must be assigned to s1 and should show the result true. But it is showing false.

    What is happening in this case?? (I am using JDK 1.8)….Plz explain

    • As per my understanding. S1 is the variable that would be pointing to the object in heap while s2 is pointing to the object in String pool. And when we do s1 == s2, we are comparing the memory address rather than the actual content. hence in this case the memory location doesn’t matches and it returns false.

    • Here s1 is pointing to the object in heap where as s2 is pointing to object in String pool.
      If you do s2==s1.intern() then you will get true as the output as intern() method will return the reference from String pool.

    • Because, s1 is pointing to address in Heap and not string pool . I tried the below. Now it shows true.

      String s1=new String(“abc”); //1st line
      s1=s1.intern(); //2nd line
      String s2=”abc”; //3nd line
      System.out.println(s1==s2); // true

  5. hi,
    As of java 8 or 1.7.x mentioned above, the issue has been resolved as i tested the above code and realised that the substring now created a string with the modified char array and not the entire original character array. Excellent blog though !! I always refer before going for a interview!

  6. suppose I have a string s=”The god is great”. how we will print like “great is god the” ? we will not hardcode the value of s. so we will provide the value at runtime. Please tell me lokesh how I will do this?

    • Let me know if something is not clear.

      import java.util.Arrays;
      import java.util.Collections;
      import java.util.List;
      
      public class Main 
      {
      	public static void main(String[] args) 
      	{
      		String initial = &quot;The god is great&quot;;
      
      		String[] arr = initial.split(&quot; &quot;);
      
      		List&lt;String&gt; list = Arrays.asList(arr);
      
      		Collections.reverse(list);
      
      		arr = (String[]) list.toArray();
      
      		System.out.println(joinArr(arr));
      	}
      
      	private static String joinArr(String[] array) 
      	{
      		StringBuilder sb = new StringBuilder();
      		for (String word : array) {
      			sb.append(&quot; &quot;);
      			sb.append(word);
      		}
      		String result = sb.toString();
      		return result.replaceFirst(&quot; &quot;, &quot;&quot;);
      	}
      }
      
      Output:
      
      great is god The
      
  7. how many objects will get created

    String str1=new String(“nitesh”);
    String str2=new String(“nitesh”);
    String str3=”nitesh”;
    String str4=str3;
    String str5=str2;

    • String str1=new String(“nitesh”); //Two objects (1 in heap + 1 in pool)
      String str2=new String(“nitesh”); //One object (In heap only)
      String str3=”nitesh”; //No new object
      String str4=str3; //No new object
      String str5=str2; //No new object

      Total 3 objects.

  8. String s1 = “abcd5”;
    String s2 = “abcd”+”5″;
    String s3 = “adcd”+s1.length();
    System.out.println(s1 == s2);//true
    System.out.println(s2 == s3);//false
    System.out.println(s2 == s3);//false

    in this code why output is true,false,false and how many objects actually create in heap and string pool?

    • String s1 = “abcd5”;
      String s2 = “abcd”+”5″;

      If you look into .class file for the above two lines then you will find them identical meaning compiler changes second line to make it look like first line so ultimately at runtime in the string pool there will be only one string “abcd5”. – This justifies that s1 == s2 should return true.

      String s3 = “abcd”+s1.length();

      In for this line “abcd” will be inserted into string pool but s1.length() is just a integer concatenation which is not similar to the string “abcd5”. – I might be wrong here…

      • First two strings are compile time constants hence they will go to Pool. While last one will be created on heap as s1.length is not compile time constant so compile will leave this to JVM who eventually put this on heap.

  9. String s1 = “abc”;
    String s2 = new String(s1);
    System.out.println(s1 == s2);
    String s3 = s2.intern();
    System.out.println(s1 == s3);

    in this code how many objects actually create ?

    and my ans is 2 .one in pool coz of literal & 2nd one in heap bt not in intern pool due to the same literal already present in pool sir is this correct or not

  10. Hi Lokesh,

    I need some help in understanding the concept “Using new keyword creating two objects in memory. One object in string pool having char sequence “abc” and second in heap memory referred by variable str and having same char sequence as “abc”.
    Is there a way to test this scenario? Because in some other blogs i had read like when we use new operator,JVM will be creating object in heap memory but if we need same string object to String constant pool we need to user intern() method, is that true?

  11. Hi Sir,

    Can you Explain in detail,how String constant pool works.Eg-String s1=new String(“abc”); ,String s2=new String(“abc”); how this two string is handled in String pool.

  12. What is happening in stringbuffer means how it allows to append values on the same memory location which is not possible in string as it is immutable

    • String buffer internally maintains a char array. All appended content is added into this array only. when you call toString() method, a string is returned with content of this array.

  13. After concatanation strings, StringBuilder return the value using toString() method. This method is written as:

    public String toString() {
      // Create a copy, don't share the array
      return new String(value, 0, count);
    }
    

    So it return a new String object which end up creating two objects in memory. One in heap as spring object and another in as string literal in string pool.

  14. This string leak is annoying. If you are parsing xml with the default xerces parser, all attributes and values will be substrings! If you store just one attribute value of each xml-stream you have parsed, your heap is floated with those original strings….
    So the fix for java.lang.String in java 7u6 is simple but great!

  15. FYI, the memory leak thing is not true anymore. I use Java 1.7.0u13, and running your code outputs:
    [i, _, l, o, v, e, _, j, a, v, a]
    [j, a, v, a]

    I had a look at the String.java file, and indeed the field ‘offset’ is gone.

  16. It’s wrong you just create a memory leak by doing String(original.substring(beginIndex)); as you create a new array.
    and a performence issue too (arrays copy are not free).

    In some case it’s usefull to do this if you don’t use the oiginal string anymore. BUT just in some special case. in your case for 100 substring your create 100 arrays instead of one.

    And string is also immutable for the same reason. if you have
    String s1 = “toto”;
    String s2 = s1.substring(0,2);
    s2.changeCharAt(0,’m’)

    you will have s1 equals to “moto”

    …

    • Benjamin, thanks for analyzing the substring method and providing more insight. Yes, you are right that array copy is not free and so holding multiple arrays.
      My analysis was originally for the case when you read some large text file (say an XML file over 1 MB) in a string and use tostring() method to extract only some tokens out of it. In this case or similar cases, you end up having 3-4 strings, which should be ideally 100-200 characters but actually in memory you store a very large array for no good use. Thus memory leak.

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.