String Interview Questions:-


  1. What is String in Java? String is a data type?

Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms.

String is a Class in java and defined in java.lang package. It's not a primitive data type like int and long. String class represents character Strings. String is used in almost all the Java applications and there are some interesting facts we should know about String. String in immutable and final in Java and JVM uses String Pool to store all the String objects.

Some other interesting things about String is the way we can instantiate a String object using double quotes and overloading of "+"operator for concatenation.


  2. What is string constant pool?

String objects are most used data objects in Java. Hence, java has a special arrangement to store the string objects. String Constant Pool is one such arrangement. String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content.

Whenever you create a string object using string literal, JVM first checks the content of the object to be created. If there exist an object in the string constant pool with the same content, then it returns the reference of that object. It doesn't create a new object. If the content is different from the existing objects then only it creates new object


  3. What are different ways to create String Object?

We can create String object using new operator like any normal java class or we can use double quotes to create a String object. There are several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilder.

For Example :-

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


  4. What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can't modify them once they are created. They are final in nature. Where as mutable objects are concerned, you can perform modifications to them.


  5. Why String is immutable or final in Java?

There are several benefits of String because it's immutable and final.

(a). String Pool is possible because String is immutable in java.

(b). It increases security because any hacker can't change its value and it's used for storing sensitive information such as database username, password etc.

(c). Since String is immutable, it's safe to use in multi-threading and we don't need any synchronization.

(d). Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.


  6. Where exactly string constant pool is located in the memory?

Inside the heap memory. JVM reserves some part of the heap memory to store string objects created using string literals.


  7. What is string intern?

String object in the string constant pool is called as String Intern. You can create an exact copy of heap memory string object in string constant pool. This process of creating an exact copy of heap memory string object in the string constant pool is called interning. intern() method is used for interning.


  8. What is the main difference between Java strings and C, C++ strings?

In C and C++, strings are terminated with null character. But in java, strings are not terminated with null character. Strings are treated as objects in java.


  10. Is String a primitive type or derived type?

String is a derived type.


  11. What are the difference between String, StringBuffer and StringBuilder?

String is immutable and final in java, so whenever we do String manipulation, it creates a new String. String manipulations are resource consuming, so java provides two utility classes for String manipulations :-

1. StringBuffer and

2. StringBuilder

StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder.

StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.


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

Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms.

String is a Class in java and defined in java.lang package. It's not a primitive data type like int and long. String class represents character Strings. String is used in almost all the Java applications and there are some interesting facts we should know about String. String in immutable and final in Java and JVM uses String Pool to store all the String objects.

Some other interesting things about String is the way we can instantiate a String object using double quotes and overloading of "+"operator for concatenation.



  13. How to Split String in java?

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

String split(String regex, int numOfStrings) is the overloaded function to split the input String into specific number of Strings. We can use backslash to use java regular expression special characters as normal characters.


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

There are two ways to check if two Strings are equal or not :-

1. By "==" Operator and

2. By equals Operator

When we use "==" operator, it checks for value of String as well as reference but in our programming, most of the time we are checking equality of String for value only. So we should use equals method to check if two Strings are equal or not.

There is another function equalsIgnoreCase that we can use to ignore case.

For Example :-

String x1="abc";

String x2="abc";

String x3=new String("abc");

System.out.println("x1 == x2 ? "+(x1==x2)); //true

System.out.println("x1 == x3 ? "+(x1==x3)); //false

System.out.println("x1 equals x3 ? "+(x1.equals(x3))); //true


  15. Why String is popular HashMap key in Java?

Since String 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 key in a Map and it's processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.


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

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.

If we use char array to store password, we can set it to blank once we are done with it. So we can control for how long it's available in memory that avoids the security threat with String.


  17. Can we use String in switch case?

Java 7 extended the capability of switch case to use Strings also, earlier java versions doesn't support this.

If you are 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.

There are some keys points to know for java switch case String are :-

(a). Java switch case String make code more readable by removing the multiple if-else-if chained conditions.

(b). Java switch case String is case sensitive.

(c). Java Switch case uses String.equals() method to compare the passed value with case values, so make sure to add a NULL check to avoid NullPointerException.

(d). According to Java 7 documentation for Strings in Switch, java compiler generates more efficient byte code for String in Switch statement than chained if-else-if statements.

(e). Make sure to use java switch case String only when you know that it will be used with Java 7 else it will throw Exception.


  18. How to convert String to char and vice versa?

We can't convert it to a single character.We can use use charAt method to get the character at given index or we can use toCharArray()method to convert String to character array.


  19. Why StringBuffer and StringBuilder classes are introduced in java when there already exist String class to represent the set of characters?

The objects of String class are immutable in nature. i.e you can't modify them once they are created. If you try to modify them, a new object will be created with modified content. This may cause memory and performance issues if you are performing lots of string modifications in your code.

To overcome these issues, StingBuffer and StringBuilder classes are introduced in java.


  20. How does substring method work in Java?

Substring shares same character array as original String which can create a memory leak if original String is quite big and not required to retain in memory but unintentionally retained by substring which is very small in size and prevents large array from begin claimed during Garbage collection in Java.


  21. Write a method in Java to remove any character from String?

For example, you need to write method remove(String word, char removeThis), this method should return a String without character, which is asked to remove. you can use indexOf(), substring() and similar methods from String class, but your method must handle corner cases e.g. passing null or empty String, String containing just one character etc.


  22. Can we create an Immutable object, which contains a mutable object?

Yes, its possible to create an Immutable object which may contain a mutable object, you just need to be a little bit careful not to share the reference of the mutable component, instead, you should return a copy of it if you have to. Most common example is an Object which contain the reference of java.util.Date object.


  23. what is the Substrings in Java?

You can extract a part of a String. This is called a substring. You do so using the substring() method of the String class.

Here is an Example :-

String s1 = "Hello Gps";

String substring = s1.substring(0,5);

After this code is executed the substring variable will contain the string Hello.

The substring() method takes two parameters. The first is the character index of the first character to be included in the substring. The second is the index of the character after the last character to be included in the substring. Remember that. The parameters mean "from - including, to - excluding". This can be5b a little confusing until you memorize it.

The first character in a String has index 0, the second character has index 1 etc. The last character in the string has has the index String.length() - 1.


  24. How to replacing characters in Strings with replace() method?

The Java String class contains a method named replace() which can replace characters in a String. The replace() method does not actually replace characters in the existing String. Rather, it returns a new String instance which is equal to the String instance it was created from, but with the given characters replaced.

Here is a Java String replace() method Example :-

String source = "123gps";

String replaced = source.replace('g', 'b');

After executing this code the replaced variable will point to a String with the text :-

123bps

The replace() method will replace all character matching the character passed as first parameter to the method, with the second character passed as parameter to the replace() method.


  25. What is the work of trim() method in Java String?

The Java String class contains a method called trim() which can trim a string object. By trim is meant to remove white space characters at the beginning and end of the string. White space characters include space, tab and new lines.

Java String trim() method Example :-

String s1 = " GPS Infosolutions Pvt Ltd ";

String s2 = s1.trim();

After executing this code the s2 variable will point to a String instance with the value

"GPS Infosolutions Pvt Ltd"

The white space characters at the beginning and end of the String object have been removed. The white space character inside the String have not been touched. By inside is meant between the first and last non-white-space character.


  26. How to convert Integer to String using Integer.toString() method in Java?

Here we are discussed some key points convert Integer to String :-

(a). Integer is a wrapper class in java which is mainly used to represent or convert primitive int value to object.

(b). And Integer class having some predefined methods.

(c). Integer class has special predefined method to convert integer value to string toString();

(d). toString() is a static method in Integer class so that by using class name itself we can call that method to convert Integer to corresponding string value.

Advantages of toString() method in Java :-

(a). When ever we try to print object by default toString() method will be called and print classname@HEX_hashcode.

(b). We can represent object in String format using toString() method.

(c). Integer class has special predefined method to convert integer value to string toString();

(d). toString() is a static method in Integer class so that by using class name itself we can call that method to convert Integer to corresponding string value.


  27. Which is the final class in these three classes String, StringBuffer and StringBuilder?

All three are final classes in Java String.


  28. How do you create mutable string objects?

Using StringBuffer and StringBuilder classes. These classes provide mutable string objects.


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

To find the number of occurrences of each character in a given string, we have used HashMap with character as a key and it's occurrences as a value. First, we convert the given string to char array and check each character one by one. And update it's count in HashMap.


  30. How do you find duplicate characters in a string?

We use HashMap and Set to find the duplicate characters in a string. First, we convert the given string to char array. We then create one HashMap with Character as a key and it's number of occurrences as a value. Then we extract a Set containing all keys of this HashMap using keySet() method. Then we use this keySet to get the duplicate characters i.e characters which have appeared more than once in the given string.


  31. how to reverse a string in Java?

I have discussed three different ways to reverse a string in Java.

1. Using StringBuffer class :-

In this method, we use reverse() method of StringBuffer class to reverse the string. Here is the code snippet to reverse the string using reverse() method of StringBuffer class.

For Example :-

StringBuffer sbf = new StringBuffer("Gps");

System.out.println(sbf.reverse()); // Output : spG

2. Using iterative method :-

In this method, first we convert given string to char array using charArray() method. And then we iterate that array in the reverse order.

For Example :-

String str = "Gps";

char[] strArray = str.toCharArray();

for (int i = strArray.length - 1; i >= 0; i--) {

System.out.print(strArray[i]); //Output : spG }

3. Using recursive method :-

This method takes the first character of a string (str.charAt(0)) and puts it at the end of the string. And then calls itself on the remainder of the string (str.substring(1)). Finally adds these two things to get the reverse of the passed string (recursiveMethod(str.substring(1)) + str.charAt(0)). When the passed string is one character or less (str.length() <= 1), it stops calling itself and just returns the string passed.


  32. How about comparing the other objects like Integer, Boolean, and custom objects like "Pet"?

String class is designed with the Flyweight design pattern in mind. Flyweight is all about re-usability without having to create too many objects in memory. A pool of Strings is maintained by the String class. When the intern( ) method is invoked, equals() method is invoked to determine if the String already exist in the pool.

If it does then the String from the pool is returned instead of creating a new object. If not already in the string pool, a new String object is added to the pool and a reference to this object is returned. For any two given strings s1 & s2, s1.intern( ) == s2.intern( ) only if s1.equals(s2) is true.


  33. When a lot of changes are required in data, which one should be a preference to be used? String or StringBuffer?

Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it's always a good choice to use StringBuffer when data is being changed too much. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead.


  34.How to check if a String is numeric in Java? Use isNumeric() or isNumber().

In Java application, the simplest way to determine if a String is a number or not is by using Apache Commons lang's isNumber() method, which checks whether the String a valid number in Java or not.

Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, notation and numbers marked with a type qualifier (e.g. 123L).Non-hexadecimal strings beginning with a leading zero are treated as octal values Thus the string 09 will return false since 9 is not a valid octal value. However, numbers beginning with 0. are treated as decimal.null and empty/blank String will return false.


  35. java.util.regex consists of which classes?

java.util.regex consists of three classes:- Pattern class, Matcher class and PatternSyntaxException class.


  36. Which package is used for pattern matching with regular expressions?

java.util.regex package is used for this purpose.


  37. What is the first argument of the String array in main method?

The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.


  38. What is object reference?

Object reference is a unique hexadecimal number representing the memory address of the object. It is useful to access the members of the object.


  39. Are there any other classes whose objects are immutable?

Yes, Classes like Character, Byte, Integer, Float, Double, Long. called 'Wrapper classes' are created as 'immutable'. Classes like Class BigInteger, BigDecimal are also.


  40. What is the use of StringTokenizer class?

The StringTokenizer class allows an application to break a string into tokens. The StringTokenizer methods do not distinguish among identifiers, numbers and quoted strings, nor do they recognise and skip comments.

The set of delimiters(the characters that separate tokens) may be specified either at creation time or on a per-token basis.


  41. Is string a wrapper class?

String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and vicevers


  42. To what value is a variable of the String type automatically initialized?

The default value of an String type is null.


  43. Is "abc" a primitive value?

The String literal "abc" is not a primitive value. It is a String object.


  44. What happens when you add a double value to a String?

The result is a String object.


  45. How do you declare a variable that will hold string values?

The char keyword can only hold one character value at a time. By creating an array of characters, you can store string values in it.

For Example :- "char MyName[50]"; declares a string variable named MyName that can hold a maximum of 50 characters.


  46. What role of #&& in Querystring?

# treated as fragment delimiter to delimit the history state and && precedes is used to check on the information in the query string.


  47. What is the command used to fetch first five characters of the String?

There are many ways to fetch first five characters of the String :-

1. [sql]Select SUBSTRING(EmployeeName,1,5) as employeename from employeee.[/sql]

2. [sql]Select RIGHT(EmployeeName,5) as employeename from employeee.[/sql]

PHP

PHP is a server-side scripting language designed primarily for web development but is also used as a general-purpose programming language..

Read more