How to Use Java String Class in Java

String Class in Java

A String is a sequence of characters like “Greeting”. Java does not have String as an in-built data type, while Java standard library does keep a predefined String class. String class comes under package java.lang. It is the final type of class that is why string is an immutable object which means it is constant and cannot be changed over time once it has been created.

String object can be created in two ways

  1. Using String Literal
  2. Using a new keyword

String Literal

String literal is a reference to a string object. Java String literal is created by using double-quotes. The value of a String Literal object is the sequence of characters that is enclosed in double-quotes. String Literal has its own private pool to manage String Literal values. This pool lies in the Java heap. All various strings sit in this common String Constant Pool. When a String literal is created for any value, Java Compiler first checks in the String Constant Pool, if it exists returns the reference(memory address) of the pool string otherwise creates a new string instance and place it in the pool.

Taking an example to be more clear- If we create a String literal String Str1=”Greetings”, Java Compiler first checks it in the String Constant Pool, as it is new and Java Compiler will not find it in the pool, so it will create a new object and string “Greetings” will be available in String Constant Pool. Now we create one more variable with the same value, String Str2=”Greetings”, as per process Java Compiler will search this string in String Constant Pool and find it, now it will not create a new object while returning the same reference(memory address) of the existing string “Greetings”. In another word, str1 and Str2 will denote the same reference (memory address).

If the same value of the string is defined into another class using String Literal then also it will denote the same reference if it exists in String Constant Pool.

You can check through the program too. Once you will run this program you will always get true as both variables are referring to the same location in the String pool. We have created 2 string literals str1 and str2 with the same value. while we check both the string using == operator, it returns true which means both are denoting the same reference.

public class Example1 {
 
    private void test() {
          String str1 = "Greetings";
          String str2 = "Greetings";
          System.out.println(str1 == str2);
    }
 
    public static void main(String[] args) {
          new Example1().test();
    }
 
}
 

Output : true
String Referece
String Referece

In the String pool, values are defined as case sensitive. Means the reference of the same sequence of characters and length in uppercase and lowercase will be different, like “Greetings” and “greeting” will have different references in the string pool

public class Example1 {
 
    private void test() {
          String str1 = "Greetings";
          String str2 = "greetings";
          System.out.println(str1 == str2);
    }
 
    public static void main(String[] args) {
          new Example1().test();
    }
 
}

 
Output : false

In Java, one String object is shared by all String literals constant expression with the same characters sequence. Such Strings are called to be interned, Means all the String literals having the same value will share a unique String object.

The Compiler uses compile-time constant expression to handle String literals.  

In the below example, the Java compiler will evaluate the constant expression for the 2 String literals. Both will refer to the same string object in the string pool. So both will refer to the same location in String Constant Pool.

String str3 = "Hello! RoundTheTech";
String str4 = "Hello!" + " RoundTheTech"; // compile-time constant expression
public class Example1 {
 
    private void test() {
          String str3 = "Hello! RoundTheTech";
          String str4 = "Hello!" + " RoundTheTech"; // compile-time constant expression
          System.out.println(str3);
          System.out.println(str4);
          System.out.println(str3 == str4);
 
    }
 
    public static void main(String[] args) {
          new Example1().test();
    }
 
}
 

Output : true

In the below example, the Java compiler will evaluate the constant expression, it found one reference variable and one constant expression, resulting, it is not a string that is already interned. So it will create a new string in String Constant Pool.

String str5 = "Hello!";
String str6= str5 + " RoundTheTech"; // not a compile-time constant expression
public class Example3 {
   
    private void test() {
          String str3 = "Hello! RoundTheTech";
          String str4 = "Hello!" + " RoundTheTech"; // compile-time constant expression
          System.out.println(str3);
          System.out.println(str4);
          System.out.println(str3 == str4);
         
          String str5 = "Hello!";
          String str6= str5 + " RoundTheTech"; // not a compile-time constant expression
         
          System.out.println(str6);
          System.out.println(str3 == str6);
 
 
    }
   
    public static void main(String[] args) {
          new Example3().test();
    }
 
}
 

 
Output
Hello! Round the Tech
Hello! Round the Tech
true
Hello! Round the Tech
false

Using New Keyword

String  strObject =  new String();

String objects can be created using a new keyword. By this way, a new string object is created in normal heap memory. Using new keywords, different objects will be created in memory for the same string value. Like in the below example, for the same string “Hello! RoundTheTech” 2 different objects will be created in heap memory.

