No announcement

Frequent operations on strings

String length

Use length method to find the length of the string.

Checking empty string

Using length method check if the length of the string is 0. If the length is 0 this means that the string is empty.

String comparison and null check

Use the equals method to check whether a given string is equal to another string. For null check if the string equals “”.

Do not use the equality check (==) operator to test strings for equality, as this operator only determines whether the strings are saved at same location or not.


package com.codingnous.tutorial;

public class StringOperationsDemo {

	public static void main(String[] args) {

		// Declare and initialize two strings
		String s1 = "quick brown fox";
		String s2 = "";
		String s3 = "quick brown fox";

		// Determining string lenght using length()
		System.out.println("Length of string S1 \"" + s1 + "\" is " + s1.length());

		// Checking whether string s1 is empty.
		if (s1.length() == 0) {
			System.out.println("String S1 is empty.");
		} else {
			System.out.println("String S1 is not empty.");

		// Checking whether string s2 is empty.
		if (s2.length() == 0) {
			System.out.println("String S2 is empty.");
		} else {
			System.out.println("String S2 is not empty.");

		// Check whether s1 & s2 are equal.
		System.out.println("S1 & S2 are equal? " + s1.equals(s2));
		// Check whether s1 & s3 are equal.
		System.out.println("S1 & S3 are equal? " + s1.equals(s3));


Length of string S1 "quick brown fox" is 15 String S1 is not empty. String S2 is empty. S1 & S2 are equal? false S1 & S3 are equal? true