java 字符串面试_Java字符串面试问答

java 字符串面试

String is one of the most widely used Java Class. Here I am listing some important Java String Interview Questions and Answers.

字符串是使用最广泛的Java类之一。 在这里,我列出了一些重要的Java String Interview问答

This will be very helpful to get complete knowledge of String and tackle any questions asked related to String in an interview.

这将有助于您全面了解String并解决面试中与String有关的任何问题。

Here is the link that opens in a new tab: Java String Quiz

这是在新选项卡中打开的链接: Java字符串测验

Java字符串面试问题 (Java String Interview Questions)

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

    Java中的字符串是什么? 字符串是数据类型吗?
  2. What are different ways to create String Object?

    有什么不同的方法来创建字符串对象?
  3. Write a method to check if input String is Palindrome?

    编写一种方法来检查输入的String是否为回文?
  4. Write a method that will remove given character from the String?

    写一个方法来从字符串中删除给定的字符?
  5. How can we make String upper case or lower case?

    如何使String大写或小写?
  6. What is String subSequence method?

    什么是String subSequence方法?
  7. How to compare two Strings in java program?

    如何在Java程序中比较两个字符串?
  8. How to convert String to char and vice versa?

    如何将String转换为char,反之亦然?
  9. How to convert String to byte array and vice versa?

    如何将字符串转换为字节数组,反之亦然?
  10. Can we use String in switch case?

    我们可以在切换情况下使用String吗?
  11. Write a program to print all permutations of String?

    编写程序以打印String的所有排列?
  12. Write a function to find out longest palindrome in a given string?

    写一个函数找出给定字符串中最长的回文?
  13. Difference between String, StringBuffer and StringBuilder?

    String,StringBuffer和StringBuilder之间的区别?
  14. Why String is immutable or final in Java

    为什么String在Java中是不可变的或最终的
  15. How to Split String in java?

    如何在Java中拆分字符串?
  16. Why Char array is preferred over String for storing password?

    为什么用Char数组而不是String来首选存储密码?
  17. How do you check if two Strings are equal in Java?

    如何检查Java中两个字符串是否相等?
  18. What is String Pool?

    什么是字符串池?
  19. What does String intern() method do?

    String intern()方法有什么作用?
  20. Does String is thread-safe in Java?

    String在Java中是否是线程安全的?
  21. Why String is popular HashMap key in Java?

    为什么String是Java中流行的HashMap键?
  22. String Programming Questions

    字符串编程问题

Java中的字符串是什么? 字符串是数据类型吗? (What is String in Java? String is a data type?)

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.

String是Java中的一个类,并在java.lang包中定义。 它不是像int和long这样的原始数据类型。 字符串类表示字符串。 几乎所有Java应用程序都使用String,关于String我们应该了解一些有趣的事实。 Java中不可变的字符串和Java中的final字符串,JVM使用字符串池存储所有字符串对象。
关于String的其他一些有趣的事情是我们可以使用双引号和“ +”运算符的重载来实例化String对象的方式。

有什么不同的方法来创建字符串对象? (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.

我们可以像任何普通的Java类一样使用new运算符创建String对象,也可以使用双引号创建String对象。 String类中有几个构造函数可用于从char数组,字节数组,StringBuffer和StringBuilder中获取String。

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

当我们使用双引号创建String时,JVM会在String池中查找是否以相同的值存储了其他String。 如果找到,它将仅返回对该String对象的引用,否则它将创建一个具有给定值的新String对象并将其存储在String池中。
当我们使用new运算符时,JVM将创建String对象,但不要将其存储到String Pool中。 我们可以使用intern()方法将String对象存储到String池中,或者如果池中已经存在具有相等值的String,则返回引用。

编写一种方法来检查输入的String是否为回文? (Write a method to check if input String is Palindrome?)

A String is said to be Palindrome if it’s value is same when reversed. For example “aba” is a Palindrome String.
String class doesn’t provide any method to reverse the String but StringBuffer and StringBuilder class has reverse method that we can use to check if String is palindrome or not.

如果字符串的值在反转时相同,则称其为回文。 例如,“ aba”是回文字符串。
String类没有提供任何方法来反转String,但是StringBufferStringBuilder类具有可以用来检查String是否是回文的反转方法。

private static boolean isPalindrome(String str) {
        if (str == null)
            return false;
        StringBuilder strBuilder = new StringBuilder(str);
        strBuilder.reverse();
        return strBuilder.toString().equals(str);
    }

Sometimes interviewer asks not to use any other class to check this, in that case, we can compare characters in the String from both ends to find out if it’s palindrome or not.

有时,面试官会要求不要使用任何其他类来检查此情况,在这种情况下,我们可以从两端比较String中的字符以找出是否是回文。

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;
    }

写一个方法来从字符串中删除给定的字符? (Write a method that will remove given character from the String?)

We can use replaceAll method to replace all the occurance of a String with another String. The important point to note is that it accepts String as argument, so we will use Character class to create String and use it to replace all the characters with empty String.

我们可以使用replaceAll方法将一个String的所有出现替换为另一个String。 需要注意的重要一点是它接受String作为参数,因此我们将使用Character类来创建String并将其用空String替换所有字符。

private static String removeChar(String str, char c) {
        if (str == null)
            return null;
        return str.replaceAll(Character.toString(c), "");
    }

如何使String大写或小写? (How can we make String upper case or lower case?)

We can use String class toUpperCase and toLowerCase methods to get the String in all upper case or lower case. These methods have a variant that accepts Locale argument and use that locale rules to convert String to upper or lower case.

我们可以使用String类的toUpperCasetoLowerCase方法来获取全部大写或小写的String。 这些方法具有一个接受Locale参数并使用该Locale规则将String转换为大写或小写的变体。

什么是String subSequence方法? (What is String subSequence method?)

Java 1.4 introduced CharSequence interface and String implements this interface, this is the only reason for the implementation of subSequence method in String class. Internally it invokes the String substring method.
Check this post for String subSequence example.

Java 1.4引入了CharSequence接口,而String实现了此接口,这是在String类中实现subSequence方法的唯一原因。 在内部,它调用String子字符串方法。
查看此文章以获取String subSequence示例。

如何在Java程序中比较两个字符串? (How to compare two Strings in java program?)

Java String implements Comparable interface and it has two variants of compareTo() methods.

Java String实现Comparable接口,它具有compareTo()方法的两个变体。

compareTo(String anotherString) method compares the String object with the String argument passed lexicographically. If String object precedes the argument passed, it returns negative integer and if String object follows the argument String passed, it returns a positive integer. It returns zero when both the String have the same value, in this case equals(String str) method will also return true.

compareTo(String anotherString)方法将String对象与按字典顺序传递的String参数进行比较。 如果String对象在传递的参数之前,则返回负整数;如果String对象在传递的参数String之后,则返回正整数。 当两个String具有相同的值时,它将返回零,在这种情况下, equals(String str)方法也将返回true。

compareToIgnoreCase(String str): This method is similar to the first one, except that it ignores the case. It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison. If the value is zero then equalsIgnoreCase(String str) will also return true.
Check this post for String compareTo example.

compareToIgnoreCase(String str):此方法类似于第一个方法,但它忽略大小写。 它使用String CASE_INSENSITIVE_ORDER比较器进行不区分大小写的比较。 如果值为零,则equalsIgnoreCase(String str)也将返回true。
在这篇文章中查看String compareTo示例。

如何将String转换为char,反之亦然? (How to convert String to char and vice versa?)

This is a tricky question because String is a sequence of characters, so 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.
Check this post for sample program on converting String to character array to String.

