Tutorial

Java String Interview Questions and Answers

Updated on November 23, 2022
authorauthor

Pankaj and Andrea Anderson

Java String Interview Questions and Answers

Introduction

String is one of the most widely used Java classes. This article provides some practice questions and answers about String to help you prepare for an interview.

You can also try the Java String Quiz to test your knowledge of the String class.

What is the String class in Java? Is String a data type?

String is a class in Java and is defined in the java.lang package. It’s not a primitive data type like int and long. The String class represents character strings. String is used in almost all Java applications. String in immutable and final in Java and the JVM uses a string pool to store all the String objects. You can instantiate a String object using double quotes and you can overload the + operator for concatenation.

What are some different ways to create a String object in Java?

You can create a String object using the new operator or you can use double quotes to create a String object. For example:

String str = new String("abc");
String str1 = "abc";

There are several constructors available in the String class to get a String from char array, byte array, StringBuffer, and StringBuilder.

When you create a String using double quotes, the JVM looks in the String pool to find if any other String is stored with the same value. If the String is already stored in the pool, the JVM returns the reference to that String object. If the new String is not in the pool, the JVM creates a new String object with the given value and stores it in the string pool. When you use the new operator, the JVM creates the String object but doesn’t store it in the string pool. You can use the intern() method to store the String object in String pool or return the reference if there is already a String with equal value present in the pool.

Write a Java method to check if an input string is a palindrome.

A string is a palindrome if its value is the same when reversed. For example, aba is a palindrome string. The String class doesn’t provide any method to reverse the string but the StringBuffer and StringBuilder classes have a reverse() method that you can use to check whether a string is a palindrome. For example:

private static boolean isPalindrome(String str) {
    if (str == null)
        return false;
    StringBuilder strBuilder = new StringBuilder(str);
    strBuilder.reverse();
    return strBuilder.toString().equals(str);
}

Sometimes, an interviewer might request that you don’t use any other class to check for a palindrome. In that case, you can compare characters in the string from both ends to find out if it’s a palindrome. For example:

private static boolean isPalindromeString(String str) {
    if (str == null)
        return false;
    int length = str.length();
    System.out.println(length / 2);
    for (int i = 0; i < length / 2; i++) {
         if (str.charAt(i) != str.charAt(length - i - 1))
            return false;
    }
    return true;
}

Write a Java method that will remove a given character from a string object.

We can use the replaceAll method to replace all of the occurrences of a string with another string. The important point to note is that replaceAll() accepts String as argument, so you can use the Character class to create a string and use it to replace all the characters with an empty string.

private static String removeChar(String str, char c) {
    if (str == null)
        return null;
    return str.replaceAll(Character.toString(c), "");
}

How can you make a String upper case or lower case in Java?

You can use the String class toUpperCase and toLowerCase methods to get the String object in all upper case or lower case. These methods have a variant that accepts a Locale argument and use the rules of the given locale to convert the string to upper or lower case.

What is the String subSequence method?

Java 1.4 introduced the CharSequence interface and the String class implements this interface, which is why the String class has the subSequence method. Internally, the subSequence method invokes the String substring method.

How do you compare two strings in a Java program?

Java String implements the Comparable interface, which has two variants of the compareTo() method. The compareTo(String anotherString) method compares the String object with the String argument passed lexicographically. If the String object precedes the argument passed, it returns a negative integer, and if the String object follows the argument passed, it returns a positive integer. It returns zero when both the String objects have the same value. In this case, the equals(String str) method also returns true. The compareToIgnoreCase(String str) method is similar to the first one, except that it ignores the case. It uses Comparator with CASE_INSENSITIVE_ORDER for case insensitive comparison. If the value is zero, then equalsIgnoreCase(String str) will also return true.

How do you convert a String to a character array in Java?

A String object is a sequence of characters, so you can’t convert it to a single character. You can use use the charAt method to get the character at given index or you can use the toCharArray() method to convert a string to character array. Learn more about converting a string to a character array.

How do you convert a String to a byte array in Java?

You can use the getBytes() method to convert a String object to a byte array and you can use the constructor new String(byte[] arr) to convert a byte array to String object. Learn more about converting a string to a byte array.

Can you use String in switch case in Java?

Java 7 extended the capability of switch case to Strings; earlier Java versions don’t support this. If you’re implementing conditional flow for strings, you can use if-else conditions and you can use switch case if you are using Java 7 or higher versions. Learn more about Java switch case string.

Write a Java program to print all permutations of a string.

You’ll need to use recursion to find all the permutations of a string. For example, the permutations of AAB are AAB, ABA and BAA. You also need to use Set to make sure there are no duplicate values. Learn more about finding all the permutations of a string.

Write a Java function to find the longest palindrome in a given string.

A string can contain palindrome substrings within it. Learn more about how to find the longest palindrome substring in a string.

What are the differences between String, StringBuffer, and StringBuilder in Java?

A String object is immutable and final in Java, so whenever you manipulate a String object, it creates a new String object. String manipulations are resource consuming, so Java provides two utility classes for string manipulations, StringBuffer and StringBuilder.

StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized, while StringBuilder operations are not thread-safe. You should use StringBuffer in a multi-threaded environment and use StringBuilderin a single-threaded environment. StringBuilder performance is faster than StringBuffer because of no overhead of synchronization.

Learn more about the differences between String, StringBuffer and StringBuilder and benchmarking of StringBuffer and StringBuilder.

Why is String immutable in Java?

String is immutable in Java because this offers several benefits:

  • String pool is possible because String is immutable in Java.
  • It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as a database username or password.
  • Since String is immutable, it’s safe to use in multi-threading and you don’t need any synchronization.
  • Strings are used in Java class loaders and immutability provides assurance that the correct class is getting loaded by the ClassLoader class.

Learn more about why String is immutable in Java.

How do you split a string in Java?

You can use split(String regex) to split the String into a String array based on the provided regular expression.

Why is a character array preferred over String for storing passwords in Java?

