String
String
Method Description
s.length() Returns the number of characters in this string.
s.charAt(index) Returns the character at the specified index from this
string.
s.concat(s1) Returns a new string that concatenates this string with string s1.
s.toUpperCase() Returns a new string with all letters in uppercase.
s.toLowerCase() Returns a new string with all letters in lowercase
s.trim() Returns a new string with whitespace characters trimmed on both
sides.
instance method
static method
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());
Indices
message
message.length() is 15
public class Testing {
}
}
string literal,
empty string
Note
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.
public class Testing {
System.out.println("Welcome to Java".length());
System.out.println("".length());
}
Getting Characters from a String
Note that the index for the first character in the string is 0.
message
Caution
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.
public class Testing {
}
}
public class Testing {
}
}
Concatenating Strings
String s3 = s1.concat(s2);
public class Testing {
}
}
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
}
}
The following code combines the strings message, " and ", and "HTML" into one
string:
String message=“Welcome from Java”;
String myString = message + " and " + "HTML";
System.out.println(myString);
public class Testing {
System.out.println(myString);
}
}
concatenate strings and numbers
place. 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
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.
}
}
If neither of the operands is a string, the plus sign (+) is the addition operator that adds
two numbers.
+= 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.
String message= "Welcome to Java" ;
message += " and Java is fun";
So the new message is "Welcome to Java and Java is fun".
public class Testing {
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:
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.
public class Testing {
System.out.println("Welcome".toLowerCase());
System.out.println("Welcome".toUpperCase());
}
}
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.
public class Testing {
}
}
Reading a String from the Console
To read a string from the console, invoke the next() method on a Scanner object.
Forexample, 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 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.
The String class contains the methods as shown in following Table for comparing two
strings.
Comparison Methods for String Objects
Method Description
equals(s1) Returns true if this string is equal to string s1.
equalsIgnoreCase(s1) Returns true if this string is equal to string s1; it is case insensitive.
compareTo(s1) compareTo() method is used for comparing two strings lexicographically.
Each character of both the strings is converted into a Unicode value for
comparison.
If both the strings are equal then this method returns 0 else it returns
positive or negative value.
The result is positive if the first string is lexicographically greater than the
second string else the result would be negative.
compareToIgnoreCase(s1) Same as compareTo except that the comparison is case
insensitive.
startsWith(prefix) Returns true if this string starts with the specified prefix.
endsWith(suffix) Returns true if this string ends with the specified suffix.
However, the == operator checks only whether string1 and string2 refer to the same
object(address); 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
The compareTo method can also be used to compare two strings.
Note
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
The equalsIgnoreCase and compareToIgnoreCase methods ignore the case of the letters
str.endsWith(suffix) to check whether string str ends with a specified suffix, and str
}
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.
Gives a program that prompts the user to enter two cities and displays them
inalphabetical order.
The String class contains the methods for obtaining substrings.
Method Description
substring(beginIndex) Returns this string’s substring that begins with the character at
the specified beginIndex and extends to the end of the string,
substring(beginIndex,endIndex)Returns this string’s substring that begins at the
specified beginIndex and extends to the character at index
endIndex – 1. Note that the character at endIndex is not part of the substring.
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 in the following Table
For example,
String message = "Welcome to Java";
String message = message.substring(0, 11) + "HTML";
The string message now becomes Welcome to HTML.
Indices
message
message.substring(11)
message.substring(0, 11)
Method Description
index(ch) Returns the index of the first occurrence of ch in the string. Returns -1 if not matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string. Returns -1
if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this string. Returns -1 if not
matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after fromIndex.
Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not matched.
lastIndexOf(ch, fromIndex) Returns the index of the last occurrence of ch before fromIndex in this string.
Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched.
lastIndexOf(s, fromIndex) Returns the index of the last occurrence of string s before fromIndex. Returns -1 if not
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.
For Example:
Indicies
s.substring k is 3
(0, k) is Kim s.substring
(k + 1) is Jones
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: