Home » Core Java » lang » String » Java String Class Example

About Prateek Sharma

Prateek Sharma
Prateek has graduated in Computer Engineering from Thapar University (Patiala, India). He also holds a Master degree in Software Systems from Birla Institute of Technology & Science (Pilani, India). Currently he is working as a Full Stack Software Engineer in telecommunications sector where he is involved in multiple flavors of project ranging from development in J2EE,Groovy, JPA, Hibernate, Web Service (SOAP/REST) to DevOps tools like Jenkins, SonarQube, SonarLint, EclEmma etc. He also has experience in message queues like RabbitMQ and Kafka.

Java String Class Example

This article talks about one of the widely used String library in Java which does no less than a magic. It goes through some of the common Java String methods available previous to Java 8. Then it specifies some of the important String methods introduced in and after Java 8.

 

1. Introduction

In this example we are going to discuss about the basic characteristics of Java String Class. String is probably one of the most used types in Java programs. That’s why Java provides a number of API methods that make String manipulation easy and efficient, straight out of the box. Strings are so important that even in the latest Java releases (including 7 and 8), several changes have been made to its class methods and its internal representation, improving it even further in terms of performance and security.

2. Java String Class basic methods

A String is simply a sequence of characters. As a matter of fact, a String Object is backed by a char array. Consequently, it is not null terminated, like in C/C++.

Here is how you can create a String

1
String str= "Hello World";

"Hello World" is called a String literal. In a Java program, everything between two double quotes is a String literal. Literals are implemented as instances of String class. As you can see, you can conveniently initialize a String Object like a primitive type, e.g int i = 0;.

There is no need to do:

1
String str = new String("Hello World");

There is a difference between these two initialization methods, although the result is the same : A String with value “Hello World”. But more on that in just a bit.

For now, here is a simple main with the most important String API methods:

StringClassExample.java

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
package com.javacodegeeks.core.lang.string;
 
public class StringClassExample {
 
    public static void main(String[]args){
        //Initialization with literal
        String str1 = "Hello World";
        System.out.println("str1:"+str1);
 
        //Initialization with char array
        char arr[] = {'H','e','l','l','o'};
        String str2 = new String(arr);
        System.out.println("str2:"+str2);
 
        //Concatenation using + operator
        String str3 = "World";
        str3 = str2 + " " + str3;
        System.out.println("str3:"+str3);
 
        //find out the length of a string
        System.out.println(str3.length());
 
        //You can even apply that to literals, as with all String API methods
        //As we said. literals are implemented as String instances
        System.out.println("Length: "+"abcdefg".length());
 
        //Substring from position 2 to position 10
        String c = str1.substring(2,10);
        System.out.println("Substring :"+c);
 
        //Substring from position 1 to position 4
        System.out.println("Literal Substring :"+"abcdefghigklm".substring(1,4));
 
        // Get the charcter array of the string.
        char[] chars = c.toCharArray();
        System.out.println("Char array : ["+chars[0]+","+chars[1]+","+chars[2]+"]");
 
        //find the first index of a char inside a string
        int i = str1.indexOf('W');
        System.out.println("Index of 'W':"+i);
 
        //find the first index of a string inside another string after a certain position
        i = str1.indexOf("orld",5);
        System.out.println("Index of 'orld':"+i);
 
        //find the last index of a string inside another string
        i = str1.lastIndexOf("l");
        System.out.println("LAST Index of 'l':"+i);
 
        //find the last index of a string inside another string after a certain position
        // - like scanning the string backwards
        i = str1.lastIndexOf("l",7);
        System.out.println("LAST Index of 'l':"+i);
 
        //find a character in a certain position
        char cr = str1.charAt(5);
        System.out.println("Character at position 5:"+cr);
 
        //Lower case
        System.out.println("ABCEFAFA".toLowerCase());
 
        //Upper case
        System.out.println("abcasipasc".toUpperCase());
 
        //replace occurrences of a character
        str1 = str1.replace('o','0');
        System.out.println(str1);
 
        //Trim white spaces from the end and the beginning
        String str4 = "    Java";
        System.out.println(str4);
        System.out.println(str4.trim());
 
        //Split !!!
        String str5= "Java is great";
        String[] strArray = str5.split(" ");
 
        System.out.println(strArray[0]+","+strArray[1]+","+strArray[2]);
 
        str5= "Java-is-great";
        strArray = str5.split("-");
        System.out.println(strArray[0]+","+strArray[1]+","+strArray[2]);
 
        str5= "Java is great";
        strArray = str5.split("/*");
        System.out.println(strArray[0]+","+strArray[1]+","+strArray[2]+","+strArray[3]+","+strArray[4]+
                ","+strArray[5]+","+strArray[6]+","+strArray[7]+","+strArray[8]);
 
        //contains and equals
        System.out.println("Contains :" + "qwerty".contains("ert"));
        System.out.println ("Equals :"+str5.equals("java is great"));
        System.out.println ("Equals ignore case:"+str5.equalsIgnoreCase("java is great"));
 
        // Compare lexicographically two strings
        System.out.println ("Compare:"+str5.compareTo("abc"));
 
        //comparison attempts
        String s1 = "abc";
        String s3 = new String("abc");
 
        System.out.println(s1==s3);
        System.out.println(s1.equalsIgnoreCase(s3));
 
    }
 
}

This is the output of the above program:

str1:Hello World
str2:Hello
str3:Hello World
11
Length: 7
Substring :llo Worl
Literal Substring :bcd
Char array : [l,l,o]
Index of 'W':6
Index of 'orld':7
LAST Index of 'l':9
LAST Index of 'l':3
Character at position 5: 
abcefafa
ABCASIPASC
Hell0 W0rld
    Java
Java
Java,is,great
Java,is,great
,J,a,v,a, ,i,s, 
Contains :true
Equals :false
Equals ignore case:true
Compare:-23
false
true

From the above program is clear that Java designers decided to treat Strings somewhat differently from other Objects. For example you can initialize them like a primitive, e.g String a="abc" and you can concatenate two strings using + operator, like you would add two ints (looks like overloading + operator in C++).

The comparison attempts section of the code might seem a little fuzzy, but it will get clear in the next section. What you should take away from it now, is that you SHOULD NEVER try to compare the contents of Strings using == operator. You are only comparing reference equality, not content equality. You MUST use equals or equalsIgnoreCase.

2.1 Java String Equal Methods

The following method returns true if the content of both the strings are equal, otherwise returns false. It also takes into account the case of the contents.

equals(String str)
public class EqualsExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String s2 = "Java Code Geeks";

      String s3 = "java code geeks";

      System.out.println(s1.equals(s2));  //prints true

      System.out.println(s1.equals(s3));  //prints false

   }

}

The following method returns true if the content of both the strings are equal, otherwise returns false. It does not take into account the case of the contents.

equalsIgnoreCase(String str)
public class EqualsIgnoreCaseExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String s2 = "Java Code Geeks";

      String s3 = "java code geeks";

      System.out.println(s1.equalsIgnoreCase(s2));  //prints true

      System.out.println(s1.equalsIgnoreCase(s3));  //prints true

   }

}

The following method takes as parameter either a String or a StringBuffer object and compares the contents. Returns true if content is same considering the case as well.

contentEquals(StringBuffer str)
public class ContentEqualsExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      StringBuffer s2 = new StringBuffer("Java Code Geeks");

      System.out.println(s1.contentEquals(s2));  //prints true    

   }

}

2.2 Java String Case Methods

The following method converts the contents of the string to lowercase.

toLowerCase()
public class ToLowerCaseExample{

   public static void main(String[] args){

      String s1 = "JAVA CODE GEEKS";
      
      System.out.println(s1.toLowerCase());  //prints java code geeks    

   }

}

The following method converts the contents of the string to uppercase.

toUpperCase()
public class ToUpperCaseExample{

   public static void main(String[] args){

      String s1 = "java code geeks";
      
      System.out.println(s1.toUpperCase());  //prints JAVA CODE GEEKS    

   }

}

2.3 Java String Index Methods

The following method returns the index of the first occurrence of the character ch. Returns -1 if there is no occurrence.

indexOf(char ch)
public class IndexOfCharExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";
      
      System.out.println(s1.indexOf('a'));  //prints 1

      System.out.println(s1.indexOf('z'));  //prints -1    

   }

}

