w3resource

Java: Compare a given string to the specified string buffer


10. Compare with StringBuffer

Write a Java program to compare a given string to a specified string buffer.

Sample Solution:

Java Code:

// Define a public class named Exercise10.
public class Exercise10 {
    // Define the main method.
    public static void main(String[] args) {
        // Declare and initialize two string variables, str1 and str2.
        String str1 = "example.com", str2 = "Example.com";
        
        // Create a StringBuffer object strbuf initialized with the value of str1.
        StringBuffer strbuf = new StringBuffer(str1);
    
        // Compare str1 and strbuf for content equality and print the result.
        System.out.println("Comparing " + str1 + " and " + strbuf + ": " + str1.contentEquals(strbuf));
    
        // Compare str2 and strbuf for content equality and print the result.
        System.out.println("Comparing " + str2 + " and " + strbuf + ": " + str2.contentEquals(strbuf));
    }
}

Sample Output:

Comparing example.com and example.com: true                                                                   
Comparing Example.com and example.com: false 

Flowchart:

Flowchart: Java String Exercises - Compare a given string to the specified string buffer


For more Practice: Solve these Related Problems:

  • Write a Java program to compare a string with the contents of a StringBuffer after reversing its characters.
  • Write a Java program to test equality between a string and a StringBuffer after converting both to lowercase.
  • Write a Java program to compare two strings, one provided as a StringBuffer and one as a literal, for exact match.
  • Write a Java program to compare a string with a substring extracted from a StringBuffer, handling potential exceptions.

Go to:


PREV : Compare with Char Sequence.
NEXT : String from Character Array.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.