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

Search Java Interview Questions


 2098 questions in repository.
 There are more than 200 unanswered questions.
Click here and help us by providing the answer.
Label / Company      Label / Company / Text

   



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

Very Very frequently asked. Among the first few questions in almost all interviews.Among Top 5 frequently asked questions.
  Q1. Difference between == and .equals() ?Core Java
Anonymous
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

 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     Ebay  Cerner  GuideWire  Expeditors Associate  Revature  SAIC  ValueLabs  Realty Redefined  Bank Of America  Capgemini  HCL Technologies  Goldman Sachs  Symmetric Corp  Backstop Solutions  Frontier  IQOR   Science  Vanguard  eClinicalWorks  Experticity  Blue Cross and Blue Shield of Kansas  ComTrade  Banja Luka  Overstock.com  Intrasoft International  IBM  Apex Systems  infoview technologies      basic        frequent

Try 6 Question(s) Test


Advanced level question. Frequently asked in High end product companies. Frequently asked in Cognizant ( Based on 2 feedbacks )
  Q2. Why is String immutable in Java ?Core Java
Anonymous
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   advanced     Barclays  Jungo  Cloudera  Allston  Man Group  Prokarma  Optimus  Gamesys  ABS  TransPerfect  Fidelity  Deloitte  Zalando  Cognizant (CTS)  Zeta Interactive  SuccessFactors   EchoStar  InterGlobe Technologies  HCL Technologies  Intuit  JP Morgan  Optimus Information  Faichi Solutions  Blip  Adobe  Subex Limited  Remo Software  Allstate  IBM  Bizmatics  Bytecode Cyber Security  Calsoft Systems  IDS Infotech      expert        frequent

Try 4 Question(s) Test


Very frequently asked in different variations. Frequently asked in Deloitte ( 2 feedback ) , HCL Tech ( 3 feedback ) 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
Anonymous
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     Cognizant (CTS)   San Jose State University (SJSU)  HCL Technologies   Deloitte  Sophos  Hitachi  JPMorgan Chase  IBM  Kony Labs  Keystone  ebay  TIAA Financial Services  Ancestry      basic        frequent

Try 3 Question(s) Test


 Q4. What are different ways to create String Object? Explain.Core Java
Admin
info@buggybread.com
Ans.
String str = new String("abc");
String str1 = "abc";


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.

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.

 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     GuideWire  NTT Data  Fractal Analytics      basic        frequent

Try 3 Question(s) Test


 Q5. 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
Anonymous
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      basic        frequent

Try 1 Question(s) Test


 Q6. Why Char array is preferred over String for storing password?Core Java
Admin
info@buggybread.com
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   string pool   garbage collection   advanced     General Motors  Amura Marketing Technologies  Bloomberg  Innovive      Expert


  Q7. What is a String Pool ?Core Java
Anonymous
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     SAS Institute  Ariba  GuideWire  Harbinger  Oracle  Virtusa  Knoa  Polaris  GuideWire  HCL Technologies  Tata Consultancy (TCS)  Infosys  Technologent  MphasiS  Harbinger Group  Kony  Evergent  NTT Data  VMware  Markit  Ariba  Tech Mahindra  Bureau Veritas  InfoStretch  PTC Software  Mindtree  Centre for Internet and Society (CIS)  Trimax IT Infrastructure & Services      intermediate        frequent

Try 2 Question(s) Test


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.
  Q8. What is the difference between StringBuffer and String class ?Core Java
Anonymous
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     BlackRock  Synechron  RedMane Technology  Velopsys Technologies   American Express  Sophos  QualiTest  ebay  Infosys Technologies      basic        frequent

Try 1 Question(s) Test


Not frequently asked as it was introduced with Java 8.
 Q9. What is StringJoiner ?Core Java
Admin
info@buggybread.com
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



Do you think these are the Best Java Frameworks ?

OpenXavaSPRING MVCApache StripesCheck everything
that is Best in Java