String str10 = new String(“Hello! Round the Tech”) ; 

String str11 = new String(“Hello! Round the Tech”) ; 

 How to create String Object

In String class, numerous constructors with different types of arguments are available to create and initialize the string objects.  

Most commonly used constructors are

  1. The Constructor to create a new string object with empty content
    String strObject1 = new String();   //blank string
  2. The Constructor to create a new string object with passing content as an argument.
    String str11 = new String(“Hello! Round the Tech”);    //some string

If you create the same string “Hello! RoundTheTech” using both the ways, one by using String literal and another using new keyword, then both will denote the different string object references. When you will check using == operator you will get false as the memory address is different for both the objects. But if you will check the equality of both content using equals(). You will get true because it checks the content for both the objects

String str3 = "Hello! RoundTheTech";   // str3 object by string literal

String str11 = new String("Hello! RoundTheTech"); //str11 object by new keyword


public class Example3 {
   
private void test() {
 String str3 = "Hello! RoundTheTech";   // str3 object by string literal
 String str11 = new String("Hello! RoundTheTech");// str11 object by new keyword
 
 System.out.println(str3);
 System.out.println(str11);        
 System.out.println(str3 == str11);
 System.out.println(str3.equals(str11));
}
   
public static void main(String[] args) {
   new Example3().test();
 }
 
}

 
Output
Hello! Round the Tech
Hello! Round the Tech
false
true

Methods Used in String Class

SequenceMethodDescription
1char charAt(int index)This method is used to return the character of the string at specified index. First character is at index 0 while last is at string length-1 . StringIndexOutOfBounds Exception is thrown if valid index value is not passed.
2int length()Returns the number of characters count  in  a string.
3static String format(String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s).
4static String format(Locale l, String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s) and locale.
5String substring(int beginIndex)Returns substring from the given index position to the end index of the string.
6String substring(int beginIndex, int endIndex)Returns substring from the specified begin index to the specified end index.
7boolean contains(CharSequence s)Returns boolean value(true/false). It searches the given sequence of characters within the string and returns true/false accordingly. Characters will be case sensitive while searching in string.
8static String join(CharSequence delimiter, CharSequence… elements)Returns joined string. This method joins each passing String using the specified delimiter. It is a static method.
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)Returns the joined string. This method joins each passing string object of an iterate object using the specified delimiter and returns the concatenated string. It is a static method.
10boolean equals(Object another)Returns boolean value(true/false). It checks the equality of string with the passing object.
11boolean isEmpty()Returns boolean value(true/false). It returns true if the string is empty otherwise returns false.
12String concat(String str)Returns the concatenating string. It concatenates the passing string at the end of the string.
13String replace(char old, char new)Return the replaced string. It replaces all occurrences of the specified character with the new character.
14String replace(CharSequence old, CharSequence new)Return the replaced string. It replaces all occurrences of the specified Character sequence with the specified new Character sequence.
15String replaceAll(String regex, String replacement)Returns the replaced string. It replaces all occurrences of the sequence of characters with the given replacement string that are matching with the given regular expression.
16String replaceFirst(String regex, String replacement)Returns the replaced string. It replaces the first matching sequence of characters with the replacement string that matches with the given regular expression.
17static boolean equalsIgnoreCase(String another)Returns the boolean (true/false) value. It compares the passing string with string by ignoring the case. It  compares the content irrespective of lowercase or uppercase of the character(s).
18String[] split(String regex)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. String is breaked into strings from all  the matching regular expressions.
19String[] split(String regex, int limit)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. It breaks the string from all the matching regular expression upto the given limit.
20String intern()Returns an interned string. This method helps to compare two objects using == operator and checks in a string constant pool. it is faster for comparison.
21int indexOf(int ch)Returns the index value of first occurrence of the specified character within the string
22int indexOf(int ch, int fromIndex)Returns the index value of first occurrence of the specified character from the substring starting from specified index
23int indexOf(String substring)Returns the index value of first occurrence of the specified substring within the string.
24int indexOf(String substring, int fromIndex)Returns the index value of the first occurrence of the specified string within the substring starting from specified index to end of the string index.
25int lastIndexOf(int ch)Returns the index value of last occurrence of the specified character
26int lastIndexOf (int ch, int fromIndex)Returns the index value of last occurrence of the specified character, search starts at given fromIndex. 
27int lastIndexOf (String str)Returns the index value of last occurrence of the specified string.
28int lastIndexOf (String str, int fromIndexReturns the index value of last occurrence of the specified string, searches start from given fromIndex
29String toLowerCase()Returns all the characters of the string in lowercase .
30String toLowerCase(Locale l)Returns all the characters of the string in lowercase using specified locale.
31String toUpperCase()Returns all the characters of the string in uppercase.
32String toUpperCase(Locale l)Returns all the characters of the string in uppercase using specified locale.
33String trim()Returns the string after removing the white space from the beginning and end of the string.
34static String valueOf(int value)Return the converted string. It converts the objects and all primitive types of values into string. It is a static method.

How to Convert Primitive Values and Object to the String

String class overrides the toString() method of Object class and returns the String object itself. String class also defines the set of static overloaded valueOf() methods to convert objects and primitive datatype value into string objects.

static String valueOf(Object obj) method

This method converts passing object into String Object. This method call is equivalent to object.toString()

Example : 

     List<String> list = new ArrayList<String>();

     list.add("Round");
     list.add("The");
     list.add("Tech");            
     
     String listString = String.valueOf(list);
     System.out.println(listString);

static String valueOf(char[] character) method

This method converts the passing character array into String. Like

char ch[] = { 's', 't', 'r', 'i', 'n', 'g', 's' };

// converting charArray into String

String charArrayString = String.valueOf(ch);
System.out.println(charArrayString);

static String valueOf(boolean b) method

This method converts passing boolean value true/false into Strings “true”/”false”

boolean isTrue = true;

// converting boolean into String
String booleanString = String.valueOf(isTrue);
System.out.println(booleanString);

static String valueOf(char c) method

This method converts the passing character parameter into String.

char charTest = 's';

// converting char into String

String charString = String.valueOf(charTest);

System.out.println(charString);

static String valueOf(int i) method

This method converts the passing int type value into String.

int age = 32;

          // converting int value into String
          
          String intString = String.valueOf(age);

          System.out.println(intString);

static String valueOf(float f) method

This method converts the passing float type value into String.

float salary = 32000f;

// converting int value into String

String floatString = String.valueOf(salary);

System.out.println(floatString);

static String valueOf(long l) method

This method converts passing long value into a String.

long distance = 320000000l;

 // converting int value into String

String longString = String.valueOf(distance);

System.out.println(longString);

static String valueOf(double d) method

This method converts the passing double value into String.

double doubleNumber = 3.23456734544434d;

// converting int value into String

String doubleString = String.valueOf(doubleNumber);

System.out.println(doubleString);

Let us Learn How to use valueOf() Methods in program

Example :
 
import java.util.ArrayList;
import java.util.List;
 
public class Example3 {
 
   
    private void test() {
 
          List<String> list = new ArrayList<String>();
          list.add("Round");
          list.add("The");
          list.add("Tech");
          // converting object into String
          String listString = String.valueOf(list);
          System.out.println(listString);
 
         
          char ch[] = { 's', 't', 'r', 'i', 'n', 'g', 's' };
          // converting charArray into String
          String charArrayString = String.valueOf(ch);
          System.out.println(charArrayString);
 
         
          boolean isTrue = true;
          // converting boolean into String
          String booleanString = String.valueOf(isTrue);
          System.out.println(booleanString);
 
         
          char charTest = 's';
          // converting char into String
          String charString = String.valueOf(charTest);
          System.out.println(charString);

         
          int age = 32;
          // converting int value into String
          String intString = String.valueOf(age);
          System.out.println(intString);

         
          float salary = 32000f;
          // converting int value into String
          String floatString = String.valueOf(salary);
          System.out.println(floatString);

         
          long distance = 320000000l;
          // converting int value into String
          String longString = String.valueOf(distance);
          System.out.println(longString);

         
          double doubleNumber = 3.23456734544434d;
          // converting int value into String
          String doubleString = String.valueOf(doubleNumber);
          System.out.println(doubleString);
    }
 
    public static void main(String[] args) {
          new Example3().test();
    }
 
}

 
Output :
[Round, the, Tech]
strings
true
s
32
32000.0
320000000
3.23456734544434

In this article, we have learned all about String class, String Constant Pool, String Class available methods, and valueOf() method with examples. We learned how to create String objects using string literal and new keyword. We will come up with more articles explaining all the String methods description with examples.

Leave a Reply

Your email address will not be published. Required fields are marked *