|
RHS |
StringEquals
Do you remember that the operator "==" is used for testing values of primitive types for equality?
And if you use == with two values of reference type, you're actually testing whether the references are equal (which they will only be if they refer to the same object).
So if you want to test whether two different objects are equal, you'll have to rely on a method that can compare the state of the two objects and return the result.
That's why all objects have a method called equals() - e.g. you can test whether the two string-objects (called s1 and s2) are equal by using the equals() method for s1 and pass s2 as argument: boolean same = s1.equals(s2); (of course you'd get the same result by: s2.equals(s1))
When you construct your own classes and create objects from them, their native equals() method will actually work like the == operator. So if you want to be able to use the state of two objects to decide whether they are equal (have same state) you must include an equals() method that takes another object as parameter and returns true only if all variables have same value for the two objects.
This can be more complicated to do than you should think, so for now we'll add a method to the MyUtils class that does the same job as the equals()defined in the String class does.
One difference will be that our method needs both Strings as parameters (consider why this is so).
Create a NetBeans project - StringEquals - and mount a folder for the files.
Also mount the folder that holds the MyUtils class (if you didn't do this exercise you'd better do that first!) and open the MyUtils.java file.
Add a method into MyUtils using the following instructions:
When you have created stringEquals(String, String) and compiled MyUtils it's time to test the method.
In the folder for the StringEquals project create a form (StringEqualsForm) like the one below
![]() |
When (at run-time) the button is clicked it reads the two strings from the text fields and calls the stringEquals(String, String) method in the MyUtils class passing the two strings as arguments. The result should be shown in the output text area.