JavaRush /Java Blog /Random EN /Java String. Interview questions and answers, part 2
Andrey
Level 26

Java String. Interview questions and answers, part 2

Published in the Random EN group
Unfortunately, the article did not fit in one fragment; I had to split it into two parts. See the beginning here Java String.  Interview questions and answers, part 2 - 1

12. Write a function to find the longest palindrome in a given string

A string can contain palindromic strings, and finding the longest palindrome is a matter of programming. The key point here is that from the middle of any palindrome, if we go right and left by 1 character, it will always be the same character. For example, 12321, the middle is 3, and if we continue moving from the current position in both directions, we will get 2 and then 1. We use similar logic in our Java program to find the longest palindrome. However, if the length of the palindrome is even, the length of the middle is also even, so we need to make sure that this is also provided in our program, for example, 12333321, the middle is 33, and if we continue moving in both directions, we will get 3, 2 and 1. In our program, we go through the resulting string with the middle in the first place and check the left and right characters. We also have two global variables to store the initial position of the palindrome. We also need to check if there is a longer palindrome already found, since we can find multiple palindromes in a given string. Below is an example program that works fine in all cases. We can improve the above code by moving the while loop into a separate method, but I'll leave that part for you. Please let me know if you have a better implementation or if the program fails in some way.
package com.journaldev.util;

public class LongestPalindromeFinder {

    public static void main(String[] args) {
        System.out.println(longestPalindromeString("1234"));
        System.out.println(longestPalindromeString("12321"));
        System.out.println(longestPalindromeString("9912321456"));
        System.out.println(longestPalindromeString("9912333321456"));
        System.out.println(longestPalindromeString("12145445499"));
    }

    public static String longestPalindromeString(String in) {
        char[] input = in.toCharArray();
        int longestPalindromeStart = 0;
        int longestPalindromeEnd = 0;

        for (int mid = 0; mid < input.length; mid++) {
            // для случая нечетного палиндрома How 12321, 3 будет серединой
            int left = mid-1;
            int right = mid+1;
            // нам необходимо двигаться влево и вправо на 1 позицию до конца
            while (left >= 0 && right < input.length) {
                // ниже проверка, является ли это палиндромом
                if (input[left] == input[right]) {
                    // обновление глобальных позиций, только если палиндром длиннее имеющегося
                    if (right - left > longestPalindromeEnd
                            - longestPalindromeStart) {
                        longestPalindromeStart = left;
                        longestPalindromeEnd = right;
                    }
                }
                left--;
                right++;
            }
            // для четного палиндрома у нас должна быть подобная логика с размером середины 2
            // для этого мы начнем на одну позицию правее
            left = mid-1;
            right = mid + 2;// к примеру, для 12333321 мы выбрали 33 в качестве середины
            while (left >= 0 && right < input.length)
            {
                if (input[left] == input[right]) {
                    if (right - left > longestPalindromeEnd
                            - longestPalindromeStart) {
                        longestPalindromeStart = left;
                        longestPalindromeEnd = right;
                    }
                }
                left--;
                right++;
            }
        }
        // теперь у нас есть позиции для самого длинного палиндрома
        return in.substring(longestPalindromeStart, longestPalindromeEnd + 1);
    }
}
The program will output the following:
1
12321
12321
12333321
454454

13. What are the differences between String, StringBuffer and StringBuilder

A string is immutable and finalized in Java, so all our string manipulations will always create a new string. String manipulation is resource intensive, so Java provides two useful classes for string manipulation - StringBufferand StringBuilder. StringBufferand StringBuilderare mutable classes. Operations with StringBufferare thread safe and synchronized, but methods StringBuilderare not thread safe. So when multiple threads are working on the same string we should use StringBuffer, but in a single threaded environment we should use StringBuilder. StringBuildermore productive than StringBufferbecause it is not burdened with synchronization.

14. Why is string immutable and finalized in Java?

There are several advantages to string immutability:
  1. String pooling is only possible because string is immutable in Java, thus the virtual machine saves a lot of heap space as different string variables point to the same variable in the pool. If a string were not immutable, then string interning would not be possible, because if any variable changes its value, other variables referencing that string will also be affected.

  2. If the string is mutable, then it becomes a serious security risk for the application. For example, the database username and password are passed as a string to obtain a connection to the database and in socket programming the host and port details are passed as a string. Since the string is immutable, 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 thread-safe and one instance of the string can be shared among different threads. This avoids synchronization for thread safety, strings are completely thread safe.

  4. Strings are used in Java classloaderand immutability ensures that the class is loaded correctly using Classloader. For example, think about a class instance when you are trying to load java.sql.Connectiona class, but the reference value is changed to myhacked.Connectiona class that might do unwanted things to your database.

  5. Since the string is immutable, it hashcodeis cached at the time of creation and there is no need to calculate it again. This makes the string an excellent candidate for the key in Mapand its processing will be faster than other keys HashMap. This is the reason why string is the most commonly used object used as a key HashMap.

