Java Reference
In-Depth Information
{ String tmp;
tmp=p;
p=q;
q=tmp;}
To declare and initialize a string
2
, we proceed as follows
String title= "First Hands-on Programming!";
String anotherTitle=title;
...
title="Extreme programming sounds better!"; // String can be modified
To print a string, use the regular
System.out.println()
function:
System.out.println(title);
Java proposes many standard functions for eciently manipulating strings. Let
us next review only the very fundamental functions that operate on
String
objects.
5.6.2 Length of a string:
length()
The length of a string object is defined as its number of characters. The length
of a string is reported by calling the
length()
method
on the
String
object,
as shown below:
String s= "Supercalifragilisticexpialidocious";
System.out.println(s.length());
We get 34, which is the longest
invented
word in a song from
Mary Poppins
written by the Sherman Brothers in 1964. Observe that the syntax is different
from arrays. For an array
array
, we get its length (that is, its number of
elements) by the following syntax:
array.length
. But for a string, we use the
method
length()
(with no argument, which explains the () parentheses).
5.6.3 Equality test for strings:
equals(String str)
To test whether two strings
s1
and
s2
are identical or not, do not use the
regular
==
equality test for primitive types. Indeed testing whether two strings
are identical or not by using the comparison
==
will check whether the references
of these strings are identical or not. Instead, to test whether the contents of
2
Use
String
objects
only
for
moderate
length
strings,
otherwise
use
the
better
class
StringBuffer
.
See
Java
API
at
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html
Search WWH ::
Custom Search