Reference Types


Logic Errors


Description: when comparing two objects, the result is always false

Solution: Recall, to compare the values of two objects, we use the method equals and not the "==" operator. While the former compares the values of the two objects, the latter compares memory locations. To fix the problem, simply change == to equals.


Description: The argument is unchanged after calling a method, even though the said method is designed to change the parameter’s value. Example: In one class, we have the following mutator method:

	public class Test
	{ public void addTwo(int num)
  	  { num += 2;
  	  }
	}

In a different class, we will be calling the addTwo method using p as the argument:

	public class Test2
	{
    	   public static void main(String[] args)
     	   { Test aTest = new Test();
             int p = 8;
             aTest.addTwo(p);
             System.out.println(p);
           }
	}

Why is the output 8 and not 10?

Cause: Recall, when passing a primitive type (double, float, int, char, and boolean) into a method, it is passed in by value. In other words, a copy of the actual value is made, and passed into the method as the parameter. If the method modifies the parameter, it will be changing the copy only. The original value remains unchanged.

Solution: If you want to change the value of an argument that is a primitive type, you must use a return statement to return the new value, and assign it to the argument again. A solution to the above problem would be:

 	public class Test
	{ public int addTwo(int num)
  	  { num += 2;
            return num;
          }
        }
 
	public class Test2
	{
    	   public static void main(String[] args)
     	   { Test aTest = new Test();
             int p = 8;
             p = aTest.addTwo(p);
             System.out.println(p);
           }
     	}
     

In this case, addTwo(p) will return 10, which then assigned back to p.