Strings in Java

Adil Wadhwania
4 min readJul 28, 2023

--

In this article we will understand how strings work in java.

  1. String definition and declaration
  2. Strings are immutable
  3. Memory allocation of strings
  4. String intern method
  5. Common String methods

String definition and declaration

Strings in java are used to store sequence of characters, the implementation is given in the String class of java standard library.

  • The most used and easy way to create a string is directly assigning the value in double quotes as shown below.
String greet="Hello world";
  • Whenever the compiler encounters the String literal in the code (“”) it will create a String object with the value given in between the String literal.
  • “Hello world” is the string literal that is assigned to greet variable.
//creating the string by passing the value in the construtor
String name=new String("Adil");
char[] thanksArray={'T','h','a','n','k','s','.'};
// creating the string by passing character array in the constructor.
String thanks=new String(thanksArray);
  • The other way to declare a string is, one of that is similar to the object creation using the new keyword.
  • There are multiple constructors provided to create new string that you can refer from the official docs.

Strings are immutable

  • Java String are immutable in nature, if you modify a string after the initialization, always it creates a new object.
String name="Adil";
name="wadhwania";// modifying name will create new String object
  • If you change value of a String it will always create a new String object and reference the new object to that variable.
  1. There would be problem in Hashing if the String were mutable, if a string is used as key in hashtable and you are able to modify the string, then the hashcode of string would change that would cause lookup problems in hash table.
  2. String immutability provides thread safety, if strings were mutable then multiple threads can access the same string object and modifies it, leading to race condition and data inconsistencies.
  • This are some of the benefits of string immutability.

Memory Allocation of Strings

  1. String pools :-
  • Java string pools are special memory area to store the string literals.
  • When you create a string using string literal (eg. String str=”Hello”), JVM checks if the String pool contains similar String, if it does then the reference of similar String present in string pool is returned instead of creating new one.
  • By reusing the String we can save memory and JVM ensure that only one copy exits in the memory.
  • The immutable nature of Strings helps us in reusing the String, as we can not modify the strings after creation, multiple variables can reference the same object(that is what exactly string pool does) ensuring that the content is not modified by either one of the variables.
  • Since the string literals present in pool are commonly used and referenced to multiple variable, they remains in the string pool for the duration of the program execution. Until and unless entire string pool is no longer reachable it is not typically garbage collected.
  • String pool improve the performance, strings can be compared using the equals() method, if both strings are from the string pool, the comparison is done by comparing memory addresses which is faster than comparing each character of the string.

2. Heap memory :-

  • When you create a string using the “new ” keyword (eg. new String(“Hello”) ), a new string object is created in heap memory same as when we create any other object.
  • This will create a separate instance of string, regardless of whether the same string already exists in the string pool.
  • If we create two string with “new” keyword having same value then it will create different instances and return the reference to respective variables.
  • String created using “new ” will not lookup in string pool for other matching string it will directly create new instance in heap and return the reference.

String Intern method

  • If you want to explicitly add the strings in the string pool then you can use the intern() method of string class.
String ab=new String("Hello").intern();
  • The string ab is created using “new” keyword but it will be added in the string pool because we have called intern method on it and will be treated similar to string literals.

Common String methods

  • Strings can be concatenated using the concat method of String class, and the most common way is using ‘+’ operator.
  • Concatenation will create a new String, as the String class is immutable.
String firstName="Adil";
String lastName="Wadhwania";
String fullName=firstName+lastName;
String fullConcat=firstName.concat(lastName);
  • The String class provides various methods to manipulate and work with strings
  1. Length() :- To find the length of the string.
  2. charAt(index) :- Returns the character at a given index.
  3. subString(startingIndex,endingIndex) :- If you want particular part from a string then you can get that string by passing the starting index and ending index in the subString method.
      String name="Adil wadhwania";
int length=name.length();
System.out.println("Length of the String "+length);
char zeroth=name.charAt(0);
System.out.println("Element at oth index "+zeroth);
String surName=name.substring(5,length);
System.out.println(surName);
  • String also provides methods, indexOf(), toUpperCase(), toLowerCase() and many more. You can refer the methods from official docs.

“Thank you for taking the time to read my article! I hope you found the information and insights shared here helpful and interesting. If you enjoyed this article, be sure to follow my article for more similar content. I’m always exploring new topics and sharing my thoughts and insights on a variety of subjects. I appreciate your support and look forward to connecting with you through my writing. Until next time!”

ADIL WADHWANIA :)

Topics :- String, string in java, how to declare string in java, string immutability, why strings are immutable, memory allocation of string in java, string intern method, string pools, heap, concatenation of string, common string methods, java, core java

--

--

Adil Wadhwania

Tech-savvy writer sharing insights on programming,current affairs,sports,great personalities, and new technologies. Follow for engaging and informative content.