На одном известном сообществе Java разработчиков задали вопрос "В чем различие между оператором == и методом euqals()"? На этот вопрос я постарался ответить максимально просто с примерами кода
Если вам тоже пока не понятно, тогда этот пример для вас:
String box6;
String box7;
String box1 = new String("Apple");
String box2 = new String("Apple");
String box3 = "Apple";
String box4 = "Apple";
String box5 = "apple";
box6 = new String("Orange");
box7 = new String("Orange");
System.out.println(box6.equals(box7)); //True
System.out.println(box6 == box7); //False. box6 and box7 are pointing to two different objects even though both of them share the same string content. It is because of new String() every time a new object is created.
// When you call new for box1 and box2, each one gets a new reference that points to the "apple" in the string table. The references are different, but the content is the same.
System.out.println(box1 == box2); //It prints false(reference comparison for two objects)
System.out.println(box1.equals(box2)); //It prints true (content comparison for two Strings)
System.out.println(box3 == box4); //True. Literals are interned by the compiler and thus refer to the same object
System.out.println(box3 == box2); //False. They are not the same object
System.out.println(box3 == box5); //False
System.out.println(box3.equals(box4)); //True. These two have the same value
System.out.println(box3.equals(box2)); //True
System.out.println(box3.equals(box5)); //String equals method returns false
System.out.println(box3.equalsIgnoreCase(box5)); //String compare while ignoring case,returns true
// The == operator compares the reference value of objects
// The equals() method present in the java.lang.String class compares the contents of the String object (to another object), does a character-by-character comparison of the contents.
Комментариев нет :
Отправить комментарий
Оставить отзыв