Strings

Strings are a data type which allow us to store text. The most basic element of a string is a character which is any single element such as a single letter, number, punctuation mark or other symbol. A String is therefore a collection of characters. More specifically, it is an array of characters.

We declare a String variable as with primitive data types such as int and double but it is important to note that a String is not a primitive type but is an object which has additional functionality. For this reason it starts with a capital S.

String example

String output = "This is my first line of text.";
System.out.println(output);

Strings are enclosed within inverted commas so that our program knows where a string begins and ends. If we would like to include inverted commas within our string though then we need to use a backslash ( \ ) in order to let the Java compiler know that we do not intend to end our string yet. This backslash is know as an escape character.
Below is a list of other special characters in Java:

Special characters Display
\’ Single quotation mark.
\” Double quotation mark.
\\ Backslash
\t Tab
\r Carriage return
\f Formfeed
\n Newline

Joining Strings and other variables

Strings can be concatenated easily with other strings and other variables. When joining a string to another variable such as an int or double, it is converted to text to form a new string.

String text = "My age is: ";
 int age = 18;

 String newText = text + age;

The newText string will contain “My age is: 18″. The int age variable becomes a part of thenewText string when it is joined with the original text string.

Comparing Strings

Strings are objects and are not primitive data types like int and double variables. For this reason they do not compare like primitive data types. We can not check if two strings are equal by using the == comparison operator. Instead, we use can String methods such asequals() or equalsIgnoreCase() in order to compare strings.

Comparing strings example

String name1 = "John";
 String name2 = "John";

 if (name1.equals(name2))
 {
      System.out.println("The strings are equal.");
 }

This will print out The strings are equal.

Splitting Up Strings

Java has the ability to split up a string into different parts using a particular character. If, for example, you have a list of names that are separated by semicolons, then the split method will split up the names between the semi-colons and return a string array containing the names.

String split example

String names = "Jack;John;Michael;Mark;Matthew;Sean;Luke";

String[] listOfNames = names.split (";");
// split up the list of names using the semicolon

for (int i = 0 ; i < listOfNames.length ; i++)
{
     System.out.println (listOfNames [i]);
}
This would produce the following output:

 Jack
 John
 Michael
 Mark
 Matthew
 Sean
 Luke