1. Pengenalan
The String kelas adalah salah satu kelas yang paling banyak digunakan di Jawa, yang mendorong pereka bahasa untuk merawat khas. Tingkah laku istimewa ini menjadikannya salah satu topik paling hangat dalam temu ramah Java.
Dalam tutorial ini, kita akan membahas beberapa soalan temu ramah yang paling biasa mengenai String .
2. Asas String
Bahagian ini mengandungi soalan yang berkaitan dengan struktur dan memori dalaman String .
S1. Apakah Rentetan di Jawa?
Di Jawa, String diwakili secara dalaman oleh array nilai byte (atau nilai char sebelum JDK 9).
Dalam versi hingga dan termasuk Java 8, String terdiri dari susunan karakter Unicode yang tidak dapat diubah. Walau bagaimanapun, kebanyakan watak memerlukan hanya 8 bit (1 bait) untuk mewakili mereka dan bukannya 16 bit ( saiz char ).
Untuk meningkatkan penggunaan dan prestasi memori, Java 9 memperkenalkan Strings kompak. Ini bermaksud bahawa jika String hanya mengandungi aksara 1-byte, ia akan diwakili menggunakan pengekodan Latin-1 . Sekiranya String mengandungi sekurang-kurangnya 1 watak multi-bait, ia akan ditunjukkan sebagai 2 bait per watak menggunakan pengekodan UTF-16.
Dalam C dan C ++, String juga merupakan array karakter, tetapi di Java, objek itu terpisah dengan API sendiri.
S2. Bagaimana Kita Dapat Membuat Objek String di Java ?
java.lang.String mentakrifkan 13 cara yang berbeza untuk membuat Rentetan . Walaupun begitu, terdapat dua:
- Melalui literal String :
String s = "abc";
- Melalui kata kunci baru :
String s = new String("abc");
Semua literal String di Java adalah contoh kelas String .
S3. Adakah String adalah Jenis Primitif atau Berasal?
String adalah jenis yang berasal kerana mempunyai keadaan dan tingkah laku. Sebagai contoh, ia mempunyai kaedah seperti substring () , indexOf () , dan sama dengan (), yang tidak dapat dimiliki oleh primitif.
Tetapi, kerana kita semua sering menggunakannya, ia mempunyai beberapa ciri khas yang membuatnya terasa seperti primitif:
- Walaupun rentetan tidak disimpan di timbunan panggilan seperti primitif, ia disimpan di kawasan memori khas yang disebut kumpulan tali
- Seperti primitif, kita boleh menggunakan operator + pada rentetan
- Dan sekali lagi, seperti primitif, kita dapat membuat contoh String tanpa kata kunci baru
S4. Apakah Faedah String Tidak Berubah?
Menurut wawancara oleh James Gosling, rentetan tidak berubah untuk meningkatkan prestasi dan keselamatan.
Dan sebenarnya, kita melihat beberapa faedah untuk mempunyai rentetan yang tidak berubah:
- Kumpulan tali hanya dapat dilakukan jika tali, setelah dibuat, tidak akan pernah berubah, kerana tali itu seharusnya digunakan kembali
- Kod dengan selamat dapat meneruskan rentetan ke kaedah lain , mengetahui bahawa ia tidak dapat diubah dengan kaedah itu
- Secara automatik menjadikan kelas ini selamat untuk benang
- Oleh kerana kelas ini selamat di thread, tidak perlu menyegerakkan data biasa , yang seterusnya meningkatkan prestasi
- Oleh kerana mereka dijamin tidak akan berubah, kod hash mereka dapat di-cache dengan mudah
S5. Bagaimana Rentetan Tersimpan dalam Ingatan?
Menurut Spesifikasi JVM, String literal disimpan dalam kumpulan pemalar runtime, yang diperuntukkan dari kawasan kaedah JVM.
Walaupun wilayah metode secara logik merupakan bagian dari memori timbunan, spesifikasi tidak menentukan lokasi, ukuran memori, atau kebijakan pengumpulan sampah. Ia boleh dilaksanakan khusus.
Kumpulan pemanjangan jangka masa ini untuk kelas atau antara muka dibina semasa kelas atau antara muka dibuat oleh JVM.
S6. Adakah String Terpakai Layak untuk Pengumpulan Sampah di Jawa?
Ya, semua String di kumpulan tali layak untuk pengumpulan sampah jika tidak ada rujukan dari program ini.
S7. Apakah Kolam Kekal String
Kumpulan tali, juga dikenali sebagai kolam tetap String atau kolam inti String , adalah kawasan memori khas di mana JVM menyimpan contoh String .
Ia mengoptimumkan prestasi aplikasi dengan mengurangkan seberapa kerap dan berapa rentetan yang diperuntukkan:
- JVM menyimpan hanya satu salinan String tertentu di kolam
- Semasa membuat String baru , JVM mencari di String untuk String yang mempunyai nilai yang sama
- Sekiranya dijumpai, JVM mengembalikan rujukan ke Rentetan itu tanpa memperuntukkan memori tambahan
- Sekiranya tidak dijumpai, maka JVM menambahkannya ke kolam (melatihnya) dan mengembalikan rujukannya
S8. Adakah Benang Benang Selamat? Bagaimana?
Tali memang betul-betul selamat dari benang kerana tidak boleh diubah. Mana-mana kelas yang tidak berubah secara automatik layak untuk keselamatan benang kerana kebolehubahannya menjamin bahawa kejadiannya tidak akan berubah di beberapa utas.
Sebagai contoh, jika utas mengubah nilai rentetan, String baru akan dibuat dan bukannya mengubah yang ada.
S9. Untuk Operasi Rentetan Yang Mana Penting untuk Menyediakan Lokasi?
The Locale kelas membolehkan kita membezakan antara yang menawarkan penginapan berkualiti kebudayaan serta untuk memformat kandungan kami dengan sewajarnya.
Ketika datang ke kelas String , kami memerlukannya ketika membuat string dalam format atau ketika string dengan casing bawah atau atas.
Sebenarnya, jika kita terlupa melakukan ini, kita akan menghadapi masalah mudah alih, keselamatan, dan kebolehgunaan.
S10. Apakah Pengekodan Karakter yang Mendasari untuk Rentetan?
According to String's Javadocs for versions up to and including Java 8, Strings are stored in the UTF-16 format internally.
The char data type and java.lang.Character objects are also based on the original Unicode specification, which defined characters as fixed-width 16-bit entities.
Starting with JDK 9, Strings that contain only 1-byte characters use Latin-1 encoding, while Strings with at least 1 multi-byte character use UTF-16 encoding.
3. The String API
In this section, we'll discuss some questions related to the String API.
Q11. How Can We Compare Two Strings in Java? What’s the Difference Between str1 == str2 and str1.Equals(str2)?
We can compare strings in two different ways: by using equal to operator ( == ) and by using the equals() method.
Both are quite different from each other:
- The operator (str1 == str2) checks for referential equality
- The method (str1.equals(str2)) checks for lexical equality
Though, it's true that if two strings are lexically equal, then str1.intern() == str2.intern() is also true.
Typically, for comparing two Strings for their content, we should always use String.equals.
Q12. How Can We Split a String in Java?
The String class itself provides us with the String#split method, which accepts a regular expression delimiter. It returns us a String[] array:
String[] parts = "john,peter,mary".split(","); assertEquals(new String[] { "john", "peter", "mary" }, parts);
One tricky thing about split is that when splitting an empty string, we may get a non-empty array:
assertEquals(new String[] { "" }, "".split(","));
Of course, split is just one of many ways to split a Java String.
Q13. What Is Stringjoiner?
StringJoiner is a class introduced in Java 8 for joining separate strings into one, like taking a list of colors and returning them as a comma-delimited string. We can supply a delimiter as well as a prefix and suffix:
StringJoiner joiner = new StringJoiner(",", "[", "]"); joiner.add("Red") .add("Green") .add("Blue"); assertEquals("[Red,Green,Blue]", joiner.toString());
Q14. Difference Between String, Stringbuffer and Stringbuilder?
Strings are immutable. This means that if we try to change or alter its values, then Java creates an absolutely new String.
For example, if we add to a string str1 after it has been created:
String str1 = "abc"; str1 = str1 + "def";
Then the JVM, instead of modifying str1, creates an entirely new String.
However, for most of the simple cases, the compiler internally uses StringBuilder and optimizes the above code.
But, for more complex code like loops, it will create an entirely new String, deteriorating performance. This is where StringBuilder and StringBuffer are useful.
Both StringBuilder and StringBuffer in Java create objects that hold a mutable sequence of characters.StringBuffer is synchronized and therefore thread-safe whereas StringBuilder is not.
Since the extra synchronization in StringBuffer is typically unnecessary, we can often get a performance boost by selecting StringBuilder.
Q15. Why Is It Safer to Store Passwords in a Char[] Array Rather Than a String?
Since strings are immutable, they don't allow modification. This behavior keeps us from overwriting, modifying, or zeroing out its contents, making Strings unsuitable for storing sensitive information.
We have to rely on the garbage collector to remove a string's contents. Moreover, in Java versions 6 and below, strings were stored in PermGen, meaning that once a String was created, it was never garbage collected.
By using a char[] array, we have complete control over that information.We can modify it or wipe it completely without even relying on the garbage collector.
Using char[] over String doesn't completely secure the information; it's just an extra measure that reduces an opportunity for the malicious user to gain access to sensitive information.
Q16. What Does String’s intern() Method Do?
The method intern() creates an exact copy of a String object in the heap and stores it in the String constant pool, which the JVM maintains.
Java automatically interns all strings created using string literals, but if we create a String using the new operator, for example, String str = new String(“abc”), then Java adds it to the heap, just like any other object.
We can call the intern() method to tell the JVM to add it to the string pool if it doesn't already exist there, and return a reference of that interned string:
String s1 = "Baeldung"; String s2 = new String("Baeldung"); String s3 = new String("Baeldung").intern(); assertThat(s1 == s2).isFalse(); assertThat(s1 == s3).isTrue();
Q17. How Can We Convert String to Integer and Integer to String in Java?
The most straightforward approach to convert a String to an Integer is by using Integer#parseInt:
int num = Integer.parseInt("22");
To do the reverse, we can use Integer#toString:
String s = Integer.toString(num);
Q18. What Is String.format() and How Can We Use It?
String#format returns a formatted string using the specified format string and arguments.
String title = "Baeldung"; String formatted = String.format("Title is %s", title); assertEquals("Title is Baeldung", formatted);
We also need to remember to specify the user's Locale, unless we are okay with simply accepting the operating system default:
Locale usersLocale = Locale.ITALY; assertEquals("1.024", String.format(usersLocale, "There are %,d shirts to choose from. Good luck.", 1024))
Q19. How Can We Convert a String to Uppercase and Lowercase?
String implicitly provides String#toUpperCase to change the casing to uppercase.
Though, the Javadocs remind us that we need to specify the user's Locale to ensure correctness:
String s = "Welcome to Baeldung!"; assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase(Locale.US));
Similarly, to convert to lowercase, we have String#toLowerCase:
String s = "Welcome to Baeldung!"; assertEquals("welcome to baeldung!", s.toLowerCase(Locale.UK));
Q20. How Can We Get a Character Array from String?
String provides toCharArray, which returns a copy of its internal char array pre-JDK9 (and converts the String to a new char array in JDK9+):
char[] hello = "hello".toCharArray(); assertArrayEquals(new String[] { 'h', 'e', 'l', 'l', 'o' }, hello);
Q21. How Would We Convert a Java String into a Byte Array?
By default, the method String#getBytes() encodes a String into a byte array using the platform’s default charset.
And while the API doesn't require that we specify a charset, we should in order to ensure security and portability:
byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII); byte[] byteArray3 = "ijkl".getBytes("UTF-8");
4. String-Based Algorithms
In this section, we'll discuss some programming questions related to Strings.
Q22. How Can We Check If Two Strings Are Anagrams in Java?
An anagram is a word formed by rearranging the letters of another given word, for example, “car” and “arc”.
To begin, we first check whether both the Strings are of equal length or not.
Then we convert them to char[] array, sort them, and then check for equality.
Q23. How Can We Count the Number of Occurrences of a Given Character in a String?
Java 8 really simplifies aggregation tasks like these:
long count = "hello".chars().filter(ch -> (char)ch == 'l').count(); assertEquals(2, count);
And, there are several other great ways to count the l's, too, including loops, recursion, regular expressions, and external libraries.
Q24. How Can We Reverse a String in Java?
There can be many ways to do this, the most straightforward approach being to use the reverse method from StringBuilder (or StringBuffer):
String reversed = new StringBuilder("baeldung").reverse().toString(); assertEquals("gnudleab", reversed);
Q25. How Can We Check If a String Is a Palindrome or Not?
A palindrome is any sequence of characters that reads the same backward as forward, such as “madam”, “radar” or “level”.
To check if a string is a palindrome, we can start iterating the given string forward and backward in a single loop, one character at a time. The loop exits at the first mismatch.
5. Conclusion
Dalam artikel ini, kami meneliti beberapa soalan wawancara String yang paling lazim .
Semua sampel kod yang digunakan di sini boleh didapati di GitHub.