Click Here



Very frequently asked in HCL Tech ( Based of 4 inputs )
  Q10. Write a Program to reverse a string iteratively and recursivelyCore Java

Ans. Using String method -

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

Iterative -

Strategy - Loop through each character of a String from last to first and append the character to StringBuilder / StringBuffer

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 -

Strategy - Call the method with substring starting from 2nd character recursively till we have just 1 character.

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     string  StringBuffer  recursion  for loop  stringbuffer.append  java.lang.String  java.lang.StringBuffer  String Manipulation     HCL Technologies  Ocado  BlackRock  Oracle  FINRA  Arezzo Sky  Zalando  Boeing        frequent


 Q11. Which String class does not override the equals() and hashCode() methods, inheriting them directly from class Object?Core Java
Anonymous
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


 Q12.  What is the role of JSON.stringify ?Json
Anonymous
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


Very Frequently asked. Usually asked along with String Class related questions.
 Q13. What is an immutable class ?Core Java
Anonymous
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   immutable class   string class   basic interview question   ebay     Cognizant (CTS)  Hybris  YuMe  ebizAutos      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
Anonymous
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     Thomson Reuters  Ludia  QualiTest  United Health Group (UHG)  Sophos  JPMorgan Chase  ebay  Infosys Technologies  Experian India      basic        frequent

Try 1 Question(s) Test


  Q15. Write a method to check if input String is Palindrome?Core Java
Admin
info@buggybread.com
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     HCL Technologies  Hootsuite  ebay  Mobile Apps Company  TripAdvisor  Wallet Hub  Groupon  OpenText  Airbnb  Vantiv  Minted LLC  Boston Analytics  mint.com  Arista Networks  Dealer.com  the Zappos Family  Sony PlayStation  Taser  Wolters Kluwer  Wize Commerce  Hitachi Consulting  Quickr  SmartBrief  Liaison International  Monitise  Exilant Technologies  Enova  Wayfair  Amadeus  MakeMyTrip  Naggaro  Vudu  OnDeck Capital  HighRadius   thePlatform  Trimax IT Infrastructure & Services      Basic        frequent


 Q16. Write a method that will remove given character from the String?Core Java
Admin
info@buggybread.com
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


 Q17. What does String intern() method do?Core Java
Admin
info@buggybread.com
Ans. intern() method keeps the string in an internal cache that is usually not garbage collected.

 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     Polaris  Netflix      expert


 Q18. How substring() method of String class create memory leaks?Core Java
Admin
info@buggybread.com
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 )
 Q19. Write a program to reverse a string iteratively and recursively ?Core Java
Admin
info@buggybread.com
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     HCL Technologies  Exelis  Mahindra Comviva  Fidelity National Information Services (FIS)        frequent



Do you think these are the Best Java Frameworks ?

OpenXavaSPRING MVCApache StripesCheck everything
that is Best in Java

Click Here



 Q20. 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
Admin
info@buggybread.com
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


 Q21. How does making string as immutable helps with securing information ? How does String Pool pose a security threat ?Core Java2017-06-22 11:32:57

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


 Q22. How is string object immutable if we can concat a string to it ?Core Java2017-08-08 09:50:28

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  string concat


 Q23. Write a program to print the index of the first non repeated character in a java stringCore Java2017-01-27 18:30:21

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     Audible  Bluewolf  WorkDay  Symantec  Rubicon  Amazon  Expedia  A9.com  Google


 Q24. Which String class methods are used to make string upper case or lower case?Core Java
Admin
info@buggybread.com
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


 Q25. How to convert String to byte array and vice versa?Core Java
Admin
info@buggybread.com
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


 Q26. Why String is popular HashMap key in Java?Core Java
Admin
info@buggybread.com
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   hashmap   immutable   hashcode   hash code   advanced     TD Bank  HCL Technologies      expert        frequent


 Q27. 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
