DEV Community

Cover image for The String Type
Paul Ngugi
Paul Ngugi

Posted on

The String Type

A string is a sequence of characters. The char type represents only one character. To represent a string of characters, use the data type called String. For example, the following code declares message to be a string with the value "Welcome to Java".

String message = "Welcome to Java";
Enter fullscreen mode Exit fullscreen mode

String is a predefined class in the Java library, just like the classes System and Scanner. The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type for a variable. The variable declared by a reference type is known as a reference variable that references an object. Here, message is a reference variable that references a string object with contents Welcome to Java. This is how one declares a String variable and assigns a string to the variable. How to use the methods in the String class is discussed below.

The table below lists the String methods for obtaining string length, for accessing characters in the string, for concatenating strings, for converting a string to upper or lowercases, and for trimming a string.

Image description

Strings are objects in Java. The methods in the table can only be invoked from a specific string instance. For this reason, these methods are called instance methods. A noninstance method is called a static method. A static method can be invoked without using an object. All the methods defined in the Math class are static methods. They are not tied to a specific object instance. The syntax to invoke an instance method is referenceVariable.methodName(arguments). A method may have many arguments or no arguments. For example, the charAt(index) method has one argument, but the length() method has no arguments. Recall that the syntax to invoke a static method is ClassName.methodName(arguments). For example, the pow method in the Math class can be invoked using Math.pow(2, 2.5).

Getting String Length

You can use the length() method to return the number of characters in a string. For example, the following code

String message = "Welcome to Java";
System.out.println("The length of " + message + " is "
 + message.length());
Enter fullscreen mode Exit fullscreen mode

displays

The length of Welcome to Java is 15

When you use a string, you often know its literal value. For convenience, Java allows you to use the string literal to refer directly to strings without creating new variables. Thus, "Welcome to Java".length() is correct and returns 15. Note that "" denotes an empty string and "".length() is 0.

Getting Characters from a String

The s.charAt(index) method can be used to retrieve a specific character in a string s, where the index is between 0 and s.length()–1. For example, message.charAt(0) returns the character W, as shown below. Note that the index for the first character in the string is 0.

Image description

Attempting to access characters in a string s out of bounds is a common programming error. To avoid it, make sure that you do not use an index beyond s.length() – 1. For example, s.charAt(s.length()) would cause a StringIndexOutOfBoundsException.

Concatenating Strings

You can use the concat method to concatenate two strings. The statement shown below, for example, concatenates strings s1 and s2 into s3:

String s3 = s1.concat(s2);
Enter fullscreen mode Exit fullscreen mode

Because string concatenation is heavily used in programming, Java provides a convenient way to accomplish it. You can use the plus (+) operator to concatenate two strings, so the previous statement is equivalent to

String s3 = s1 + s2;
Enter fullscreen mode Exit fullscreen mode

The following code combines the strings message, " and ", and "HTML" into one string:

String myString = message + " and " + "HTML";
Enter fullscreen mode Exit fullscreen mode

Recall that the + operator can also concatenate a number with a string. In this case, the number is converted into a string and then concatenated. Note that at least one of the operands must be a string in order for concatenation to take place. If one of the operands is a nonstring (e.g., a number), the nonstring value is converted into a string and concatenated with the other string. Here are some examples:

// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
Enter fullscreen mode Exit fullscreen mode

If neither of the operands is a string, the plus sign (+) is the addition operator that adds two numbers.

The augmented += operator can also be used for string concatenation. For example, the following code appends the string "and Java is fun" with the string "Welcome to Java" in message.

message += " and Java is fun";
Enter fullscreen mode Exit fullscreen mode

So the new message is "Welcome to Java and Java is fun".
If i = 1 and j = 2, what is the output of the following statement?

System.out.println("i + j is " + i + j);
Enter fullscreen mode Exit fullscreen mode

The output is "i + j is 12" because "i + j is " is concatenated with the value of i first. To force i + j to be executed first, enclose i + j in the parentheses, as follows:

System.out.println("i + j is " + (i + j));
Enter fullscreen mode Exit fullscreen mode

Converting Strings

The toLowerCase() method returns a new string with all lowercase letters and the toUpperCase() method returns a new string with all uppercase letters. For example,

"Welcome".toLowerCase() returns a new string welcome.
"Welcome".toUpperCase() returns a new string WELCOME.
Enter fullscreen mode Exit fullscreen mode

The trim() method returns a new string by eliminating whitespace characters from both ends of the string. The characters ' ', \t, \f, \r, or \n are known as whitespace characters.
For example,

"\t Good Night \n".trim() returns a new string Good Night.
Enter fullscreen mode Exit fullscreen mode

Reading a String from the Console

To read a string from the console, invoke the next() method on a Scanner object. For example, the following code reads three strings from the keyboard:

Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
Enter fullscreen mode Exit fullscreen mode

Enter three words separated by spaces: Welcome to Java
s1 is Welcome
s2 is to
s3 is Java

The next() method reads a string that ends with a whitespace character. You can use the nextLine() method to read an entire line of text. The nextLine() method reads a string that ends with the Enter key pressed. For example, the following statements read a line of text.

Scanner input = new Scanner(System.in);
System.out.println("Enter a line: ");
String s = input.nextLine();
System.out.println("The line entered is " + s);
Enter fullscreen mode Exit fullscreen mode

Enter a line: Welcome to Java
The line entered is Welcome to Java

To avoid input errors, do not use nextLine() after nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or next().

Reading a Character from the Console