The following method returns the index of the first occurrence of the substring str. Returns -1 if there is no occurrence.

indexOf(String str)
public class IndexOfStringExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";
      
      System.out.println(s1.indexOf("Code"));  //prints 5

      System.out.println(s1.indexOf("Test"));  //prints -1    

   }

}

The following method returns the index of the first occurrence of the character ch after the fromIndex. It begins the search after the fromIndex in the String. Returns -1 if there is no occurrence after the fromIndex.

indexOf(char ch, int fromIndex)
public class IndexOfCharFromIndexExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";
      
      System.out.println(s1.indexOf('a',2));  //prints 3

      System.out.println(s1.indexOf('a',5));  //prints -1    

   }

}

The following method returns the index of the first occurrence of the substring str after the fromIndex. It begins the search after the fromIndex in the String. Returns -1 if there is no occurrence after the fromIndex.

indexOf(String str, int fromIndex)
public class IndexOfStringFromIndexExample{

   public static void main(String[] args){

      String s1 = "Java Code Java";
      
      System.out.println(s1.indexOf("Java",4));  //prints 10

      System.out.println(s1.indexOf("Code",10));  //prints -1    

   }

}

The following method returns the index of the last occurrence of the character ch. Returns -1 if there is no occurrence.

lastIndexOf(char ch)
public class LastIndexOfCharExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";
      
      System.out.println(s1.lastIndexOf('a'));  //prints 3

      System.out.println(s1.lastIndexOf('z'));  //prints -1    

   }

}

The following method returns the index of the last occurrence of the substring str. Returns -1 if there is no occurrence.

lastIndexOf(String str)
public class LastIndexOfStringExample{

   public static void main(String[] args){

      String s1 = "Java Code ode";
      
      System.out.println(s1.lastIndexOf("ode"));  //prints 10

      System.out.println(s1.indexOf("Test"));  //prints -1    

   }

}

The following method returns the index of the last occurrence of the character ch searching backwards beginning from the fromIndex. Returns -1 if there is no occurrence after the fromIndex.

lastIndexOf(char ch, int fromIndex)
public class LastIndexOfCharFromIndexExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";
      
      System.out.println(s1.lastIndexOf('e',9));  //prints 8

      System.out.println(s1.lastIndexOf('G',4));  //prints -1    

   }

}

The following method returns the index of the last occurrence of the substring str searching backwards beginning from the fromIndex. Returns -1 if there is no occurrence after the fromIndex.

lastIndexOf(String str, int fromIndex)
public class LastIndexOfStringFromIndexExample{

   public static void main(String[] args){

      String s1 = "Java Code Java";
      
      System.out.println(s1.lastIndexOf("Java",13));  //prints 10

      System.out.println(s1.lastIndexOf("Code",4));  //prints -1    

   }

}

2.4 Java String Substring Methods

The following method returns the substring of the string which starts from the index beginIndex and extends till endIndex-1. The beginIndex is inclusive and endIndex is exclusive.

substring(int beginIndex int endIndex)
public class SubstringExample1{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String s2 = s1.substring(0,9);
      
      System.out.println(s2);  //prints Java Code      

   }

}

The following method returns the substring of the string which starts from the index beginIndex and extends till the end of the string.

substring(int beginIndex)
public class SubstringExample2{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String s2 = s1.substring(5);
      
      System.out.println(s2);  //prints Code Geeks      

   }

}

The following method behaves exactly the same way as substring(int beginIndex, int endIndex). The only difference is subSequence returns a CharSequence.

subSequence(int beginIndex, int endIndex)
public class SubSequenceExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      CharSequence s2 = s1.subSequence(0,4);
      
      System.out.println(s2);  //prints Java      

   }

}

2.5 Java String Replace Methods

The following method replaces all the occurrences of oldChar with the newChar in the string.

replace(char oldChar, char newChar)
public class ReplaceExample1{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String s2 = s1.replace('e','i');
      
      System.out.println(s2);  //prints Java Codi Giiks      

   }

}

The following method replaces all the occurrences of string target with the string replacement.

replace(CharSequence target, CharSequence replacement)
public class ReplaceExample2{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String s2 = s1.replace("Geeks","Experts");
      
