# Strings

We have seen how variables of the primitive data type char allow us to store and use individual letters and other characters, but more often than not the programs we will want to write will require storing more than just one character. For example, we might need to store someone's name, or a website address, or song lyrics, etc.

A String is a special non‐primitive type that stores data in the form of text (i.e., a "string" of characters).

Strings can be either constructed in a manner consistent with working with other objects, as shown below:

String myString = new String("Hello World");


…or strings may be declared and initialized using the shortcut:

String myString = "Hello World";


This is not typical of most other object types.

There are many useful features of the String class that we could discuss. We will discuss most of these in detail at a later point in time -- but for now, let us confine our attention to just three things:

• ### Concatenating Strings

Just like we can add numerical values together to get a new numerical value -- we can add strings together to get a new string. In java, adding two strings results in their concatenation, as seen in the code below. (Be aware, this is again not typical of other classes.)

String s1 = "I like";
String s2 = "chocolate";
String s3 = s1 + s2;

System.out.println(s3);   //prints "I likechocolate" to the console


Notice the lack of a space between "like" and "chocolate". If we want a space between these two words, you'll need to explicitly put one into the string. This can be done in several ways. As one example, we could have made the third line above String s3 = s1 + " " + s2;

• ### Checking if Two Strings Contain Identical Text

One can produce a boolean value (i.e., true or false) that will tell whether two strings contain the same text by invoking the equals() method, as shown below.

String s1 = "bob";
String s2 = "fred";
String s3 = "bob";

boolean b1 = s1.equals(s2);    //b1 is now false
boolean b2 = s1.equals(s3);    //b2 is now true

• ### Extracting Characters

One can grab the $n^{\textrm{th}}$ character that appears in a string with the charAt() method. Note, the first character of the string is associated with $n=0$, the second with $n=1$, the third with $n=2$, and so on... As an example, consider the following:

String s = "Once upon a midnight dreary...";
char c = s.charAt(5);                           //c is now the character 'u'


† Only the String class and a handful of other classes (e.g., the wrapper classes for numerical types: Integer, Double, etc.) can be added using the "+" operator. For most non-primitive data types where addition might make some sense, such a sum can only be found via a method call.