To read a character from the console, use the nextLine() method to read a string and then invoke the charAt(0) method on the string to return a character. For example, the following code reads a character from the keyboard:

Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character entered is " + ch);
Enter fullscreen mode Exit fullscreen mode

Comparing Strings

The String class contains the methods as shown below for comparing two strings.

Image description

How do you compare the contents of two strings? You might attempt to use the == operator, as follows:

if (string1 == string2)
 System.out.println("string1 and string2 are the same object");
else
 System.out.println("string1 and string2 are different objects");
Enter fullscreen mode Exit fullscreen mode

However, the == operator checks only whether string1 and string2 refer to the same object; it does not tell you whether they have the same contents. Therefore, you cannot use the == operator to find out whether two string variables have the same contents. Instead, you should use the equals method. The following code, for instance, can be used to compare two strings:

if (string1.equals(string2))
 System.out.println("string1 and string2 have the same contents");
else
 System.out.println("string1 and string2 are not equal");
For example, the following statements display true and then false.
String s1 = "Welcome to Java";
String s2 = "Welcome to Java";
String s3 = "Welcome to C++";
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
Enter fullscreen mode Exit fullscreen mode

The compareTo method can also be used to compare two strings. For example, consider the following code:

s1.compareTo(s2)
Enter fullscreen mode Exit fullscreen mode

The method returns the value 0 if s1 is equal to s2, a value less than 0 if s1 is lexicographically (i.e., in terms of Unicode ordering) less than s2, and a value greater than 0 if s1 is lexicographically greater than s2.

The actual value returned from the compareTo method depends on the offset of the first two distinct characters in s1 and s2 from left to right. For example, suppose s1 is abc and s2 is abg, and s1.compareTo(s2) returns -4. The first two characters (a vs. a) from s1 and s2 are compared. Because they are equal, the second two characters (b vs. b) are compared. Because they are also equal, the third two characters (c vs. g) are compared. Since the character c is 4 less than g, the comparison returns -4.

Syntax errors will occur if you compare strings by using relational operators >, >=, <, or <=. Instead, you have to use s1.compareTo(s2). The equals method returns true if two strings are equal and false if they are not. The compareTo method returns 0, a positive integer, or a negative integer, depending on whether one string is equal to, greater than, or less than the other string.

The String class also provides the equalsIgnoreCase and compareToIgnoreCase methods for comparing strings. The equalsIgnoreCase and compareToIgnoreCase methods ignore the case of the letters when comparing two strings. You can also use str.startsWith(prefix) to check whether string str starts with a specified prefix, str.endsWith(suffix) to check whether string str ends with a specified suffix, and str.contains(s1) to check whether string str contains string s1. For example,

"Welcome to Java".startsWith("We") returns true.
"Welcome to Java".startsWith("we") returns false.
"Welcome to Java".endsWith("va") returns true.
"Welcome to Java".endsWith("v") returns false.
"Welcome to Java".contains("to") returns true.
"Welcome to Java".contains("To") returns false.
Enter fullscreen mode Exit fullscreen mode

Image description

The program reads two strings for two cities (lines 11, 13). If input.nextLine() is replaced by input.next() (line 11), you cannot enter a string with spaces for city1. Since a city name may contain multiple words separated by spaces, the program uses the nextLine method to read a string (lines 11, 13). Invoking city1.compareTo(city2) compares two strings city1 with city2 (line 15). A negative return value indicates that city1 is less than city2.

Obtaining Substrings

You can obtain a single character from a string using the charAt method. You can also obtain a substring from a string using the substring method in the String class, as shown below.
For example,

String message = "Welcome to Java";
String message = message.substring(0, 11) + "HTML";
The string message now becomes Welcome to HTML.
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Finding a Character or a Substring in a String

The String class provides several versions of indexOf and lastIndexOf methods to find a character or a substring in a string, as shown below:

Image description

For example,

"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('o') returns 4.
"Welcome to Java".indexOf('o', 5) returns 9.
"Welcome to Java".indexOf("come") returns 3.
"Welcome to Java".indexOf("Java", 5) returns 11.
"Welcome to Java".indexOf("java", 5) returns -1.
Enter fullscreen mode Exit fullscreen mode
"Welcome to Java".lastIndexOf('W') returns 0.
"Welcome to Java".lastIndexOf('o') returns 9.
"Welcome to Java".lastIndexOf('o', 5) returns 4.
"Welcome to Java".lastIndexOf("come") returns 3.
"Welcome to Java".lastIndexOf("Java", 5) returns -1.
"Welcome to Java".lastIndexOf("Java") returns 11.
Enter fullscreen mode Exit fullscreen mode

Suppose a string s contains the first name and last name separated by a space. You can use the following code to extract the first name and last name from the string:

int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
Enter fullscreen mode Exit fullscreen mode

For example, if s is Kim Jones, the following diagram illustrates how the first name and last name are extracted.

Image description

Conversion between Strings and Numbers

You can convert a numeric string into a number. To convert a string into an int value, use the Integer.parseInt method, as follows:

int intValue = Integer.parseInt(intString);
Enter fullscreen mode Exit fullscreen mode

where intString is a numeric string such as "123".

To convert a string into a double value, use the Double.parseDouble method, as follows:

double doubleValue = Double.parseDouble(doubleString);
Enter fullscreen mode Exit fullscreen mode

where doubleString is a numeric string such as "123.45".

If the string is not a numeric string, the conversion would cause a runtime error. The Integer and Double classes are both included in the java.lang package, and thus they are automatically imported.

You can convert a number into a string, simply use the string concatenating operator as follows:

String s = number + "";
Enter fullscreen mode Exit fullscreen mode

Top comments (0)