1. Въведение
Класът String е един от най-често използваните класове в Java, което накара дизайнерите на езици да го третират специално. Това специално поведение го прави една от най-горещите теми в интервютата за Java.
В този урок ще разгледаме някои от най-често срещаните въпроси за интервюто за String .
2. Основи на струните
Този раздел се състои от въпроси, които се отнасят до вътрешната структура и паметта на String .
Q1. Какво е низ в Java?
В Java String е представен вътрешно от масив от байтови стойности (или char стойности преди JDK 9).
Във версии до Java 8 включително, String беше съставен от неизменяем масив от Unicode символи. Повечето знаци обаче изискват само 8 бита (1 байт), за да ги представят вместо 16 бита ( размер на символа ).
За да подобри консумацията и производителността на паметта, Java 9 представи компактни Strings. Това означава, че ако String съдържа само 1-байтови символи, той ще бъде представен с помощта на кодиране Latin-1 . Ако String съдържа поне 1 многобайтов символ, той ще бъде представен като 2 байта на символ, използвайки UTF-16 кодиране.
В C и C ++ String също е масив от символи, но в Java това е отделен обект със собствен API.
Q2. Как можем да създадем низ обект в Java ?
java.lang.String дефинира 13 различни начина за създаване на низ . Като цяло обаче има две:
- Чрез Stral литерал:
String s = "abc";
- Чрез новата ключова дума:
String s = new String("abc");
Всички Stral литерали в Java са екземпляри от класа String .
Q3. Дали String примитивен или производния клас?
String е производен тип, тъй като има състояние и поведение. Например има методи като substring () , indexOf () и equals (), които примитивите не могат да имат.
Но тъй като всички го използваме толкова често, той има някои специални характеристики, които го карат да се чувства като примитив:
- Докато низовете не се съхраняват в стека на повикванията, както примитивите, те се съхраняват в специална област на паметта, наречена пул от низове
- Подобно на примитивите, можем да използваме оператора + върху низове
- И отново, като примитиви, можем да създадем екземпляр на String без новата ключова дума
Q4. Какви са ползите от това, че струните са неизменни?
Според интервю на Джеймс Гослинг, струните са неизменни за подобряване на производителността и сигурността.
И всъщност виждаме няколко ползи от наличието на неизменни низове:
- Пулът от низове е възможен само ако низовете, веднъж създадени, никога не се променят, тъй като се предполага, че ще бъдат използвани повторно
- Кодът може безопасно да предаде низ на друг метод , знаейки, че не може да бъде променен от този метод
- Immutably автоматично прави този клас безопасен за нишки
- Тъй като този клас е безопасен за нишки, няма нужда да синхронизирате общи данни , което от своя страна подобрява производителността
- Тъй като гарантирано не се променят, техният хеш код може лесно да се кешира
Q5. Как се съхранява низ в паметта?
Съгласно спецификацията на JVM, String литералите се съхраняват в постоянен пул по време на изпълнение, който се разпределя от областта на метода на JVM.
Въпреки че областта на метода логично е част от паметта на купчината, спецификацията не диктува местоположението, размера на паметта или политиките за събиране на боклука. Тя може да бъде специфична за изпълнението.
Този пул на константа по време на изпълнение за клас или интерфейс се изгражда, когато класът или интерфейсът са създадени от JVM.
Q6. Подходящи ли са интернирани низове за събиране на боклук в Java?
Да, всички низове в пула от низове отговарят на условията за събиране на боклука, ако няма референции от програмата.
Q7. Какво е пул с постоянен низ?
Струнният пул, известен също като String pool пул или String intern pool, е специален регион на паметта, където JVM съхранява String екземпляри.
It optimizes application performance by reducing how often and how many strings are allocated:
- The JVM stores only one copy of a particular String in the pool
- When creating a new String, the JVM searches in the pool for a String having the same value
- If found, the JVM returns the reference to that String without allocating any additional memory
- If not found, then the JVM adds it to the pool (interns it) and returns its reference
Q8. Is String Thread-Safe? How?
Strings are indeed completely thread-safe because they are immutable. Any class which is immutable automatically qualifies for thread-safety because its immutability guarantees that its instances won't be changed across multiple threads.
For example, if a thread changes a string's value, a new String gets created instead of modifying the existing one.
Q9. For Which String Operations Is It Important to Supply a Locale?
The Locale class allows us to differentiate between cultural locales as well as to format our content appropriately.
When it comes to the String class, we need it when rendering strings in format or when lower- or upper-casing strings.
In fact, if we forget to do this, we can run into problems with portability, security, and usability.
Q10. What Is the Underlying Character Encoding for Strings?
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
В тази статия преминахме през някои от най-разпространените въпроси за интервюта със String .
Всички примерни кодове, използвани тук, са достъпни в GitHub.