Core Java - Interview Questions and Answers for 'String' | Search Interview Question - javasearch.buggybread.com
Javasearch.buggybread.com

Search Interview Questions


 More than 3000 questions in repository.
 There are more than 900 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Core Java - Interview Questions and Answers for 'String' - 83 question(s) found - Order By Newest

next 30
Very frequently asked. Among first few questions in almost all interviews. Among Top 5 frequently asked questions. Frequently asked in Indian service companies (HCL,TCS,Infosys,Capgemini etc based on multiple feedback ) and Epam Systems
  Q1. Difference between == and .equals() ?Core Java
Ans. "equals" is the method of object class which is supposed to be overridden to check object equality, whereas "==" operator evaluate to see if the object handlers on the left and right are pointing to the same object in memory.

x.equals(y) means the references x and y are holding objects that are equal. x==y means that the references x and y have same object.

Sample code:

String x = new String("str");
String y = new String("str");

System.out.println(x == y); // prints false
System.out.println(x.equals(y)); // prints true

  Sample Code for equals

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string comparison   string   object class   ==    equals   object equality  operator   == vs equals   equals vs ==     Asked in 294 Companies      basic        frequent

Try 6 Question(s) Test


Advanced level question. Frequently asked in High end product companies. Frequently asked in Google , Cognizant and Deloitte ( Based on 2 feedback )
  Q2. Why is String immutable in Java ?Core Java
Ans. 1. String Pool - When a string is created and if it exists in the pool, the reference of the existing string will be returned instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

Example -

String str1 = "String1";
String str2 = "String1"; // It doesn't create a new String and rather reuses the string literal from pool

// Now both str1 and str2 pointing to same string object in pool, changing str1 will change it for str2 too

2. To Cache its Hashcode - If string is not immutable, One can change its hashcode and hence it's not fit to be cached.

3. Security - String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   oops   string   string class   immutable  immutability   advanced     Asked in 39 Companies      expert        frequent

Try 4 Question(s) Test


Very frequently asked in different variations. Frequently asked in Deloitte ( 2 feedback ) , HCL Tech ( 3 feedback ), TCS and Coginizant (CTS)
  Q3. Explain the scenerios to choose between String , StringBuilder and StringBuffer ?

or

What is the difference between String , StringBuilder and StringBuffer ?
Core Java
Ans. If the Object value will not change, use String Class because a String object is immutable.

If the Object value can change and will only be modified from a single thread, use StringBuilder because StringBuilder is unsynchronized(means faster).

If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

  Sample Code for String

  Sample Code for StringBuffer

  Sample Code for StringBuilder

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string   stringbuilder   stringbuffer   String vs StringBuffer   String vs StringBuilder   String vs StringBuilder vs StringBuffer   StringBuffer vs stringBuilder     Asked in 29 Companies      basic        frequent

Try 3 Question(s) Test


Asked multiple times in Capgemini.
 Q4. Why Char array is preferred over String for storing password?Core Java
Ans. String is immutable in java and stored in String pool. Once it's created it stays in the pool until unless garbage collected, so even though we are done with password it's available in memory for longer duration and there is no way to avoid it. It's a security risk because anyone having access to memory dump can find the password as clear text.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string   immutable  immutability   string pool   garbage collection   advanced     Asked in 6 Companies      Expert


 Q5. What are different ways to create String Object? Explain.Core Java
Ans. There are total six ways

1. literals

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.

2. new keyword

When we use new operator, JVM creates the String object but dont 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.

3. string buffer
4. string builder
5. System.out.println
6. char to string




 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string   jvm   memory management   string pool     Asked in 5 Companies      basic        frequent

Try 3 Question(s) Test


Frequently asked in Infosys India
  Q6. What is a String Pool ?Core Java
Ans. String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   oops   string   string class   string pool   heap memory     Asked in 31 Companies      intermediate        frequent

Try 2 Question(s) Test


 Q7. How does making string as immutable helps with securing information ? How does String Pool pose a security threat ?Core Java
Ans. String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment or hacker over internet.

Once a String constant is created in Java , it stays in string constant pool until garbage collected and hence stays there much longer than what's needed. Any unauthorized access to string Pool pose a threat of exposing these values.


 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     Security  String pool   string immutable  immutability      expert        rare


 Q8. How is string object immutable if we can concat a string to it ?Core Java
Ans. Because it doesn't make the change in the existing string but would create a new string by concatenating the new string to previous string. So Original string won't get changed but a new string will be created. That is why when we say

str1.concat("Hello");

It means nothing because we haven't specified the reference to the new string and we have no way to access the new concatenated string. Accessing str1 with the above code will still give the original string.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     string  string immutable  immutability  string concat


 Q9. What will this code print ?

String a = new String ("TEST");
String b = new String ("TEST");
if(a == b) {
System.out.println ("TRUE");
} else {
System.out.println ("FALSE");
}
Core Java
Ans. FALSE. == operator compares object references, a and b are references to two different objects, hence the FALSE. .equals method is used to compare string object content.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     string   string class   java   ==   object references   coding     Asked in 2 Companies      basic        frequent

Try 1 Question(s) Test


Not frequently asked as it was introduced with Java 8.
 Q10. What is StringJoiner ?Core Java
Ans. StringJoiner is a util method to construct a string with desired delimiter. This has been introduced with wef from Java 8.

Sample Code

StringJoiner strJoiner = new StringJoiner(".");
strJoiner.add("Buggy").add("Bread");
System.out.println(strJoiner); // prints Buggy.Bread


 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   java8   java 8   string   stringjoiner


 Q11. Which String class does not override the equals() and hashCode() methods, inheriting them directly from class Object?Core Java
Ans. java.lang.StringBuffer.

  Sample Code for StringBuffer

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   object class   stringbuffer      expert        rare


Very frequently asked. Usually asked in different variants like Diff between StringBuffer , String Builder ; Difference between StringBuilder and String class; Choice between these classes etc.
  Q12. What is the difference between StringBuffer and String class ?Core Java
Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string   stringbuffer   frequently asked     Asked in 18 Companies      basic        frequent

Try 1 Question(s) Test


Very Frequently asked. Usually asked along with String Class related questions.
  Q13. What is an immutable class ?Core Java
Ans. Class using which only immutable (objects that cannot be changed after initialization) objects can be created.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   oops   immutable  immutability   immutable  immutability class   string class   basic interview question     Asked in 18 Companies      Basic        frequent

Try 2 Question(s) Test


Very frequently asked. Usually difference between String,StringBuffer and StringBuilder is asked in different variations.
  Q14. Difference between StringBuffer and StringBuilder ?Core Java
Ans. StringBuffer is synchronized whereas StringBuilder is not.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string   stringbuffer   string class   stringbuilder   synchronized   basic interview question   infosys technologies     Asked in 17 Companies      basic        frequent

Try 1 Question(s) Test


 Q15. Trim a string without using String library methodCore Java
 This question was recently asked at 'Ariba'.This question is still unanswered. Can you please provide an answer.


 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     code  coding.string  trim a string     Asked in 1 Companies


 Q16.  What is the role of JSON.stringify ?Json
Ans.  JSON.stringify() turns an object into a JSON text and stores that JSON text in a string. 

So If we stringfy above notation , it will become

{"name":"xyz","gender":"male";"age":30}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     json   JSON.stringify      intermediate        rare


  Q17. Write a method to check if input String is Palindrome?Core Java
Ans. private static boolean isPalindrome(String str) {

if (str == null)
return false;

StringBuilder strBuilder = new StringBuilder(str);

strBuilder.reverse();

return strBuilder.toString().equals(str);

}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string   stringbuilder   stringbuilder   string class   code   palindrome     Asked in 38 Companies      Basic        frequent


 Q18. Write a method that will remove given character from the String?Core Java
