Java String Interview Questions And Answers

Interview Questions

25 Java String Interview Questions And Answers – String in Java Interview Questions For Experienced 2018 from Codingcompiler. Test your Java Strings knowledge by answering these tricky interview questions on Java strings. Let’s start learning Java strings interview questions and prepare for Java interviews. All the best for your future and happy learning.

Java String Interview Questions

  1. What “string” classes do you know?
  2. What are the main properties of “string” classes (their features)?
  3. Is it possible to inherit a string type, why?
  4. Define the concept of string concatenation.
  5. How to convert a string to a number?
  6. How to compare the value of two lines?
  7. How to flip a string?
  8. How does the comparison of two lines work?
  9. How to trim spaces at the end of a line?
  10. How to replace a character in a string?
  11. How to get part of the line?
  12. Define the concept of “string pool”.
  13. What method allows you to select a substring in a string?
  14. How to split a string into substrings for a given delimiter?
  15. What method is called to convert a variable to a string?
  16. How to know the value of a specific character of a string, knowing its ordinal number in a string?
  17. How to find the required character in the string?
  18. Is it possible to synchronize access to the string?
  19. What does the intern () method do?
  20. What is the difference and what does the String, StringBuffer and StringBuilder classes have in common?
  21. How to compare the string values ​​of two different objects of type String and StringBuffer?
  22. Why is the string unchanged and finalized in Java?
  23. Why an array of characters is preferable to the string to store the password?
  24. Why is string a popular key in a HashMap in Java?
  25. Write a method to remove this character from the string.

Related Java Interview Questions

  1. Java Collections Interview Questions
  2. Java Exceptions Interview Questions
  3. Java OOPS Interview Questions
  4. Core Java Interview Questions
  5. JSF Interview Questions
  6. JSP Interview Questions
  7. JPA Interview Questions
  8. Spring Framework Interview Questions
  9. Spring Boot Interview Questions
  10. Core Java Multiple Choice Questions
  11. 60 Java MCQ Questions And Answers
  12. Aricent Java Interview Questions
  13. Accenture Java Interview Questions
  14. Advanced Java Interview Questions For 5 8 10 Years Experienced
  15. Core Java Interview Questions For Experienced

Java String Interview Questions & Answers

1. What “string” classes do you know?

  • public final class String  implements java.io.Serializable, Comparable <String>, CharSequence
  • public final class StringBuffer  extends AbstractStringBuilder implements java.io.Serializable, CharSequence
  • public final class StringBuilder  extends AbstractStringBuilder implements java.io.Serializable, CharSequence

2. What are the main properties of “string” classes (their features)?

All string classes are final (hence, they cannot be inherited).

String .

A string is an object that represents a sequence of characters. To create and manipulate Java strings, the platform provides a publicly available final (cannot have subclasses) java.lang.String class . This class is immutable ( immutable ) – the created object of class String cannot be changed.

StringBuffer

Strings are immutable, so their frequent modification leads to the creation of new objects, which in turn consumes precious memory. To solve this problem, the java.lang.StringBuffer class was created , which allows you to work more effectively on the modification of the string.

The class is mutable , that is, mutable – use it if you want to change the contents of the string. StringBuffer can be used in multi-threaded environments, since all the necessary methods are synchronized.

StringBuilder

StringBuilder is a class that represents a variable character sequence. The class was introduced in Java 5 and has a completely identical API with a StringBuffer .

The only difference is that StringBuilder is not synchronized. This means that its use in multi-threaded environments is undesirable. Therefore, if you are working with multithreading, StringBuffer is perfect for you , otherwise use StringBuilder , which works much faster in most implementations.

3. Is it possible to inherit a string type, why?

Classes are declared final, so it cannot be inherited.

4. Define the concept of string concatenation.

Concatenation is a string merging operation that returns a new string, which is the result of merging the second string with the end of the first. Concatenation operations can be performed as follows:

1

2

3

4

5

6

7

8

9

10

11

StringBuffer stringBuffer = new StringBuffer();

StringBuilder stringBuilder = new StringBuilder();

String str = “ABC”;

str += “DEF”;

String str2 = “one”.concat(“two”).concat(“three”);

stringBuffer.append(“DDD”).append(“EEE”);

stringBuilder.append(“FFF”).append(“GGG”);

System.out.println(str + ” ” +str2 + ” ” + stringBuffer.toString() + ” ” + stringBuilder.toString());//ABCDEF onetwothree DDDEEE FFFGGG

Comparison of string concatenation performance:

Operator ‘+ =’> 92.243 s ;

String.concat ()> 1.254 seconds ;

StringBuffer> 1.208 s ;

The StringBuilder> 1.121 with .

5. How to convert a string to a number?

Each wrapper for primitives has its own valueOf (String s) method , which returns the converted numeric value from the string. In this case, the format of the string and the type to be accepted must match. For example:

1

2

3

4

5

6

String x = “523.5”;

Double xd = Double.valueOf(x);

/*

Integer xy = Integer.valueOf(x); //java.lang.NumberFormatException: For input string: “523.5”

*/

System.out.println(xd); //523.5

6. How to compare the value of two lines?

The == operator works with references to the String object . If two String variables point to the same object in memory, the comparison will return a result of true . Otherwise, the result will be false , although the text may contain exactly the same characters. The == operator does not compare the char data itself . For comparison, it is necessary to use the equals () method ;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

       String s1 = new String(“ABC”);

       String s2 = new String(“ABC”);

       String s3 = “ABC”;

       String s4 = “ABC”;

       System.out.println(s1==s2); //false

       System.out.println(s3==s4); //true. Since one set of literals will point to one memory area

       System.out.println(s1.equals(s2));//true

       s1=s2;

       System.out.println(s1==s2); //true

       if(“someString” == “someString”) { //true

           System.out.println(“true”);

       }

       System.out.println(s1.compareTo(s2)); //0

       System.out.println(“C”.compareTo(“A”)); //2

       System.out.println(“A”.compareTo(“C”)); //-2

7. How to flip a string?

1

2

3

4

String s = “ABCDEFG”;

StringBuilder stringBuilder = new StringBuilder(s);

stringBuilder.reverse();

System.out.println(stringBuilder.toString()); //GFEDCBA

You can also rearrange each char by the algorithm , but this is up to you :).

Related Java Tutorials For Beginners

Introduction to Java Programming

Java Keywords Tutorial For Beginners

Java Data Types Tutorial For Beginners

Java Operators Tutorial For Beginners

Java Control Flow Statements Tutorial

Java Performance Tuning Tips

Java Class Tutorial For Beginners

Java Exceptions Tutorial For Beginners

Java Annotations Tutorial For Beginners

Java Generics Tutorial For Beginners

Java Enumeration Tutorial For Beginners

Java Class Instance Tutorial For Beginners

8. How does the comparison of two lines work?

A string in Java is a separate object that may not coincide with another object, although the result of the displayed string may look the same on the screen. Just Java in the case of the logical operator == (and also ! = ) Compares references to objects.

The equals method compares character by character for equivalence.

9. How to trim spaces at the end of a line?

1

2

3

String s = “a    “;

System.out.println(s.trim() + “b”);//ab

System.out.println(s + “b”);//a    b

Advanced Java String Interview Questions And Answers

10. How to replace a character in a string?

You can use the replace method (CharSequence target, CharSequence replacement) , which changes the characters in a string. You can convert to an array of characters and replace the character there. You can use StringBuilder and the setCharAt method (int index, char ch)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

String sb = “AABAA”;

String s = “ABCDEF”.replace(“C”, “**”);

String sb2 = sb.replace(sb, “##”);

System.out.println(s + ” ” + sb2); //AB**DEF and ##

String fs = “123456789”;

char[] charSequence = fs.toCharArray();

charSequence[3] = ‘$’;

String nStr = String.valueOf(charSequence);

System.out.println(nStr); //123$56789

StringBuilder str = new StringBuilder(“AMIT”); //0-A, 1-M, 2-I, 3-T

str.setCharAt(3, ‘L’);

//AMIL

11. How to get part of the line?

The substring method (int beginIndex, int lastIndex) – returns part of a string at the specified indices.

1

2

3

4

String fs = “123456789”;

String sub = fs.subSequence(3,6).toString();

String sub2 = fs.substring(3,6);

System.out.println(sub2); //456

12. Define the concept of “string pool”.

A row pool is a set of rows that is stored in the Java heap memory. We know that a String is a special class in Java, and we can create objects of this class using the new operator in the same way as creating objects, providing the value of a string in double quotes.

The diagram below explains how a string pool is placed in the Java heap memory and what happens when we use different ways to create strings.

A string pool is possible only due to the immutability of strings in Java and the implementation of the idea of ​​string interning. The row pool is also an example of the Flyweight pattern.

A row pool helps save a lot of memory, but on the other hand creating a row takes more time.

When we use double quotes to create a string, we first look for a string in the pool with the same value, if it is, then the link is simply returned, otherwise a new string is created in the pool, and then the link is returned.

However, when we use the new operator, we force the String class to create a new string object, and then we can use the intern () method to put a string into the pool, or get a reference to another String object from the pool with the same value .

Below is an example showing the operation of the row pool.

1

2

3

4

5

6

String s1 = “Cat”;

String s2 = “Cat”;

String s3 = new String(“Cat”);

System.out.println(“s1 == s2 :”+(s1==s2)); //s1 == s2 :true

System.out.println(“s1 == s3 :”+(s1==s3)); //s1 == s3 :false

Java String Interview Questions And Answers For Experienced

13. What method allows you to select a substring in a string?

In addition to “how to get part of a string,” you can use the string.indexOf (char c) method , which returns the index of the first occurrence of a character. Thus you can then use this number to highlight the substring using substring ();

14. How to split a string into substrings for a given delimiter?

We can use the split (String regex) method to split a string into an array of characters using a regular expression as a separator. The split method (String regex, int numOfStrings) is an overloaded method for splitting a string into a specified number of strings. We can use the backslash to use special regular expression characters as ordinary characters.

1

2

3

4

5

6

7

8

9

10

11

12

13

String line = “I am a java developer”;

String[] words = line.split(” “);

String[] twoWords = line.split(” “, 2);

System.out.println(“String split with delimiter: “+Arrays.toString(words));//String split with delimiter: [I, am, a, java, developer]

System.out.println(“String split into two: “+Arrays.toString(twoWords));//String split into two: [I, am a java developer]

//split string delimited with special characters

String wordsWithNumbers = “I|am|a|java|developer”;

String[] numbers = wordsWithNumbers.split(“\\|”);

System.out.println(“String split with special character: “+ Arrays.toString(numbers));//String split with special character: [I, am, a, java, developer]

15. What method is called to convert a variable to a string?

1

2

3

public static String valueOf(Object obj) {

       return (obj == null) ? “null” : obj.toString();

}

16. How to know the value of a specific character of a string, knowing its ordinal number in a string?

str.charAt (int i) will return the character in by index.

17. How to find the required character in the string?

str.indexOf (char ch) or lastIndexOf (char c) – returns the index of the first and last occurrence of the character.

1

2

3

String fs = “12345678904”;

int a = fs.indexOf(“456”); //3

int b = fs.lastIndexOf(“4”); //10

18. Is it possible to synchronize access to the string?

The string itself is a thread safe class. If we work with variable strings, then we need to use a StringBuffer .

19. What does the intern () method do?

When the intern () method is called, if the row pool already contains a string equivalent to our object, which is confirmed by the equals (Object) method , then a reference to the string from the pool is returned. Otherwise, the row object is added to the pool, and a reference to this object is returned.

This method always returns a string that has the same value as the current string, but guarantees that it will be a string from the pool of unique strings.

Below is an example of how the intern () method works.

1

2

3

4

5

6

7

String a = “string a”;

String b = new String(“string a”);

String c = b.intern();

System.out.println(a == b); //false

System.out.println(b == c); //false

System.out.println(a == c); //true

String in Java Interview Questions And Answers

20. What is the difference and what does the String, StringBuffer and StringBuilder classes have in common?

In addition to the answer, first I will give a comparison of the performance of classes.

Performance comparison Linux

ClassOpen JDK 1.6.0_18HotSpot 1.6.0_20JRockit 4.0.1
String27390ms26850ms26940ms
Stringbuffer35.55ms34.87ms15.41ms
Stringbuilder33.01ms31.78ms12.82ms

Performance comparison Windows XP:

ClassHotSpot 1.6.0_20JRockit 4.0.1
String55260ms45330ms
Stringbuffer19.38ms14.50ms
Stringbuilder16.83ms12.76ms

21. How to compare the string values ​​of two different objects of type String and StringBuffer?

Bring them to one type and compare.

22. Why is the string unchanged and finalized in Java?

There are several advantages to storing strings:

  1. A string pool is possible only because the string is unchanged in Java, so the virtual machine saves a lot of memory space (heap space), since different string variables point to the same variable in the pool. If the string were not immutable, then the internment of the strings would not be possible, because if any variable changes the value, this will also be reflected in the other variables referring to this string.
  2. If the string is mutable, then it will become a serious threat to the security of the application. For example, the database username and password are passed as a string to get a connection to the database, and in socket programming, the host and port details are passed as a string. Since the string is unchangeable, its value cannot be changed, otherwise any hacker can change the value of the link and cause problems in the security of the application.
  3. Since the string is immutable, it is safe for multithreading and a single instance of the string can be shared by different threads. This avoids synchronization for thread safety, the strings are completely thread safe.
  4. Strings are used in the Java classloader and immutability ensures that the class is correctly loaded using the Classloader. For example, think about an instance of a class when you are trying to load a java.sql.Connection class, but the value of the link is changed to the myhacked.Connection class that can do unwanted things with your database.
  5. Since the string is unchanged, its hashcode is cached at the time of creation and there is no need to count it again. This makes the string a great candidate for a key in a Map and its processing will be faster than other HashMap keys. This is the reason why the string is the most frequently used object as the HashMap key.

23. Why an array of characters is preferable to the string to store the password?

The string is unchangeable in Java and is stored in a string pool. Since it was created, it remains in the pool until it is deleted by the garbage collector, so when we think that we’ve finished using the password, it remains available in memory for a while and there’s no way to avoid it. This is a security risk, since anyone with access to the memory dump will be able to find the password in clear text.

If we use an array of characters to store the password, we can clear it after we finish working with it. Thus, we can control how long it is in memory, which avoids the security risk inherent in the string.

24. Why is string a popular key in a HashMap in Java?

Since the strings are unchanged, their hashcode is cached at the time of creation, and does not require recalculation. This makes strings a great candidate for a key in a Map and they are processed faster than other HashMap key objects. This is why strings are primarily used as HashMap keys.

25. Write a method to remove this character from the string.

We can use the replaceAll method to replace all entries in a string with another string. Notice that the method takes a string as an argument, so we use the Character class to create a string from a character, and use it to replace all characters with an empty string.

1

2

3

4

5

public static String removeChar(String str, char ch) {

       if (str == null)

           return null;

       return str.replaceAll(Character.toString(ch), “”);

}

Must Read Java Interview Questions Books

RELATED INTERVIEW QUESTIONS

  1. Java Collections Interview Questions
  2. Java Exceptions Interview Questions
  3. Java OOPS Interview Questions
  4. Core Java Interview Questions
  5. JSF Interview Questions
  6. JSP Interview Questions
  7. JPA Interview Questions
  8. Spring Framework Interview Questions
  9. Spring Boot Interview Questions
  10. Core Java Multiple Choice Questions
  11. 60 Java MCQ Questions And Answers
  12. Aricent Java Interview Questions
  13. Accenture Java Interview Questions
  14. Advanced Java Interview Questions For 5 8 10 Years Experienced
  15. Core Java Interview Questions For Experienced
  16. GIT Interview Questions And Answers
  17. Network Security Interview Questions
  18. CheckPoint Interview Questions
  19. Page Object Model Interview Questions
  20. Apache Pig Interview Questions
  21. Python Interview Questions And Answers
  22. Peoplesoft Integration Broker Interview Questions
  23. PeopleSoft Application Engine Interview Questions
  24. RSA enVision Interview Questions
  25. RSA SecurID Interview Questions
  26. Archer GRC Interview Questions
  27. RSA Archer Interview Questions
  28. Blockchain Interview Questions
  29. Commvault Interview Questions
  30. Peoplesoft Admin Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *