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

Java String. Interview questions and answers, part 1

Published in the Random EN group
members
The class Stringis one of the most widely used classes in Java. This article provides some important Java String interview questions and answers. Java String.  Interview questions and answers, part 1 - 1They will be very helpful in getting a complete picture of the class Stringand will prepare you for any class-related Stringinterview question.

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

String is a class in Java that is defined in the java.lang package. It is not a primitive data type like int and long. The String class represents a string character set. Strings are used across almost all Java applications and there are a few facts that we should know about the String class. It is an immutable ( immutable) and finalized data type in Java and Stringthe virtual machine stores all objects of the class in a string pool. Another feature Stringis the way to obtain class objects Stringusing double quotes and overloading the “+” operator for concatenation.

2. What are the different ways to create a String object?

We can create objects using the new operator just like any other class in Java or we can use double quotes to create an object String. There are also several class constructors Stringfor getting a string from a character array, a byte array, and also using StringBufferor StringBuilder.
String str = new String("abc");
String str1 = "abc";
When we create a string using double quotes, the Java Virtual Machine looks in the string pool for another string with the same value. If the string is found, then only a reference to an existing object of the class is returned String, otherwise a new object is created with the received value and stored in the pool. When we use the new operator, the virtual machine creates an object Stringbut does not store it in the string pool. We can use the method intern()to store a string in a string pool, or get a reference if such a string is already in the pool.

3. Write a method to check whether a string is a palindrome.

A string is called a palindrome if it reads the same in both directions. For example, “aba” is a palindromic string. The class Stringdoes not provide any method for reversing a string, but classes StringBufferdo StringBuilderhave a reversing method with which we can check whether our string is a palindrome or not.
private static boolean isPalindrome(String str) {
        if (str == null)
            return false;
        StringBuilder strBuilder = new StringBuilder(str);
        strBuilder.reverse();
        return strBuilder.toString().equals(str);
    }
Sometimes the interviewer may ask not to use other classes for this check, in which case we can compare the characters in the string on both sides to check for palindrome.
private static boolean isPalindromeString(String str) {
        if (str == null)
            return false;
        int length = str.length();
        System.out.println(length / 2);
        for (int i = 0; i < length / 2; i++) {

            if (str.charAt(i) != str.charAt(length - i - 1))
                return false;
        }
        return true;
    }

4. Write a method for removing a given character from a string.

We can use a method replaceAllto replace all occurrences of a string with another string. Note that the method takes a string as an argument, so we use the class Characterto create a string from a character, and use it to replace all characters with the empty string.
private static String removeChar(String str, char ch) {
        if (str == null)
            return null;
        return str.replaceAll(Character.toString(ch), "");
    }

5. How can we convert a string to upper case or lower case?

We can use class methods String toUpperCaseto toLowerCaceget both uppercase and lowercase strings. These methods have an overload that takes an argument Localeand uses its localization rules to convert the string to upper or lower case.

6. What does the subSequence method do?

Java 1.4 introduced the interface CharSequence, a class Stringinherits this interface and that is the only reason to implement a method subSequencein a class String. Internally it calls the substring. A simple example of using the method:
public class StringSubsequence {

    public static void main(String[] args) {
        String str = "www.journaldev.com";
        System.out.println("Last 4 char String: "+str.subSequence(str.length()-4, str.length()));
        System.out.println("First 4 char String: "+str.subSequence(0, 4));
        System.out.println("website name: "+str.subSequence(4, 14));

        //substring vs subSequence
        System.out.println("substring == subSequence ? "
			+(str.substring(4, 14) == str.subSequence(4, 14)));

        System.out.println("substring equals subSequence ? "
			+(str.substring(4, 14).equals(str.subSequence(4, 14))));
    }
}
The output of the program will show the following:
Last 4 char String: .com
First 4 char String: www.
website name: journaldev
substring == subSequence ? false
substring equals subSequence ? true
Ideally you should always use the substring.

7. How to compare two strings in Java?

The class Stringinherits the interface Comparableand has two method options compareTo(). The method compareTo(String anotherString)compares the object Stringwith the received argument Stringlexicographically. If the current line precedes the received string, the method returns a negative integer, and if the string follows the received argument, it returns a positive integer integer. If the method returns 0, then the string has the same value, in which case the method equals(String str)will also return true. compareToIgnoreCase(String str): This method is similar to the previous one except that it ignores case. It uses CASE_INSENSITIVE_ORDER Comparator for case-insensitive comparison. If the return value is zero, then the method equalsIgnoreCase(String str)will also return true. Let's look at a small example to explain these methods:
public class StringCompareToExample {
    public static void main(String[] args) {
        String str = "ABC";
        System.out.println(str.compareTo("DEF"));
        System.out.println(str.compareToIgnoreCase("abc"));
    }
}
The program will output the following:
-3
0

8. How to convert a string to a character and vice versa?

This is a trick question because a string is a sequence of characters, so we can only convert it to a single character. We can use a method charAtto get the character located at a specified position or we can use a method toCharArray()to convert a string to an array of characters. A simple example showing how to convert string to character and character to string in Java.
import java.util.Arrays;

public class StringToCharToString {
    public static void main(String[] args) {
        //String to char array
        String str = "123";
        char[] chArr = str.toCharArray();
        System.out.println("String to char array: "+Arrays.toString(chArr));
        //String to char
        char c = str.charAt(1);
        System.out.println("String to char: "+c);
        //char to String
        String s = Character.toString(c);
        System.out.println("char to String: "+s);
        //удалить все заданные символы из строки
        System.out.println("removing all chars from String: "
                                 +removeCharFromString("1ABCD12DW", '1'));
    }

