Strings
Strings in Java are objects that can hold a sequence of characters contained within a pair of double quotes ("
). It is not a primitive data type.
Strings can either be compared by value via method (e.g., .equals()
) or by reference, or location in memory, (e.g., ==
) via operator.
Example
Java strings provide a way to store text such as words, sentences, or whole paragraphs. They can be any length and may contain letters, numbers, symbols, and spaces:
import java.util.*;class StringExample {public static void main(String[] args) {// Using a string literalSystem.out.println("Codecademy");// Creating a String variableString address = "575 Broadway #5, New York, NY 10012";System.out.println(address);}}
This will output the following:
Codecademy575 Broadway #5, New York, NY 10012
Strings
- .charAt()
- Returns the character at the given index in the string.
- .codePointAt()
- Returns the Unicode value at the given index in the string.
- .codePointBefore()
- Returns the Unicode value before the given index in the string.
- .codePointCount()
- Returns the number of Unicode values in specified range of a string.
- .compareTo()
- Returns 0 if two strings are equal in Unicode value. Otherwise, the lexicographical difference is returned.
- .compareToIgnoreCase()
- Returns 0 if two strings are equal in Unicode value, regardless of character case. Otherwise, the lexicographical difference is returned.
- .concat()
- Returns a string that is the concatenation of the given strings.
- .contains()
- Returns true if a sequence of characters exists in a given string, otherwise false.
- .contentEquals()
- Returns true if the sequence of characters in the string is equal to the content of the specified string. If not, returns false.
- .copyValueOf()
- Returns a string with characters copied from an array.
- .equals()
- Returns true if two strings are equal in value and false otherwise.
- .format()
- Returns a string with additional arguments in a specifically defined format.
- .indexOf()
- Returns the zero-indexed position of the first occurrence of the given character(s) in a string.
- .length()
- Returns the number of characters contained in a string.
- .replace()
- Returns a new string where all instances of a given value are switched with a new value.
- .split()
- Splits a string into an array of substrings based on a delimiter pattern.
- .valueOf()
- Returns the string representation of a given value.