A String object is immutable in Java and is stored in the string pool. Once it’s created it stays in the pool until garbage collection completes, so even though you’re done with the password it’s available in memory for longer duration. It’s a security risk because anyone having access to memory dump can find the password as clear text. If you use a character array to store password, you can set it to blank once you’re done with it. You can control for how long it’s available in memory and that avoids the security threat.

How do you check if two Strings are equal in Java?

There are two ways to check if two Strings are equal. You can use the == operator or the equals() method. When you use the == operator, it checks for the value of String as well as the object reference. Often in Java programming you want to check only for the equality of the String value. In this case, you should use the equals() method to check if two Strings are equal. There is another function called equalsIgnoreCase that you can use to ignore case.

String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");

System.out.println("s1 == s2 ? " + (s1 == s2)); //true
System.out.println("s1 == s3 ? " + (s1 == s3)); //false
System.out.println("s1 equals s3 ? " + (s1.equals(s3))); //true

What is the string pool in Java?

The string pool is a pool of String objects stored in Java heap memory. String is a special class in Java and you can create a String object using the new operator as well as by providing values in double quotes. Learn more about the Java string pool.

What does the Java String intern() method do?

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. This method always returns a String object that has the same contents as this String but is guaranteed to be from a pool of unique strings.

Is String thread-safe in Java?

A String object is immutable, so you can’t change its value after creation. This makes the String object thread-safe and so it can be safely used in a multi-threaded environment. Learn more about thread Safety in Java.

Since a String object is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for the key in a Map since its processing is faster than other HashMap key objects.

Guess the Output

Test yourself by guessing the output of the following Java code snippets.

public class StringTest {
    
  	public static void main(String[] args) {
   		String s1 = new String("digitalocean");
   		String s2 = new String("DIGITALOCEAN");
   		System.out.println(s1 = s2);
   	}
    
}
Output
DIGITALOCEAN

The output is DIGITALOCEAN because the code assigns the value of String s2 to String s1. = is an assignment operator that assigns the value of y to x in the format (x = y). == is a comparison operator that would check if the reference object is the same for the two strings.


public class Test {
    
   	 public void foo(String s) {
   	 System.out.println("String");
   	 }
    
   	 public void foo(StringBuffer sb) {
   	 System.out.println("StringBuffer");
   	 }
    
   	 public static void main(String[] args) {
   		new Test().foo(null);
   	}
    
}
Output
Test.java:12: error: reference to foo is ambiguous
   		new Test().foo(null);
   		           ^
  both method foo(String) in Test and method foo(StringBuffer) in Test match

This code results in a compile time error because both foo methods have the same name and the call for the foo method in main is passing null. The compiler doesn’t know which method to call. You can also refer to the method X is ambiguous for the type Y error.


String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2);
Output
false

The output is false because the code uses the new operator to create the String object, so it’s created in the heap memory and s1 and s2 will have a different reference. If you create the strings using only double quotes, then they will be in the string pool and it will print true.


String s1 = "abc";
StringBuffer s2 = new StringBuffer(s1);
System.out.println(s1.equals(s2));
Output
false

The output is false because s2 is not of type String. The equals() method implementation in the String class has an instanceof operator to check if the type of passed object is String and return false if the object is not String.


String s1 = "abc";
String s2 = new String("abc");
s2.intern();
System.out.println(s1 == s2);
Output
false

The output is false. The intern() method returns the String object reference from the string pool. However, the code doesn’t assign it back to s2 and there is no change in s2 and sos1 and s2 have a different object reference. If you change the code in line 3 to s2 = s2.intern();, then the output will be true.

How many String objects are created by the following code?

String s1 = new String("Hello");  
String s2 = new String("Hello");
Answer

The answer is three. The code in line 1 creates a String object with the value Hello in the string pool (first object) and then creates a new String object with the value Hello in the heap memory (second object). The code in line 2 creates a new String object with value Hello in the heap memory (third object) and reuses the Hello string from the string pool.

Conclusion

In this article you reviewed some Java interview questions specifically about String.

Recommended Reading:

Java Programming Questions String Programs in Java

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 1, 2013

Can you please explain the statement "Strings are immutable, so we can’t change it’s value in program. " by a sample program

- Ayan

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 3, 2013

String str = "abc"; str = "xyz"; // here the value of Object str is not changed, a new String literal "xyz" is created and str is now holding reference to this new String. I would suggest you to go through this post to know the properties of a immutable class and how you can write your own immutable class. Immutable Classes in Java

- Pankaj

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 13, 2013

String s1=new String(“Hello”) above code How many objects will create?

- siddu

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 15, 2013

There will be two objects created one is in heap and one is in constant pool. Ques… how and Why … How Everything that is inserted within the " " (double quote) is a string and JVM forces to allocate the memory in the Constantpool… ok fine. And we also know the new Keyword that is used to allocate the memory in the Heap. And as the SCJP standard in case of string making the object with new keyword is certainly memory lose. example: String s=new String(“Deepak”);//line 1 String s1=“Deepak”; the reference Id of “Deepak” object will be assigned to s1.because It is already in the pool.//see line1 Question Arise: What kind of Memory is used by the ConstantPool…Heap or other…

- Deepak Chauhan

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 14, 2014

String s=new String(“Deepak”); when u have create a String object by using new keword than every time create new object in heap; but by using literal String than check in the memory but here there are two object is created one is heap , and second in pool; public class java { public static void main(String arr[]) { String s=new String(“Deepak”); String s1=“Deepak”; String s2=new String(“Deepak”); System.out.println(s==s2); System.out.println(s==s1); } } output is false false that is solution

