how do you compare two java string object if they have the same string stored in them ?
Anonymous
The equals method returns a boolean primitive. This is so that it can be used to drive an if, while or other looping statement. It can be used where you would use the == operator with a primitive. The operation of the equal method and == operator has some strange side effects though when used to compare Strings. This is one occasion when the immutable nature of Strings, and the way they are handled by Java(uses Pooling), can be confusing. There are two ways of creating a String in Java. The one way does not use the new operator. Thus normally a String is created String s = new String("Hello"); but a slightly shorter method can be used String s= "GoodBye"; << like in C (as == comes from C) Generally there is little difference between these two ways of creating strings, but such questions as this one require you to know the difference. The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String pool. The String pool is a way Java conserves resources. To illustrate the effect of this String s = "Hello"; String s2 = "Hello"; if (s==s2){ System.out.println("Equal without new operator"); } String t = new String("Hello"); string u = new String("Hello"); if (t==u){ System.out.println("Equal with new operator"); } From the previous objective you might expect that the first output "Equal without new operator" would never be seen as s and s2 are different objects, and the == operator tests what an object points to, not its value. However because of the way Java conserves resources by re-using identical strings that are created without the new operator, then s and s2 will have the same "address" and the code does output the string "Equal without new operator" However with the second set of strings t and u, the new operator forces Java to create separate strings. Because the == operator only compares the address of the object, not the value, t and u have different addresses and thus the string "Equal with new operator" is never seen. ANS : The equals method applied to a String, regardless of how that String was created, always performs a character by character comparison, its safer than == which depends on how it was created - if new was used the pointer ref would be different even for the same contents, if assignment was used then pooling uses the same reference for both same words thus pointer ref would be same.
Check out your Company Bowl for anonymous work chats.