All of us must have gone though some common questions related to String class in java. These questions range from immutability to memory leak issues. I will try to cover such questions in this post.
Questions discussed below:
- Why strings are immutable?
- String pool concept
- Keyword ‘intern’ usage
- Matching Regular expressions?
- Strings comparison?
- Memory leak issue
String in java are like any other programming language, a sequence of characters. This is more like a utility class to work on that char sequence. This char sequence is maintained in following variable:
1
2
|
/** The value is used for character storage. */
private
final
char
value[];
|
To access this array in different scenarios, following variables are used:
1
2
3
4
5
|
/** The offset is the first index of the storage that is used. */
private
final
int
offset;
/** The count is the number of characters in the String. */
private
final
int
count;
|
Why strings are immutable?
We all know that strings in java are immutable. If you want to know, what immutability is and how it is achieved? follow this post: How to make a java class immutable?
Here the question is WHY? Why immutable? Lets analyze.
1) The very first reason i can think of is performance increase. Java language was developed to speed up the application development as it was not that much fast in previous languages. JVM designers must have been smart enough to identify that real world applications will consist of mostly Strings in form of labels, messages, configuration, output and such numerous ways.
Seeing such over use, they imagined how dangerous can be string’s improper use. So they came up with concept of String pool (next section). String pool is nothing but a collection of some strings mostly unique. The very basic idea behind String pool is to reuse string once created. This way if a particular string is created 20 times in code, application end up having only one instance.
2) Second reason i see as security considerations. Strings are most used parameter type in each aspect of java programming. Be it loading a driver or open a URL connection, you need to pass the information as parameter in form of string. If strings have not been final then they have opened up a Pandora box of security issues.
Apart from above two reasons, i didn’t find any convincing answer for this question. If you any something appealing, please share with me.
String pool concept
String pool is a special memory area separate from regular heap memory where these string constants are stored. These objects are referred string variables during the life cycle of application.
In java, String can be created by many ways. Lets understand them:
1) String assignment
1
|
String str = "abc";
|
Above code causes JVM to verify if there is already a string “abc” (same char sequence). If such string exist, JVM simply assign the reference of existing object to variable str, otherwise a new object “abc” will be created and its reference will be assigned to variable str.
2) Using new keyword
1
|
String str =
new
String("abc");
|
This version end up creating two objects in memory. One object in string pool having char sequence “abc” and second in heap memory referred by variable str and having same char sequence as “abc”.
As java docs says : Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
Keyword ‘intern’ usage
This is best described by java docs:
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.
1
2
3
|
String str =
new
String("abc");
str.intern();
|
It follows that for any two strings s
and t
, s.intern() == t.intern()
is true
if and only if s.equals(t)
is true
. Means if s and t both are different string objects and have same character sequence, then calling intern() on both will result in single string pool literal referred by both variables.
Matching Regular expressions
Not so secret but useful feature if you still have not explored it. You must have seen usage of Pattern and Matcher for regular expression matching. String class provides its own shortcut. Use it directly. This method also uses Pattern.matches() inside function definition.
1
2
3
|
String str =
new
String("abc");
str.matches(
"<regex>"
);
|
Strings comparison
Another favorite area in interviews. There are generally two ways to compare objects
- Using == operator
- Using equals() method
== operator compare for object references i.e. memory address equality. So if two string objects are referring to same literal in string pool or same string object in heap then s ==t will return true, else false.
equals() method is overridden in String class and it verify the char sequences hold by string objects. If they store the same char sequence, the s.equals(t) will return true, else false.
转自:http://howtodoinjava.com/2012/10/28/interview-stuff-about-string-class-in-java/
最后关于内存泄露的我没有转,那个应该是之前版本,有兴趣的大家去网站看看吧。