Admin
info@buggybread.com
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


 Q28. What is the use of HashCode in objects ?Core Java
Admin
info@buggybread.com
Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc.

 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     Verilogue


  Q29. Write a Program to check if 2 strings are Anagrams ?Core Java2016-11-30 20:52:37

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     Amazon  DataMetica  Hewlett Packard (HP)  Opera Solutions  AirWatch  Booking.com  JP Morgan  Verdantis  AppDynamics  QSI Healthcare  Vistaar Technologies  Maventic  5AM Solutions  Rare Mile Technologies  Shutterfly  Fiberlink  Veeva Systems  Flipkart  eHarmony  Splunk  Zoho  Betterment  WisdmLabs  Adap.tv  Spotify  Yahoo  Wissen Infotech  GlobalLogic      basic        frequent



Do you think these are the Best Java Frameworks ?

OpenXavaSPRING MVCApache StripesCheck everything
that is Best in Java

Click Here



 Q30. What will be the output of the following code ?

String s1 = "Buggy Bread";
String s2 = "Buggy Bread";
if(s1 == s2)
   System.out.println("equal 1");
String n1 = new String("Buggy Bread");
String n2 = new String("Buggy Bread");
if(n1 == n2)
   System.out.println("equal 2");
Core Java
Admin
info@buggybread.com
Ans. equal 1

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

   Like      Discuss      Correct / Improve     java   string class   string   string pool   code   coding      basic        frequent


 Q31. what will be the output of this code ?

public static void main(String[] args){
   StringBuffer s1=new StringBuffer("Buggy");                       
   test(s1);                    
   System.out.println(s1);              
}       

private static void test(StringBuffer s){      
   s.append("Bread");   
}
Core Java
Admin
info@buggybread.com
Ans.  BuggyBread

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

   Like      Discuss      Correct / Improve     java   code   coding   stringbuffer   string   method calling   pass by reference


 Q32. what will be the output of this code ?

public static void main(String[] args)    {          
   String s1=new String("Buggy");                         
   test(s1);                    
   System.out.println(s1);              
}       

private static void test(StringBuffer s){      
   s.append("Bread");   
}
Core Java
Admin
info@buggybread.com
Ans.  Buggy

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

   Like      Discuss      Correct / Improve     java   code   coding   stringbuffer   string   method calling   pass by reference


 Q33. what will be the output of this code ?

public static void main(String[] args)    {          
   StringBuffer s1=new StringBuffer("Buggy");                         
   test(s1);                    
   System.out.println(s1);              
}       

private static void test(StringBuffer s){      
   s=new StringBuffer("Bread");   
}
Core Java
Admin
info@buggybread.com
Ans.  Buggy

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

   Like      Discuss      Correct / Improve     java   code   coding   stringbuffer   string   method calling   pass by reference


 Q34. Which methods of the Pattern class have equivalent methods in the String class? Core Java
Admin
info@buggybread.com
Ans. split() and macthes()

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

   Like      Discuss      Correct / Improve     java   io   string class   string   pattern


 Q35. public class BuggyBread1{

public static void main (String args[]) {
Set<String> mySet = new TreeSet<String>();
mySet.add(""1"");
mySet.add(""2"");
mySet.add(""111"");
for(String d: mySet){
System.out.println(d);
}
}
}
Core Java
Admin
info@buggybread.com
Ans. 1
111
2

TreeSet maintains the elements in the ascending order which is identified by the compareTo method. compareTo method in String has been defined such that it results in the natural alphabetic Order. Here the elements in the TreeSet are of String and not of Integer. In String Natural Order, 111 comes before 2 as ascii of 1st character first determines the order.

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

   Like      Discuss      Correct / Improve     java   code   coding   set   treeset   string   integer


 Q36. Give an Example for Builder Pattern ?Core Java
