Can a String
be a parameter for a method?
Yes, a String reference is often a parameter.
Some methods require a parameter that is a reference to a String object. For example,
String stringA = "Random Jottings"; String stringB = "Lyrical Ballads"; if ( stringA.equals( stringB ) ) System.out.println("They are equal."); else System.out.println("They are different.");
The String referred to by stringA
has an equals()
method.
That method is
called with a parameter, a reference to stringB
.
The method checks if both strings contain identical characters, and
if so, evaluates to true ("returns true").
Careful:
The previous paragraph is correctly stated, but awkward.
People often say "String" when they really mean "reference to a String".
This is fine,
but remember that a variable like stringA
is not the object, but only a reference to an object.
This may seem picky, but there is nothing quite as picky as a computer.
I (the author) frequently see students that are not careful about this
and who later run into problems.
What is usually said | Careful meaning |
---|---|
The equals method of stringA
is called with stringB. |
The equals method of the String referenced
by stringA
is called with a reference to stringB. |