    private static String removeCharFromString(String str, char c) {
        return str.replaceAll(Character.toString( c ), "");
    }
}
The program will output the following:
String to char array: [1, 2, 3]
String to char: 2
char to String: 2
removing all chars from String: ABCD2DW

9. How to convert a string to a byte array and vice versa?

We can use a method getBytes()to convert a string to a byte array and we can use a constructor new String(byte[] arr)to convert a byte array to a string.
import java.util.Arrays;

public class StringByteArray {
     public static void main(String[] args) {
        String str = "www.journaldev.com";
        //преобразование String в byte array
        byte[] byteArr = str.getBytes();
        System.out.println("String to byte array : "+Arrays.toString(byteArr));
        //преобразование byte array и String
        String str1 = new String(byteArr);
        System.out.println("byte array to String : "+str1);
        //посмотрим, str и str1 одинаковые or нет
        System.out.println("str == str1? " + (str == str1));
        System.out.println("str.equals(str1)? " + (str.equals(str1)));
    }
}
The program will output the following:
String to byte array : [119, 119, 119, 46, 106, 111, 117, 114, 110, 97, 108, 100, 101, 118, 46, 99, 111, 109]
byte array to String : www.journaldev.com
str == str1? false
str.equals(str1)? true

10. Can we use a string in a switch construct?

This tricky question is used to test your knowledge of the current development of the language. Java 7 extends the switch statement to use strings; earlier versions of Java do not support this. If you are implementing a conditional flow for strings, you can use if-else conditions and you can use a switch statement if you are using Java 7 or later. A small example of using a string in a statement switchand another method that shows the same logic using conditions if-else.
public class SwitchStringExample {

    public static void main(String[] args) {
        printColorUsingSwitch("red");
        printColorUsingIf("red");
        // оператор switch регистрозависимый
        printColorUsingSwitch("RED");
        printColorUsingSwitch(null);
    }

    private static void printColorUsingIf(String color) {
        if (color.equals("blue")) {
            System.out.println("BLUE");
        } else if (color.equals("red")) {
            System.out.println("RED");
        } else {
            System.out.println("INVALID COLOR CODE");
        }
    }

    private static void printColorUsingSwitch(String color) {
        switch (color) {
        case "blue":
            System.out.println("BLUE");
            break;
        case "red":
            System.out.println("RED");
            break;
        default:
            System.out.println("INVALID COLOR CODE");
        }
    }
}
The program will output the following:
RED
RED
INVALID COLOR CODE
Exception in thread "main"
java.lang.NullPointerException
    at com.journaldev.util.SwitchStringExample.printColorUsingSwitch(SwitchStringExample.java:24)
    at com.journaldev.util.SwitchStringExample.main(SwitchStringExample.java:10)
Key usage points switchfor strings in Java.
  • using strings in the design switchmakes the code more readable by eliminating multiple chains of conditions if-else.
  • strings in are switchcase sensitive, the example above shows this.
  • operator switchuses a method String.equals()to compare the resulting value with case values , so add a check for NULL to avoid NullPointerException.
  • According to the Java 7 documentation for strings in switch, the Java compiler generates more efficient bytecode for strings in a construct switchthan for concatenated conditions if-else.
  • make sure this will be used with Java 7 or later, otherwise you will get xception.

11. Write a program that prints all permutations of a string.

This is a tricky question and we have to use recursion to find all the permutations of a string, for example the permutations of “AAB” could be “AAB”, “ABA” and “BAA”. We also need to use Set to make sure we don't have duplicate rows. To get all the permutations, we first take the first character of the string and rearrange the remaining characters. If String = “ABC” First character char = A and remaining permutations BC and CB. Now we can insert the first character into the available positions in the permutations. BC -> ABC, BAC, BCA CB -> ACB, CAB, CBA Example program:
import java.util.HashSet;
import java.util.Set;

public class StringHelper {
    public static Set<String> permutationFinder(String str) {
        Set<String> perm = new HashSet<String>();
        //Handling error scenarios
        if (str == null) {
            return null;
        } else if (str.length() == 0) {
            perm.add("");
            return perm;
        }
        char initial = str.charAt(0); // первый символ
        String rem = str.substring(1); // полная строка без первого символа
        Set<String> words = permutationFinder(rem);
        for (String strNew : words) {
            for (int i = 0;i<=strNew.length();i++){
                perm.add(charInsert(strNew, initial, i));
            }
        }
        return perm;
    }

    public static String charInsert(String str, char c, int j) {
        String begin = str.substring(0, j);
        String end = str.substring(j);
        return begin + c + end;
    }

    public static void main(String[] args) {
        String s = "AAC";
        String s1 = "ABC";
        String s2 = "ABCD";
        System.out.println("\nPermutations for " + s + " are: \n" + permutationFinder(s));
        System.out.println("\nPermutations for " + s1 + " are: \n" + permutationFinder(s1));
        System.out.println("\nPermutations for " + s2 + " are: \n" + permutationFinder(s2));
    }
}
Program output:
Permutations for AAC are:
[AAC, ACA, CAA]

Permutations for ABC are:
[ACB, ABC, BCA, CBA, CAB, BAC]

Permutations for ABCD are:
[DABC, CADB, BCAD, DBAC, BACD, ABCD, ABDC, DCBA, ADBC, ADCB, CBDA, CBAD, DACB, ACBD, CDBA, CDAB, DCAB, ACDB, DBCA, BDAC, CABD, BADC, BCDA, BDCA]
Continuation of the article
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet