10 Important points about String in Java

someone might question that why do we need another article about string in Java, haven't we had enough about the string is already written? Yes, I agree there are a lot of articles related to Java string covering topics like how to use Java String, an example of Java string and almost everything you can do with string in Java. But, I wanted to document my experience of using String in Java and some nasty and little-known things I discovered about the Java String class, which may not be obvious to many Java developers. A string is available in almost every programming language and its probably the most used data structure or a data type, hence a good knowledge of String is very important for every Java developers.


For example, do you know what the string is not a data type in Java is represented by a class called java.lang.String in JDK?  It's backed by a character array and you can get those character array by calling the toCharArray() method?

Do you know that instances of String are maintained in a private String pool and they are Immutable, which means cannot be changed once they are created? Well, if you don't know then you will learn in this article.    Now let's see some important points to String in Java.


10 Points about String in Java

1) Sting is a class in the java.lang package, which means you don't need to import String class to use in your program. All classes from the java.lang package is automatically imported in Java.

2) Internally String is represented as a character array in Java. This is similar to other programming languages like C but the only difference is here String is not NULL terminated.

Btw, there has been some talk that from Java 9 onwards String should be represented using byte array and a place for encoding to reduce the memory consumption from String.



3) A string is immutable in Java it means you can not modify a String object once it gets created. if you want a mutable String to consider using StringBuffer or StringBuilder class in Java. You can see the difference between StringBuffer and StringBuilder to learn more about their differences.


4) The "+" operator is overloaded for String in Java and usually use to concatenate two String. Java doesn't support operator overloading but this is the special feature only available for String class. also, "+" operator is internally implemented using either StringBuilder or StringBuffer object and by using their append() method.


5) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain an exactly same character in the same order and in the same case. if you want to ignore case comparison of two strings consider using equalsIgnoreCase() method.


6) When we represent a string in double quotes like "abcd" they are referred as String literal and they are stored in a special area called "String pool" which I will explain in the next point.


7)  String pool in Java
String class maintains a private pool of all String literals created in the JVM. Earlier this pool was part of PermGen space but from JDK 8 the PermGen space has been removed and String pool becomes a part of Java heap space.

Whenever you create a String object using String literal syntax e.g. "Java" then it is added to the pool. You can also force to add a String to a pool by calling the intern() method of java.lang.String class.

For example, when you create a String object as String data = new String("data") then it will not be added into the pool but when you call the intern method on it e.g. data.intern() then it will be added to the pool and if already exists then the reference of the same object is return by intern() method.

If you are interested in the internal working of JVM then you can further read Java Performance Companion by Charlie Hunt to learn more about String pool and JVM performance optimization.

10 Important points about String in Java


8) The toString() method provides a string representation of an object and its declared in Object class and its recommended for other class to implement this and provide string representation.

9) In Java, you can create String from a byte array, char array, another string, from StringBuffer or from StringBuilder. Java String class provides a constructor for all of these.

10) Useful Methods from String class
Now, let's talk about some of the important methods of String class in Java. You will often need these methods to write code and solve any coding problem, hence it's better you get familiar with them. If you are new to Java then you can also benefit from Complete Java 9 Masterclass by Udemy which explains how to use these methods along with other useful Java concepts.

1) indexOf 
Returns index of a character from String

2) toCharArray
Converts String to a character array, actually, return the copy of internal character array from a String object.

3) valueOf
Used to convert int, long, float, the double and other data type to String in Java. See this post to learn more about how to convert String to an integer in Java.

4) charAt
Returns the character at given index

5) compareTo
Compares this String to given String. it returns a positive integer if this String comes after given String in lexicographic order, a negative integer if this string comes before and zero if both strings is equal.


6) concat
Concatenates the specified string to the end of this string.

7) contains
Returns true if and only if this string contains the specified sequence of char values. See here for an example of this method.

8) startsWith
Checks if this string starts with the specified suffix.

9) endsWith
Tests if this string ends with the specified suffix.

10) equals
Compares this string to the specified object.

11) equalsIgnoreCase
Compares this string to given string and ignore case. see here for an example

12) format
Returns a formatted string using the specified format string and arguments. See here for an example of this method.

13) length
Returns the number of character in a given String. See here for an example of this method.

14) lastIndexOf
Returns the index of given character from the end.

15) matches
Tells whether or not this string matches the given regular expression. See here for an example of this method.

16) replace
Returns a string resulting from replacing all occurrences of given character with new character. See here for an example of this method.

17) replaceAll
Replaces each substring of this string that matches the given regular expression with the given replacement.

18) split
Used to break String into small pieces or substring based upon given delimiter. See here for an example of this method.

19) substring
Returns a substring of given range from this String.  See here for an example of this method.


20) intern
Used to put a given String into the pool, also return the reference of String object from the pool if present already.  See here for an example of this method.

21) trim
Used to remove whitespace from both ends of String.  See here for an example of this method.


22) toUpperCase and toLowerCase
Used to change the case of this String. Since String is Immutable, a new String is returned.


11) The string is represented using the UTF-16 format in Java. If you don't know what is UTF-16 then please read my post about the difference between UTF-8 and UTF-16 encoding.

That's all about some of the important points about String class in Java. As I said, its one of the most important concept and class in Java and solid knowledge of String is must for any Java developer. There is hardly any program written in Java which doesn't use String and that's why it often caused performance issue and excessive garbage collection.

You can prevent those kinds of things if you understand how String works internally and how their instances are maintained in the String pool.

If you want to learn more about String class and its different application, I suggest you attend a proper Java course which covers String in depth, something like Java for Absolute Beginners from Udemy.


Other Java and String tutorials and articles you may like to explore
Introduction to Java for Programmers
How to format String in Java?
How to join String in Java 8? 
Complete Java 9 Masterclass by Udemy

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or feedback then please drop a comment. 

1 comment: