+ 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?

28th Aug 2017, 5:10 AM
shadab gada
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
28th Aug 2017, 5:25 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 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
28th Aug 2017, 5:26 AM
shadab gada
+ 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.
28th Aug 2017, 5:18 AM
Venkatesh Pitta
Venkatesh Pitta - avatar
+ 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
28th Aug 2017, 5:21 AM
Marco
+ 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
28th Aug 2017, 5:31 AM
kamakshi
kamakshi - avatar
+ 2
i don't understand wt u said @kamakshi plz try different way.
30th Aug 2017, 4:46 AM
Sahil Luthra
Sahil Luthra - avatar
+ 2
It's a general question, we can assume any two strings
30th Aug 2017, 8:58 AM
kamakshi
kamakshi - avatar
+ 2
okay okay thanks @kam 😊
30th Aug 2017, 9:05 AM
Sahil Luthra
Sahil Luthra - avatar
+ 1
Question is whether any two strings are compared by this code
30th Aug 2017, 8:57 AM
kamakshi
kamakshi - avatar