Strings and Object References in Java

3. String References as Parameters


Answer:

Yes, a String reference is often a parameter.

String References as Parameters

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.");


Some methods require a parameter that is a reference to a String object. The example program shows this.

The picture that shows how the method call works. (Both objects have many methods, but only the equals() method of one object is pictured.)

The String object referred to by stringA has an equals() method. That method is called with a parameter, a reference to another String object, stringB. The method checks if both String objects contain identical sequences of characters, and if so, evaluates to 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 reference variable like stringA does not contain an object, but only a reference to an object. This may seem picky, but there is nothing quite as picky as a computer. Students who are not careful about this often run into problems.

equalsMethodCall


Annotation 2020-02-24 152747


Question 3:

(Review:) Examine the following snippet of code.
Answer the questions using careful words (like the above on the right).

String a;
Point  b;       
      • What is the data type of the variable a?
      • What is the data type of the variable b?
      • How many objects are there (so far)?