Java String With Examples

In this lecture, we are going to discuss the String class in Java. As stated in the previous lecture, String is a sequence of characters. Unlike int, short, byte, etc it is not a primitive data type, but a reference data type i.e objects.

The Java platform provides String class for storage and manipulation of textual information. String class is a part of java.lang library( This is a library which is an implicit part of every Java program.

How to create a String?

The String can be created by any of the following ways:

Constructor:

This is the process of creating an object of the class using a new keyword. The use of a new keyword calls the constructor (This is a method which is called implicitly whenever the object is created using a new keyword. We discuss this in detail in our upcoming lectures). There are eleven different versions of constructors. We are going to see a few of the ones used frequently.

Example 1:

// This statement results in creating an empty string.
String myString1 = new String(); 

// This statement results in a string with value "My First String" as a 
// result of calling a constructor with a value passed in it.
String myString2 = new String("My First String"); 

Example 2:

char[] charArray = { 'M', 'y', '  ' ,'S' ,'t' ,'r' ,'i' ,'n' ,'g' };

// This statement results in a string with value "My String" as a
// result of calling a constructor with an array of characters passed in it.
String myString3 = new String(charArray); 

Assign value directly:

This is the most frequently used process. The value is put directly into the variable. For example:

String myString4 = “Hello String”;

The String is Immutable/Constant

Let us understand its concept. Whenever we try to create a String (say String myString = “Hello” ), Java stores the value(“Hello”) of the string in a dedicated section called String Constant Pool inside the heap. The variable(myString) refers to the value. So as many numbers of variables are created with the same value, no new memory allocation occurs, only the new reference variable is created pointing to the data.

Any operation performed on a string does not change its original value. The method creates a new String after the operation, stores it in String Constant Pool, and returns the reference of the generated string.

As a result, it is important to assign the generated string to a variable else it will be unreferenced and lost.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String a = "Hello ";
		String b = "World";
		System.out.println("a = "+a);
		System.out.println("b = "+b);

		System.out.println("The value of a before operation: "+a);
		a.concat(b); //This method concatenates a and b. After this operation "Hello World" is stored in String Constant Pool but stays unreferenced.
		System.out.println("The value of a after operation: "+a);
		a=a.concat(b); //This method concatenates a and b. After this operation "Hello World" is stored in String Constant Pool and is referenced by a.
		System.out.println("The value of a after operation and assignment: "+a);
	}
}

Output:

a = Hello 
b = World
The value of a before operation: Hello 
The value of a after operation: Hello 
The value of a after operation and assignment: Hello World

In order to have a mutable alternative to String, one can use String Buffer and String Builder.

How to get the String’s length?

There is a method called length(), which returns the number of characters in the String object. This method is an accessor method. The method used to obtain information about any object is known as an accessor method.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "How are you?";
		int lengthOfString = myString.length();
		System.out.println("The length of String myString is "+ lengthOfString);
	}
}

Output:

The length of String myString is 12

How to format Strings?

We are aware of printf() method which is used to print formatted output. There is another static method that belongs to the String class, format(), which is used to create a formatted String. The advantage of using format() over printf() is that format() returns String object unlike printf() which yields PrintStream object. The String is reusable and will be available post formatting.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		int myInt = 123;
		float myFloat = 12.12f;
		System.out.printf("The Formatted printf() of float variable is %f, integer variable is %d , string variable is %s.\n",myFloat,myInt,myString);
		String myFormattedString = String.format("The Formatted format() of float variable is %f, integer variable is %d , string variable is %s.",myFloat,myInt,myString);
		System.out.println(myFormattedString);
	}
}

Output:

The Formatted printf() of float variable is 12.120000, integer variable is 123 , string variable is Hello.
The Formatted format() of float variable is 12.120000, integer variable is 123 , string variable is Hello.

String Methods

String provides a wide range of methods used very frequently. Let us have a look at a few of them:

Java.lang.String.charAt() Method:

Name: charAt(int inputIndex)
Return: char
Purpose: Returns the character available at the position inputIndex.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		System.out.println(myString.charAt(1));
	}
}

Output:

e

Java.lang.String.compareTo() Method:

Name: compareTo(String inputString)
Return: int
Purpose: Returns the integer value after comparing the string to another lexicographically.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		System.out.println(myString.compareTo("Shello"));
	}
}

Output:

-11

Java.lang.String.compareToIgnoreCase() Method:

Name: compareToIgnoreCase(String inputString)
Return: int
Purpose: Returns the integer value after comparing the string to another lexicographically discarding the difference of case.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		System.out.println(myString.compareToIgnoreCase("hello"));
		System.out.println(myString.compareToIgnoreCase("heLLO"));
	}
}

Output:

0
0

Java.lang.String.concat() Method:

Name: concat(String inputString)
Return: String
Purpose: returns the new String after Concatenating the inputString to the end of the calling String

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello ";
		System.out.println(myString.concat("World"));
	}
}

Output:

Hello World

Java.lang.String.endsWith() Method:

Name: endsWith(String inputString)
Return: boolean
Purpose: Returns true/false after checking if the calling String ends with inputString.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		System.out.println(myString.endsWith("lo"));
		System.out.println(myString.endsWith("xyz"));
	}
}

Output:

true
false

Java.lang.String.equals() Method:

Name: equals(Object inputObject)
Return: boolean
Purpose: Returns true/false after comparing the calling String to inputObject object.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		System.out.println(myString.equals("Hello"));
		System.out.println(myString.equals("hello"));
	}
}

Output:

true
false

Java.lang.String.equalsIgnoreCase() Method:

Name: equalsIgnoreCase(Object inputObject)
Return: boolean
Purpose: Returns true/false after comparing the calling String to inputObject object, discarding the case difference.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		System.out.println(myString.equalsIgnoreCase("Hello"));
		System.out.println(myString.equalsIgnoreCase("hello"));
	}
}

Ouput:

true
true

Java.lang.String.indexOf() Method:

Name: indexOf(Object inputChar)
Return: int
Purpose: Returns the first index of inputChar occurrence in calling String.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		System.out.println(myString.indexOf("l"));
	}
}

Output:

2

Java.lang.String.replace() Method:

Name: replace(char presentChar, char toUpdateChar)
Return: String
Purpose: Returns the String after replacing all the presentChar with toUpdateChar in the calling String.

Example:

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello";
		System.out.println(myString.replace('l','r'));
	}
}

Output:

Herro

Java.lang.String.split() Method:

Name: split(String inputRegex)
Return: String[]
Purpose: Returns the array of String after splitting the calling String on the basis of inputRegex

Example:

import java.util.Arrays;

public class MyString
{
	public static void main(String args[])
	{
		String myString = "Hello,How,Are,You";
		System.out.println(Arrays.toString(myString.split(",")));
	}
}

Output:

[Hello, How, Are, You]

This was just a glimpse among so many methods that are available to be utilized effectively. The readers are expected to explore more methods available with String class. In the next lecture, we will discuss Java Boolean.