This page shows how to perform common string-related operations in Java
using methods from the String class and related classes. In some cases, there
may be more efficient ways to perform that task, but we've generally chosen the
one that involves the simplest code.
String operation | Java code |
Represent a fixed string in your program | Put the fixed string in quotes:
|
Print a fixed string to the console, e.g. for debugging. |
System.out.println("Hello!");
Don't rely on accented characters etc from being written properly.
The Console class may allow you to
output accented characters correctly.
|
Assign a string to a variable, then later print it |
String str = "Hello"; ... System.out.println(str);
|
Append strings |
You can generally use the + operator between strings; you can also use +=:
String str = "Hello" + " " + "world!"; str = "Well... " + str; str += "And goodbye!";
Note that Java Strings are immutable. So srtictly speaking, code that appears to be appending
one string to another will actually be either: (a) creating a brand new string object on each "addition" (even if no-longer needed
are immediately garbage collectable) or (b) compiled in such a way that a StringBuilder is actually
used, and the += operations are effectively translated into calls to StringBuilder.append().
|
Check which character is in a given position. |
Use charAt(), remembering that the positions start at zero. For example:
char firstChar = str.charAt(0);
char secondChar = str.charAt(1);
|
Get the last character in a string. |
Use charAt() again, but use the list index in the string, which is equal
to the length minus one (because indexes start at zero):
char lastChar = str.charAt(str.length() - 1);
|
Put a line break inside a string | Put "\n" where you want the line break:
|
Pop up a string in a dialog box |
JOptionPane.showMessageDialog(null, "Hello, world!");
|
Append an integer (int or long) to a string | For integers, just use +:
String msg = "Lives left: " + livesLeft;
|
Append a float or double to a string | To print or append a floating point value, it's best to use String.format() to
specify the number of decimal places you want to print to:
String msg = "Value of x = " + String.format("%.3f", x);
Here, .3 specifies three decimal places.
|
Print/append a number padded with spaces |
String.format("% 8d", number);
Note the space before the 8; the 8 indicates the padding width.
|
Print/append a string padded with spaces |
String.format("% 20s", str);
|
Print a number in hex (convert a number to hex) | Use Integer.toHexString() or Long.toHexString():
String msg = "Hex: " + Integer.toHexString(val);
|
Convert a String into an int, long, double etc. |
Use Integer.parseInt(), Long.parseLong(), Double.parseDouble() etc.
String str = "12345";
int n = Integer.parseInt(str);
|
Print a date, or add it to a string |
Format a date as DD/MM/YYYY:
Date d = new Date();
String str = String.format("%td/%<tm/%<tY", d);
You can rearrange the elements as required; those after the first need the <.
Format a date in the "usual numeric form for the local region":
Date d = new Date();
String str = String.format("%tD", d);
|
Convert a string to upper/lower case |
str = str.toUpperCase();
str = str.toLowerCase();
|
Test if "string contains only digits" |
if (str.matches("\\d*")) {
...
}
To test if the string consists of "between 5 and 10 digits":
if (str.matches("\\d{5,10}")) {
...
}
For more information on how this works, see the section on
regular expressions.
|
Test if string X equals string Y |
if (strX.equals(strY)) {
...
}
Note that this will throw an exception if strX is null.
|
Test if string X is equal to a constant string |
if ("constantString".equals(str)) {
...
}
Putting the constant string first in the expression prevents a
NullPointerException from being thrown if str is null.
|
Test if string X contains string Y, taking case into account |
if (strX.contains(strY)) {
...
}
|
Test if string X contains string Y, ignoring case |
if (strX.toUpperCase().contains(strY.toUpperCase())) {
...
}
You could also use:- regular expressions,
using a case-insensitive match;
- the String.regionMatches() method
inside a loop;
But you may find this version easier to understand and remember!
|
Limit a string to a maximum length |
he following ensures that str has a maximum length of 50:
str = String.format("%50s", str).trim();
|
Read strings from a file |
File f = new File("C:\\TextFile.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
try {
String line;
while ((line = br.readLine()) != null) {
... do something with line ...
}
} finally {
br.close();
}
Exception handling has been omitted for simplicity. If you're fussy about
character encoding (i.e. your file contains characters other than
the "standard" English unaccented letters, numbers and punctuation),
then you may need to use:
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(f), "ISO-8859-1"));
Where ISO-8859-1 is the character encoding (the most
common alternative is UTF-8).
|