Methods of the Class String
In this lesson, we will look at the behavior of strings by examining some of the methods in the class String.
We'll cover the following...
All strings are objects belonging to the class String
. As such, every string has certain behaviors that are defined by the methods in the class String
.
The method length
The method length
provides the number of characters that are in a string, including any spaces. For example, the statements in the following program display 21
:
public class Example{public static void main( String args[] ){String fact = "Java is my dog's name"; // 21 charactersSystem.out.println(fact.length());} // End main} // End Example
The string object named fact
calls the method length
by using a dot notation, fact.length()
. The pair of parentheses after the method name length
is required. This method returns an int
value.
We can use the expression fact.length()
anywhere that we can use an int
value. Thus, we can embed the expression within an arithmetic expression.
📝 Syntax: Calling a method
You call, or invoke, an object’s method by using the notation
object_name.method_name ( ... )
The object is the receiving object, or receiver, as it receives the invocation. For some methods, nothing appears between the required parentheses. For other methods, one or more arguments—which can be expressions—occur. You separate multiple arguments with commas.
The method concat
We can concatenate two strings, either by using the +
operator or by using the String
method concat
. For example, if we define the two strings
String one = "sail";
String two = "boat";
the expressions one + two
and one.concat(two)
produce the same string, "sailboat"
. Notice that concat
has one argument, the variable two
in this
example. Also, notice that the strings one
and two
are unchanged by concat
.
Checkpoint question
Using the String
method concat
, complete the following program to assign your full name to the String
variable fullName
. Also, write a Java statement that assigns the length of the string in fullName
to the int
variable nameLength
. Display your name and its length.
public class CheckpointQuestion{public static void main(String[] args){firstNamelastNamefullNamenameLength} // End main} // End CheckpointQuestion
Now, try to predict the following program’s output:
public class Example{public static void main( String args[] ){String dogName = "Spot";String fact = dogName + " ";fact = fact.concat("is my dog's name.");System.out.println(fact);System.out.println("The variable dogName references the string " +dogName + ".");} // End main} // End Example
The variable dogName
references the string "Spot"
and remains unchanged by these statements. The assignment to the variable fact
adds a blank space at the ...