The String class is immutable: once it’s created, a String object can’t be changed. Therefore its methods never affect the original String object but create and return a new String object that contains the result of the operation.

In order to correctly answer questions in the exam about strings you must know the String class main methods and what’s the behaviour of these methods.

Basic Operations

char charAt(int index)   Returns the character at the given index
String trim() Returns a copy of the string with no leading and trailing whitespace
String concat(String s2) Returns a new string  (this + s2)


Getting Portions

String substring(int begin[, int end]) Returns a new string containing characters from begin to the end of this [or to the character end-1]
CharSequence subSequence(int begin, int end) Same as substring but returns a CharSequence object
String[] split(String regex[, limit]) Splits the string around matches of the given regular expression (limit is the max size of the array)


Replacing Characters

String replace(char oldChar, char newChar) Replaces all occurrences of the character oldChar with newChar
String replaceAll(String regex, String replacement) Replaces each substring that matches the regular expression regex with replacement
String replaceFirst(String regex, String replacement) Same as replaceAll but only replaces the first occurrence of regex


Comparing Strings

boolean startsWith(String prefix)

boolean endsWith(String suffix)

Checks if a string starts/end with the given prefix/suffix
boolean equals(Object anObject) Checks if this string has the same sequence of characters as the given string parameter
boolean equalsIgnoreCase(String anotherString) Same as equals but ignores case considerations (e.g "abc" equals to "AbC")
int compareTo(String anotherString)

int compareToIgnoreCase(String str)

Compares two strings lexicographically (e.g. "A" > "a", "a" > "b")
boolean matches(String regex) Checks if a string matches a given regular expression

Strings and Primitive Data Types

There are different ways of converting primitive data types to String objects:

For converting String to primitive data types, see the methods in the wrapper classes.


  1. Hey Raul, shouldn’t the line “String.format(“Value = %d” + i);” look like “String.format(“Value = %d”, i);” instead?

Leave a Reply