when I have told about concatenation of strings in java I'm wondered that this post was still in my draft so adding these lines at the starting of this post.
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.
Though I know you guys 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.
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.
Though I know you guys 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.
Immutable Java String
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(somehow later). But my guess is, implementors of String didn’t want anybody else to mess with String type and they wanted de-facto definition for all the behaviours of String.
Java String Instantiation
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.
Following are some of the ways to instantiate a java String
String str1 = "javaphobia";
String str2 = new String("Hello");
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.
Java String Comparison
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 strArray1 = new String(“come”, “came”);
“come” == strArray1[0]; gives FALSE.
“come” == strArray1[0]; gives FALSE.
- You claim that, using == operator with intern will give right result but it is not necessary.
- For equality comparison in java String, simplest and easiest way is to go with equals() method.
“come”.equals(strArray1[0]); 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:
- Compare references (if both String references are same return true else continue)
- Compare length (if both String length are not same return false else continue)
- Compare character by character sequentially.
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.
“javaString”.equalsIgnoreCase(“JAVASTRING”); returns TRUE.
Java String Conversion
Java String conversion is a huge topic by itself. I will take only String as scope for this section.
- + operator can be used to perform String conversion.
- If + operator is used with two int primitives, it returns sum the two numbers.
- To use it as a concatenation operator either one of the operand should be a java String.
Example: 1+” java”; results in “1 java”.
So how does the above happen? When + operator is used with a java primitive, following happens:
- Use respective type class and convert the primitive to an object. Like 1 -> new Integer(1);
- Invoke toString() of that respective class.
- toString() is a method that belongs to Object class. Every wrapper classes implements toString() method which returns a String object of the passed primitive.
- If you specifically target converting number to String, apart from + operator we can use printf() doing format conversion.
What is intern()
Hope you remember about the memory pool of java String discussed in above paras . We have a method named intern() in java String. When you invoke this method on a String,
- it checks if the same String is available in memory pool.
- If it exists, returns it.
- Else, adds this String to the memory pool and returns the String.
Java String Transformation
How to transform a String to upper / lower case. Java String has got nice utility methods.
toLowerCase(Locale locale)
toUpperCase(Locale locale)
and String can be trimmed using trim()
toUpperCase(Locale locale)
and String can be trimmed using trim()
No comments:
Post a Comment