这是一个棘手的问题,因为String是字符序列,所以我们不能将其转换为单个字符。 我们可以使用charAt方法获取给定索引处的字符,也可以使用toCharArray()方法将String转换为字符数组。
在这篇文章中查看有关将String转换为String的字符数组的示例程序。

如何将字符串转换为字节数组,反之亦然? (How to convert String to byte array and vice versa?)

We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.
Check this post for String to byte array example.

我们可以使用String getBytes()方法将String转换为字节数组,并且可以使用String构造函数new String(byte[] arr)将字节数组转换为String。
检查这篇文章中的字符串到字节数组示例。

我们可以在切换情况下使用String吗? (Can we use String in switch case?)

This is a tricky question used to check your knowledge of current Java developments. Java 7 extended the capability of switch case to use Strings also, earlier Java versions don’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.

这是一个棘手的问题,用于检查您对当前Java开发的了解。 Java 7将切换大小写的功能扩展为也使用Strings,早期的Java版本不支持此功能。
如果要为字符串实现条件流,则可以使用if-else条件,如果使用的是Java 7或更高版本,则可以使用切换用例。

Check this post for Java Switch Case String example.

查看此文章以获取Java Switch Case String示例。

编写程序以打印String的所有排列? (Write a program to print all permutations of String?)

This is a tricky question and we need to use recursion to find all the permutations of a String, for example “AAB” permutations will be “AAB”, “ABA” and “BAA”.
We also need to use Set to make sure there are no duplicate values.
Check this post for complete program to find all permutations of String.

这是一个棘手的问题,我们需要使用递归来查找字符串的所有排列,例如,“ AAB”排列将是“ AAB”,“ ABA”和“ BAA”。
我们还需要使用Set来确保没有重复的值。
检查此文章以获取完整的程序以查找String的所有排列

写一个函数找出给定字符串中最长的回文? (Write a function to find out longest palindrome in a given string?)

A String can contain palindrome strings in it and to find longest palindrome in given String is a programming question.
Check this post for complete program to find longest palindrome in a String.

字符串中可以包含回文字符串,要在给定的字符串中找到最长的回文是一个编程问题。
检查此职位的完整程序,以在String中找到最长的回文

String,StringBuffer和StringBuilder之间的区别? (Difference between String, StringBuffer and StringBuilder?)

The 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 – StringBuffer and StringBuilder.
StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So in a multi-threaded environment, we should use StringBuffer but in the single-threaded environment, we should use StringBuilder.
StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.

该字符串在Java中是不可变的,并且是最终的,因此,每当我们执行String操作时,它都会创建一个新的String。 字符串操作消耗资源,因此java为String操作提供了两个实用程序类-StringBuffer和StringBuilder。
StringBuffer和StringBuilder是可变的类。 StringBuffer操作是线程安全的,并且在StringBuilder操作不是线程安全的情况下是同步的。 因此,在多线程环境中,我们应该使用StringBuffer,但是在单线程环境中,我们应该使用StringBuilder。
由于没有同步开销,因此StringBuilder的性能比StringBuffer快。

Check this post for extensive details about String vs StringBuffer vs StringBuilder.
Read this post for benchmarking of StringBuffer vs StringBuilder.

检查这篇文章以获取有关String vs StringBuffer vs StringBuilder的详细信息。
阅读这篇文章,了解StringBuffer与StringBuilder的基准测试。

为什么String在Java中是不可变的或最终的 (Why String is immutable or final in Java)

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

字符串有几个好处,因为它是不变的且是最终的。

  • String Pool is possible because String is immutable in java.

    字符串池是可能的,因为字符串在Java中是不可变的。
  • 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.

    它提高了安全性,因为任何黑客都无法更改其值,并且它用于存储敏感信息,例如数据库用户名,密码等。
  • Since String is immutable, it’s safe to use in multi-threading and we don’t need any synchronization.

    由于String是不可变的,因此在多线程中使用是安全的,并且我们不需要任何同步。
  • Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.

    字符串用于java类加载器中,并且不变性提供了确保正确的类正在由类加载器加载的安全性。

Check this post to get more details why String is immutable in java.

检查这篇文章以获得更多详细信息, 为什么String在Java中是不可变的

如何在Java中拆分字符串? (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.
Learn more at java String split.

我们可以使用split(String regex)根据提供的正则表达式将String拆分为String数组。
java String split中了解更多信息。

为什么用Char数组而不是String来首选存储密码? (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 a 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.

字符串在Java中是不可变的,并存储在字符串池中。 一旦创建,它将一直保留在池中,直到除非进行垃圾收集为止,所以即使我们使用密码完成操作,它也可以在内存中使用更长的时间,并且无法避免。 这是一种安全风险,因为任何有权访问内存转储的人都可以找到明文形式的密码。
如果我们使用char数组存储密码,则在完成密码设置后可以将其设置为空白。 因此,我们可以控制它在内存中的可用时间,从而避免String带来的安全威胁。

如何检查Java中两个字符串是否相等? (How do you check if two Strings are equal in Java?)

There are two ways to check if two Strings are equal or not – using “==” operator or using equals method. When we use “==” operator, it checks for the value of String as well as the reference but in our programming, most of the time we are checking equality of String for value only. So we should use the equals method to check if two Strings are equal or not.
There is another function equalsIgnoreCase that we can use to ignore case.

有两种检查两个字符串是否相等的方法–使用“ ==”运算符或使用equals方法。 当我们使用“ ==”运算符时,它会检查String的值以及引用,但是在我们的编程中,大多数时候我们只检查String的相等性是否为value。 因此,我们应该使用equals方法检查两个String是否相等。
还有另一个函数equalsIgnoreCase可以用来忽略大小写。

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

什么是字符串池? (What is String Pool?)

As the name suggests, String Pool is a pool of Strings stored in Java heap memory. We know that String is a special class in Java and we can create String object using new operator as well as providing values in double quotes.
Check this post for more details about String Pool.

顾名思义,字符串池是存储在Java堆内存中的字符串池。 我们知道String是Java中的一个特殊类,我们可以使用new运算符以及提供双引号中的值来创建String对象。
查看此帖子以获取有关String Pool的更多详细信息。

String intern()方法有什么作用? (What does String intern() method do?)

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
This method always returns a String that has the same contents as this string but is guaranteed to be from a pool of unique strings.

调用intern方法时,如果池已经包含等于equals(Object)方法确定的此String对象的字符串,则返回池中的字符串。 否则,将此String对象添加到池中,并返回对此String对象的引用。
此方法总是返回一个与该字符串具有相同内容的字符串,但是可以保证该字符串来自唯一字符串池。

String在Java中是否是线程安全的? (Does String is thread-safe in Java?)

Strings are immutable, so we can’t change it’s value in program. Hence it’s thread-safe and can be safely used in multi-threaded environment.
Check this post for Thread Safety in Java.

字符串是不可变的,因此我们无法在程序中更改其值。 因此,它是线程安全的,可以在多线程环境中安全使用。
查看此文章以获取Java中的线程安全性

为什么String是Java中流行的HashMap键? (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 the 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.

由于String是不可变的,因此其哈希码将在创建时进行缓存,因此无需再次计算。 这使其成为Map中密钥的理想候选者,并且其处理速度比其他HashMap密钥对象快。 这就是为什么String主要用作Object作为HashMap键的原因。

字符串编程问题 (String Programming Questions)

  1. What is the output of below program?
    package com.journaldev.strings;
    
    public class StringTest {
    
    	public static void main(String[] args) {
    		String s1 = new String("pankaj");
    		String s2 = new String("PANKAJ");
    		System.out.println(s1 = s2);
    	}
    
    }

    It’s a simple yet tricky program, it will print “PANKAJ” because we are assigning s2 String to s1. Don’t get confused with == comparison operator.

    这是一个简单但棘手的程序,它将打印“ PANKAJ”,因为我们将s2字符串分配给s1。 不要与==比较运算符混淆。

  2. What is the output of below program?
    package com.journaldev.strings;
    
    public class Test {
    
    	 public void foo(String s) {
    	 System.out.println("String");
    	 }
    
    	 public void foo(StringBuffer sb){
    	 System.out.println("StringBuffer");
    	 }
    
    	 public static void main(String[] args) {
    		new Test().foo(null);
    	}
    
    }

    The above program will not compile with error as “The method foo(String) is ambiguous for the type Test”. For complete clarification read Understanding the method X is ambiguous for the type Y error.

    上面的程序不会编译错误,因为“方法foo(String)对于Test类型是不明确的”。 为了完全澄清,请阅读了解方法X对于类型Y错误是模棱两可的

  3. What is the output of below code snippet?
    String s1 = new String("abc");
    String s2 = new String("abc");
    System.out.println(s1 == s2);

    It will print false because we are using new operator to create String, so it will be created in the heap memory and both s1, s2 will have different reference. If we create them using double quotes, then they will be part of string pool and it will print true.

    因为我们正在使用new运算符创建String,所以它将显示false ,因此它将在堆内存中创建,并且s1,s2都有不同的引用。 如果我们使用双引号创建它们,则它们将成为字符串池的一部分,并且将显示true。

  4. What will be output of below code snippet?
    String s1 = "abc";
    StringBuffer s2 = new StringBuffer(s1);
    System.out.println(s1.equals(s2));

    It will print false because s2 is not of type String. If you will look at the equals method implementation in the String class, you will find a check using instanceof operator to check if the type of passed object is String? If not, then return false.

    因为s2不是String类型,它将打印false。 如果您要查看String类中的equals方法实现,则会发现使用instanceof运算符进行检查以检查传递的对象的类型是否为String? 如果不是,则返回false。

  5. What will be the output of below program?
    String s1 = "abc";
    String s2 = new String("abc");
    s2.intern();
    System.out.println(s1 ==s2);

    It’s a tricky question and output will be false. We know that intern() method will return the String object reference from the string pool, but since we didn’t assigned it back to s2, there is no change in s2 and hence both s1 and s2 are having different reference. If we change the code in line 3 to s2 = s2.intern(); then output will be true.

    这是一个棘手的问题,输出将为false 。 我们知道intern()方法将从字符串池中返回String对象引用,但是由于我们没有将其分配回s2,因此s2没有变化,因此s1和s2都有不同的引用。 如果我们将第3行中的代码更改为s2 = s2.intern(); 那么输出将为真。

  6. How many String objects got created in below code snippet?
    String s1 = new String("Hello");  
    String s2 = new String("Hello");

    The answer is 3.
    First – line 1, “Hello” object in the string pool.
    Second – line 1, new String with value “Hello” in the heap memory.
    Third – line 2, new String with value “Hello” in the heap memory. Here “Hello” string from string pool is reused.

    答案是3。
    首先-字符串池中的第1行,“ Hello”对象。
    第二行–第1行,堆内存中值为“ Hello”的新字符串。
    第三行–第2行,堆内存中值为“ Hello”的新字符串。 在这里,字符串池中的“ Hello”字符串被重用。

I hope that the questions listed here will help you in Java interviews, please let me know if I have missed anything.

我希望这里列出的问题对Java面试有帮助,请让我知道是否错过了任何事情。

进一步阅读 (Further Reading)

  1. Java Programming Questions

    Java编程问题
  2. String Programs in Java

    Java中的字符串程序
  3. Core Java Interview Questions

    Java核心面试问题
  4. Java Interview Questions

    Java面试问题

翻译自: https://www.journaldev.com/1321/java-string-interview-questions-and-answers

java 字符串面试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值