J2EEOnline J2EE

Java Certification Questions 111 -120  «Prev  Next»

Java Questions 111

  1. How do you override the toString() method in your class?
    By writing, creating, or defining the toString() method in your class.
    public String to String() {
    return "" + "" ; 
    toString() provides a simple conversion of the object to a String.
    The format and content of the resulting String is class specific, and (from the perspective of the java.lang.Object contract) there are no guarantees that it will be meaningful.
  2. What is the difference between == and equals in Java?
    1. == compares object references. It tests if two object references are equal; i.e. if they refer to the same object.
    2. equals(Object) tests if this object is "equal to" another one. What "equal to" means depends on how the object's class defines equality.
      The java.lang.Object class defines equals(other) to be this == other, but many classes override this definition.
  3. When do you use the equals() method?

    When you need to know if the objects themselves (not the references) are equal.
  4. What must you do in order to use the objects as a key in a hashtable?
    If you do not override the methods of a class, you will not be able to use those objects as keys in a hashtable and you will not get accurate results.
  5. What does the equals() method in the class Object use for comparisons?
    The equals() method in the class Object uses only the == operator for comparisons.
  6. When should you override the equals method?
    If you want objects of your class to be used as keys for a hashtable, then you must override equals() so that 2 different instances can be considered the same.
  7. Why do the String and wrapper classes work well as keys in hashtables?
    The String and wrapper classes work well as keys in hashtables since they override the equals () method.
  8. How would you implement an equals method for comparing private String lastName ?
    public boolean equals(Object o){
    if(o instanceof Student){
     Student other = (Student)o;
       return this.lastName.equals(other.lastName);
       return false;
  9. What happens if the object does not pass the "instanceof" test when attempting to cast one object to another?
    If the object does not pass the instanceof test, then you will get a runtime ClassCastExceptiion.
  10. Which three class methods are all public?
    1. equals()
    2. hashCode()
    3. toString()
    public int hashCode(): This method returns the hash code value for the object on which this method is invoked.
    This method returns the hash code value as an integer and is supported for the benefit of "hashing based collection classes" such as Hashtable, HashMap, and HashSet .
    This method must be overridden in every class that overrides the equals method.