Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

Strings and text in Java

The following table gives a summary of some common String-related operations, and at least one way of performing each one in Java. Note that 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. (Except in applications that perform a high volume of language-related functions, it's rare to have to worry about performance down to the number of clock cycles taken by string operations.)

If you think there's something missing from this list, then Let us know!.

OperationJava code
Represent a fixed string in your programPut the fixed string in quotes:
Print a fixed string to the console, e.g. for debugging.
Don't rely on accented characters etc from being written properly. If it's available, the Console class may allow you to output accented characters correctly.
Assign a string to a variable, then later print it
String str = "Hello";
Append strings Use the + operator between strings; you can also use +=:
String str = "Hello" + " " + "world!";
str = "Well... " + str;
str += "And goodbye!";
Strictly, each "modification" actually creates a brand new string.
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 stringPut "\n" where you want the line break:
"Line one\nLine two";
Pop up a string in a dialog box
JOptionPane.showMessageDialog(null, "Hello, world!");
Append an integer (int or long) to a stringFor integers, just use +:
String msg = "Lives left: " + livesLeft;
Append a float or double to a stringTo 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 The following ensures that str has a maximum length of 50:
str = String.format("%50s", str);
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 {
Exception handling 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).

Article written by Neil Coffey (@BitterCoffey).


 LetterMeister (word puzzle game for iPhone)
 Currency Quoter (currency converter/predictor)
 French Vocab Games for iPhone/iPad
 Vocabularium: create Spanish vocab podcasts

Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2015. All rights reserved.