using-equality-(==)-operator-to-compare-strings-in-java

In Java, evaluating two strings is a frequently encountered activity in contexts such as file verification, user validation, form submission analysis, and database interactions. Java offers various techniques for string comparison, one of which is the == operator.

This article will explore how we can evaluate two strings utilizing the == operator in Java.

Table of Contents:

What is the == Operator in Java?

The ‘==’ operator in Java is utilized to compare the reference points (memory addresses) of two strings rather than their actual contents. It determines whether both references lead to the same string object in memory. This operator == is mainly used for comparing primitive data types, whereas .equals() is more suitable for comparing the content of strings.

Syntax:

boolean result = string1 == string2;

Where:

  • String1: The first string under evaluation.
  • String2: The second string under evaluation.
  • Result: A boolean value (true if both references point to the same object, false otherwise).

Return Type: It invariably returns a boolean value, either true or false.

Illustrations for Comparing Strings using the == Operator

Below are some examples to evaluate strings using the == Operator.

Illustration 1: Evaluating Strings Using the == Operator

In the following example, we will employ the == operator to compare two strings in Java:

Java

Code Copied!

var isMobile = window.innerWidth “);

editor48362.setValue(decodedContent); // Set the default text editor48362.clearSelection();

editor48362.setOptions({ maxLines: Infinity });

function decodeHTML48362(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard48362() { const code = editor48362.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor48362 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor48362 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode48362() {

var code = editor48362.getSession().getValue();

jQuery(“#runBtn48362 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “java”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output48362”).html(“

"+data+"

“); jQuery(“.maineditor48362 .code-editor-output”).show(); jQuery(“#runBtn48362 i.run-code”).hide(); } }) }

function closeoutput48362() { jQuery(“.maineditor48362 .code-editor-output”).hide(); }

// Attach event listeners to the buttons document.getElementById(“copyBtn48362”).addEventListener(“click”, copyCodeToClipboard48362); document.getElementById(“runBtn48362”).addEventListener(“click”, runCode48362); document.getElementById(“closeoutputBtn48362”).addEventListener(“click”, closeoutput48362);

Output:

Comparing Strings Using == Operator

Explanation: As both str1 and str2 are string literals located in the string pool, they point to the same memory location, thus making == return true. Conversely, str3 is found in the heap, and comparing it with str1 via == results in false.

Illustration 2: Comparing String Instances Created

“`html

Utilizing the new Keyword

Let’s examine the example below, where we generated string instances utilizing the new Keyword:

Java

Code Copied!

var isMobile = window.innerWidth “);

editor54630.setValue(decodedContent); // Assign the default text editor54630.clearSelection();

editor54630.setOptions({ maxLines: Infinity });

function decodeHTML54630(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard54630() { const code = editor54630.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert(“Code copied to clipboard!”);

jQuery(“.maineditor54630 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor54630 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode54630() {

var code = editor54630.getSession().getValue();

jQuery(“#runBtn54630 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”,

data: { language: “java”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output54630”).html(“

"+data+"");
									jQuery(".maineditor54630 .code-editor-output").show();
									jQuery("#runBtn54630 i.run-code").hide();

} })

}

function closeoutput54630() { var code = editor54630.getSession().getValue(); jQuery(".maineditor54630 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn54630").addEventListener("click", copyCodeToClipboard54630); document.getElementById("runBtn54630").addEventListener("click", runCode54630); document.getElementById("closeoutputBtn54630").addEventListener("click", closeoutput54630);

Result:

Comparing String Objects Created Using new Keyword

Clarification: In the above demonstration, we established two strings through the new keyword. As new String(“Intellipaat”) generates two distinct instances in memory, == yields false, despite the equivalence of string content.

Attention: This is a constraint of the == operator; it solely compares two strings that share the same memory reference. 

Instance 3: Comparing String Literals and Instances

In the subsequent example, we will employ string literals and instances to evaluate two strings in Java:

Instance:

Java

Code Copied!

var isMobile = window.innerWidth ");

editor62264.setValue(decodedContent); // Assign the default text editor62264.clearSelection();

editor62264.setOptions({ maxLines: Infinity });

function decodeHTML62264(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard62264() { const code = editor62264.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor62264 .copymessage").show(); setTimeout(function() { jQuery(".maineditor62264 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); } ``````javascript 2000); }).catch(err => { console.error("Issue copying code: ", err); }); }

function executeCode62264() {

var code = editor62264.getSession().getValue();

jQuery("#runBtn62264 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "java", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output62264").html("

"+data+"");
									jQuery(".maineditor62264 .code-editor-output").show();
									jQuery("#runBtn62264 i.run-code").hide();

} })

}

function hideOutput62264() { var code = editor62264.getSession().getValue(); jQuery(".maineditor62264 .code-editor-output").hide(); }

// Bind event listeners to the buttons document.getElementById("copyBtn62264").addEventListener("click", copyCodeToClipboard62264); document.getElementById("runBtn62264").addEventListener("click", executeCode62264); document.getElementById("closeoutputBtn62264").addEventListener("click", hideOutput62264);

Result:

Contrasting String Literals and Objects

Clarification: In the preceding illustration, str1 is a string literal located in the string pool, whereas str2 is a newly created object in heap memory. Given that they point to distinct memory locations, == yields false.

Summary

In this article, we have discovered how to utilize the == operator for comparing two strings through various examples. We have also examined the constraints of the == operator in Java.

The == operator is predominantly applied to compare primitive data types.

If you aspire to master the Java Programming language, you may check out our Java Course.

Alternative Approaches to Compare Strings in Java

  • Employing User-Defined Function
  • Using String.equalsIgnoreCase() Method
  • Utilizing Objects.equals() Method
  • Implementing String.compareTo() Method
  • Deploying compareToIgnoreCase() Method
  • Using startsWith() Method
  • Applying endsWith() Method

The article Using Equality (==) Operator to Compare Strings in Java first appeared on Intellipaat Blog.

“`


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This