2.7 String Methods
Enduring Understanding
To find specific solutions to generalizable problems, programmers include variables in their code so that the same algorithm runs using different input values.
Learning Objective
For String class:
a. Create String objects.
b. Call String methods.
Essential Knowledge
Application program interfaces (APIs) and libraries simplify complex programming tasks.
Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class.
Classes in the APIs and libraries are grouped into packages.
The String class is part of the java.lang package. Classes in the java.lang package are available by default.
A String object has index values from 0 to length – 1. Attempting to access indices outside this range will result in an IndexOutOfBoundsException.
A String object can be concatenated with an object reference, which implicitly calls the referenced object’s toString method.
The following String methods and constructors—including what they do and when they are used—are part of the Java Quick Reference:
String(String str) — Constructs a new String object that represents the same sequence of characters as str
int length()— Returns the number of characters in a String object
String substring(int from, int to)— Returns the substring beginning at index from and ending at index to -1
String substring(int from) — Returns substring(from, length())
int indexOf(String str) — Returns the index of the first occurrence of str; returns -1 if not found
boolean equals(String other) — Returns true if this is equal to other; returns false otherwise
int compareTo(String other) — Returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other
A string identical to the single element substring at position index can be created by calling substring(index, index + 1).
Last updated
Was this helpful?