Admin
info@buggybread.com
Ans. String str = new StringBuilder().append("Buggy").append("Bread").toString();

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

   Like      Discuss      Correct / Improve     java   builder pattern   design pattern   stringbuilder   string     Power System Consultants (PSC)  Xactly Corp  BetterCloud

Try 1 Question(s) Test


 Q37. Have you ever used StringTokenizer ?Core Java
Admin
info@buggybread.com
Ans. No, Alternatively I have used String.split("\\s") for achieving the same function.

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

   Like      Discuss      Correct / Improve     java   string   stringtokenizer


 Q38. Name few String related classes and interfaces ?Core Java
Admin
info@buggybread.com
Ans. http://www.buggybread.com/2015/01/java-string-classes-and-interfaces.html

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

   Like      Discuss      Correct / Improve     java   string


 Q39. How many elements will be there in TreeSet after the last line and Why ?

TreeSet set = new TreeSet();
set .add(new String("abc"));
set .add(new String("abc"));
Core Java
Admin
info@buggybread.com
Ans. One.

As we haven't specified the type of TreeSet, it being evaluated with the first element insertion. Once it's identified that it's of type String and as no comparator has been defined, the comparison is done using the String compareTo method. String compareTo method compares the elements by the content / value.

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

   Like      Discuss      Correct / Improve     java   set   treeset   string   compareto   coding   code



Do you think these are the Best Java Frameworks ?

OpenXavaSPRING MVCApache StripesCheck everything
that is Best in Java

Click Here



 Q40. Strings in switch were introduced in Which Java version ?

a. Java 5
b. Java 6
c. Java 7
d. Java
Core Java
Anonymous
Ans. Java 6

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

   Like      Discuss      Correct / Improve     java   switch   string in switch


Rarely asked as it was introduced with Java 8.
 Q41. Which of the following has been introduced with Java 8 ? a. StringBuffer b. StringBuilder c. StringFilter d. StringJoinerCore Java
Anonymous
Ans. StringJoiner

 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


 Q42. Write a method to convert all elements of a set to lower case.Core Java

Ans. http://javasearch.buggybread.com/CodeSnippets/searchCodeSamples.php?keyword=Method+to+convert+all+elements+of+a+collection&category=code

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

   Like      Discuss      Correct / Improve     code  coding  string  String.toLowerCase  set  collections


 Q43. Write java code to Get all words from a String and display themCore Java

Ans. http://javasearch.buggybread.com/CodeSnippets/searchCodeSamples.php?keyword=+Get+all+words+from+a+String&category=code

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

   Like      Discuss      Correct / Improve     string   get all words from strings   string.split


 Q44. How does the String Class stores the string in memory ?Core Java2016-06-14 14:33:03

Ans. It stores the string as a character array with 2 bytes for each character.

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

   Like      Discuss      Correct / Improve     String  String Class


 Q45. Are Strings objects in Java ?Core Java2016-07-31 13:08:46

Ans. Yes, everything except primitive types are objects in Java.

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

   Like      Discuss      Correct / Improve     string


 Q46. Which method of String class is used to convert Boolean to String ?Core Java2016-12-17 11:00:44

Ans. toString() is an overloaded method of String class that is used to convert many data types to String, Boolean being one of them.

toString(Boolean bool)

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

   Like      Discuss      Correct / Improve     String  String class  Boolean     Techurate Systems      Basic


 Q47. Trim a string without using String library methodCore Java2017-01-11 15:44:10

 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     Ariba


 Q48. Which memory segment holds String Pool in Java ?Core Java2017-01-14 20:57:22

Ans. String Pool resides in runtime constant Pool which is a part of Heap memory segment.

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

   Like      Discuss      Correct / Improve     string pool  memory management      Expert        rare


 Q49. How and Why Strings are interned in Java ?Core Java2017-01-25 11:00:00

Ans. String class has a public method intern() that returns a canonical representation for the string object. String class privately maintains a pool of strings, where String literals are automatically interned.

these are automatically interned so as to have efficient String comparison using == operator instead of equals which is usually slower.

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

   Like      Discuss      Correct / Improve     string  string pool  string intern     HCL Technologies



Do you think these are the Best Java Frameworks ?

OpenXavaSPRING MVCApache StripesCheck everything
that is Best in Java

Click Here



 Q50. Write a program to check is a string is substring of another ?Core Java2017-01-27 14:32:44

Ans. public class Class{
   public static void main(String[] args){
      String string1 = "Hello I am Jack. I live in United States. I live in california state.";

      String string2 = "I live in";

      if(string1.indexOf(string2) >= -1){
         System.out.println("string2 is sub string of string1");
      } else {
         System.out.println("string2 is not sub string of string1");
      }
   }
}

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

   Like      Discuss      Correct / Improve     string  coding  code


 Q51. Write a Program to check number of occurrences of one string within another ? Core Java2017-01-27 14:44:07

Ans. public class Class{
   public static void main(String[] args){
      String string1 = "Hello I am Jack. I live in United States. I live in california state.";

      String string2 = "I live in";

      int startIndex = 0;
      int endIndex = string1.length()-1;

      int countNoOfOccurences = 0;

      String remainingString = string1;

      while(startIndex < endIndex){
         if(remainingString.indexOf(string2) != -1){
            countNoOfOccurences++;
            startIndex = remainingString.indexOf(string2) + string2.length();
            remainingString = remainingString.substring(startIndex);
         } else {
            break;
         }
      }

      System.out.println(countNoOfOccurences);
   }
}

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

   Like      Discuss      Correct / Improve     string  code  coding     Google  Zoho


 Q52. Write a Program to check if string is a Colidrome ?
(Colidrome is a word that has n alphabets followed by the reverse of the n alphabets, for ex - mallom)
Core Java2017-01-27 14:53:14

Ans.
public class Class {
   public static void main(String[] args) {
      String str = "mallam";
      String firstHalf = str.substring(0, str.length() / 2);
      String secondHalf = str.substring(str.length() / 2);

      if (firstHalf.equals(new StringBuilder(secondHalf).reverse().toString())) {
         System.out.println("It's a Colidrome");
      } else {
         System.out.println("It's not a Colidrome");
      }
   }
}

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

   Like      Discuss      Correct / Improve     Colidrome  String  Code  Coding     Maventic


 Q53. Write a Program to print count of each character in a String.Core Java2017-01-27 20:32:20

Ans. public class BuggyBread {
public static void main(String args[]) {
Map<Character, Integer> countMap = new HashMap();
String str = "hello world";
for (char character : str.toCharArray()) {
if (countMap.containsKey(character)) {
countMap.put(character, countMap.get(character) + 1);
} else {
countMap.put(character, 1);
}
}
System.out.println(countMap);
}
}

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

   Like      Discuss      Correct / Improve     String  Code  Coding  Character     Compro Technologies


 Q54. Write a Program to only print characters that have occured more than once in a StringCore Java2017-01-27 20:37:26

Ans. public class BuggyBread{
public static void main (String args[]) {
Set<Character> set = new HashSet();
Set<Character> setWithDuplicateChar = new HashSet();
String str = "hello world";
for(char character: str.toCharArray()){
if(set.contains(character)){
setWithDuplicateChar.add(character);
} else {
set.add(character);
}
}

System.out.println(setWithDuplicateChar);
}
}

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

   Like      Discuss      Correct / Improve     String  Code  Coding


 Q55. Write a Program to find common words in 2 separate stringsCore Java2017-01-29 17:29:52

Ans. public class BuggyBread {
   public static void main(String args[]) {
       String str1 = "we are what we repeatedly Do excellence, then, is not an act but a haBit";
       String str2 = "we are what we repeatedly Do is";
       String[] str1Words = str1.split(" ");
       String[] str2Words = str2.split(" ");
      
       Set str1WordsSet = new HashSet();
      
       for(String word:str1Words){
          str1WordsSet.add(word);
       }
      
       for(String word:str2Words){
          if(str1WordsSet.contains(word)){
             System.out.println(word);
          }
       }
      
   }
}

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

   Like      Discuss      Correct / Improve     String  coding  code


 Q56. Write a program to print count / no of common words in 2 separate stringsCore Java2017-01-29 17:31:39

Ans. public class BuggyBread {
   public static void main(String args[]) {
       String str1 = "we are what we repeatedly Do excellence, then, is not an act but a haBit";
       String str2 = "we are what we repeatedly Do is";
       String[] str1Words = str1.split(" ");
       String[] str2Words = str2.split(" ");
      
       Set str1WordsSet = new HashSet();
      
       for(String word:str1Words){
          str1WordsSet.add(word);
       }
      
       int commonWordsCount = 0;
      
       for(String word:str2Words){
          if(str1WordsSet.contains(word)){
             commonWordsCount++;
          }
       }
      
       System.out.println(commonWordsCount);
   }
}

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

   Like      Discuss      Correct / Improve     String  coding  code


 Q57. Write a Program to remove duplicate words from the StringCore Java2017-01-29 17:36:31

Ans.
public class BuggyBread {
public static void main(String args[]) {
String str = "we are what we repeatedly Do excellence, then, is not an act but a haBit";
Set<String> wordSet = new LinkedHashSet(); // Using Linked Hash Set as we would like to retrieve words in the insertion order

for(String word: str.split(" ")){
wordSet.add(word);
}

for(String word: wordSet){
System.out.print(word);
System.out.print(" ");
}
}
}

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

   Like      Discuss      Correct / Improve     String  coding  code     Microsoft      basic


 Q58. Write a Program to display the words of a String in alpahbetical or Dictionary OrderCore Java2017-01-29 17:38:02

Ans. public class BuggyBread {
   public static void main(String args[]) {
       String str = "we are what we repeatedly do excellence then is not an act but a haBit";
       Set<String> wordSet = new TreeSet(); // Using Linked Hash Set as we would like to retrieve words in the insertion order
      
       for(String word: str.split(" ")){
          wordSet.add(word);
       }
      
       for(String word: wordSet){
          System.out.print(word);
          System.out.print(" ");
       }
   }
}

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

   Like      Discuss      Correct / Improve     String  coding  code


 Q59. Write a Program to validate if a particular character occurs after another in a stringCore Java2017-01-30 11:13:29

Ans. public class Class{
   public static void main(String[] args){
      String str = "xyz123.co@m";
      
      if(str.indexOf('.') < str.indexOf('@')){
         System.out.println("Not a Valid Email Address");
      }
   }
}

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

   Like      Discuss      Correct / Improve     string  string.indexOf  coding  code



Do you think these are the Best Java Frameworks ?

OpenXavaSPRING MVCApache StripesCheck everything
that is Best in Java

Click Here



 Q60. Write a method / program that will determine if the parenthesis are balanced in a given string.Core Java2017-02-03 13:13:55

 This question was recently asked at 'Jetbro,Booking.com,Cloudera,UrjaNet,Wissen Infotech,ThoughtWorks,Capital One,Experian,Remaxys,MongoDB,One.com,Lime Brokerage,Netcracker Technology,Ooyala'.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     string  code  coding     Jetbro  Booking.com  Cloudera  UrjaNet  Wissen Infotech  ThoughtWorks  Capital One  Experian  Remaxys  MongoDB  One.com  Lime Brokerage  Netcracker Technology  Ooyala


 Q61. Can StringBuffer and StringBuilder in Java be inherited?Core Java2017-03-15 13:54:44

Ans. No, they have been declared final and hence cannot be extended.

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

   Like      Discuss      Correct / Improve     StringBuffer  StringBuilder


 Q62. What will be the output of following code

Integer x = 1;
Integer y = 2;
System.out.println(x == y);

