String is one of the widely used java classes. It is special in java as it has some special characteristics than a usual java class. Lets explore java String in this article and this page aims to serve you as a single point reference for all your queries on Java String.
Though you might be knowing most of the things, this will help you to recall them and I am sure you will find one or two new things. I recommend you to take your time and read through this completely as java String is a basic building block of your java programs.
Java String is a immutable object. For an immutable object you cannot modify any of its attribute’s values. Once you have created a java String object it cannot be modified to some other object or a different String. References to a java String instance is mutable. There are multiple ways to make an object immutable. Simple and straight forward way is to make all the attributes of that class as final. Java String has all attributes marked as final except hash field.
Java String is final. I am not able to nail down the exact reason behind it. But my guess is, implementors of String didn’t wany anybody else to mess with String type and they wanted de-facto definition for all the behaviours of String.
We all know java String is immutable but do we know why java String is immutable? Main reason behind it is for better performance. Creating a copy of existing java String is easier as there is no need to create a new instance but can be easily created by pointing to already existing String. This saves valuable primary memory. Using String as a key for Hashtable guarantees that there will be no need for re hashing because of object change. Using java String in multithreaded environment is safe by itself and we need not take any precautionary measures.
In continuation with above discussion of immutability of java String we shall see how that property is used for instantiating a Sting instance. JVM maintains a memory pool for String. When you create a String, first this memory pool is scanned. If the instance already exists then this new instance is mapped to the already existing instance. If not, a new java String instance is created in the memory pool.
This approach of creating a java String instance is in sync with the immutable property. When you use ‘new’ to instantiate a String, you will force JVM to store this new instance is fresh memory location thus bypassing the memory map scan. Inside a String class what you have got is a char array which holds the characters in the String you create.
String str1 = "javapapers"; String str2 = new String("Apple"); String str3 = new String(char ); String str4 = new String(byte ); String str5 = new String(StringBuffer); String str6 = new String(StringBuilder);
We have an empty constructor for String. It is odd, java String is immutable and you have an empty constructur which does nothing but create a empty String. I don’t see any use for this constructor, because after you create a String you cannot modify it.
Do not use == operator to compare java String. It compares only the object references and not its contents. If you say, “if references are same, then the value must be same” – this doesn’t cover, “even if references are not same, the content can be same”. Therefore == operator doeenot 100% guarantee the equality of java String. Consider,
String stringArray1 = new String(“apple”, “orange”);
“apple” == stringArray1; gives FALSE.
“apple”.equals(stringArray1); gives TRUE.
equals() method is part of Object class. Java String class overrides it and provides implementation for equality comparison. String’s equals() implemetation uses three step process to compare two java String:
Shall we always use equals() method for equality comparison in any type of objects? No. You need to check the implementation in its respective class. StringBuffer and StringBuilder do not have an implementation for equals() method.
Use equalsIgnoreCase(String) to compare String irrespective of case (Case insensitivity).
“javaString”.equalsIgnoreCase(“JAVASTRING”); returns TRUE.
First what is lexicographic comparison? Consider, ‘A’ for ‘Apple’ and ‘B’ for ‘Ball’. Term ‘Apple’ appears first in dictionary and later follow ‘Ball’. Java String has got an excellent method to do this sort of comparison for two String and identify which comes first and the other follows.
In the above, “Apple” calls compareTo(String) and “Apple” comes first lexicograpically before “Ball”, therefore this returns value < 0. If calling String and argument String are same then returned value is 0. That is, “Apple”.compareTo(“Apple”); Else, you get > 0.
Java conversion is a huge topic by itself. I will take only String as scope for this section.
Example: 1+” Apple”; results in “1 Apple”.
So how does the above happen? When + operator is used with a java primitive, following happens:
One of the most frequent questions on String conversion is
Best way to convert String to Date is as follows:
String dateInString = "November 21, 2011"; SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH); Date formattedDate = dateFormat.parse(dateInString);
How to transform a String to upper / lower case. Java String has got nice utility methods.
and String can be trimmed using trim()
Hope you remember about the memory pool of java String that we discussed at the start of this article. We have a method named intern() in java String. When you invoke this method on a String,
+ is a special operator when it comes to java String. It helps to concatenate two String. I have already written a post exclusively for String concatenation. Please refer that for more on java String concatenation.
This Core Java tutorial was added on 21/11/2011.