String handling in Java

String is one of the most widely used concepts in Java. It belongs to the Reference Data type category. String is basically an object which represents a sequence of characters in Java Language.

Java Programming language provides us with the String Class, which helps to perform various actions on the strings. Due to this class, we are able to manipulate and create a string Object.

**String Class is held up in java.lang package

Syntax

<String_Type> <string_variable> = “<sequence_of_string>”;

Example

String name =”QaTechHub”;

** One important aspect to note about the String is, they are immutable in nature. Which means that once the String Object has been created it cannot be changed.

Different Ways to Create a String Object

We can create the strings in a number of ways, and as of now we will be discussing the following 2 ways that will be usually used in the programming life-cycle:

  • Using String literal

String literal is one of the very basic ways of creating a simple object, by just enclosing the value of the object in double quotes “ ”.

Example-

class Test {

	public static void main(String[] args) {
		String var = "Welcome to QATechHub";
		System.out.println(var);
	}

}

Output –

Welcome to QATechHub

var is String Literal that has value = “Welcome to QATechHub”

  • New Keyword

Second and one of the most commonly used way of creating the String object is by using the new keyword. The new keyword helps us in allocating the memory to the Object.

class Test {

	public static void main(String[] args) {
		String var = new String("Welcome to QATechHub");
		System.out.println(var);
	}

}

Output-

Welcome to QATechHub

Each time we make a String Object, the JVM internally checks the string pool first. There might be a chance that the string Object exists in the pool, in that case a reference to the pool is returned.

On the other hand, if any reference of the string doesn’t exist in the pool, another string object is made and is set in the pool.

How is the string stored in memory?

Let’s take the following example to understand so as to how the strings are stored inside the memory.

  • When the user creates new string:

String var= "Welcome to QATechHub";

It checks if it exists in the heap, then it will create a reference, but if not then will assign memory to the same.

  • When the user creates a new string

String var2= "Hello";

Since it is not there in memory, so new memory will be allocated.

  • And another new string variable is created with the same value

String var3= "Hello";

Since now we already have a variable(var2) which holds the similar value, hence no new memory will be allocated to the variable, instead a reference will be created to ‘var2’ variable , as shown below.

String Manipulation

We usually have to perform various kinds of operations on String during the whole programming life Cycle.

Lets’ discuss some of the ways to work with strings:

  1. String Comparison
  2. String Concatenation
  3. String length

String comparison

Java allows us to compare string values with each other. For this we can either use operator or methods as shown below:

  • “==” Operator

The double equal to “==” operator is used for comparing the object reference. i.e. it checks whether the objects belong to the same reference or not.  It returns a Boolean value as a result, if it belongs to the same instance then we get the output as true, otherwise false.

Example-

public class Test {

	public static void main(String[] args) {
		String str1 = "QA";
		String str2 = "QA";
		String str3 = new String("QA");
		boolean result = (str1 == str2); // true
		System.out.println(result);
		result = (str1 == str3); // false
		System.out.println(result);
	}

}
  • equals() method

This method is used to verify if the String variables are holding equal values or not. It matches the assigned value to the variables. It also returns a Boolean value depending on the result, whether it is true or false.

Example-

public class Test {

	public static void main(String[] args) {
		String str1 = "QA";
		String str2 = "QA";
		String str3 = new String("QA");
		boolean result = str1.equals(str2); // true
		System.out.println(result);
		result = str1.equals(str3); // true
		System.out.println(result);
	}

}
  • comparesTo() method

comparesTo() method helps to compare the String alphabetically. It compares the value and returns an integer output as a result.

It returns a positive, negative or zero (0) value if a String is greater than, or smaller than, or if they are equal respectively. Following illustration would help in understanding the end result.

Example-

public class Test {

	public static void main(String[] args) {
		String str1 = "Java";
		String str2 = "JAVA";
		String str3 = "Java";
		int a = str1.compareTo(str2); // return 32 because str2 &gt; str1
		System.out.println(a);
		a = str1.compareTo(str3); // return 0 because str1 == str3
		System.out.println(a);
		a = str2.compareTo(str1); // return -32 because str2 < str1
		System.out.println(a);
	}
}

String Concatenation

We have 2 different ways that we can use to concatenate two or more strings.

  • concat() method

This method is used for adding two or more strings into a single Object of type String. We can use this whenever we need to combine different String objects into one.

Syntax-

String finalString = string1.concat(string2);

Example-

public class Test {

	public static void main(String[] args) {
		String str1 = "QA";
		String str2 = "TechHub";
		String str3 = str1.concat(str2);
		System.out.println(str3); //QATechHub
	}

}
  • ‘+’ Operator

Another way that has been provided by Java for the concatenation of the String is using the ‘+’ operator.

This operator has two different functionalities, one which we all are aware of, i.e., adding two or more integer numbers. Another functionality can be understood with the help of the below example, where we use this operator to join two strings.

Example-

public class Test {

	public static void main(String[] args) {
		String str1 = "QA";
		String str2 = "TechHub";
		String str3 = str1+str2;
		System.out.println(str3); //QATechHub
	}

}

String length

While writing programs, we might come across many occasions when we are needed to calculate the length of the string object, which might be required for the manipulation of the Strings.

This method helps in determining the number of characters in the String Object. It is provided to us by the String class.

Example –

public class Test {

	public static void main(String[] args) {
		String str1 = "QA";
		String str2 = "TechHub";

		System.out.println(str1.length()); // 2
		System.out.println(str2.length());// 7
	}

}

But the String handling is not limited to the above mentioned methods only, there are many methods available that could help us in performing different kinds of operations on different String Objects.

The following table provides brief information about different functions in java:

MethodDescription
charAt()Output – Provides the character at the specified index (position)
codePointAt()Output- Provides a Unicode of the character at the specified index (position)
compareToIgnoreCase()Provides the comparison mechanism by ignoring whether it is a capital or a small letter
contains()To check whether a String object contains a specified value or not 
contentEquals()Checks whether a string contains the exact same sequence of characters of the specified CharSequence or StringBuffer
copyValueOf()Returns a String that represents the characters of the character array
endsWith()Returns true, if the String Object ends with the mentioned character
equalsIgnoreCase()Compares two strings, ignoring case considerations
format()Returns a formatted string based on the provided expression
getChars()Copies characters from a string to an array of chars
hashCode()Provides the hash code of a string
indexOf()Returns the position of the first found occurrence of specified characters in a string
isEmpty()Verifies whether a String object is holding any value or not
lastIndexOf()Output- Provides the last positional occurrence of the mentioned character in the String
matches()Searches a string for a match against a regular expression, and returns the matches
replace()Returns a new string by replacing the specified characters with the new replacement character or text
replaceAll()Returns a new string by replacing the expression with the new replacement expression or text
split()Returns an array of substrings 
startsWith()Returns true, if the String Object starts with the mentioned character 
subSequence()Returns a Substring out of the main String Object
substring()Returns the characters from a String Object, taking into consideration start position and end position
toCharArray()Converts  object to a new character array
toLowerCase()Returns the String in lower case
toString()Converts to String Object 
toUpperCase()Returns the String in upper case
trim()Helps in removing the whitespace from both left and right side of the String object 
valueOf()Output – Provides the primitive value of the object
Tejasvi Nanda

About the Author

Tejasvi Nanda