java.lang.String contentEquals()

Description :

This java tutorial shows how to use the contentEquals() method of java.lang.String class. This method returns a boolean data type if the input parameter is equal to the String in terms of character sequence.

Method Syntax :

public boolean contentEquals(StringBuffer sb)
public boolean contentEquals(CharSequence cs)

Parameter Input :

Data Type Parameter Description
StringBuffer sb The String is compared to this StringBuffer character sequence
CharSequence cs The String is compared to this Charsequence

Method Returns :

This method returns booelan datatype that corresponds to the character sequence equality of the String to the parameter input.

Compatibility Version :

Requires Java 1.4 for Stringbuffer parameter input
Requires Java 1.5 for CharSequence parameter input

Java Code Example :

This example source code demonstrates the use of contentEquals(StringBuffer sb) method of String class. A String variable equals to “Mark Philly” will be compared to the input coming from the console input. The input is break down first in first name and last name. The two input strings will be combined into one string ‘full name’ using StringBuffer append method.

package com.javatutorialhq.java.tutorial.string;

import java.util.Scanner;

/*
 * This java example source code gets two string
 * input first name and last name
 * combines two strings using StringBuffer
 * Verify equality of two string using contentEquals
 */

public class StringContentEqualsDemo {

    private static Scanner s;

    public static void main(String[] args) {
        String fullName = "Mark Philly";
        System.out.print("FirstName:");
        // get the String first name from console input

        s = new Scanner(System.in);
        StringBuffer sb = new StringBuffer(s.nextLine());
        System.out.print("LastName:");
        // get the String last name from console input
        s = new Scanner(System.in);
        sb.append(" "+s.nextLine());

        // verify equality of fullName and string inputs
        if(fullName.contentEquals(sb)){
            System.out.println("String content is equal");
        }
        else{
            System.out.println("String content is not equals");
        }

    }

}

Sample Output :

Running the contentEquals() example source code will give you the following output

java string contentequals method example

java string contentequals method example

Suggested Reading List :