Guidewire Interview Question
32 Interview Reviews |
Back to all Guidewire Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Technical Consultant at Guidewire:
how do you compare two java string object if they have the same string stored in them ?
| Tags: | java question See more , See less 8 |
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (3)
4 of 4 people found this helpful
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.
Helpful Answer?
Yes |
No
Inappropriate?
1 of 2 people found this helpful
String s1="xxx"
String s2="xxx"
the expression s1==s2 would evaluate false as the are actually different expressions
so you can use equals("xxx") or compareTo("xxxx"). I like using compareTo("xxx")==0 to test whether strings point to the same value.
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up



0 of 0 people found this helpful
by Rajan: