Java字符串面試問題和答案

介紹

String 是最常用的 Java 類別之一。本文提供了一些有關 String 的練習問題和答案,以幫助您準備面試。

您還可以嘗試 Java String 測驗 來測試您對 String 類別的了解程度。

在 Java 中,String 類別是什麼?String 是一種資料型別嗎?

String 是 Java 中的一個類別,並且在 java.lang 套件中定義。它不像 intlong 這樣的原始資料型別。String 類別代表字元字串。幾乎所有的 Java 應用程式都會使用到 String。在 Java 中,String 是不可變的 (immutable) 和 final 的,而 JVM 使用字串池 (string pool) 來儲存所有的 String 物件。您可以使用雙引號實例化一個 String 物件,也可以重載 + 運算子進行字串串接。

有哪些不同的方法可以在Java中创建字符串对象?

您可以使用new运算符创建字符串对象,也可以使用双引号创建字符串对象。例如:

String str = new String("abc");
String str1 = "abc";

String类中有几个构造函数可用于从char数组byte数组StringBufferStringBuilder获取字符串。

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

撰寫一個 Java 方法來檢查輸入的字串是否為回文。

A string is a palindrome if its value is the same when reversed. For example, aba is a palindrome string. The String class doesn’t provide any method to reverse the string but the StringBuffer and StringBuilder classes have a reverse() method that you can use to check whether a string is a palindrome. For example:

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

有時,面試官可能要求您不使用其他類別來檢查回文。在這種情況下,您可以從字串的兩端比較字符,以確定它是否為回文。例如:

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

撰寫一個 Java 方法,從字串物件中移除指定的字符。

我們可以使用 replaceAll 方法將所有出現的字串替換為另一個字串。重要的一點是 replaceAll() 接受 String 作為參數,因此您可以使用 Character 類別來創建一個字串並將其用於將所有字符替換為空字串。

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

如何在 Java 中將字串轉換為大寫或小寫?

您可以使用String类的toUpperCase和toLowerCase方法将字符串对象转换为全大写或全小写。这些方法有一个变体,接受一个Locale参数,并使用给定的locale规则将字符串转换为大写或小写。

String subSequence方法是什么意思?

Java 1.4引入了CharSequence接口,String类实现了这个接口,这就是为什么String类有subSequence方法。在内部,subSequence方法调用了String substring方法。

如何在Java程序中比较两个字符串?

Java String 實現了 Comparable 接口,該接口有兩個 compareTo() 方法的變體。 compareTo(String anotherString) 方法按字典順序比較 String 對象和傳遞的 String 參數。如果 String 對象在參數之前,它返回一個負整數,如果 String 對象在參數之後,它返回一個正整數。當兩個 String 對象的值相同時,它返回零。在這種情況下,equals(String str) 方法也返回 truecompareToIgnoreCase(String str) 方法與第一個方法類似,只是忽略大小寫。它使用 ComparatorCASE_INSENSITIVE_ORDER 進行不區分大小寫的比較。如果值為零,則 equalsIgnoreCase(String str) 也將返回 true。

如何將 String 轉換為字符數組(character array)?

A String object is a sequence of characters, so you can’t convert it to a single character. You can use use the charAt method to get the character at given index or you can use the toCharArray() method to convert a string to character array. Learn more about converting a string to a character array.

如何將 String 轉換為字节数組(byte array)?

您可以使用getBytes()方法将String对象转换为字节数组,并使用构造函数new String(byte[] arr)将字节数组转换为String对象。了解更多关于将字符串转换为字节数组的信息。

在Java中可以使用String在switch case中吗?

Java 7扩展了switch case对String的支持;之前的Java版本不支持。如果您要实现对字符串的条件流程控制,您可以使用if-else条件,如果您使用的是Java 7或更高版本,则可以使用switch case。了解更多关于Java switch case字符串的信息。

编写一个Java程序来打印字符串的所有排列。

您需要使用遞迴來找出字符串的所有排列組合。例如,字符串 AAB 的排列組合是 AABABABAA。您還需要使用 Set 來確保沒有重複的值。了解更多關於找出字符串的所有排列組合的資訊。

寫一個 Java 函數來找到給定字符串中最長的迴文串。

A string can contain palindrome substrings within it. Learn more about how to find the longest palindrome substring in a string.

StringStringBufferStringBuilder 在 Java 中有哪些區別?

A String object is immutable and final in Java, so whenever you manipulate a String object, it creates a new String object. String manipulations are resource consuming, so Java provides two utility classes for string manipulations, StringBuffer and StringBuilder.

StringBufferStringBuilder是可變類。 StringBuffer操作是線程安全和同步的,而StringBuilder操作則不是線程安全的。在多線程環境中應該使用StringBuffer,在單線程環境中應該使用StringBuilder。由於不需要同步的開銷,StringBuilder的性能比StringBuffer更快。

了解更多關於StringStringBufferStringBuilder之間的差異以及StringBufferStringBuilder的基準測試

為什麼在Java中String是不可變的?

