Java Reference
In-Depth Information
For example, if
s
is
Kim Jones
, the following diagram illustrates how the first name and last
name are extracted.
Indices
Message
012345678
Ki
m
Jones
k is 3
s.substring
(0, k) is Kim
s.substring
(k + 1) is Jones
4.4.10 Conversion between Strings and Numbers
You can convert a numeric string into a number. To convert a string into an
int
value, use the
Integer.parseInt
method, as follows:
Integer.parseInt
method
int
intValue = Integer.parseInt(intString);
where
intString
is a numeric string such as
"123"
.
To convert a string into a
double
value, use the
Double.parseDouble
method, as
follows:
Double.parseDouble
method
double
doubleValue = Double.parseDouble(doubleString);
where
doubleString
is a numeric string such as
"123.45"
.
If the string is not a numeric string, the conversion would cause a runtime error. The
Integer
and
Double
classes are both included in the
java.lang
package, and thus they are
automatically imported.
You can convert a number into a string, simply use the string concatenating operator as
follows:
String s = number +
""
;
number to string
4.16
✓
✓
Suppose that
s1
,
s2
, and
s3
are three strings, given as follows:
Check
Point
String s1 =
"Welcome to Java"
;
String s2 =
"Programming is fun"
;
String s3 =
"Welcome to Java"
;
What are the results of the following expressions?
(a)
s1 == s2
(b)
s2 == s3
(c)
s1.equals(s2)
(d)
s1.equals(s3)
(e)
s1.compareTo(s2)
(f)
s2.compareTo(s3)
(g)
s2.compareTo(s2)
(h)
s1.charAt(
0
)
(i)
s1.indexOf(
'j'
)
(j)
s1.indexOf(
"to"
)
(k)
s1.lastIndexOf(
'a'
)
(l)
s1.lastIndexOf(
"o"
,
15
)
(m)
s1.length()
(n)
s1.substring(
5
)
(o)
s1.substring(
5
,
11
)
(p)
s1.startsWith(
"Wel"
)
(q)
s1.endsWith(
"Java"
)
(r)
s1.toLowerCase()
(s)
s1.toUpperCase()
(t)
s1.concat(s2)
(u)
s1.contains(s2)
(v)
"\t Wel \t"
.trim()
Search WWH ::
Custom Search