इस लेख में हम समझेंगे कि Java में == ऑपरेटर और equals() मेथड में क्या अंतर है। == (बराबर) ऑपरेटर जांचता है कि दो ऑपरेंड्स के मान बराबर हैं या नहीं, यदि हां तो कंडीशन सत्य हो जाती है।
equals() मेथड इस स्ट्रिंग की तुलना निर्दिष्ट ऑब्जेक्ट से करता है। परिणाम तभी सत्य होता है जब आर्गुमेंट null नहीं है और एक String ऑब्जेक्ट है जो इस ऑब्जेक्ट के समान कैरेक्टर सीक्वेंस को दर्शाता है।
उदाहरण
इनपुट:
The first string : abcde The second string: 12345
आउटपुट:
Using == operator to compare the two strings: false Using equals() to compare the two strings: false
एल्गोरिदम
- शुरुआत
- दो स्ट्रिंग्स
input_string_1,input_string_2और दो बूलियन मानresult_1,result_2डिक्लेयर करें - मान परिभाषित करें
- == ऑपरेटर का उपयोग करके दो स्ट्रिंग्स की तुलना करें और परिणाम को
result_1में असाइन करें equals()फंक्शन का उपयोग करके दो स्ट्रिंग्स की तुलना करें और परिणाम कोresult_2में असाइन करें- परिणाम प्रदर्शित करें
- रोकें
उदाहरण 1: मुख्य फंक्शन में सभी ऑपरेशन
public class Compare {
public static void main(String[] args) {
String input_string_1 = new String("abcde");
System.out.println("The first string is defined as: " + input_string_1);
String input_string_2 = new String("12345");
System.out.println("The second string is defined as: " + input_string_2);
boolean result_1 = (input_string_1 == input_string_2);
System.out.println("\nUsing == operator to compare the two strings: " + result_1);
boolean result_2 = input_string_1.equals(input_string_2);
System.out.println("Using equals() to compare the two strings: " + result_2);
}
}
आउटपुट
The first string is defined as: abcde The second string is defined as: 12345 Using == operator to compare the two strings: false Using equals() to compare the two strings: false
उदाहरण 2: ऑब्जेक्ट-ओरिएंटेड दृष्टिकोण
public class Demo {
static void compare(String input_string_1, String input_string_2) {
boolean result_1 = (input_string_1 == input_string_2);
System.out.println("\nUsing == operator to compare the two strings: " + result_1);
boolean result_2 = input_string_1.equals(input_string_2);
System.out.println("Using equals() to compare the two strings: " + result_2);
}
public static void main(String[] args) {
String input_string_1 = new String("abcde");
System.out.println("The first string is defined as: " + input_string_1);
String input_string_2 = new String("12345");
System.out.println("The second string is defined as: " + input_string_2);
compare(input_string_1, input_string_2);
}
}
आउटपुट
The first string is defined as: abcde The second string is defined as: 12345 Using == operator to compare the two strings: false Using equals() to compare the two strings: false