Ans.
private static String removeChar(String str, char c) {    
if (str == null)
return null;

return str.replaceAll(Character.toString(c), "");
}


 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string   string class   code   write code


 Q19. Why String is popular HashMap key in Java?Core Java
Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesnt need to be calculated again. This makes it a great candidate for key in a Map and its processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string   immutable  immutability   hashmap   immutable  immutability   hashcode   hash code   advanced     Asked in 2 Companies      expert        frequent


 Q20. What does String intern() method do?Core Java
Ans. intern() method keeps the string in an internal cache that is usually not garbage collected.

Moreover provide reference for scp object for corresponding string object present in heap memory.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string   intern method   garbage collection   advanced     Asked in 2 Companies      expert


 Q21. How substring() method of String class create memory leaks?Core Java
Ans. substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. Hence you can inadvertently keep a reference to a very big character array with just a one character string.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string   substring   memory leaks   jvm   memory management   advanced   architecture   technical architect   technical lead      expert


Very frequently asked in HCL Tech ( Based of 4 inputs )
  Q22. Write a program to reverse a string iteratively and recursively ?Core Java
Ans. Using String method -

new StringBuffer(str).reverse().toString();

Iterative -

public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}

Recursive -

public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string   reverse   stringbuffer   string class   code     Asked in 6 Companies        frequent


  Q23. Write a Program to check if 2 strings are Anagrams ?Core Java
Ans. public void checkIfAnagram(String str1,String str2){
boolean anagram = true;
for(char c:str1.toCharArray()){
if(!str2.contains(String.valueOf(c))){
System.out.println("Strings are Anagrams");
anagram = false;
}

if(anagram == true){
System.out.println("Strings are not Anagrams");
}
}
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve      check if 2 strings are Anagrams     Asked in 30 Companies      basic        frequent


 Q24. What will be the output of following Code ?

class BuggyBread {
   public static void main(String[] args) {
      String s2 = "I am unique!";
      String s5 = "I am unique!";

      System.out.println(s2 == s5);
   }
}
Core Java
Ans. true, due to String Pool, both will point to a same String object.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   code   coding   tricky questions   interesting questions   string   string pool   .equal   ==      intermediate        frequent


 Q25. Is String final in Java ?Core Java
Ans. Strings are immutable in Java and not final.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     is string final  final  string  immutable  immutability  immutability


 Q26. Find different combination of given String and trace the output

Core Java
Ans. private void permutation(String prefix, String sufix)
{
int ln = sufix.length();
if(ln == 0) {
System.out.println(prefix);
} else {
IntStream.range(0, ln).forEach(i->permutation(prefix sufix.charAt(i), sufix.substring(0,i) sufix.substring(i 1, ln)));
}
}

call:permutation("", "abcdef");

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     String  code  coding     Asked in 1 Companies


 Q27. Write a program to print the index of the first non repeated character in a java stringCore Java
Ans. public class BuggyBread1{
public static void main (String args[]) {
   String str = "hheello world";
   char[] charArray = str.toCharArray();
   char selectedChar = 'a';
   for(char char1: charArray){
      if(!str.contains(Character.toString(char1).concat(Character.toString(char1)))){
         selectedChar = char1;
         break;
      }
   }
   System.out.println(str.indexOf(Character.toString(selectedChar)));
}
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     string  code  coding     Asked in 9 Companies


 Q28. Which String class methods are used to make string upper case or lower case?Core Java
Ans. toUpperCase and toLowerCase

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string


 Q29. How to convert String to byte array and vice versa?Core Java
Ans. We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string


 Q30. public class a {
   public static void main(String args[]){
      final String s1=""job"";
      final String s2=""seeker"";
      String s3=s1.concat(s2);
      String s4=""jobseeker"";
      System.out.println(s3==s4); // Output 1
      System.out.println(s3.hashCode()==s4.hashCode()); Output 2
   }
}

What will be the Output 1 and Output 2 ?
Core Java
Ans. S3 and S4 are pointing to different memory location and hence Output 1 will be false.

Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string   hashcode   hash code   string comparison   string pool

Try 1 Question(s) Test


next 30

Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: