Java String Interview Questions with Answers

All of us must have gone though interview questions related to String class in java. These String interview questions range from immutability to memory leak issues. I will try to cover such questions in this post.

Frequently asked String Interview Questions

1. Is String keyword in Java?
2. Why are strings immutable?
3. What is String constant pool?
4. Keyword 'intern' usage
5. Matching Regular expressions?
6. String comparison with equals() and '=='?
7. Memory leak issue in String class
8. How does String work in Java?
9. What are different ways to create String Object?
10. How to check if String is Palindrome.
11. How to remove or replace characters from String.
12. How to make String upper case or lower case?
13. How to compare two Strings in java program?
14. Can we use String in the switch case?
15. Write a program to print all permutations of String?
16. Write a java program to reverse each word of a given string??
17. How to Split String in java?
18. Why is Char array preferred over String for storing password?
19. Is String thread-safe in Java
20. Why String is popular HashMap key in Java
21. Difference between String, StringBuffer and StringBuilder?
22. How to concatenate multiple strings.
23. How many objects will be created with string initialization code?
24. How do you count the number of occurrences of each character in a string?
25. Write a java program to reverse a string?

1. Is String keyword in Java?

NO. String is not a Java reserved keyword. It is a derived type data type i.e. class.

public class StringExample 
{
    public static void main(String[] args) 
    {
        Integer String = 10;
        
        System.out.println(String);		//Prints 10
    }
}

2. Why strings are immutable?

We all know that strings in java are immutable. If you want to know, what immutability is and how it is achieved? follow this post: How to make a java class immutable?

Here the question is WHY? Why immutable? Let’s analyze.

  1. The very first reason i can think of is performance increase. Java language was developed to speed up the application development as it was not that much fast in previous languages. JVM designers must have been smart enough to identify that real-world applications will consist of mostly Strings in form of labels, messages, configuration, output and such numerous ways.

    Seeing such overuse, they imagined how dangerous can be string’s improper use. So they came up with a concept of String pool (next section). String pool is nothing but a collection of some strings mostly unique. The very basic idea behind String pool is to reuse string once created. This way if a particular string is created 20 times in code, application end up having only one instance.

  2. Second reason I see as security considerations. Strings are most used parameter type in each aspect of java programming. Be it loading a driver or open a URL connection, you need to pass the information as parameter in form of string. If strings have not been final then they have opened up a Pandora box of security issues.All of us must have gone though interview questions related to String class in java. These questions range from immutability to memory leak issues. I will try to cover such questions in this post.

Apart from the above two reasons, I didn’t find any convincing answer to this question. If you any something appealing, please share with me.

3. String pool concept

String pool is a special memory area separate from regular heap memory where these string constants are stored. These objects are referred string variables during the life cycle of the application.

In Java, String can be created in many ways. Let’s understand them:

1) String assignment


String str = "abc";

Above code causes JVM to verify if there is already a string “abc” (same char sequence). If such string exists, JVM simply assigns the reference of the existing object to variable str, otherwise, a new object “abc” will be created and its reference will be assigned to variable str.

2) Using new keyword


String str = new String("abc");

This version end up 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”.

As java docs says : Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

4. Keyword ‘intern’ usage

This is best described by java docs:

When the intern() method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

String str = new String("abc");

str.intern();

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. Means if s and t both are different string objects and have same character sequence, then calling intern() on both will result in single string pool literal referred by both variables.

5. Matching Regular expressions

Not so secret but useful feature if you still have not explored it. You must have seen usage of Pattern and Matcher for regular expression matching. String class provides its own shortcut. Use it directly. This method also uses Pattern.matches() inside function definition.


String str = new String("abc");

str.matches("<regex>");

6. String comparison with equals() and ‘==’

Another favorite area in interviews. There are generally two ways to compare objects

  • Using == operator
  • Using equals() method

== operator compare for object references i.e. memory address equality. So if two string objects are referring to same literal in string pool or same string object in heap then s==t will return true, else false.

equals() method is overridden in String class and it verify the char sequences hold by string objects. If they store the same char sequence, the s.equals(t) will return true, else false.

7. Memory leak issue

Till now we have gone through basic stuff. Now something serious. Have you tried creating substrings from a string object? I bet, Yes. Do you know the internals of substring in java? How they create memory leaks?

Substrings in Java are created using method substring(int beginIndex) and some other overloaded forms of this method. All these methods create a new String object and update the offset and count variable which we saw at the start of this article.

