Java J2EE Question and Answers

13. How to compare two Strings in java program?
  • Java String implements Comparable interface and it has two variants of compareTo() methods.
  • compareTo(String another String) method compares the String object with the String argument passed lexicographically.
  • If String object precedes the argument passed, it returns negative integer and if String object follows the argument String passed, it returns positive integer.
  • It returns zero when both the String have same value, in this case equals (String str) method will also return true.
  • compare ToIgnoreCase (String str): This method is similar to the first one, except that it ignores the case.
  • It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison.
  • If the value is zero thenequalsIgnoreCase(String str) will also return true.
Your Name Your Email-ID
Your Answer
14. Why StringBuffer is called mutable?
  • The string class is considered as immutable; so that once it is created a String object cannot be changed.
  • If there is a necessity to make a lot of modifications to Strings of characters then StringBuffer should be used.
Your Name Your Email-ID
Your Answer
15. How do you check if two Strings are equal in Java?
  • There are two ways to check if two Strings are equal or not – using "==" operator or using equals method.
  • When we use "==" operator, it checks for value of Strings as well as reference but in our programming, most of the time we are checking equality of String for value only.
  • So we should use equal method to check if two Strings are equal or not.
Your Name Your Email-ID
Your Answer
16. What is Hash Code collision?
  • The idea of hashing is to store an element into array at a position index computed as below.
  • obtain element_hash_code of the element by processing the element's data and generating an integer value.
  • use a simple mod operation to map into the array's range: index = hash(element) = abs(element_hash_code % array_capacity)
  • The hash code collision occurs when the index calculated by hash function results same for two or more elements.
Your Name Your Email-ID
Your Answer
12345 Page 4 of 5