+ 4
What will be output of following...true or false?
the method compares two strings. public static boolean compare (String a , String b){ if(a.length()!=b.length()) return false; for (int i=0;i<a.length():i++) if(a.CharAt(i)!=b.CharAt(i)) return false; return true; } can anyone explain me, whats going on here in this code?
9 Answers
+ 4
If you actually look through your code and see what each line carefully the answer should be obvious.
If I can do it, you can. I am beginner at Java
+ 3
l'm asking this because the answer is 'true' for above code. I'm confused how can we get this without knowing the Strings a and b
+ 2
two strings are compared to see if their contents are equal.
if they are of different lengths, they are not equal.
running through them one character at a time, if two corresponding characters are different, the strings are not equal.
otherwise they are equal.
+ 2
In the first if-condition it is checked whether the length of both Strings are the same or not.
Obviously, if they don't share the same length, they can not be the same string and so, the output would be false.
In the following for - loop, you iterate over the chars of the Strings and compare each of them with the other String (so char at Position 0 from string A must be the same as char at Position 0 from string B).
Since Strings are basically char Arrays, you can compare them like iterating through an Array.
After the for loop ran through and no differences in the chars were detected, true will be returned.
I hope i could help you
+ 2
yes the answer is true. It is because the question is whether any two strings are compared in a correct way in this code. In general, any two strings can be compared in this way. so it's true
+ 2
i don't understand wt u said @kamakshi
plz try different way.
+ 2
It's a general question, we can assume any two strings
+ 2
okay okay
thanks @kam
đ
+ 1
Question is whether any two strings are compared by this code