Unit 2: Using Objects

Unraveling Java's String Class for AP CSA


Introduction to String

String is a class in Java that represents a sequence of characters. It is one of the most fundamental classes in the Java API, and is used extensively in the AP CSA curriculum. This guide will explore the various methods of the String class, and how to use them effectively.

The String is a reference data type, meaning that it is a class and not a primitive data type. However, it is treated as a primitive data type in many ways.

String Immutability

Strings are immutable, meaning that they cannot be changed once they are created. This is because the String class is final, and therefore cannot be extended. This is a common source of confusion for students, as they may attempt to modify a string using a method, only to find that the original string is unchanged. Instead, the method returns a new string with the desired modifications.


Creating Strings

String Literals and the new Keyword

String literals are created by enclosing text in double quotes. For example, the following code creates a string literal with the value "Hello World!": Strings can be created in two ways:

  • Using string literals: String s = "Hello";
  • Using the new keyword: String s = new String("Hello");
  • The difference between these methods and the impact on the String Pool.
// String literal
String s = "Hello World!";
// Using the new keyword
String s = new String("Hello World!");

Essential String Methods

There are many methods in the String class. The following are some of the most important methods that you should know for the AP CSA exam:

  • length(): Fundamental to many string manipulations.
  • charAt(int index): Basic method to understand string indexing.
  • substring(int beginIndex, int endIndex): Frequently used in string manipulations.
  • equals(Object obj): Essential for string comparison.
  • equalsIgnoreCase(String str): Important for case-insensitive comparisons.
  • indexOf(String str): Commonly used in string searching.
  • contains(CharSequence s): Direct way of checking for a substring.
  • isEmpty(): Useful in condition checking.
  • concat(String str): Although + is more common, this is the method version of string concatenation.
  • replace(char oldChar, char newChar): Basic string replacement.
  • replace(CharSequence target, CharSequence replacement): More generalized replacement.
  • startsWith(String prefix) & endsWith(String suffix): Important for certain pattern checks.
  • trim(): Sometimes needed for cleaning up inputs or outputs.
  • toLowerCase() & toUpperCase(): Basic case conversion.
  • split(String regex): More advanced, but useful for parsing input or tokenizing.
  • valueOf(): Useful for converting other types to strings.

Additional methods that might come up or be useful:

  • compareTo(String anotherString): Compares two strings lexicographically.
  • toCharArray(): Converts the string to a character array.
  • matches(String regex): Tells whether the string matches the given regular expression.

String vs. StringBuilder vs. StringBuffer

The String class is immutable, meaning that it cannot be changed once it is created. This is because the String class is final, and therefore cannot be extended. This is a common source of confusion for students, as they may attempt to modify a string using a method, only to find that the original string is unchanged. Instead, the method returns a new string with the desired modifications.

Performance and Use-Cases

  • Delving into performance nuances.
  • Introducing mutable counterparts: StringBuilder and StringBuffer.
  • Determining the best use-cases for each (AP CSA emphasizes String).

The String Pool

The String Pool is a special area in the Java heap that stores string literals. When a string literal is created, it is stored in the String Pool. If another string literal with the same value is created, it is not stored in the String Pool. Instead, a reference to the existing string literal is returned. This is why the following code will return true:

String s1 = "Hello World!";
String s2 = "Hello World!";
System.out.println(s1 == s2); // true

String Pool and the new Keyword

  • The new keyword creates a new object in the heap, even if the value already exists in the String Pool.
  • The new keyword is rarely used for strings, as it is less efficient and more verbose.

String Concatenation

Concatenation with the + Operator

  • The + operator is used to concatenate strings.
  • The + operator can also be used to concatenate strings with other data types.
  • The + operator can be used to concatenate multiple strings at once.
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + " " + s2 + "!";
System.out.println(s3); // Hello World!

Concatenation with the concat() Method

  • The concat() method is the method version of string concatenation.
  • The concat() method can be used to concatenate multiple strings at once.
String s1 = "Hello";
String s2 = "World";
String s3 = s1.concat(" ").concat(s2).concat("!");
System.out.println(s3); // Hello World!

Comparison of Strings

== vs. equals()

The == operator compares the references of two objects, while the equals() method compares the values of two objects. This is a common source of confusion for students, as they may attempt to compare two strings using the == operator, only to find that the comparison does not work as expected. Instead, the equals() method should be used.

String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // true
System.out.println(s1.equals(s2)); // true

String and Array Interconversion

String and array interconversion is a common source of confusion for students. The following table shows the methods for converting between strings and arrays:

String to ArrayArray to String
toCharArray()String(char[] value)
String(char[] value, int offset, int count)
// String to Array
String s = "Hello World!";
char[] c = s.toCharArray();
// Array to String
char[] c = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'};
String s = new String(c);
String s = new String(c, 0, 12);

String Searching

indexOf() and lastIndexOf()

  • The indexOf() method returns the index of the first occurrence of a substring.
  • The lastIndexOf() method returns the index of the last occurrence of a substring.
String s = "Hello World!";
System.out.println(s.indexOf("l")); // 2
System.out.println(s.lastIndexOf("l")); // 9

contains()

  • The contains() method returns true if a string contains a substring.
  • The contains() method is case-sensitive.
String s = "Hello World!";
System.out.println(s.contains("l")); // true
System.out.println(s.contains("L")); // false

String Parsing

split()

  • The split() method splits a string into an array of substrings.
  • The split() method takes a regular expression as an argument.
  • The split() method is useful for parsing input or tokenizing.
String s = "Hello World!";
String[] words = s.split(" ");
System.out.println(words[0]); // Hello
System.out.println(words[1]); // World!

String Formatting

String.format()

  • The String.format() method is used to format strings.
  • The String.format() method takes a format string and a list of arguments.
  • The format string contains placeholders for the arguments.
  • The format string can be used to specify the number of decimal places for floating point numbers.
  • The letter s is used for strings, d is used for integers, and f is used for floating point numbers.
String s = String.format("Hello %s!", "World");
System.out.println(s); // Hello World!
String s = String.format("Hello %.2f!", 3.14159);
System.out.println(s); // Hello 3.14!

String Methods for Condition Checking

isEmpty()

  • The isEmpty() method returns true if a string is empty.
  • The isEmpty() method is useful for condition checking.
String s = "";
System.out.println(s.isEmpty()); // true

startsWith() and endsWith()

  • The startsWith() method returns true if a string starts with a substring.
  • The endsWith() method returns true if a string ends with a substring.
String s = "Hello World!";
System.out.println(s.startsWith("Hello")); // true
System.out.println(s.endsWith("World!")); // true

String Methods for Case Conversion

toLowerCase() and toUpperCase()

  • The toLowerCase() method converts a string to lowercase.
  • The toUpperCase() method converts a string to uppercase.
String s = "Hello World!";
System.out.println(s.toLowerCase()); // hello world!
System.out.println(s.toUpperCase()); // HELLO WORLD!

String Methods for Replacement

replace()

  • The replace() method replaces all occurrences of a character with another character.
  • The replace() method can also be used to replace all occurrences of a substring with another substring.
String s = "Hello World!";
System.out.println(s.replace("l", "L")); // HeLLo WorLd!
System.out.println(s.replace("Hello", "Goodbye")); // Goodbye World!

String Methods for Trimming

trim()

  • The trim() method removes leading and trailing whitespace from a string.
  • The trim() method is useful for cleaning up inputs or outputs.
String s = " Hello World! ";
System.out.println(s.trim()); // Hello World!

String Methods for Comparison

equals()

  • The equals() method returns true if two strings are equal.
  • The equals() method is case-sensitive.
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1.equals(s2)); // true

equalsIgnoreCase()

  • The equalsIgnoreCase() method returns true if two strings are equal, ignoring case.
String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.equalsIgnoreCase(s2)); // true

compareTo()

  • The compareTo() method compares two strings lexicographically.
  • The compareTo() method returns 0 if the strings are equal.
  • The compareTo() method returns a negative number if the first string is lexicographically less than the second string.
  • The compareTo() method returns a positive number if the first string is lexicographically greater than the second string.
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1.compareTo(s2)); // 0

Escape Sequences in Strings

  • Special characters: \n (newline), \t (tab), \" (double quote), \\ (backslash).
  • Unicode characters: \u#### (unicode character).

Formatting with Strings

  • Utilizing String.format() for structured string outputs.
  • Placeholders: %s (string), %d (decimal), %f (float).

AP CSA Homework Assignment

Assignment

Instructions

Strings have a ton of methods and you do not to memorize all of them. But there are some that will be used over and over again. Those are:

  • length()
  • charAt(int index)
  • substring(int beginIndex, int endIndex)
  • equals(Object obj)
  • equalsIgnoreCase(String str)
  • indexOf(String str)
  • contains(CharSequence s)
  • isEmpty()
  • concat(String str)
  • replace(char oldChar, char newChar)
  • replace(CharSequence target, CharSequence replacement)
  • startsWith(String prefix)
  • endsWith(String suffix)
  • trim()
  • toLowerCase()
  • toUpperCase()
  • split(String regex)
  • valueOf()

I know! This is a lot. But you will get used to them. For now, just know that they exist and what they do. In the references you will find a link to the Java API for the String class. You can use that to look up the methods and their descriptions.

For your homework familiarize yourself with the methods listed above. You do not need to memorize them, but you should know what they do and how to use them, but more importantly where the documentation is where you can find them. You will be using them a lot in the future.

Java Documentation

The Java API documentation is a great resource for learning about the methods of the String class. You can find the documentation for the String class here: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

References

Previous
Methods