8000 words long text diagram String, this time I completely understand

Java is one of the most popular programming languages, it is simple, safe, and robust.

When you're preparing for a Java interview, you'll find that in most interviews, the starting questions are about Java strings.

In this article, I will introduce the top 20 interview questions about Java Strings, after reading this article, you will easily deal with Java String related interview questions.

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

String is a class defined in java.lang package in Java. You can assign a sequence of characters to a string variable. For example, String name = "Gaurav".

Also, String in Java is not a data type like int, char or long.

When you assign a sequence of characters to a String variable, you are creating a String object.

Each string literal is an instance of the String class, and its value cannot be changed.

2. What is the difference between strings in C language and strings in Java?

If your resume includes something related to the C language, they can ask you this question.

Strings in Java and C are completely different.

In C, a string is a null-terminated array of characters.

In the picture below, I show the structure of a string in C and Java.

In Java, strings are more abstract.

The string class comes from the java.lang package and has many predefined methods that programmers can use to operate on strings or obtain information about strings.

Therefore, in Java, strings are more feature-rich than C.

3. What is String Pooling in Java?

String pool is a special type of memory maintained by the JVM.

String pools are used to store unique string objects.

When you assign the same string prefix to different string variables, the JVM keeps only one copy of the string object in the string pool, and the string variable will start referencing that string object.

I have illustrated the above sentence in the image below.

The purpose of maintaining this special type of memory is memory optimization.

4. Why are strings immutable?

In most Java interviews, you will have questions like this.

Why do you think the Java language designers kept strings immutable?

If you assign the same string literal notation to many string variables, the JVM will keep only one copy of the string object in the Java string pool, and those variables will start referencing that string object.

If no one has asked you about string pooling before this question, could you please give some background on the concept of string pooling in Java. Please refer to the previous question.

Also, another reason is security. We know that almost every Java program contains strings, which are used to hold important data such as usernames and passwords. So it shouldn't be changed in the middle. Otherwise, security issues will arise.

5. How many objects will the following code create?

String firstString = "Gaurav";
String secondString = "Gaurav";
String thirdString =  new String("Gaurav");

Seeing the code above, only two string objects will be created. The first two variables will refer to the same string object with the value "Gaurav". JVM uses the concept of string pool to store only one copy of repeated string objects in the string constant pool.

However, when we use the newkeyword to create a new string, a new string object will be created and stored in Java heap memory.

So for the third variable thirdString, a new string object will be created and stored in Java heap space.

So there will be two objects in total, one from the Java string pool and one from the Java heap memory.

Below, I have shown these two objects in the image below.

6.  intern()What does the method do?

intern()method is used to manually add a unique copy of the string object to the Java string pool.

We know that when we create a string using the new keyword, it will be stored in heap memory.

We can intern()store a unique copy of that string object in the Java string pool using methods.

When you do something like this, the JVM checks to see if a string object with the same value exists in the string pool.

If a string object with the same value exists, the JVM will simply provide a reference to that object to the corresponding string variable.

If there is no string object with the same value in the string pool, the JVM creates a string object with the same value in the string pool and returns its reference to the string variable.

7. What is the difference between String and StringBuffer?

String is a final class in Java, String is immutable, which means we can no longer change the value of String object.

Since strings are widely used in applications, we have to perform multiple operations on string objects. Each time a new String object is generated, and all previous objects become garbage objects, putting pressure on the garbage collector.

Therefore, the Java team introduced the StringBuffer class. It's a mutable String object, which means you can change its value.

Strings are immutable, but StringBuffers are mutable.

8. What is the difference between StringBuffer and StringBuilder?

We know that strings are immutable in Java. But with StringBuffer and StringBuilder, you can create editable string objects.

When the Java team realized the need for editable string objects, they introduced the StringBuffer class. But all methods of StringBuffer class are synchronized.

This means that only one thread can access one method of StringBuffer at the same time.

Therefore, it takes more time.

Later, the Java team realized that it was not a good idea to synchronize all the methods of the StringBuffer class, so they introduced the StringBuilder class.

All methods of StringBuilder class are not synchronized.

Since all methods of the StringBuffer class are synchronized, StringBuffer is thread-safe, slower, and less efficient than StringBuilder.

Since none of the methods of the StringBuilder class are synchronized, StringBuilder is not thread-safe compared to StringBuffer, but it is faster and more efficient than StringBuffer.

9. Can we use ==operators to compare strings? What are the risks?

The answer is yes, we can use ==operators to compare strings.

However, when we ==compare strings using operators, we are comparing their object references whether or not those string variables point to the same string object.

Most of the time, developers want to compare the contents of strings, but they mistakenly use ==operators to compare strings when they should be using equals()methods, which leads to an error.

Below, I present a program that compares string comparisons using ==operators and equals()methods.

publicclass StringCompareUsingEqualsOperator {
 
 public static void main(String[] args) {
 
 String firstString = "Gaurav";
 String secondString = "Gaurav";
 
 String thirdString =  new String("Gaurav");
 
 System.out.print("Case 1 : ");
 System.out.println(firstString == secondString); // true
 
 System.out.print("Case 2 : ");
 System.out.println(firstString == thirdString); // false
 
 // Comparing strings using equals() method
 System.out.print("Case 3 : ");
 System.out.println(firstString.equals(thirdString)); // true
 }
 
}

The output of the above program is as follows:

Case 1 : true
Case 2 : false
Case 3 : true

In 'Case 1', we use the equivalence operator (==) to compare firstString and secondString, which prints true because both variables point to the same string object.

In 'Case 2', we use the equivalence operator (==) to compare firstString and thirdString, which prints false since neither variable points to the same string object.

You can see that for thirdString we used the new keyword which creates a new object in Java heap memory.

In "Case 3", we compare firstString and thirdString using the equals() method. Even though the two are different string objects, its content is the same, so it prints true.

10. What are the ways to compare strings?

We can use equals()methods, ==operators and compareTo()methods to compare strings.

When we compare strings using the equals() method, we are comparing the contents of the strings to see if these strings have the same contents.

When we compare strings using the == operator, we are comparing references to strings, i.e. whether these variables point to the same string object.

Also, we can compare strings alphabetically (compare strings alphabetically). We can use the compareTo() method to compare strings in alphabetical order.

The compareTo() method returns a negative integer, 0, or a positive integer.

firstString.compareTo(secondString)

If firstString is less than secondString, it will return a negative integer, i.e. firstString < secondString → return a negative integer.

If firstString is equal to secondString, it will return 0, i.e. firstString == secondString → return 0.

If firstString is greater than secondString, it will return a positive integer, that is, firstString > secondString → return a positive integer.

11. What is the purpose of the substring() method?

The substring() method in Java returns a substring of the specified string.

The creation of the substring depends on the arguments passed to the substring() method.

The Substring method can be used in two ways:

  • substring(int beginIndex)

  • substring(int beginIndex, int endIndex)

In the first method, we only give the parameter beinIndex, while in the second variant, we give both beginIndex and endIndex.

For the first variant, the substring will be taken from beginIndex (inclusive) to the last character of the string.

For the second variant, the substring will be taken from beginIndex (inclusive) to endIndex (exclusive).

Please see the figure below to understand the substring() method.

In the first picture, the first usage of substring() is used.

String name = "Gaurav Kukade";
String result = name.substring(4);
 
System.out.println(result);

In the second image, I have a second usage of the substring() method.

String name = "Gaurav Kukade";
String result = name.substring(4, 9);
 
System.out.println(result);

12. How to check if a string is empty?

The Java String class has a special method to check if the string is empty.

isEmpty()The method checks if the length of the string is zero, if it is zero, which means the string is empty, the isEmpty() method will return true.

If the length of the string is not zero, the isEmpty() method will return false.

13. What is the format() method in Java String? What is the difference between the format() method and the printf() method?

The format() method and the printf() method both format strings.

The only difference is that the format() method returns a formatted string, while the printf() method prints the formatted string.

Therefore, when you want to use formatted strings in a program, you can use the format method.

And when you want to print the formatted string directly, you can use the printf() method.

14. Is String "thread safe" in Java?

Yes, strings are thread safe.

As we know, in Java, strings are immutable. This means that once we have created a string, we can no longer modify it.

Therefore, there is no problem of multiple threads accessing a string object.

15. Why are strings used as HashMap keys in most cases?

This string is immutable. So one thing is fixed, that once it's created it won't be changed.

Therefore, the calculated hash code can be cached and used in the program.

This will save us the effort of computing the hash code again and again, so strings can be used more efficiently than other HashMap key objects.

16. Can you convert String to Int and vice versa?

Yes, you can convert string to int and vice versa.

You can convert strings to integers using the valueOf() method and parseInt() method of the Integer class.

Also, you can use the valueOf() method of the String class to convert integers to strings.

Below, I have given a program that shows the conversion of strings to integers and integers to strings.

publicclass Conversion{
 public static void main(String [] args){
 
 String str = "1254";
 
 int number = 7895;
 
 // convert string to int using Integer.parseInt() method
 int parseIntResult1 = Integer.parseInt(str);
 
 // convert string to int using Integer.valueOf() method
 int valueOfResult1 = Integer.valueOf(str);
 
 System.out.println("Converting String to Integer:");
 System.out.println("Using the Integer.parseInt() method : "+parseIntResult1);
 System.out.println("Using the Integer.valueOf() method : "+valueOfResult1);
 
 System.out.println("\n");
 // convert integer to string using String.valueOf() method
 String valueOfResult2 = String.valueOf(number);
 
 System.out.println("Converting Integer to String :");
 System.out.println("Using the String.valueOf() method : "+valueOfResult2);
 
 }
}

The output of the above program is as follows:

Converting String to Integer:
Using the Integer.parseInt() method : 1254
Using the Integer.valueOf() method : 1254
 
 
Converting Integer to String :
Using the String.valueOf() method : 7895

17. What is the split() method?

The split method is used to split the string according to the provided regex expression.

This method will return an array splitting the substrings:

publicclass SplitExample {
 
 public static void main(String[] args) {
 String name = "My, name, is ,Gaurav!";
 
 String [] substringArray = name.split(",");
 
 for(String substring : substringArray) {
 System.out.print(substring);
 }
 }
}

The input to the above program is:

My name is Gaurav!

18. What is the difference between "Gaurav Kukade".equals(str) and str.equals("Gaurav Kukade")?

Both look the same, it will check if the content of the string variable str is equal to the string "Gaurav Kukade".

But they are different when the string variable str = null.

The first code snippet will return false, but the second code snippet will throw NullPointerExpection.

Below I have given a program that compares two ways of strings using the equals() method.

publicclass StringExample {
 
 public static void main(String[] args) {
 
 String str = "Gaurav Kukade";
 
 System.out.println("Gaurav Kukade".equals(str)); // true
 
 System.out.println(str.equals("Gaurav Kukade")); // true
 } 
}

The input to the above program is:

true
true

Both times it prints true because the contents of both strings are equal.

Now, we'll examine a program where str=null:

publicclass StringNullExample {
 
 public static void main(String[] args) {
 
 String str = null;
 
 System.out.println("Gaurav Kukade".equals(str)); // false
 
 System.out.println(str.equals("Gaurav Kukade")); // NullPointerException
 }
}

The input to the above program is:

false
Exception in thread "main" java.lang.NullPointerException
 at StringNullExample.main(StringNullExample.java:14)

We can see the above output, for the first code snippet it is printing false but for the second code snippet it is throwing NullPointerException.

This is one of the most important tips to avoid null pointer exceptions in java strings.

19. In java, can we use a string in switch case?

Yes, since Java 7, we can use String in switch case.

Below, I give a program that shows the use of strings in the switch case.

publicclass StringInSwitchExample  
{ 
    public static void main(String[] args) 
    { 
        String str = "two"; 
        switch(str) 
        { 
            case"one": 
                System.out.println("January"); 
                break; 
            case"two": 
                System.out.println("February"); 
                break; 
            case"three": 
                System.out.println("March"); 
                break; 
            default: 
                System.out.println("Invalid month number"); 
        } 
    } 
}

The input to the above program is:

February

How to use + operator for string concatenation in Java?

The + operator is the only overloaded operator that you can use to add two numbers and also to concatenate strings.

If you are using Java version 1.5 or above, string concatenation uses StringBuilder's append() method internally. For versions lower than 1.5, it uses the append() method of the StringBuffer class.


Hello, everyone, my name is Jackpop. I graduated from Harbin Institute of Technology with a master's degree. I have worked in big factories such as Huawei and Ali. If you have doubts about further education, employment, and technical improvement, you may wish to make friends:

I'm Jackpop, let's be friends! icon-default.png?t=M276https://mp.weixin.qq.com/s/fCHn8JpLQDH-M_QkVxwR1w

Guess you like

Origin blog.csdn.net/jakpopc/article/details/124067676