What if you change 1 to "1" and Integer to String?
Core Java2017-05-07 19:30:13

Ans. It will print "true" with integers as well as strings. The reason is "Integer constant pool" and "String pool"

String pool maintains pool of string literals. When a string literal is used for the first time, a new string object is created and is added to the pool. Upon it's subsequent usage , the reference for the same object is returned. Similarly java uses integer constant pool.

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

   Like      Discuss      Correct / Improve     string pool  object equality  ==


 Q63. What will be result of following code and why

Integer int1 = 1;
Integer int2 = 1;
String str1 = new String("str");
String str2 = new String("str");
String str3 = "str";
String str4 = "str";

      
System.out.println(int1 == int2);
System.out.println(str1 == str2);
System.out.println(str3 == str4);
Core Java2017-05-08 10:15:00

Ans. true
false
true

Just like Strings, java maintains an integer constant pool too. So 1 will be maintained in integer constant pool and hence reference int2 will point to same integer in pool.

String pool is only for string literals ( defined by "" ) and not for newly created objects and hence str1 == str2 will return false as they are separate objects in memory.

String pool is used for storing string literals so that they can be reused and str3 and str4 will point to same string literal in string pool.


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

   Like      Discuss      Correct / Improve     string pool  integer constant pool  string comparison  integer comparison


 Q64. What is the purpose of String Pool ? Don't you think it's a performance overhead to have unnecessary check for string in string pool ?Core Java2017-05-13 09:05:03

Ans. String Pool makes Java more memory efficient by providing a reusable place for string literals. It might be a little performance inconvenience but results in good amount memory saving.

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

   Like      Discuss      Correct / Improve     string pool  memory management      Intermediate


 Q65. Is String a Data type in Java ?Core Java2017-06-18 18:04:10

Ans. String is not a primitive type in java. Anything defined within double quotes like "abc" is an object of String class.

  Sample Code for String

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

   Like      Discuss      Correct / Improve     string  data type      Basic


 Q66. Are char,String and Char data types in java ? Core Java2017-06-18 18:05:30

Ans. char is a primitive data type. String is a class. Char is a wrapper class for primitive char.

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

   Like      Discuss      Correct / Improve     char  string  data type      Basic


 Q67. Why do we pass an array of strings to main method ?Core Java2017-06-23 12:58:05

Ans. Array of strings in the main method are the list of arguments or parameters which are sent to the application / program.

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

   Like      Discuss      Correct / Improve     main method   main method string array argument


 Q68. What is the difference between being final and being immutable ? Are string final or immutable in Java ?Core Java2017-07-22 15:57:55

Ans. Being final in the sense of objects or object reference means that the reference cannot be reassigned to a different object whereas being immutable means that the object contents cannot be changed.

Strings in Java are immutable.

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

   Like      Discuss      Correct / Improve     string  immutable  final vs immutable


 Q69. Is String final in Java ?Core Java2017-07-22 15:58:16

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



Do you think these are the Best Java Frameworks ?

OpenXavaSPRING MVCApache StripesCheck everything
that is Best in Java

Click Here



 Q70. Is a string an array of characters in Java ? Core Java2017-07-23 20:08:29

Ans. No, String is a class whose objects are called strings in Java.

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

   Like      Discuss      Correct / Improve     String


 Q71. Do we have a method to reverse a string in String class ?Core Java2017-07-29 09:52:30

Ans. No but we have it in StringBuilder.

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

   Like      Discuss      Correct / Improve     String  StringBuilder  Reverse a string


 Q72. How can we convert char into a String ?Core Java2017-07-29 09:53:43

Ans. We can use StringBuilder. StringBuilder accepts char as the argument for it's constructor.

new StringBuilder('').toString();

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

   Like      Discuss      Correct / Improve     convert char to String  char  String


 Q73. How can we convert String into Char array and vice versa ?Core Java2017-07-30 15:56:01

Ans. There is a method toCharArray() within String class that can be used to convert string to char array.

string.toCharArray();

String class has an argument constructor that takes a char array and create a string

new String(charArray);

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

   Like      Discuss      Correct / Improve     string  char array


 Q74. How can we convert a character or a character array into a String ?Core Java2017-07-30 15:57:10

Ans. String has an argument constructor that take char array as argument and creates a string.

There is no constructor available with String that takes in a character and creates a String. We can use StringBuilder which has a char argument constructor.

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

   Like      Discuss      Correct / Improve     character  char  char array  String  char to String  char array to String


 Q75. Why shouldn't we use string concatenation extensively or in a loop ?Core Java2017-08-08 09:52:53

Ans. Because String being an immutable object creates a new object upon each concatenation cycle. If there is any such need , we should use String Builder whose object is immutable.

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

   Like      Discuss      Correct / Improve     string  string immutable


 Q76. Suppose we have a string "Java is object oriented language" and we have to reverse every alternate word in string. How would we do that using Java program.Core Java2017-09-06 20:29:59

 This question was recently asked at 'datalake solutions'.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     string manipulation  code  coding     datalake solutions


 Q77. Write a program / method to print first letter of words in a string.2016-12-06 10:15:25

Ans. public void printFirstLetterOfWords(String str){
   String[] splittedStringArray = str.split(" ");
   for(String word:splittedStringArray){
      System.out.println(word.charAt(0));
   }
}

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

   Like      Discuss      Correct / Improve     Code  Coding  String     Lanyon      basic


 Q78. Write a Program to replace characters in a String ( without using String replace method )2017-07-30 15:53:58

Ans. public class ReplaceCharacters{
   public static void main(String[] args){
      String str = "Hello BuggyBread";
      
      char[] charArray = str.toCharArray();
      int countCharacter = str.length();
      for(int count=0;count<countCharacter;count++){
         if(charArray[count] == 'g'){
            charArray[count] = 'd';
         }
      }
      String replacedString = new String(charArray).toString();
      
      System.out.println(replacedString);
   }
}

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

   Like      Discuss      Correct / Improve     string  replace characters in a string


 Q79. Write a Program to right shift single character in a string2017-08-24 20:12:56

Ans. public class RightShiftCharacter {
   public static void main(String args[]) {
      String str = "Hello";
      
      char[] charArray = str.toCharArray();
      
      for(int count=charArray.length-1;count>0;count--){
         charArray[count] = charArray[count-1];
      }
      
      String newString = new StringBuilder().append(charArray).toString();
      
      System.out.println(newString);      
   }
}

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

   Like      Discuss      Correct / Improve     string manipulation.right shift character


 Q80. What will be the output of following code ?

String str1 = "String1";
String str2 = "String1";
System.out.print(str1 == str2);
System.out.print(str1.equals(str2));
str1 = str2;
System.out.print(str1 == str2);
Core Java
a. falsetruetrue
b. falsefalsetrue
c. truetruetrue
d. falsefalsefalse

Ans.c. truetruetrue

 Q81. Which of the following class creates immutable objects ?Core Java
a. String
b. StringBuffer
c. StringBuilder
d. None of these create immutable objects.

Ans.a. String

 Q82. Which of the following class is synchronized ?Core Java
a. String
b. StringBuffer
c. StringBuilder
d. None of these

Ans.b. StringBuffer

 Q83. Which memory segment holds String Pool ?Core Java
a. Stack
b. Heap
c. Code Segment
d. Class Segment

Ans.b. Heap

 Q84. Which of the following class cannot be extended or inherited ?

StringBuffer , StringBuilder
Core Java
a. StringBuffer
b. StringBuilder
c. Both cannot be extended
d. Both can be extended

Ans.c. Both cannot be extended



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus
 

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:
         

X Close this

X Close this

Help Us Improve.
Please share your
interview experience.

Company Name:   


Questions Asked: