String


Collapse Content

Intro

Java strings are immutable, so whenever you want to modify one, you will instead create a new string with the same name. (For example, str1 = str1.substring(2,4).) If the String needs to be modified frequently, use StringBuffer instead, which is mutable.

Strings work like regular Java objects and can be created and handled in the standard manner. However, since Strings are so basic, Java also includes certain shortcuts that can be used with them:

  • Quick construction: String str = "hello" instead of String str = new String("hello")
  • "hello" in your code automatically creates an object, so you can call methods on it directly: "hello".length()
  • '+' operator for concatenating strings: String str = "hel"+"lo"

toString()

Objects get converted to Strings automatically when they're concatenated with a String or printed. This is done with the toString() method that belongs to every Object. Java also automatically turns primitive values into a readable String representation. For example:

int num = 5;
String str = num + " years ago";
System.out.println(str);

..will output 5 years ago.

The default toString() method that's included with Object is usually not very useful, so you should often override it with your own method which can print the information you want. For example, if you had a class called AircraftCarrier, you could create a method:

public String toString() {
return name + ": "+ weight + " tons, " + aircraft + " aircraft";
}

Which could be used like this:

AircraftCarrier nim = new AircraftCarrier("USS Nimitz", 100000, 80);
String str = "Your boat is " + nim;
System.out.println(str);

Which would output:

Your boat is USS Nimitz: 100000 tons, 80 aircraft

Most String Methods

You can view most string methods below. The table includes columns for each method's purpose, the type it returns, variant methods, example code, and what the example code will set the variable value to.
(Note: You can toggle the sidebar on this page to leave more space for the table.)

String Methods 
Purpose
(Modifier) and Return Type Method and Description Variant Methods and their differences
Example
Example value =
Get / extract characters




Get 1 character
char charAt(int index)
Gets one character from a  String, by returning the char value at the specified index.

 char value = "abc".charAt(1); 'b'
Get multiple characters
void
getChars(int sorcBegin, int sorcEnd, char[] dest, int destBegin)
Gets multiple characters from a  string, by copying characters from this string into the destination character array.

char [] value = new char2; "abc".getChars(1,3,value,0); [b,c]
Get all characters
char[]
toCharArray()
Converts this string to a new character array.

char [] value = "abcd".toCharArray(); [a,b,c,d]
String Comparisons




Alphabetic comparsion
int compareTo(String anotherString)
Compares two strings alphabetically and returns a negative number, 0, or positive number if the first String comes first, is equal, or comes after the second string.
compareToIgnoreCase(String str)
Ignores case differences.
"abc".compareTo("cba"); "abc".compareTo("abc"); "abc".compareTo("aaa"); -2 0 1
Check 1st character
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.

startsWith(String prefix, int toffset)
Checks if specific index starts with prefix.

boolean value = "abcd".startsWith("ab"); true
Check last characters
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.



Compare strings
boolean equals(Object anObject)
Check if two strings are equivalent. Use this method, not "==".
equalsIgnoreCase(String anotherString)
Ignores case differences.
boolean value = "abc".equals("ABC"); value="abc".equalsIgnoreCase("ABC"); false true
Compare parts of strings
boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two parts of two different strings are equal.
regionMatches(boolean ignoreCase,
int toffset, String other,
int ooffset, int len)
Option to ignore case differences.
boolean value = "abcd".regionMatches(1,"zbczz",0,2); true
regex check
boolean matches(String regex)
Tells whether or not this string matches the given regular expression. (Regex is for a later page... )



Search / Find Characters




Check if character sequence there
boolean contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.



Find where character is
int indexOf(int ch)
Finds a character within a String, by returning the index where specified character first occurs.
indexOf(int ch, int fromIndex)
Starts the search at the specified index, skipping characters before it.
int value = "abcba".indexOf('a'); value = "abcba".indexOf('a', 2); 0 4

int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
indexOf(String str, int fromIndex)



int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
Can also look for lastIndexOf Strings, and can search backwards from a specified index.


"Modify"   Strings

Note: Since String is immutable, these methods return a new String.



Combine strings
String concat(String str)
Concatenates the specified string to the end of this string. You can also just use "+".

String value = "hel".concat("lo"); value = "hel"+"lo"; "hello" "hello"
copy piece of string
String substring(int beginIndex)
Returns a new string that is a substring of this string, starting from the character at beginIndex and going until the end of the string.
substring(int beginIndex, int endIndex)
This gets a substring that goes until (just before) endIndex.
String value = "abcde".substring(2); value = "abcde".substring(2,4); "cde" "cd"
replace character
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
replace(CharSequence target, CharSequence replacement)
replaceAll(String regex, String replacement)
replaceFirst(String regex, String replacement)
String value = "food".replace('o', 'e'); "feed"
get rid of whitespace
String trim()
Gets rid of 'bad' whitespace (as is common in user input), by returning a copy of the string with leading and trailing whitespace omitted.

String value = "  the quick fox   ".trim(); "the quick fox"
convert case
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
String value = "ABCD".toLowerCase(); "abcd"
split up string into array
String[] split(String regex)
Splits this string around matches of the given regular expression.
split(String regex, int limit)
Will stop splitting 1 before it reaches "limit" matches.
String[] value = "the quick fox".split(" "); ["the", "quick", "fox"]
Get String Properties




get length
int length()
Returns the length of this string, i.e. the number of characters in it.

int value = "abc".length(); 3

boolean isEmpty()
Returns true if, and only if, length() is 0.

boolean value = " ".isEmpty(); value = "".isEmpty(); false true
Convert things to Strings
valueOf() gets the String representation of an item, and is automatically called on items that are concatenated to a  String.




static String valueOf(primitive p)
Returns the string representation of the primitive argument.

String value = String.valueOf(32); "32"

static String valueOf(Object obj)
Returns the string representation of the Object argument, which won't be very useful unless the Object overloaded toString().



To practice these methods, check out the challenges in Programming Practice - Strings.

Challenge

Review common String operations below. Complete the small tasks in the comments to pass the challenge. Feel free to try out other String operations below too!

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • I'm trying to wrap my head around the code lines 11-14. Line 6 is a constructor, which defines attributes of an instance of the StringSample class. (I think this language is correct...). Then there are four print commands; will those be run whenever an instances of StringSample is created? Is that all there is to it?

    cont...
  • Right, the StringSample constructor initializes 2 String instance variables, and it then calls print on 4 different methods. A constructor is just a method that runs when an object instance is

    cont...
Contact Us
Sign in or email us at [email protected]