Java : Check Your Understanding


Name:
  1. Equality
    In Java, what is the difference between the comparision operator, ==, and the comparision method, equals, when comparing objects?
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
      
  2. Object References
    Consider the following two innocent looking methods:
  3. StringBuffer getText ()
    {
        return myText;
    }
    
    
    String getName ()
    {
        return myName;
    }

    Because every object variable in Java is a reference, explain why the first method has the potential to break the encapsulation of the object, while the second method does not.

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  4. Swapping two values
    In C++, the following method swaps any two values passed:
  5. template<class T>
    void swap (T& a, T& b)
    {
        T tmp = a;
        a = b;
        b = tmp;
    }
    

    In Java, however, the following version of the method has no effect on the two values passed:

    void swap (Object a, Object b)
    {
        Object tmp = a;
        a = b;
        b = tmp;
    }
    
    1. Even though all object variables in Java are actually references, explain why the Java version of swap does not work.
      		
      		
      		
      		
      
      
      		
      
      
      		
      
      
      
      
      
      
      
      		
      		
      	
    2. Describe a way to write a generic swap method in Java. You do not need write your solution in Java code, just explain what is needed to make a swap method possible.
       
      
      
      
      
      
      
      
       
      
      
      
       
      
      
       
       
       
       
      
      
      
      
       
       
             
  6. What is the main difference between running programs in C++ and Java? What impact does that have in terms of compile-time versus run-time errors?
  7.