top of page
Writer's pictureMathu Studies

String Operations explained with Hashcodes in Java

Java supports different data types like int, char, float, double, boolean which are primitive data types. There are non-primitive data types like Array, String, Interface, Class, Enum. Though we say String as data type it’s actually a class in java.lang package.  What makes String class so special?  String is a collection of characters; characters include any type of character. Our main method in java takes in String array as arguments. All the text form of data needs String to store them.  

Let’s start with how to create an object and store value in it. There are two ways to create string object, 




  


String object s1 is created using the new keyword, so it will be stored in heap memory like all java objects, but String s2 is created without new keyword, it is called string literal. S2 is stored in a special space in heap memory called as SCP or String Constant Pool. 

We can confirm this by using a simple code. String class provides two operators namely “==” and “.equals”. They are different int the sense, “==” compares the object reference and .equals compares the value. In our case lets see what happens... 



String Object and String Literal

 

The following screenshot explains that s1 and s2 both having the same value but referring different objects. 



 


Here we see the “== operator” compares the object references which shows two different objects have been created at different addresses that’s why we got false as the output. 

Whereas the “.equals” operator compares the values that’s why we got the output as true. 

Let’s see why String is called IMMUTABLE. String value cannot be changed. When we change the value of a String  the old value is not overwritten, instead a new object is created and the field started pointing the new object. And the garbage collector plays it role by collecting the unused objects. 

 

public static void main(String args[]) 

String s1= "String Manipulation";  

String s2="String Manipulation";  

System.out.println("I am address of s1: "+s1.hashCode());  

System.out.println("I am address of s2: "+s2.hashCode());  

s2="String Manipulation in Java";  

System.out.println("After changing s2 value"); 

System.out.println("I am address of s1: "+s1.hashCode());  

System.out.println("I am address of s2: "+s2.hashCode());  

Output: 

I am address of s1: 1577159500 

I am address of s2: 1577159500 

After changing s2 value 

I am address of s1: 1577159500 

I am address of s2: 1707510665 



 

Why String is immutable? Consider a scenario where a database is created for storing patient records. Patient1’city is Texas, Patient2 to Patient 50 has same city as Texas. So 50 objects are not created instead JVM looks for Texas which is already there so all the remaining patient city starts pointing towards Texas the single object. Now lets change the value of patient1’s city from Texas to NewJersey. What happens if String has been mutable. The value of Texas gets overwritten to NewJersey, all the remaining city’s reference will start pointing to null which results in null pointer exception 





But in reality since String is immutable, a new object for NewJersey gets created and the first patient city alone will points to the new object of NewJersey and the other city fields keep referring to the old object of Texas. 




 

 

Overriding toString()  


To print an output in the console, we use “System.out.println()” function. When we call this function this calls the toString() method by default and converts everything into a String and prints in the console. 



 

In the above code snippet, we have tried to print a string object and java object. But why the outputs are different, if both the statements call toString() method. That’s because the toString() method is designed to print the hashcode of any object, but in String class this method is overridden to print the value of the input string. We can achieve this for the java object by  manually overriding the toString() method as follows... 


package stringManipulation; 

public class ReadingObjectValue { 

String string2

public ReadingObjectValue(String string1) { 

this.string2=string1

public String toString() //overriden toString() method 

return string2

public static void ReadObjVal() 

ReadingObjectValue obj=new ReadingObjectValue("Diyanika"); 

System.out.println(obj); 

 

String s1=new String("Matuhra"); 

System.out.println(s1); 

 

Output: 

Diyanika 

Matuhra 

 

Functions in String 

 

String class provide various functions to manipulate strings. Let’s discuss few of the functions with code snippets. 

 

Searching Methods: 

 

indexOf(), this method returns the index of a character or a string. This method has few variations. 

 

String newstr="String Search methods"

System.out.println("index of char:" + newstr.indexOf('t')); 

System.out.println("last index of char:" + newstr.lastIndexOf('t')); 

System.out.println("index of string: "+ newstr.indexOf("ring")); 

System.out.println("index of char after certain string: "+ newstr.indexOf("t",7)); 

 

 

For a given string the indexes start from 0. indexOf('t') method returns the first occurrence of alphabet ‘t’ in the string.lastIndexOf('t') displays the index of t in the string from the last. It reads the string in reverse. This indexOf("ring") is used to display the starting index of the string “ring”. IndexOf("t",7) displays the index of the occurrence of character 't', after the index 7. This is captured as output in the following screenshot

 

OUTPUT: 

 




 

 

 

Character Extraction Methods: 

 

charAt(), substring() are the two extraction methods in String. The charAt() function returns character and the substring() function returns a string. 

 

str="Character Extraction in String"

System.out.println("charAt method: "+str.charAt(2)); //charAt 

try { 

System.out.println("o/p when we get indexvalue that is not present: "+str.charAt(200));//exception 

System.out.println("o/p when we get indexvalue that is not present: "+str.charAt(-1)); 

} catch (Exception e) {  e.printStackTrace();  } 

System.out.println("substring sample:"+str.substring(0,10));//substring 

 

 

CharAt(int index) function returns the character present at that index value. What if the index value we provide is larger than the length of the string itself or smaller than the string length. We get StringIndexOutOfBoundException in such cases. The substring(int startindex,int endindex) outputs the chararcter sequence present from start index to endindex excluding endindex gets displayed. 





There are other widely used methods in String class. They are, 

length() - returns length of a string 

isBlank() - returns true when there are no characters 

isEmpty() - returns true when string length is 0 

trim() - trims blank spaces on both ends of a string 

stripTrailing() - removes blank spaces in the end of a string 

stripLeading() - removes blank spaces in the beginning of a string 

replace(char,char) - this method replaces the first parameter charactes with the second parameter character  

 

 

 

 String Buffer and String Builder 

String class is immutable for certain reasons, for security purpose, caching, synchronization. But sometimes this could be an inconvenience. Consider a scenario where we need to create paragraph from array of strings, if the paragraph has to have 500 words, then 500 objects will be created for each word. This is waste of memory and overload for Garbage Collector too. To avoid this we can use String builder or String buffer. Both are mutable. String buffer is thread safe, it provides synchronization because of that its slower than String builder which is not thread safe nut faster. 

Below code snippet shows how single object is created in String buffer for each appended word in contrast to String where three separate objects are created. 

 

 



 

String is one of the vital class in Java. With its rich methods we could perform various operations. With string buffer and string builder classes we can achieve mutability as well. 

Happy  reading!!! 

 

 

10 views

Recent Posts

See All
bottom of page