Next to numbers, strings are the most important data type that most programs use. A string is a sequence of characters such as "Hello". In Java, strings are enclosed in quotation marks, which are not themselves part of the string
String
objects can be constructed in two ways:
String name = "Bob Binary";
String anotherName = new String("Betty Binary");
Due to the usefulness and frequency of use of Strings
, a shorter version without the keyword new
, was developed as a short-cut way of creating a String
object. This creates a String
object containing the characters between quote marks, just as before. A String
created in this method is called a Stringliteral. Only String
s have a short-cut like this. All other objects are constructed by using the new
operator.
Assignment can be used to place a reference to adifferent String
into the variable.
name = "Boris";
anotherName = new String("Bessy");
The number of characters in a String
is called the length of the string. For example, the length of "Hello World!" is 12. You can compute the length of a String
with the length
method.
int n = name.length();
Unlike numbers, String
s are objects. Therefore, you can call methods on strings. In the above example, the length of the String
object name
is computed with the method call name.length()
.
A String
of length zero, containing no characters, is called the empty string and is written as ""
. For example:
String empty = "";
Programmers often make one String
object from two strings with the +
operator, which concatenates (connects) two or more strings into one string. Concatenation and these string messages are illustrated below.
public class DemoStringMethods
{
public static void main(String[] args)
{
String a = new String("Any old");
String b = " String";
String aString = a + b; // aString is "Any old String"
// Show string a
System.out.println("a: " + a);
// Show string b
System.out.println("b: " + b);
// Show the result of concatenating a and b
System.out.println("a + b: " + aString);
// Show the number of characters in the string
System.out.println("length: " + aString.length());
}
}
Run output:
a: Any old
b: String
a + b: Any old String
length: 14
Notice that using strings in the context of input and output statements is identical to using other data types.
The String
class will be covered in depth in a later lesson. For now you will use strings for simple input and output in programs.