The original value[] is unchanged. Thus if you create a string with 10000 chars and create 100 substrings with 5-10 chars in each, all 101 objects will have the same char array of size 10000 chars. It is memory wastage without any doubt.

Let see this using a program:


import java.lang.reflect.Field;
import java.util.Arrays;

public class SubStringTest {
	public static void main(String[] args) throws Exception
	{
		//Our main String
		String mainString = "i_love_java";
		//Substring holds value 'java'
		String subString = mainString.substring(7);

		System.out.println(mainString);
		System.out.println(subString);

		//Lets see what's inside mainString
		Field innerCharArray = String.class.getDeclaredField("value");
		innerCharArray.setAccessible(true);
		char[] chars = (char[]) innerCharArray.get(mainString);
		System.out.println(Arrays.toString(chars));

		//Now peek inside subString
		chars = (char[]) innerCharArray.get(subString);
		System.out.println(Arrays.toString(chars));
	}
}

Output:

i_love_java
java
[i, _, l, o, v, e, _, j, a, v, a]
[i, _, l, o, v, e, _, j, a, v, a]

Clearly, both objects have the same char array stored while subString need only four characters.

Let’s solve this issue using our own code:


import java.lang.reflect.Field;
import java.util.Arrays;

public class SubStringTest
{
	public static void main(String[] args) throws Exception
	{
		//Our main String
		String mainString = "i_love_java";
		//Substring holds value 'java'
		String subString = fancySubstring(7, mainString);

		System.out.println(mainString);
		System.out.println(subString);

		//Lets see what's inside mainString
		Field innerCharArray = String.class.getDeclaredField("value");
		innerCharArray.setAccessible(true);
		char[] chars = (char[]) innerCharArray.get(mainString);
		System.out.println(Arrays.toString(chars));

		//Now peek inside subString
		chars = (char[]) innerCharArray.get(subString);
		System.out.println(Arrays.toString(chars));
	}

	//Our new method prevents memory leakage
	public static String fancySubstring(int beginIndex, String original)
	{
		return new String(original.substring(beginIndex));
	}
}

Output:

i_love_java
java
[i, _, l, o, v, e, _, j, a, v, a]
[j, a, v, a]

Now substring has only characters which it needs, and intermediate string used to create our correct substring can be garbage collected and thus leaving no memory footprint.

8. How String works in Java?

String in Java is like any other programming language, a sequence of characters. This is more like a utility class to work on that char sequence. This char sequence is maintained in the following variable:

/** The value is used for character storage. */
private final char value[];

To access this array in different scenarios, the following variables are used:

/** The offset is the first index of the storage that is used. */
private final int offset;

/** The count is the number of characters in the String. */
private final int count;

10. How to check is String in Palindrome?

A String is said to be Palindrome if it’s value is same when reversed. To check Palindrome, simply reverse the String and check the content of original string and revered String.

public class StringExample 
{
    public static void main(String[] args) 
    {
        String originalString = "abcdcba";
        
        StringBuilder strBuilder = new StringBuilder(originalString);
        String reverseString = strBuilder.reverse().toString();

        
       boolean isPalindrame = originalString.equals(reverseString);
       
       System.out.println(isPalindrame);	//true
    }
}

11. How to remove or replace characters from String?

To replace or remove characters, use String.replace() or String.replaceAll(). These methods take two arguments. First argument is character to be replaced, and second argument is new character which will be placed in string.

If you want to remove characters, then pass blank character in the second argument.

String originalString = "howtodoinjava";

//Replace one character
System.out.println( originalString.replace("h", "H") );         //Howtodoinjava

//Replace all matching characters
System.out.println( originalString.replaceAll("o", "O") );      //hOwtOdOinjava

//Remove one character
System.out.println( originalString.replace("h", "") );         //owtodoinjava

//Remove all matching characters
System.out.println( originalString.replace("o", "") );         //hwtdinjava

12. How to make String upper case or lower case?

Use String.toLowerCase() and String.toUpperCase() methods to convert string to lowercase or upper case.

String blogName = "HowToDoInJava.com";

System.out.println(blogName.toLowerCase());     //howtodoinjava.com

System.out.println(blogName.toUpperCase());     //HOWTODOINJAVA.COM

13. How to compare two Strings in java program?

Always use equals() method to verify string equality. Never use "==" operator. Double equal operator always check the object references in memory. equals() method checks the String content.

String blogName = "HowToDoInJava.com";
        
String anotherString = new String("HowToDoInJava.com");

System.out.println(blogName == anotherString);     //false

System.out.println(blogName.equals(anotherString));     //true

14. Can we use String in switch case?

Yes, you can use String class in switch statements since Java 7. Before Java 7, it was not possible and you had to use if-else statements to achieve similar behavior.

String number = "1";

switch (number) 
{
case "1":
    System.out.println("One");	//Prints '1'
    break;
case "2":
    System.out.println("Two");
    break;
default:
    System.out.println("Other");
}

15. Write a program to print all permutations of String?

A permutation is a re-arrangement of the elements of an ordered list of characters in such a way that each arrangement is unique with respect to other arrangements. e.g. below are the permutations of string “ABC” – ABC ACB BAC BCA CBA CAB.

A string of length N has N! (N Factorial) permutations.

import java.util.HashSet;
import java.util.Set;

public class StringExample 
{
    public static void main(String[] args) 
    {
        System.out.println(getPermutations("ABC"));	

        //Prints
        //[ACB, BCA, ABC, CBA, BAC, CAB]
    }

    public static Set<String> getPermutations(String string) 
    {
        //All permutations
        Set<String> permutationsSet = new HashSet<String>();
        
        // invalid strings
        if (string == null || string.length() == 0) 
        {
            permutationsSet.add("");
        } 
        else 
        {
            //First character in String
            char initial = string.charAt(0); 
            
            //Full string without first character
            String rem = string.substring(1); 
            
            //Recursive call
            Set<String> wordSet = getPermutations(rem);
            
            for (String word : wordSet) {
                for (int i = 0; i <= word.length(); i++) {
                    permutationsSet.add(charInsertAt(word, initial, i));
                }
            }
        }
        return permutationsSet;
    }

    public static String charInsertAt(String str, char c, int position) 
    {
        String begin = str.substring(0, position);
        String end = str.substring(position);
        return begin + c + end;
    }
}

16. Write a java program to reverse each word of a given string?

To reverse each word separately, first, tokenize the string and get all words separate in an array. Then apply reverse word logic to each word, and finally concatenate all words.

String blogName = "how to do in java dot com";

//spilt on white space
String[] tokens = blogName.split(" ");

//It will store reversed words 
StringBuffer finalString = new StringBuffer();

//Loop all words and reverse them
for (String token : tokens) {
    String reversed = new StringBuffer(token).reverse().toString();
    finalString.append(reversed);
    finalString.append(" ");
}

//Check final string
System.out.println(finalString.toString());     //woh ot od ni avaj tod moc

17. How to Split String in java?

Use String.split() method which breaks a given string around matches of the given regular expression. It’s also called get string tokens based on delimiter.

split() method returns the array of string. Each string in array is individual token.

String numbers = "1,2,3,4,5,6,7";
        
String[] numArray = numbers.split(",");

System.out.println(Arrays.toString(numArray));	//[1, 2, 3, 4, 5, 6, 7]

18. Why Char array is preferred over String for storing password?

We know that strings are stored in the constant pool in Java. Once a string is created in the string pool, it stays in the pool until unless garbage collected. By this time, any malicious program can access the memory location in the physical memory location and access the string as well.

If we store the password as a string, then it will also be stored in spring pool and will be available in memory for the longer duration than required, because garbage collection cycles are unpredictable. This makes sensitive password strings vulnerable to hacking and data theft.

Can we make String blank after using it? No, we cannot. We know that once a String is created, we cannot manipulate it e.g. you cannot change its content. Strings are final and immutable.

But char arrays are mutable, their content can be overwritten after use it. So your application shall use char[] to store password text, and after using the password, replace array content with a blank.

String password = "123456";     //Do not use it
        
char[] passwordChars = new char[4];      //Get password from some system such as database

//use password

for(char c : passwordChars) {
    c = ' ';
}

19. Is string thread-safe in Java?

Yes, strings are thread safe. They are immutable and all immutable instances in java are thread-safe, by default.

20. Why String is popular HashMap key in Java?

In Java, A key which has be to used in Map – shall be immutable and should honor the contract between equals() and hashCode() method. String class satisfies both conditions.

Also, String class provides many useful methods to compare, sort, tokenize or lower-upper cases. These methods can be used while performing CRUD operations on Map. It makes it a very useful class to use in Map rather than creating your own class.

21. Difference between String, StringBuffer and StringBuilder?

  • String class represents a sequence of characters and provides useful methods to work with characters. String class instances are immutable. So each time you perform string concatenation using string class, a new object will be created with the concatenated string.
  • StringBuilder class is used to perform string concatenation operations in more memory efficient way. It internally maintains a char array and manipulate the content in this array only.

    When you need to get the complete concatenated string after performing all operations, it creates a new String with character array content.

  • StringBuffer is very much same as StringBuilder class. Only difference is that it is thread-safe. It’s all methods are synchronized.

22. How to concatenate multiple strings?

Use StringBuffer or StringBuilder classes based on you need thread safety or not. Use append() methods in both classes to concatenate strings.

StringBuffer buffer = new StringBuffer();
        
buffer.append("how")
        .append("to")
        .append("do")
        .append("in")
        .append("java")
        .append(".")
        .append("com");

String blogName = buffer.toString();

System.out.println(blogName); //howtodoinjava.com

23. How many objects will be created with string initialization code?

String s1 = "howtodoinjava.com";
String s2 = "howtodoinjava.com";
String s3 = new String("howtodoinjava.com");
  1. Above code will create 2 objects.
  2. First object will be created in string pool by first statement.
  3. Second statement will not create any new object, and s2 will refer to same string constant as s1.
  4. Third statement will create a new string object in heap memory.

24. How do you count the number of occurrences of each character in a string?

To find the number of occurrences of each character in a given string, we have used HashMap with the character as a key and it’s occurrences as a value. With each new occurrence, we will increment the value for that character.

String blogName = "howtodoinjava.com";

HashMap<Character, Integer> occurancesMap = new HashMap<Character, Integer>();

char[] strArray = blogName.toCharArray();

for (char c : strArray)
{
    if(occurancesMap.containsKey(c))
    {
        occurancesMap.put(c, occurancesMap.get(c)+1);
    }
    else
    {
        occurancesMap.put(c, 1);
    }
}

System.out.println(occurancesMap);
//{a=2, c=1, d=1, h=1, i=1, j=1, m=1, n=1, .=1, o=4, t=1, v=1, w=1}

25. Write a java program to reverse a string without StringBuilder or StringBuffer?

Best way to reverse a string is definitely the StringBuffer.reverse() and StringBuilder.reverse() methods. Still, interviewer may ask you to write your own program, to check your skill level.

Use below-given recursion based example to reverse the string. This program takes the first character from the string and places at the last position in the string. It uses this replacement for all characters in the string until whole string is revered.

public class StringExample
{
    public static void main(String[] args) 
    {
        String blogName = "howtodoinjava.com";
        
        String reverseString = recursiveSwap(blogName);
        
        System.out.println(reverseString);
    }
    
    static String recursiveSwap(String str)
    {
         if ((null == str) || (str.length() <= 1))
         {
                return str;
         }
         return recursiveSwap(str.substring(1)) + str.charAt(0);
    }
}

I can think of these frequently asked String interview questions will help you in your next interview. If you know any more questions specifically regarding String class, please share.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

48 thoughts on “Java String Interview Questions with Answers”

  1. Feedback:
    In 25th questions, we should go with iterative approach. Recursion will be overhead here and also we are using substring() function too many times here, which is not memory efficient.

  2. “`
    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 `.

  3. 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);

  4. 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.

  5. 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

  6. 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!

  7. 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
      
  8. 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.

  9. 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.

  10. 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

  11. In the Intern() method description you might wanna add following point:

    All literal strings and string-valued constant expressions are interned.

  12. 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?

  13. 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.

  14. 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.

  15. Excellent stuff sir,but i faced one question in interview,please guide sir.question is

    String st=”abc”; // st will create in string pool since it is a String Literal

    String st1=new String(“XYZ”) + st ; // it will gets created in both pool as well as heap.and concatenation internally uses StringBuilder(from 1.5 onwards.).now where st1 will create sir.please Help.

    • 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.

      • Thanks alot sir.if you have time please write article on How to maintain HttpSession in cluster mode sir.whenever any variable is putting in Session.if the request goes to another machine means that session variable returning null sir.i dont know whether any entry to made in web.xml or some xml file in order to handle by application server.Thanks sir

        • Have the variable in an object and serialize the object. When the request goes to another machine,try porting the serialized object file to the new machine as well. De-serialize your object in the new machine and put the object into session. You can now get the variable from the object in session.
          @ Lokesh: Correct me if I’m wrong anywhere.

          Thanks

  16. Hi Lokesh,

    I also found the same output ..
    [i, _, l, o, v, e, _, j, a, v, a]
    [j, a, v, a]

    could not get memory leakage issue here.

    i tried it in JDK 1.5 , 1.6 and 1.7 as well .

  17. 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!

  18. 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.

  19. 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.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.