String在Java中是不可變的,這帶來了幾個好處:

  • 因為String在Java中是不可變的,所以可以使用字符串池。
  • 它增加了安全性,因為任何黑客都不能更改它的值,它用於存儲敏感信息,例如數據庫的用戶名或密碼。
  • 由於String是不可變的,在多線程中使用它是安全的,並且不需要任何同步。
  • 字串在Java類加載器中使用,且不可變性確保正確的類被ClassLoader類加載。

了解更多關於為什麼在Java中String是不可變的

如何在Java中分割字串?

你可以使用split(String regex)根據提供的正則表達式將字串分割為字串陣列。

為什麼在Java中使用字符陣列而不是String來存儲密碼?

A String object is immutable in Java and is stored in the string pool. Once it’s created it stays in the pool until garbage collection completes, so even though you’re done with the password it’s available in memory for longer duration. It’s a security risk because anyone having access to memory dump can find the password as clear text. If you use a character array to store password, you can set it to blank once you’re done with it. You can control for how long it’s available in memory and that avoids the security threat.

如何在Java中檢查兩個字串是否相等?

有兩種方法可以檢查兩個字串是否相等。您可以使用==運算符或equals()方法。當您使用==運算符時,它會檢查String的值以及物件參考。在Java編程中,通常只想檢查String值的相等性。在這種情況下,應該使用equals()方法來檢查兩個Strings是否相等。還有一個名為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

什麼是Java中的字符串池?

字符串池是存儲在Java堆內存中的一個String對象池。String是Java中的一個特殊類,您可以使用new運算符創建String對象,也可以通過在雙引號中提供值來創建。了解有關Java字符串池的更多信息。

Java的String intern()方法是做什麼用的?

調用intern()方法時,如果字符串池已經包含一個與此String對象相等的String(由equals(Object)方法確定),則返回池中的字符串。否則,將此String對象添加到池中並返回對此String對象的引用。該方法始終返回具有與此String相同內容的String對象,但保證來自唯一字符串池中。

在Java中,String是線程安全的嗎?

A String object is immutable, so you can’t change its value after creation. This makes the String object thread-safe and so it can be safely used in a multi-threaded environment. Learn more about thread Safety in Java.

由於 String 物件是不可變的,它的哈希碼在創建時被緩存,並且不需要再次計算。這使得它成為 Map 中的鍵的絕佳候選者,因為它的處理速度比其他 HashMap 鍵對象更快。

猜測輸出結果

通過猜測以下 Java 代碼片段的輸出來測試自己。

public class StringTest {
    
  	public static void main(String[] args) {
   		String s1 = new String("digitalocean");
   		String s2 = new String("DIGITALOCEAN");
   		System.out.println(s1 = s2);
   	}
    
}
Output
DIGITALOCEAN

輸出結果是 DIGITALOCEAN,因為代碼將 String s2 的值賦給了 String s1= 是一個賦值運算符,它將 y 的值賦給 x,格式為 (x = y)== 是一個比較運算符,用於檢查兩個字符串的引用對象是否相同。


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);
   	}
    
}
Output
Test.java:12: error: reference to foo is ambiguous
   		new Test().foo(null);
   		           ^
  both method foo(String) in Test and method foo(StringBuffer) in Test match

此代碼導致編譯時錯誤,因為兩個 foo 方法具有相同的名稱,而在 main 中調用 foo 方法時傳遞了 null。編譯器不知道應該調用哪個方法。您還可以參考 方法 X is ambiguous for the type Y error


String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2);
Output
false

輸出是false,因為程式碼使用new運算子在堆記憶體中建立String物件,所以它們有不同的參考。如果只使用雙引號建立字串,它們將在字串池中,並且會輸出true


String s1 = "abc";
StringBuffer s2 = new StringBuffer(s1);
System.out.println(s1.equals(s2));
Output
false

輸出是false,因為s2的類型不是String。在String類別的equals()方法實作中,使用instanceof運算子檢查傳遞物件的類型是否為String,如果不是String,則返回false


String s1 = "abc";
String s2 = new String("abc");
s2.intern();
System.out.println(s1 == s2);
Output
false

輸出是falseintern()方法從字串池中返回String物件的參考。但是,程式碼沒有將其重新賦值給s2,因此s2沒有變化,所以s1s2具有不同的物件參考。如果將第3行的程式碼更改為s2 = s2.intern();,則輸出將為true

以下程式碼創建了多少個String物件?

String s1 = new String("Hello");  
String s2 = new String("Hello");
Answer

答案是三。第一行的代码创建了一个字符串池中值为”Hello”的String对象(第一个对象),然后创建了一个堆内存中值为”Hello”的新String对象(第二个对象)。第二行的代码在堆内存中创建了一个值为”Hello”的新String对象(第三个对象),并重用了字符串池中的”Hello”字符串。

結論

在本文中,您回顧了一些關於String的Java面試問題。

推薦閱讀:

Java編程問題
Java中的字符串程序

Source:
https://www.digitalocean.com/community/tutorials/java-string-interview-questions-and-answers