$show=/label

String contentEquals​() method in java with example - Internal Implementation

SHARE:

Java String contentEquals​() method. Learn contentEquals​() method in Java with example in java.lang.String package and how works its internal implementation. Learn about String class methods usage.

String contentEquals​() method in java with example:

contentEquals​ method is overloaded method in String class and these two are non static methods.

Read about Static in Java.

Syntax:

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

Return type:

boolean in both cases. Returns true if content is matches, otherwise false.


String contentEquals​() method




public boolean contentEquals​(StringBuffer sb):

Compares this string to the specified StringBuffer. The result is true if and only if this String represents the same sequence of characters as the specified StringBuffer. This method synchronizes on the StringBuffer. 

This StringBuffer method version is introduced in java 1.4.

Java String contentEquals​(StringBuffer sb) example:

In this example program, we will compare String contents with StringBuffer contents by calling contentEquals​ method. 

Taking three strings and three StringBuffer's. We compare each string value againest StringBuffer value calling contentEquals​ method. For everytime, we call contentEquals​ method, it returns boolean value. We store the result in boolean variable. Printing the result using statement System.out.println() method.

package examples.java.w3schools.string;

public class StringcontentEqualsExample {
 public static void main(String[] args) {

  String string1 = "String One"; // This is String 1
  String string2 = "String Two"; // This is String 2
  String string3 = "String Three"; // This is String 3

  StringBuffer buffer1 = new StringBuffer("String One"); // This is StringBuffer 1
  StringBuffer buffer2 = new StringBuffer("String Two"); // This is StringBuffer 1
  StringBuffer buffer3 = new StringBuffer("String Three"); // This is StringBuffer 1
  
  // invoking contentEquals(StringBuffer sb) method
  
  boolean result1 = string1.contentEquals(buffer1);
  System.out.println("Result of comparing conents of string1 with buffer1 : "+result1);
  
  boolean result2 = string2.contentEquals(buffer2);
  System.out.println("Result of comparing conents of string2 with buffer2 : "+result2);
  
  boolean result3 = string3.contentEquals(buffer3);
  System.out.println("Result of comparing conents of string3 with buffer3 : "+result3);
  
  boolean result4 = string1.contentEquals(buffer3);
  System.out.println("Result of comparing conents of string1 with buffer3 : "+result4);
 }
}

Output:

The above program will produce the following output.


String contentEquals​() method-2

Result of comparing conents of string1 with buffer1 : true
Result of comparing conents of string2 with buffer2 : true
Result of comparing conents of string3 with buffer3 : true
Result of comparing conents of string1 with buffer3 : false


result 1,2,3 are comparing same conents of StringBuffer. So, it returned true. But when compared string1 with buffer3, the result4 was false because conents are different.

Java String contentEquals​(CharSequence sb) example:

Compares this string to the specified CharSequence. The result is true if and only if this String represents the same sequence of characters as the specified CharSequence. This method synchronizes on the StringBuffer. 

This CharSequence method version is introduced in java 1.5.

CharSequence is an interface in java. It's direct implementation classes are CharBuffer, Segment, String, StringBuffer, StringBuilder.

CharBuffer, Segment, String, StringBuffer, StringBuilder


We can pass any of these to contentEquals method.

Java String contentEquals​(CharSequence sb) example:

Writing a program to compare the conents of string and StringBuilder.

Taking three strings and three StringBuilder's. We compare each string value againest StringBuilder value calling contentEquals​ method. For everytime, we call contentEquals​ method, it returns boolean value. We store the result in boolean variable. Printing the result using statement System.out.println() method.

public class StringcontentEqualsExample2 {
 public static void main(String[] args) {
  
  String string1 = "One"; // This is String 1
  String string2 = "Two"; // This is String 2
  String string3 = "Three"; // This is String 3

  StringBuilder builder1 = new StringBuilder("One"); // This is StringBuilder 1
  StringBuilder builder2 = new StringBuilder("Two"); // This is StringBuilder 1
  StringBuilder builder3 = new StringBuilder("Three"); // This is StringBuilder 1

  // invoking contentEquals(StringBuilder sb) method

  boolean result1 = string1.contentEquals(builder1);
  System.out.println("Result of comparing conents of string1 with builder1 : " + result1);

  boolean result2 = string2.contentEquals(builder2);
  System.out.println("Result of comparing conents of string2 with builder2 : " + result2);

  boolean result3 = string3.contentEquals(builder3);
  System.out.println("Result of comparing conents of string3 with builder3 : " + result3);

  boolean result4 = string1.contentEquals(builder3);
  System.out.println("Result of comparing conents of string1 with buffer3 : " + result4);
 }
}

Output:

The above program will produce the following output

Result of comparing conents of string1 with builder1 : true
Result of comparing conents of string2 with builder2 : true
Result of comparing conents of string3 with builder3 : true
Result of comparing conents of string1 with buffer3 : false


Read about: What is the difference between String.equals() and String.contentEquals() method?


String contentEquals() method Internal Implementation:

We will see now how contentEquals method is implemented internally or how contentEquals method works internally. Below codes from java 11 or jdk 11 version.

public boolean contentEquals(CharSequence cs) internal code:

public boolean contentEquals(CharSequence cs) {
        // Argument is a StringBuffer, StringBuilder
        if (cs instanceof AbstractStringBuilder) {
            if (cs instanceof StringBuffer) {
                synchronized(cs) {
                   return nonSyncContentEquals((AbstractStringBuilder)cs);
                }
            } else {
                return nonSyncContentEquals((AbstractStringBuilder)cs);
            }
        }
        // Argument is a String
        if (cs instanceof String) {
            return equals(cs);
        }
        // Argument is a generic CharSequence
        int n = cs.length();
        if (n != length()) {
            return false;
        }
        byte[] val = this.value;
        if (isLatin1()) {
            for (int i = 0; i < n; i++) {
                if ((val[i] & 0xff) != cs.charAt(i)) {
                    return false;
                }
            }
        } else {
            if (!StringUTF16.contentEquals(val, cs, n)) {
                return false;
            }
        }
        return true;
    }

AbstractStringBuilder:

A mutable sequence of characters. Implements a modifiable string. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. StringBuffer and StringBuilder are sub classes for AbstractStringBuilder.

Explanation:

1) First checks cs is instance of AbstractStringBuilder. Next checks for cs is instance of StringBuffer then call nonSyncContentEquals from synchronized block. If cs is instance of StringBuilder then call directly nonSyncContentEquals method.

2) If cs is instance of String then calls String class equal mehtod for comparing contents of both strings are equal.

3) If lengths of both cs and String are not equal then returns false.

4) IF string is latin then compare char by char in both cs and string.
5) If string is UTF then calls StringUTF16.contentEquals(val, cs, n).

public boolean contentEquals(StringBuffer sb) internal code:

   public boolean contentEquals(StringBuffer sb) {
        return contentEquals((CharSequence)sb);
    }


StringBuffer version method will call CharSequence conentEquals method internally.

Please post your questions and understanding in comment section for summary.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: String contentEquals​() method in java with example - Internal Implementation
String contentEquals​() method in java with example - Internal Implementation
Java String contentEquals​() method. Learn contentEquals​() method in Java with example in java.lang.String package and how works its internal implementation. Learn about String class methods usage.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxlcDhgiKni-MO0009immwI7Sc_vWidCKhCz9Nzc07IrlYz7zaKbno6nWAMz1-PS4pBHH0atXnvEy92Fj4uQFeR8-iNODyOTDAl1EBx9MlJgJIlfts0lhHjtYIQvKN_HLkZ02wSeKjCWw/s640/String+contentEquals%25E2%2580%258B%2528%2529+method.PNG
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxlcDhgiKni-MO0009immwI7Sc_vWidCKhCz9Nzc07IrlYz7zaKbno6nWAMz1-PS4pBHH0atXnvEy92Fj4uQFeR8-iNODyOTDAl1EBx9MlJgJIlfts0lhHjtYIQvKN_HLkZ02wSeKjCWw/s72-c/String+contentEquals%25E2%2580%258B%2528%2529+method.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/03/string-contentequals.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/03/string-contentequals.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content