15. How to split a string into parts?

We can use a method split(String regex)to split a string into an array of strings using a regular expression as the delimiter.
import java.util.Arrays;

public class JavaSplitString {
    public static void main(String[] args) {
        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));
        System.out.println("String split into two: "+Arrays.toString(twoWords));
        //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));
    }
}
The method split(String regex, int numOfStrings)is an overloaded method for splitting a string into a specified number of lines. We can use backslash to use regular expression special characters as regular characters. The program will output the following:
String split with delimiter: [I, am, a, java, developer]
String split into two: [I, am a java developer]
String split with special character: [I, am, a, java, developer]

16. Why is a string array preferable to a string for storing a password?

A string is immutable in Java and is stored in a string pool. Once it is created, it remains in the pool until it is garbage collected, so when we think we are done with the password, it remains available in memory for a while and there is no way to avoid this. This is a security risk because anyone with access to the memory dump will be able to find the password in clear text. If we use a character array to store the password, we can clear it after we're done with it. This way we can control how long it stays in memory, avoiding the security risks inherent in a string.

17. How do you check two strings for similarity in Java?

There are two ways to check if two strings are equivalent - using the “ ==” operator, or using the equals. When we use the “ ==” operator, it checks the value of the string as a reference, but in programming most of the time we check the string equivalence only for the value. Therefore, we must use the equals method to test two strings for equality. There is also a method equalsIgnoreCasewe can use to ignore case.
String s1 = "abc";
String s2 = "abc";
String s3= new String("abc");
System.out.println("s1 == s2 ? "+(s1==s2)); //true
System.out.println("s1 == s3 ? "+(s1==s3)); //false
System.out.println("s1 equals s3 ? "+(s1.equals(s3))); //true

18. What is a string pool?

As the name suggests, a string pool is a collection of strings that is stored in a Java heap. We know that Stringthis is a special class in Java and we can create objects of this class using the new operator just like we can create objects by providing the value of a string in double quotes. The diagram below explains how the string pool is allocated in the Java heap and what happens when we use different ways to create strings. Java String.  Interview questions and answers, part 2 - 2String pooling is possible solely because of Java's immutability of strings and the implementation of the idea of ​​string interning. A string pool is also an example of the Flyweight pattern. String pool helps to 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, it first looks for a string in the pool with the same value, if found then simply returns a reference, otherwise a new string is created in the pool and then returns a reference. However, when we use the new operator, we force the class Stringto create a new string object, and then we can use the method intern()to put the string into the pool, or get a reference from the pool to another object Stringwith the same value. Below is an example showing how the string pool works.
public class StringPool {
    public static void main(String[] args) {
        String s1 = "Cat";
        String s2 = "Cat";
        String s3 = new String("Cat");

        System.out.println("s1 == s2 :"+(s1==s2));
        System.out.println("s1 == s3 :"+(s1==s3));
    }
}
The program will output the following:
s1 == s2 :true
s1 == s3 :false

19. What does the intern() method do?

When the method intern()is called, if the string pool already contains a string equivalent to our object, as verified by the method equals(Object), then a reference to the string from the pool is returned. Otherwise, the string object is added to the pool and a reference to that 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 method works intern():
public class StringPool {
    public static void main(String[] args) {
        String a = "string a";
        String b = new String("string a");
        String c = b.intern();

        System.out.println(a == b);
        System.out.println(b == c);
        System.out.println(a == c);
    }
}
Программа выведет следующее:false
false
true

20. Are strings thread safe in Java?

Strings are immutable, so we cannot change their value in the program. Therefore they are thread safe and can be safely used in a multi-threaded environment.

21. Why is String a popular key in HashMap in Java?

Since strings are immutable, their hash code is cached at the time of creation and does not require recalculation. This makes strings an excellent candidate for a key Mapand they are processed faster than other key objects HashMap. This is why strings are predominantly used as keys HashMap. I hope the questions listed in this article will help you in your interviews, please let me know if I missed anything. Link to original article Author: Pankaj Kumar
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION