xhtml
 

Strings

Declarations and expressions so far have used the int type, which is one of the main ones which programs use for internal computation. For external communication with the user, programs use text, and often need to declare variables which hold text, and use expressions which manipulate text.

The type String is the one used in Java for variables which hold text. It starts with a capital letter, unlike int, because it is a compound type. There is a basic type char which holds a single character, but a String consists of a sequence of characters.

To get a fixed piece of text into a program, it has to have double quote marks, e.g. "the answer is". This is a constant of type String, just like 42 is a constant of type int.

One of the most important operators for calculating with text in Java is the + operator. As well as being used to add numbers, it is also used to "add" text, i.e. glue two pieces of text next to each other. For example, "car" + "pet" gives "carpet".

More interestingly, Java's + operator also "adds" numbers to text. If the first item is text, and the second is a number, Java will convert the number to text before gluing the two things together. For example, if you write "the answer is " + 42 then Java converts the number 42 to the text "42" and glues the two strings together to get "the answer is 42". The constant "the answer is " needs the space at the end so that when the two strings are glued together, you don't get "the answer is42"


Back