Java Reference
In-Depth Information
You can declare variables of type
String
and use the assignment statement to give
values to these variables. You can also write code that involves
String
expressions:
String s1 = "hello";
String s2 = "there";
String combined = s1 + " " + s2;
This code defines two
String
s that each represent a single word and a third
String
that represents the concatenation of the two words with a space in between.
You'll notice that the type
String
is capitalized (as are the names of all object types
in Java), unlike the primitive types such as
double
and
int
.
These examples haven't shown what's special about
String
objects, but we're
getting there. Remember that the idea behind objects was to include basic operations
with the data itself, the way we make cars that have controls built in. The data stored
in a
String
is a sequence of characters. There are all sorts of operations you might
want to perform on this sequence of characters. For example, you might want to
know how many characters there are in the
String
.
String
objects have a
length
method that returns this information.
If the
length
method were static, you would call it by saying something like
length(s) // this isn't legal
But when you perform operations on objects, you use a different syntax. Objects
store data and methods, so the method to report a
String
's length actually exists
inside that
String
object itself. To call an object's method, you write the name of the
variable first, followed by a dot, and then the name of the method:
s.length()
Think of it as talking to the
String
object. When you ask for
s.length()
, you're
saying, “Hey,
s
. I'm talking to you. What's your length?” Of course, different
String
objects have different lengths, so you will get different answers when you
communicate with different
String
objects.
The general syntax for calling a method of an object is the following:
<variable>.<method name>(<expression>, <expression>, ..., <expression>)
For example, suppose that you have initialized two
String
variables as follows:
String s1 = "hello";
String s2 = "how are you?";
You can use a
println
to examine the length of each
String
:
System.out.println("Length of s1 = " + s1.length());
System.out.println("Length of s2 = " + s2.length());
Search WWH ::
Custom Search