      System.out.println(s2);  //prints Java Code Experts      

   }

}

The following method replaces all the occurrences of substring which matches the regular expression regex with the string replacement.

replaceAll(String regex, String replacement)
public class ReplaceAllExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String s2 = s1.replaceAll("Geeks","Experts");  
      
      //The below line removes all white spaces
      String s3 = s1.replaceAll("\\s", "");

      System.out.println(s2);  //prints Java Code Experts  

      System.out.println(s3);  //prints JavaCodeGeeks    

   }

}

The following method replaces only the first occurrence of substring which matches the regular expression regex with the string replacement.

replaceFirst(String regex, String replacement)
public class ReplaceFirstExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks helps to learn Java";

      String s2 = s1.replaceFirst("Java","JAVA");       
      
      String s3 = s1.replaceFirst("[a]", "A");

      System.out.println(s2);  //prints JAVA Code Geeks helps to learn Java  

      System.out.println(s3);  //prints JAva Code Geeks helps to learn Java    

   }

}

2.6 Java String Compare Methods

The following method compares two string lexicographically i.e. Unicode value of each character in the strings. It returns a positive number (character value difference) if the first string is lexicographically greater than the second string, returns a negative number if first string is lexicographically lower than the second string and returns 0 if two strings are lexicographically equal. This method is case sensitive.

compareTo(String str)
public class CompareToExample1{

   public static void main(String[] args){

      String s1 = "Code";

      String s2 = "Node";

      String s3 = "Code";

      String s4 = "code";    

      System.out.println(s2.compareTo(s1));  //prints 11 as 'N' is 11 characters ahead of 'C'

      System.out.println(s1.compareTo(s3));  //prints 0  

      System.out.println(s1.compareTo(s4));  //prints -32 as 'C' is 32 characters behind 'c' 

   }

}

The following method compares two string lexicographically i.e. Unicode value of each character in the strings. It returns a positive number (character value difference) if the first string is lexicographically greater than the second string, returns a negative number if first string is lexicographically lower than the second string and returns 0 if two strings are lexicographically equal. This method is not case sensitive.

compareToIgnoreCase(String str)
public class CompareToExample2{

   public static void main(String[] args){

      String s1 = "Code";

      String s2 = "code";    

      System.out.println(s2.compareToIgnoreCase(s1));  //prints 0    

   }

}

2.7 Java String Split Methods

The following method splits the string on the matches of the regular expression regex and returns a String array containing all the elements after the split.

split(String regex)
public class SplitExample1{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String[] s2 = s1.split(" "); //Splits s1 on white spaces and stores the elements in array s2 as {"Java","Code","Geeks"}    

      System.out.println(s2.length);  //prints 3    

   }

}

The following method splits the string on the matches of the regular expression regex and returns a String array containing all the elements after the split. The number of elements in the array will not be more than the parameter limit.

split(String regex, int limit)
public class SplitExample2{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";

      String[] s2 = s1.split(" ",2); //Splits s1 on white spaces and stores only 2 elements in array s2 as {"Java","Code"}    

      System.out.println(s2.length);  //prints 2    

   }

}

2.8 Java String Other Common Methods

The following method returns the length of the string.

length()
public class LengthExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";      

      System.out.println(s1.length());  //prints 15 

   }

}

The following method returns a character Array containing all the chars of the String.

toCharArray()
public class ToCharArrayExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";      

      char[] s2 = s1.toCharArray();

      System.out.println("["+s2[0]+","+s2[1]+","+s2[2]+"]"); //prints [J,a,v]

   }

}

The following method removes the trailing and leading white spaces from the String.

trim()
public class TrimExample{

   public static void main(String[] args){

      String s1 = "     Java Code Geeks     ";      

      System.out.println(s1.trim()); //prints Java Code Geeks

   }

}

The following method returns the character present at the index specified.

charAt(int index)
public class CharAtExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";      

      char ch = s1.charAt(5);

      System.out.println(ch); //prints C

   }

}

The following method returns true if the String contains the substring represented by sequence, otherwise returns false.

contains(CharSequence sequence)
public class ContainsExample{

   public static void main(String[] args){

      String s1 = "Java Code Geeks";      

      System.out.println(s1.contains("Code")); //prints true

      System.out.println(s1.contains("Node")); //prints false

   }

}