- Paramjeet Singh

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 19, 2021

    Hi, Thank you for providing the insight on this topic! My question here is what will happen to String “abc” stored in pool memory, meaning how long will exist and when & how the same will be removed from memory? Similarly what happens to object stored outside of constant pool memory?

    - Arun

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 16, 2013

      Hi Pankaj, There is always something new to learn in your posts. But I would like to correct one thing in above post. When we create a String using new keyword, a whole new reference is being assigned, not from a literal. Up to this its right. But this instance is not added into the String Pool until we call intern(). We can check it out by below example: String s1 = new String("abc"); // new object - not from pool. String s2 = "abc"; // tries to search it from pool. System.out.println(s1 == s2); // returns false that means s1 has not been added to pool.

      - Ravi

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 7, 2013

      Thanks Ravi, yes you are right. Corrected the post.

      - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 10, 2013

      Pankaj, I think you were right before. when we create string with String s1 = new String(“abc”) then two objects are created. One is created on heap and second on constant pool(created only if it is not there in the pool). Since we are using new operator to create string so s1 always refers to the object created on the heap. When we create string with String s2 = “abc” then s2 will refer to object created in the constant pool. No object will be created on the heap. Since s1 and s2 are referring to different objects s1 == s2 will return false. If we want s1 to refer object created on the pool then use s1.intern().

      - Amit Malik

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 10, 2013

      Thats what is mentioned here…

      - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 1, 2016

      please explain why intern() is needed if the object will be created in both constant pool and heap when we use new operator.

      - deepak

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 1, 2016

        Hi I’ve a query!! please correct me if I’m wrong. String s = new String(“Hello”); When above code is executed two objects will be created. One in heap another in SCP(String Constant Pool) So what is the need to use intern() explicitly.? Or when do we use intern() exactly?? by above discussion i got that object will not be added to SCP but its created.!! then where it is created.?

        - deepak

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 14, 2019

        I have the exactly same question

        - Rhicha

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 3, 2013

          Nice Material… Keep it up to make us knowledgeable…

          - Prosenjit

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            June 1, 2013

            Thanks for finally talking about > Java String Interview Questions and Answers | JournalDev < Loved it!

            - aicotutorial.com

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 24, 2013

              Hi pankaj , your stuff regarding strings in java is really great . it is really helpful in prospective of interviews and gaining some knowledge over java strings … Loved it …Keep up good work buddy!!!

              - nandan

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 7, 2013

              Thanks Nandan for kind words. It’s these appreciations that helps me keep going.

              - Pankaj

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 27, 2013

                really this material is gud. definitely it will help a lot 2 give a good concept in string…

                - Trilochan

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 7, 2013

                Thanks for liking it.

                - Pankaj

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 15, 2013

                  sir pls clearly explain the java in string concept

                  - tamil

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 15, 2013

                  I have already wrote a lot about String class in java, String is like other classes in java with some additional features because of it’s heavy usage. Read these posts for better understanding: https://www.journaldev.com/802/why-string-is-immutable-or-final-in-java https://www.journaldev.com/797/what-is-java-string-pool

                  - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 6, 2013

                    after readind all your questions i realfeel like am getting real basic and clear from all my doubts. pls increase your collections. i read String and COllection and it helped m e

                    - nilesh shinde

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 7, 2013

                    Thanks Nilesh, it really feels good that my articles are helping and cleared your doubts.

                    - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    February 3, 2014

                    its really good and useful…try to post some typical and tricky programs on strings which will be helpful for interviews and thanks…

                    - dinesh

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 5, 2013

                      All your tutorials are great. Helping me in my job jump. Thanks a lot.

                      - devs

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        December 9, 2013

                        Hi pankaj, Thanks a lot for providing examples and good explanations.if you have stuff about GWT framework(Google Web Toolkit) please post that frame work concepts too.it will be really help to for those who new to this framework

                        - senthil hari

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          February 18, 2014

                          Please also put some light on the implementation of substring? How substring method can cause memory leaks? How can we avoid these memory leaks in java?

                          - Ashi

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            March 29, 2014

                            excellent post !!! could you discuss programming questions related to strings such as reverse a stringand other string operations… which algorithm will be best and its time complexity… thanks

                            - kiki

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              April 8, 2014

                              Hi Pankaj, I liked you post because the coding question you put in it. We can get the theory knowledge from any web site, but questions like coding based we can’t get from other site. Keep up good job and keep concentrate on coding related question. I really like one ans. i.e Write a method that will remove given character from the String? I know this method, but you used in a different manner. Expecting more like this from you. I will be in touch with you after this. I met this site first time.

                              - ADITYA VALLURU

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              April 8, 2014

                              Thanks Aditya, please look into other posts too. I am sure you find a lot of good stuffs. :)

                              - Pankaj

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                April 18, 2014

                                Very helpful, just wanted to say that I appreciate the clarity with which the answers are presented.

                                - Gary

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  May 22, 2014

                                  Hi , in answer of ‘What are different ways to create String Object?’ you have said when we use new operator with string .it will create one object…but in scjp 6 book author is saying there will be 2 objects , one in string pool and second is in heap. see this link also ‘https://www.coderanch.com/t/245707/java-programmer-SCJP/certification/String-object-created’ (https://www.coderanch.com/t/245707/java-programmer-SCJP/certification/String-object-created’) … please elaborate this string concept

                                  - saurabh moghe

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    May 28, 2014

                                    String is not final by default since you have mentioned “String immutable and final in java”?

                                    - Harikrishna

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    May 28, 2014

                                    String is a final class and immutable too.

                                    - Pankaj

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    September 24, 2014

                                    not satisfied…see the code class StringFinal{ public static void main(String args[]){ //String s1 = new String(“hi”); String s1 = “hello”; s1 = “hi”; System.out.println(s1); } } it will print hi,not hello

                                    - Rajesh

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    September 25, 2014

                                    You need to understand that s1 is reference only to object. First it’s referring to “hello” and then “hi”, hence the output. I would suggest you to read about immutability.

                                    - Pankaj

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      November 14, 2014

                                      lol…pankaj is saying String class is declared final in JDK source code dumbo… final class String {} in JDK

                                      - Anshul

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        January 5, 2017

                                        whatever Pankaj said that is True. String s1 = “hello”; --> new object created System.out.println(s1.toUpperCase()); -->In String class we have methods like toUpper() and toLower() you are trying to make Uppercase to s1. this will result “HELLO” but this will not store in s1. System.out.println(s1) -->results hello only s1 = s1.toUpperCase System.out.println(s1) ---->results HELLO s1 = “hi”; —> here you are not changing object. you are changing object reference.

                                        - Hareesh

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          September 11, 2014

                                          public void testFinally(){ System.out.println(setOne().toString()); } protected String setOne(){ String s1=new String(); try{ s1.concat(“Cool”); return s1=s1.concat(“Return”); }finally{ s1=null; /* ;) */ } } When s1 string concatenates with cool it has content as “cool”. In next statement it points it to same reference s1.so the output should be “returncool”.Why its “return”.

                                          - Ruchi Gupta

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          September 12, 2014

                                          The point to remember is that String is immutable, so in s1.concat(“Cool”); line, a new String is created but since you didn’t assigned it, it’s lost. s1 value is still “”. s1=s1.concat(“Return”);: here you are assigning after concat, so s1 is “return” now, hence the output.

                                          - Pankaj

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            September 19, 2014

                                            String is Immutable ,whenever we are adding anything using concat method it points new ref after concatination if string not modified then it point same ref ,1st time u r not assigned any variable so it will create other obj and second time your storing in again s1 so it returns return only,but this process not applicable for Adding string using "+ " operator.

                                            - rose

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              September 20, 2014

                                              Hi Pankaj, I have one doubt. I want to know if we execute the below statements then how many objects and references will be created on each line 1, 2 and 3. 1.) String s1 = “abc”; 2.) String s2 = “abc”; 3.) String s3= new String(“abc”); Thanks, Ishan

                                              - Ishan Aggarwal

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              September 20, 2014

                                              1. “abc” in String Pool and s1 reference in the stack memory. 2. s2 reference created in stack memory, referring to the same string object “abc” in the pool. 3. s3 reference created and new String object with value “abc” in the heap memory. So total 2 string objects and 3 references.

                                              - Pankaj

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              September 25, 2014

                                              Hi Pankaj Thanks for these wonderful questions I have a doubt that if we can create objects through String literals than why do we use creating string objects through new keyword as it is not memory efficient way. Is it possible to completely remove the feature of creating String objects through new keyword…Please Explain

                                              - vallabhi

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              September 25, 2014

                                              Since String is an Object and we can use new operator to instantiate it. It’s not possible to remove this option.

                                              - Pankaj

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                September 29, 2014

                                                Strings created in pool are not garbage collected. Please correct me Pankaj if i am wrong.

                                                - Ruchi Gupta

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  December 17, 2014

                                                  If the references were defined as instance variables, they are created in the heap memory.

                                                  - Anoop

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    October 16, 2014

                                                    Only two objects will be created … one objects for String s1 = “abc” and another for new String(“abc”)

                                                    - aditya

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      December 21, 2014

                                                      Hello Ishan, String x = “abc”; // It creates 1 String object and 1 reference variable. //“abc” will go to pool memory and x will refer to it. String y = new String(“xyz”); //It creates 2 objects and one reference variable. //In this case, because we used the new keyword, java will create a new String object in the normal (non-pool) memory, one object in the pool memory(for storing “xyz”), and y will refer to it. 1.) String s1 = “abc”; -> 1 object and 1 refercene 2.) String s2 = “abc”; -> 0 object and 1 reference 3.) String s3= new String(“abc”); -> 2 objects and 1 reference. So the correct answer to your question would be 3 objects and 3 reference. Regards Dhruba

                                                      - Dhruba Jyoti Talukdar

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        September 22, 2014

                                                        can you expalin about thread in real time?

                                                        - sudhakar

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          October 1, 2014

                                                          Hi, I need a solution for this Consider String str1 = “hari”; String str2 = “malar”; now find the same characters in both the string and delete the repeated characters So, the output must be str1 = hi str2 = mla

                                                          - Sanjana

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            October 2, 2014

                                                            Hi pankaj, I have a question in string permutation? for example: Input: sarita key :ri the out put should be :sarita, sarIta, saRita, saRIta

                                                            - Sarita

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              December 26, 2014

                                                              hi I have one small doubt which data type is used to check whether the given string student is present or absent

                                                              - arun

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                January 16, 2015

                                                                hi… How to print program source code as output in java language…?

                                                                - amar

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  January 16, 2015

                                                                  How to Print source code as output in java??

                                                                  - amar

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    March 18, 2015

                                                                    I need program: write a java program to give the spaces b/w words Ex: i/o : ramisagoodboy o/p : ram is a good boy

                                                                    - ram

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    September 9, 2015

                                                                    use trim() method when need spaces

                                                                    - siddharth

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    September 9, 2015

                                                                    sorry use append(" "); method

                                                                    - siddharth

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      January 5, 2017

                                                                      search in GOOGLE with below words: how to trim a string in java

                                                                      - Hareesh

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        March 24, 2015

                                                                        Hi Pankaj, Very useful work… keep it up…

                                                                        - Lukman

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          May 31, 2015

                                                                          I have two Strings str1=“ABC”,str2=“BC” ,then output will come op1=A, op2=null, and next string are change str1=“B” str2= “BANGALORE”, then op1=“ANGALORE” op2=null, how can write write the program please could you explian ?

                                                                          - srikanth

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          May 31, 2015

                                                                          What is the logic for this, what are you trying to achieve here? If you have logic, create an algorithm for that and then writing code is the easy part.

                                                                          - Pankaj

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            July 12, 2015

                                                                            Dear sir, I have one basic question. Why java supports both features of string string creation. String str=“abc”; String strObj=new String(“abc”); str=“abc” is better than new String(). So why Java supports new String();

                                                                            - maitrey

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            September 23, 2015

                                                                            I am also having the same question. Recently interviewer asked this to me that what is the significance of string object creation with new keyword. If you have any thoughts then please add it

                                                                            - Chetan

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            November 21, 2015

                                                                            In case of instance of string in constant string pool while in second case two instance will be created one will be stored constant string pool while other in heap (as commonly object reference are stored in case of using new keyword). so String str=“abc” is memeory efficient compared to String strObj=new String(“abc”);

                                                                            - ashish

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              February 17, 2016

                                                                              Only designer of Java can give you more specific and correct answer we can only make few assumption on that (1) if someone want to create new string each and ever time so they can use new keyword.etc

                                                                              - Ashutosh

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              February 17, 2016

                                                                              one more point is on why to create string using new keyword, you can use different constructors to create a string. For example: creating string by char array creating string for specific encoding etc.

                                                                              - Ashutosh

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                July 29, 2015

                                                                                Amazing work Pankaj… keep up the good work…I have been a regular visitor of your site and posts.

                                                                                - irfan

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  August 11, 2015

                                                                                  Very helpful… thanks pankaj:)

                                                                                  - Senthil Narayanan

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  October 4, 2015

                                                                                  deep approach in string…its really helpful

                                                                                  - shank’s

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    November 7, 2015

                                                                                    Hey Pankaj… Where is comparison operator in Question 1 for which U R saying that don’t confuse with that?

                                                                                    - ARVIND AGGARWAL

                                                                                      JournalDev
                                                                                      DigitalOcean Employee
                                                                                      DigitalOcean Employee badge
                                                                                      December 26, 2014

                                                                                      hi I have one small doubt which data type is used to check whether the given string student is present or absent

                                                                                      - arun

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        January 16, 2015

                                                                                        hi… How to print program source code as output in java language…?

                                                                                        - amar

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          January 16, 2015

                                                                                          How to Print source code as output in java??

                                                                                          - amar

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            March 18, 2015

                                                                                            I need program: write a java program to give the spaces b/w words Ex: i/o : ramisagoodboy o/p : ram is a good boy

                                                                                            - ram

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            September 9, 2015

                                                                                            use trim() method when need spaces

                                                                                            - siddharth

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              January 5, 2017

                                                                                              search in GOOGLE with below words: how to trim a string in java

                                                                                              - Hareesh

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                March 24, 2015

                                                                                                Hi Pankaj, Very useful work… keep it up…

                                                                                                - Lukman

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  May 31, 2015

                                                                                                  I have two Strings str1=“ABC”,str2=“BC” ,then output will come op1=A, op2=null, and next string are change str1=“B” str2= “BANGALORE”, then op1=“ANGALORE” op2=null, how can write write the program please could you explian ?

                                                                                                  - srikanth

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  May 31, 2015

                                                                                                  What is the logic for this, what are you trying to achieve here? If you have logic, create an algorithm for that and then writing code is the easy part.

                                                                                                  - Pankaj

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    July 12, 2015

                                                                                                    Dear sir, I have one basic question. Why java supports both features of string string creation. String str=“abc”; String strObj=new String(“abc”); str=“abc” is better than new String(). So why Java supports new String();

                                                                                                    - maitrey

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    September 23, 2015

                                                                                                    I am also having the same question. Recently interviewer asked this to me that what is the significance of string object creation with new keyword. If you have any thoughts then please add it

                                                                                                    - Chetan

                                                                                                      JournalDev
                                                                                                      DigitalOcean Employee
                                                                                                      DigitalOcean Employee badge
                                                                                                      February 17, 2016

                                                                                                      Only designer of Java can give you more specific and correct answer we can only make few assumption on that (1) if someone want to create new string each and ever time so they can use new keyword.etc

                                                                                                      - Ashutosh

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        July 29, 2015

                                                                                                        Amazing work Pankaj… keep up the good work…I have been a regular visitor of your site and posts.

                                                                                                        - irfan

                                                                                                          JournalDev
                                                                                                          DigitalOcean Employee
                                                                                                          DigitalOcean Employee badge
                                                                                                          August 11, 2015

                                                                                                          Very helpful… thanks pankaj:)

                                                                                                          - Senthil Narayanan

                                                                                                          JournalDev
                                                                                                          DigitalOcean Employee
                                                                                                          DigitalOcean Employee badge
                                                                                                          October 4, 2015

                                                                                                          deep approach in string…its really helpful

                                                                                                          - shank’s

                                                                                                            JournalDev
                                                                                                            DigitalOcean Employee
                                                                                                            DigitalOcean Employee badge
                                                                                                            November 7, 2015

                                                                                                            Hey Pankaj… Where is comparison operator in Question 1 for which U R saying that don’t confuse with that?

                                                                                                            - ARVIND AGGARWAL

                                                                                                              JournalDev
                                                                                                              DigitalOcean Employee
                                                                                                              DigitalOcean Employee badge
                                                                                                              November 10, 2015

                                                                                                              Pankaj, you said like char array is more preferable than String to store password but if you go with the security concern String immutability is big advantage to store such sensitive information like Username,password. Looks conflicting to me.

                                                                                                              - Walter Frobin Ekka

                                                                                                              JournalDev
                                                                                                              DigitalOcean Employee
                                                                                                              DigitalOcean Employee badge
                                                                                                              November 12, 2015

                                                                                                              Strings are stored in String Pool as plain text and have longer life, anybody having access to memory dump can find it. In favor of this, getPassword() method of JPasswordField returns a char[] and deprecated getText() method which returns password in clear text stating security reason.

                                                                                                              - Pankaj

                                                                                                                JournalDev
                                                                                                                DigitalOcean Employee
                                                                                                                DigitalOcean Employee badge
                                                                                                                December 12, 2015

                                                                                                                It is tremendously written thanks for such great explanation … Keep writing we will hope for more and more concept

                                                                                                                - Ravi

                                                                                                                JournalDev
                                                                                                                DigitalOcean Employee
                                                                                                                DigitalOcean Employee badge
                                                                                                                December 13, 2015

                                                                                                                Thanks Ravi, we are determined to write best articles. You should also subscribe to our newsletter where we send exclusive tips and free eBooks.

                                                                                                                - Pankaj

                                                                                                                  JournalDev
                                                                                                                  DigitalOcean Employee
                                                                                                                  DigitalOcean Employee badge
                                                                                                                  December 20, 2015

                                                                                                                  Hii pankaj, Your articles are super,first i tq u to ur thinking like to make it all useful info into one place.

                                                                                                                  - mani_v

                                                                                                                    JournalDev
                                                                                                                    DigitalOcean Employee
                                                                                                                    DigitalOcean Employee badge
                                                                                                                    February 7, 2016

                                                                                                                    String str2 = new String(“abc”); String str1 = “abc”; System.out.println("value = " + str1.equals(str2)); The above program returns value true, can you explain why?

                                                                                                                    - Sundara Baskaran

                                                                                                                    JournalDev
                                                                                                                    DigitalOcean Employee
                                                                                                                    DigitalOcean Employee badge
                                                                                                                    February 8, 2016

                                                                                                                    Equals() method always compares contents of the strings.

                                                                                                                    - dilli

                                                                                                                      JournalDev
                                                                                                                      DigitalOcean Employee
                                                                                                                      DigitalOcean Employee badge
                                                                                                                      March 17, 2016

                                                                                                                      because equals method in String class is overridden.

                                                                                                                      - Amit

                                                                                                                        JournalDev
                                                                                                                        DigitalOcean Employee
                                                                                                                        DigitalOcean Employee badge
                                                                                                                        February 17, 2016

                                                                                                                        Hi Pankaj, I am very use to go through with your tutorials they are excellent and simple to understand, but while reading above string interview questions I saw that “when you create string using new keyword it would create 2 object one in pool and another one in heap(if the same string was not exist in pool)”. So can you please explain how exactly it works internally , I checked across on internet but unluckily didn’t find any satisfactory answer or logic? I hope you will reply. Thanks- Your’s Reader .

                                                                                                                        - Ashutosh

                                                                                                                        JournalDev
                                                                                                                        DigitalOcean Employee
                                                                                                                        DigitalOcean Employee badge
                                                                                                                        February 19, 2016

                                                                                                                        When new keyword is used, it will just create in the heap and not in String pool. You will have to use intern() method to move it to Pool.

                                                                                                                        - Pankaj

                                                                                                                          JournalDev
                                                                                                                          DigitalOcean Employee
                                                                                                                          DigitalOcean Employee badge
                                                                                                                          March 5, 2016

                                                                                                                          How many String objects got created in below code snippet? 1. String s1 = new String(“Hello”); 2. String s2 = new String(“Hello”); Answer is 3. First – line 1, “Hello” object in the string pool. Second – line 1, new String with value “Hello” in the heap memory. Third – line 2, new String with value “Hello” in the heap memory. Here “Hello” string from string pool is reused. Here, how the “Hello” will be created in String Pool since we have not used either double quote String s1 = “Hello” or s1 = s1.intern() method, then how it will be created in Pool as you explained. If I am not wrong, you might have missed any one of the above way of creation. Please explain me…

                                                                                                                          - Vijay

                                                                                                                          JournalDev
                                                                                                                          DigitalOcean Employee
                                                                                                                          DigitalOcean Employee badge
                                                                                                                          June 9, 2016

                                                                                                                          whenever you write any string in double quotes it automatically creates an object of string in string pool.

                                                                                                                          - Puneet Srivastava

                                                                                                                            JournalDev
                                                                                                                            DigitalOcean Employee
                                                                                                                            DigitalOcean Employee badge
                                                                                                                            March 10, 2016

                                                                                                                            Difference between String, StringBuffer and StringBuilder? Ans : So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder. Hi please correct this answer it makes lots of confusion. it must be like below Ans : So when multiple threads are working on same String, we should use StringBuilder but in single threaded environment we should use StringBuffer.

                                                                                                                            - Ajay Dwivedi

                                                                                                                            JournalDev
                                                                                                                            DigitalOcean Employee
                                                                                                                            DigitalOcean Employee badge
                                                                                                                            March 11, 2016

                                                                                                                            The given answer is correct. StringBuffer is thread safe, not StringBuilder.

                                                                                                                            - Pankaj

                                                                                                                              JournalDev
                                                                                                                              DigitalOcean Employee
                                                                                                                              DigitalOcean Employee badge
                                                                                                                              July 1, 2016

                                                                                                                              How many object will create? String str1 = new String(“abc”); String str2 = new String(“xyz”);

                                                                                                                              - Jigar

                                                                                                                              JournalDev
                                                                                                                              DigitalOcean Employee
                                                                                                                              DigitalOcean Employee badge
                                                                                                                              July 5, 2016

                                                                                                                              4 objects First – line 1, “abc” object in the string pool. Second – line 1, new String with value “abc” in the heap memory. Third – line 2, new String with value “xyz” in the heap memory. Fourth - line 2, “xyz” object in the string pool Here since the value of string is different for both str1 and str2 hence “abc”,“xyz” string from string pool is not reused.

                                                                                                                              - Ankita

                                                                                                                                JournalDev
                                                                                                                                DigitalOcean Employee
                                                                                                                                DigitalOcean Employee badge
                                                                                                                                July 5, 2016

                                                                                                                                Hi Pankaj, In different ways to create string you have said: "When we use new operator, JVM creates the String object but DON’T store it into the String Pool. " And in string programming question: String s1 = new String(“Hello”); String s2 = new String(“Hello”); Athough string s1 is creating using new operator, you are saying Hello will be saved in String pool. Isn’t both statements are contradictory. Kindly let me know if I am missing something here. Thanks, Gaurav

                                                                                                                                - GAURAV PANT

                                                                                                                                JournalDev
                                                                                                                                DigitalOcean Employee
                                                                                                                                DigitalOcean Employee badge
                                                                                                                                July 5, 2016

                                                                                                                                “Hello” in the String constructor argument will be created first in the Pool, since it’s a string literal. Then s1 will be created in the heap.

                                                                                                                                - Pankaj

                                                                                                                                  JournalDev
                                                                                                                                  DigitalOcean Employee
                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                  February 18, 2017

                                                                                                                                  total 3 objects created new keyword creates objects in heap area------------------2 objects in string constant pool same content so it create ---------- 1 object -------------------------------------------------------------------------------- total 3 objects created

                                                                                                                                  - arun

                                                                                                                                    JournalDev
                                                                                                                                    DigitalOcean Employee
                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                    August 10, 2016

                                                                                                                                    Stringbuffer sb=new Stringbuffer(“ab”); Stringbuffer sb1=new Stringbuffer(“ab”); syso(sb==sb1); O/P ?

                                                                                                                                    - Srinivas

                                                                                                                                    JournalDev
                                                                                                                                    DigitalOcean Employee
                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                    August 14, 2016

                                                                                                                                    False

                                                                                                                                    - Ujjwal

                                                                                                                                      JournalDev
                                                                                                                                      DigitalOcean Employee
                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                      November 8, 2016

                                                                                                                                      false

                                                                                                                                      - siva ranjan

                                                                                                                                        JournalDev
                                                                                                                                        DigitalOcean Employee
                                                                                                                                        DigitalOcean Employee badge
                                                                                                                                        January 1, 2017

                                                                                                                                        false because == operator works on reference comparison . It means if one object is referred by two reference variable then it will return true . but here there are two objects are created in heap memory so it returns false.

                                                                                                                                        - anshu

                                                                                                                                          JournalDev
                                                                                                                                          DigitalOcean Employee
                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                          August 11, 2016

                                                                                                                                          Could you please add some details about hashcode() and equals operator in String class

                                                                                                                                          - Abhi

                                                                                                                                            JournalDev
                                                                                                                                            DigitalOcean Employee
                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                            September 29, 2016

                                                                                                                                            My program is::: package interviews; public class InternMethod { public static void main(String[] args) { String str1=“java”; String str2=str1.intern(); String str3=new String(str1.intern()); System.out.println(“hash1=”+str1.hashCode()); System.out.println(“hash2=”+str2.hashCode()); System.out.println(“hash3=”+str3.hashCode()); System.out.println(“str1==str2==>>”+(str1==str2)); System.out.println(“str1==str3==>>”+(str1==str3)); } } ============================================output===> hash1=3254818 hash2=3254818 hash3=3254818 str1==str2==>>true str1==str3==>>false ================================= Can anyone explain how == returns false even though s1 and s3 having same hashcode?

                                                                                                                                            - shailesh

                                                                                                                                              JournalDev
                                                                                                                                              DigitalOcean Employee
                                                                                                                                              DigitalOcean Employee badge
                                                                                                                                              October 17, 2016

                                                                                                                                              Hi, I have one doubts for below code. String str = “test”; str = str+“test2”; str = str+“test3”; str = str + ''test4"; str = str + “test5”; Now many objects will be created and how many objects will be available for garbage collection? Can you please explain this?

                                                                                                                                              - Vimal

                                                                                                                                                JournalDev
                                                                                                                                                DigitalOcean Employee
                                                                                                                                                DigitalOcean Employee badge
                                                                                                                                                November 17, 2016

                                                                                                                                                hi pankaj, can u please explain the following doubt… String have two methods for creating one is literal,another way is new keyword ,if literal is the way which is memory efficient ,then why we also using ‘new’ ,please explain the scenarios where we can use them and main differentiating point to use them.

                                                                                                                                                - Sunitha Kristipati

                                                                                                                                                  JournalDev
                                                                                                                                                  DigitalOcean Employee
                                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                                  November 17, 2016

                                                                                                                                                  Hi Pankaj, can u please look on the following, String s1=new String(“sun”); String s=“sun”; System.out.println(s1.hashCode()); System.out.println(s.hashCode()); System.out.println(s1==s); O/P: -1856818256 -1856818256 false. here 1st i am creating s1 with new keyword .so as you said , its creates object in heap memory and in pool,next i created using literal which will creates object only in pool. As the s1 and s are present in the pool so they are having same hashcode, but when i am comparing them why its giving false.???

                                                                                                                                                  - Sunitha Kristipati

                                                                                                                                                    JournalDev
                                                                                                                                                    DigitalOcean Employee
                                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                                    December 30, 2016

                                                                                                                                                    Hi Pankaji, thanks for the tutorial, is very good. I have doubts about last exercise: How many String objects got created in below code snippet? String s1 = new String(“Hello”); String s2 = new String(“Hello”); You say that the object created will be 3. I would answered 2, as new operator creates new object in the heap memory (not in the string pool) regardless of wheter there is same string stored in the string pool. Why you say 3? Thanks in advice.

                                                                                                                                                    - Szanowne

                                                                                                                                                      JournalDev
                                                                                                                                                      DigitalOcean Employee
                                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                                      February 18, 2017

                                                                                                                                                      sir i have doubt string objects are created in 4 ways 1. literal method -----------------> String s1=“arun” 2. new operator -----------------> String s2=new String(“arun”); 3. satic factory method---------->String s3=.String.valueOf(“arun”); 4.instance factory method------> String s4=s1.concat(s2); it is correct or not

                                                                                                                                                      - arun

                                                                                                                                                        JournalDev
                                                                                                                                                        DigitalOcean Employee
                                                                                                                                                        DigitalOcean Employee badge
                                                                                                                                                        April 14, 2017

                                                                                                                                                        good

                                                                                                                                                        - Ketki Gawande

                                                                                                                                                          JournalDev
                                                                                                                                                          DigitalOcean Employee
                                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                                          April 17, 2017

                                                                                                                                                          doesn’t your question 3 and 6 have ambiguity?? String s =new (“Hello”); object is created and also stored in string pool as per q6. String s2 =new (“Hello”); object is created and reference of s is passed . when checked with if (s==s2) ,shouldn’t it return true? but your q 3 says it as false. 2 different objects are created in heap. please clarify

                                                                                                                                                          - jayashree

                                                                                                                                                            JournalDev
                                                                                                                                                            DigitalOcean Employee
                                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                                            May 23, 2017

                                                                                                                                                            When we create a string object by using new keyword… 2 objects created one in heap… and another in SCP. Please confirm and reply back thank you.

                                                                                                                                                            - Sidagouda Patil

                                                                                                                                                              JournalDev
                                                                                                                                                              DigitalOcean Employee
                                                                                                                                                              DigitalOcean Employee badge
                                                                                                                                                              June 10, 2017

                                                                                                                                                              Im totally confused. in one article you write "When we use new operator, JVM creates the String object but don’t store it into the String Pool. " in another “String str = new String(“Cat”); In above statement, either 1 or 2 string will be created. If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool. If there is no string literal “Cat” in the pool, then it will be first created in the pool and then in the heap space, so total 2 string objects will be created.” So which one is right ?

                                                                                                                                                              - Sever

                                                                                                                                                                JournalDev
                                                                                                                                                                DigitalOcean Employee
                                                                                                                                                                DigitalOcean Employee badge
                                                                                                                                                                June 30, 2017

                                                                                                                                                                Hi Pankaj, I read all the comments and got more confused. Can you please explain the pointers below. In “What are different ways to create String Object?” you answered: When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool. and then in last 6th question “How many String objects got created in below code snippet?” you answered. String s1 = new String(“Hello”); String s2 = new String(“Hello”); Answer is 3. First - line 1, “Hello” object in the string pool. Second - line 1, new String with value “Hello” in the heap memory. Third - line 2, new String with value “Hello” in the heap memory. Here “Hello” string from string pool is reused. So will it store the object in String pool or not. I hope this will clear things to all

                                                                                                                                                                - Mayank Tyagi

                                                                                                                                                                  JournalDev
                                                                                                                                                                  DigitalOcean Employee
                                                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                                                  July 21, 2017

                                                                                                                                                                  for interview point of view String is a most important topic. thank you to share this knowlge.

                                                                                                                                                                  - Anurag Singh

                                                                                                                                                                    JournalDev
                                                                                                                                                                    DigitalOcean Employee
                                                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                                                    November 29, 2017

                                                                                                                                                                    Awesome collection of question keeps it Up Good work.

                                                                                                                                                                    - bhupendra patidar

                                                                                                                                                                      JournalDev
                                                                                                                                                                      DigitalOcean Employee
                                                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                                                      January 4, 2018

                                                                                                                                                                      String s1=new String(“abc”).intern(); String s2=“abc”; How many objects will be created here ?

                                                                                                                                                                      - gundamaiah

                                                                                                                                                                        JournalDev
                                                                                                                                                                        DigitalOcean Employee
                                                                                                                                                                        DigitalOcean Employee badge
                                                                                                                                                                        February 3, 2018

                                                                                                                                                                        It feels good after go thru these Q&A. Thanks bro.

                                                                                                                                                                        - Packiaraj Thusianthan

                                                                                                                                                                          JournalDev
                                                                                                                                                                          DigitalOcean Employee
                                                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                                                          March 12, 2018

                                                                                                                                                                          How many objects is created in following code? String a1=“hello”; String a2=“hello”; String a3=new String(“hello”);

                                                                                                                                                                          - pintu

                                                                                                                                                                            JournalDev
                                                                                                                                                                            DigitalOcean Employee
                                                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                                                            April 18, 2018

                                                                                                                                                                            Question 6 answer will be 2 instead of 3. We can test it whether new String(“Hello”) creates Hello object in string pool or not. String s = new String(“Hello”); //only creates in Heap Memory not in String Pool System.out.println(s==“Hello”); //prints False

                                                                                                                                                                            - Vedant Kumar

                                                                                                                                                                              JournalDev
                                                                                                                                                                              DigitalOcean Employee
                                                                                                                                                                              DigitalOcean Employee badge
                                                                                                                                                                              July 11, 2018

                                                                                                                                                                              'As the name suggests, String Pool is a pool of Strings stored in Java heap memory. ', is it correct on the following page? https://www.journaldev.com/1321/java-string-interview-questions-and-answers

                                                                                                                                                                              - Fake

                                                                                                                                                                                JournalDev
                                                                                                                                                                                DigitalOcean Employee
                                                                                                                                                                                DigitalOcean Employee badge
                                                                                                                                                                                September 7, 2018

                                                                                                                                                                                public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println(“\nThe longest palindrom of the input is \n” + getLongestPalindrom(scanner.nextLine())); scanner.close(); } private static String getLongestPalindrom(String input) { String longestPalindrom = “”; for(int i= 0;i<input.length()-longestPalindrom.length();i++) { String substring = input.substring(i); boolean isSubStringPalindrom = false; for(int j=0;j longestPalindrom.length())) { longestPalindrom = substring; } } return longestPalindrom; }

                                                                                                                                                                                - Charli

                                                                                                                                                                                  Try DigitalOcean for free

                                                                                                                                                                                  Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                                                                                                                                  Sign up

                                                                                                                                                                                  Join the Tech Talk
                                                                                                                                                                                  Success! Thank you! Please check your email for further details.

                                                                                                                                                                                  Please complete your information!

                                                                                                                                                                                  Become a contributor for community

                                                                                                                                                                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                                                                                                                  DigitalOcean Documentation

                                                                                                                                                                                  Full documentation for every DigitalOcean product.

                                                                                                                                                                                  Resources for startups and SMBs

                                                                                                                                                                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                                                                                                                  Get our newsletter

                                                                                                                                                                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                                                                                                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                                                                                                                  The developer cloud

                                                                                                                                                                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                                                                                                                  Get started for free

                                                                                                                                                                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                                                                                                                  *This promotional offer applies to new accounts only.