本文共 17897 字,大约阅读时间需要 59 分钟。
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:
这是在新选项卡中打开的链接:
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对象的方式。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 useintern()
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,则返回引用。 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 butStringBuffer
and StringBuilder
class has reverse method that we can use to check if String is palindrome or not. 如果字符串的值在反转时相同,则称其为回文。 例如,“ aba”是回文字符串。
String类没有提供任何方法来反转String,但是StringBuffer
和StringBuilder
类具有可以用来检查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; }
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), ""); }
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类的toUpperCase
和toLowerCase
方法来获取全部大写或小写的String。 这些方法具有一个接受Locale参数并使用该Locale规则将String转换为大写或小写的变体。
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 example.Java 1.4引入了CharSequence接口,而String实现了此接口,这是在String类中实现subSequence方法的唯一原因。 在内部,它调用String子字符串方法。
查看此文章以获取示例。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.
compareToIgnoreCase(String str):此方法类似于第一个方法,但它忽略大小写。 它使用String CASE_INSENSITIVE_ORDER比较器进行不区分大小写的比较。 如果值为零,则equalsIgnoreCase(String str)
也将返回true。
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.
这是一个棘手的问题,因为String是字符序列,所以我们不能将其转换为单个字符。 我们可以使用charAt
方法获取给定索引处的字符,也可以使用toCharArray()
方法将String转换为字符数组。
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.
我们可以使用String getBytes()
方法将String转换为字节数组,并且可以使用String构造函数new String(byte[] arr)
将字节数组转换为String。
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 example.
查看此文章以获取示例。
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 .这是一个棘手的问题,我们需要使用递归来查找字符串的所有排列,例如,“ AAB”排列将是“ AAB”,“ ABA”和“ BAA”。
我们还需要使用Set来确保没有重复的值。 检查此文章以获取完整的程序以 。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 .字符串中可以包含回文字符串,要在给定的字符串中找到最长的回文是一个编程问题。
检查此职位的完整程序,以找到最长的 。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 .
Read this post for benchmarking of .检查这篇文章以获取有关详细信息。
阅读这篇文章,了解基准测试。There are several benefits of String because it’s immutable and final.
字符串有几个好处,因为它是不变的且是最终的。
Check this post to get more details .
检查这篇文章以获得更多详细信息, 。
We can use split(String regex)
to split the String into String array based on the provided regular expression.
我们可以使用split(String regex)
根据提供的正则表达式将String拆分为String数组。
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带来的安全威胁。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.
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
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 .顾名思义,字符串池是存储在Java堆内存中的字符串池。 我们知道String是Java中的一个特殊类,我们可以使用new运算符以及提供双引号中的值来创建String对象。
查看此帖子以获取有关更多详细信息。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对象的引用。
此方法总是返回一个与该字符串具有相同内容的字符串,但是可以保证该字符串来自唯一字符串池。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 .字符串是不可变的,因此我们无法在程序中更改其值。 因此,它是线程安全的,可以在多线程环境中安全使用。
查看此文章以获取 。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键的原因。
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。 不要与==比较运算符混淆。
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 .
上面的程序不会编译错误,因为“方法foo(String)对于Test类型是不明确的”。 为了完全澄清,请阅读 。
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。
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。
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();
那么输出将为真。
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面试有帮助,请让我知道是否错过了任何事情。
翻译自:
java 字符串面试
转载地址:http://xvlzd.baihongyu.com/