2.9 Java 8 String Methods

The following method takes input as various Strings in var-args format and joins them separated the by the argument delimiter.

join(CharSequence delimiter, CharSequence… elements)
public class JoinExample1{

   public static void main(String[] args){     

      String joinedString = String.join("-","Java","Code","Geeks");      

      System.out.println(joinedString); //prints Java-Code-Geeks      

   }

}

The following method takes input either a list of Strings or an String Array and joins the items in the list or array separated the by the argument delimiter.

join(CharSequence delimiter, Iterable elements)
public class JoinExample2{

   public static void main(String[] args){     

      List strList = Arrays.asList("Java","Code","Geeks");     

      String joinedString = String.join("-",strList);

      System.out.println(joinedString); //prints Java-Code-Geeks      

   }

}

2.10 Java 9 String Methods

The following method converts the String into char values and returns the char values as stream of int.

chars()
public class CharsExample{

   public static void main(String[] args){        

      String str = "Java Code Geeks";

      IntStream stream = str.chars();
      
      stream.forEach(x -> System.out.printf("-%s", (char)x)); //prints -J-a-v-a- -C-o-d-e- -G-e-e-k-s    

   }

}

The following method converts the String into a stream of code point values.

codePoints()
public class CodePointsExample{

   public static void main(String[] args){        

      String str = "Java Code Geeks";

      IntStream stream = str.codePoints();
      
      stream.forEach(x -> System.out.print(
                new StringBuilder().appendCodePoint(Character.toChars(x)[0]).toString()));  //prints Java Code Geeks

   }

}

2.11 Java 11 String Methods

The following method removes the trailing and leading whitespaces from the String.

strip()
public class StripExample{

   public static void main(String[] args){        

      String str = "    Java Code Geeks   ";

      System.out.println(str.strip()); //prints Java Code Geeks

   }

}
Output
Java Code Geeks
strip() is different from already existing method trim() in the way that trim() removes only those whitespaces whose codepoint is less than or equal to ‘U+0020’ (the space character) whereas strip() removes all whitespaces.

The following method removes all leading whitespaces from the String.

stripLeading()
public class StripLeadingExample{

   public static void main(String[] args){        

      String str = "    Java Code Geeks";

      System.out.println(str.stripLeading()); //prints Java Code Geeks

   }

}
Output
Java Code Geeks

The following method removes all trailing whitespaces from the String.

stripTrailing()
public class StripTrailingExample{

   public static void main(String[] args){        

      String str = "Java Code Geeks    ";

      System.out.println(str.stripTrailing()); //prints Java Code Geeks

   }

}
Output
Java Code Geeks

The following method returns true if the String is blank, otherwise false.

isBlank()
public class IsBlankExample{

   public static void main(String[] args){        

      String str = "   ";

      System.out.println(str.isBlank()); //prints true

   }

}
Output
true
isBlank() is different from isEmpty() in the way that isBlank() also detects U+2005 whitespaces.

The following method splits a String into Stream of separate lines and separated by line terminators which could be “\n”, “\r” and “\r\n”.

lines()
public class LinesExample{

   public static void main(String[] args){        

      String str = "Java Code Geeks hosts a lot of examples in Java.\nThis is an example of lines() method.";

      str.lines().forEach(System.out::println);

   }

}
Output
Java Code Geeks hosts a lot of examples in Java.
This is an example of lines() method.

The following method concatenates the String with itself ‘n’ number of times. ‘n’ cannot be negative. If ‘n’ is 0 then it will return an empty String.

repeat(int n)
public class RepeatExample{

   public static void main(String[] args){        

      String str = "Java Code Geeks";

      System.out.println(str.repeat(2)); //prints Java Code GeeksJava Code Geeks

      System.out.println(str.repeat(0)); //prints an empty String

   }

}
Output
Java Code GeeksJava Code Geeks

2.12 Java 12 String Methods

The following method indents each line of the String with ‘n’ number of whitespaces. The method first breaks the String into separate lines wherever it finds \n and then inserts ‘n’ number of whitespaces before each line. If n is greater than 0 then it appends n whitespaces before each line. If n is smaller than 0 then it removes n whitespaces or all whitespaces if n is greater than the number of whitespaces. If n is equal to 0 then it remains unchanged.

indent(int n)
public class IndentExample{

   public static void main(String[] args){        

      String str = "Java Code Geeks.\nLearn Java";

      String str1 = "  Java Code Geeks.\n     Learn Java";

      String indentStr = str.indent(5);

      String indentStr1 = str1.indent(-3);

      System.out.println(str); 

      System.out.println(indentStr); 

      System.out.println(str1);

      System.out.println(indentStr1);

   }

}
Output
Java Code Geeks.
Learn Java
     Java Code Geeks.
     Learn Java
  Java Code Geeks.
     Learn Java
Java Code Geeks.
  Learn Java

The following method executes the function f by taking the String as input and returns output from the function.

transform(Function f)
public class TransformExample{

   public static void main(String[] args){        

      String str = "Java Code Geeks";

      var output = str.transform(input -> input.concat(" Learn Java")).transform(String::toUpperCase);

      System.out.println(output.toString());  //prints JAVA CODE GEEKS LEARN JAVA

   }

}
Output
JAVA CODE GEEKS LEARN JAVA

3. Other characteristics of String objects

String objects are immutable. This means that once a String is created, its contents cannot be changed. In the above example, every time we attempt to change its contents, e.g when concatenating, a new String object is created representing the result. Additionally, String class is final, so you cannot override its behavior.

Immutability was mostly chosen for security reasons and for performance. It also means that two different thread can share the same String and manipulate it as they want, not having to synchronize anything, because every time they make a change in the original string, a new one is created, while the old one remains untouched.

Now let’s see this :

1
2
3
4
5
6
7
String s1 = "abc";
String s2= "abc";
 
String s3 = new String("abc");
 
System.out.println(s1==s2);
System.out.println(s1==s3);

This outputs:

true
false

Literals are stored in a special place in memory, called a String pool, of course in the form of String Objects. In that pool, a String object with value “abc” is only created and stored once. Any other String that gets the value “abc” (statically – hard coded) will reference the same String object. So, every time you create a String using a literal, the system will search that pool and checks if the value of the literal exists in an object of the pool. If it does, it sends back the reference to that matching object, if not it creates a new Object and stores it in the pool. So, String references, initialized with the same literals, will point to the same String object. This technique was used to save precious memory, as it shares as much common data as possible.

Now, you can also see another reason why Strings are immutable. Imagine thread A creating a local string “abc” and then a second thread B creating his own local string “abc”. These two threads will share the same String object… If String was mutable, then if A changed the string, the change would affect thread B, but in a meaningless (put catastrophic) way.

When creating a String using new, you explicitly create a brand new object in the heap. This is also the case for non hard coded String initialization, for example, if you are reading input Strings from a source. These String Objects will not be stored in the pool. Imagine that you create an application that has to hold addresses for users living in Greece. There are four million people living in Athens, so consider the massive waste of space should you store four million String objects with value “Athens”. In order to pool those non hard coded Strings, there is an API method called intern, and can be used like so:

01
02
03
04
05
06
07
08
09
10
String s1 = "abc";
String s2= "abc";
 
String s3 = new String("abc");
 
System.out.println(s1==s2);
System.out.println(s1==s3);
 
s3 = s3.intern();
System.out.println(s1==s3);

This will now output:

true false true

When calling intern, the system follows the same procedure as if we did s3 = "abc", but without using literals.

But be careful. Before Java 7, this pool was located in a special place in the Java Heap, called PermGen. PermGen is of fixed size, and can only hold a limited amount of string literals. So, interning should be used with ease. From Java 7 onward, the pool will be stored in the normal heap, like any other object (making them eligible for garbage collection), in a form of a hashmap and you can adjust its size using -XX:StringTableSize option. You could create your own String pool for that matter, but don’t bother.

This is only one of the aspects that Java creators changed in the String class. Even more radical changes were made, including the internal String representation (it now has two less static fields).

4. Download the Eclipse Project

This was an example of Java String Class.
Download
You can download the full source code of this example here: Java String Class Example

Last updated on Aug 26, 2019

(+12 rating, 12 votes)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Ankita Swain Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Ankita Swain
Guest
Ankita Swain

Nicely explained