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:
"Hello!" |
Print a fixed string to the console, e.g. for debugging. |
System.out.println("Hello!"); |
Assign a string to a variable, then later print it |
String str = "Hello"; |
Append strings |
You can generally use the + operator between strings; you can also use +=:
String str = "Hello" + " " + "world!"; |
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:
"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 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); |
Print/append a number padded with spaces |
String.format("% 8d", number); |
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); 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*")) { ... } if (str.matches("\\d{5,10}")) { ... } |
Test if string X equals string Y |
if (strX.equals(strY)) { ... } |
Test if string X is equal to a constant string |
if ("constantString".equals(str)) { ... } |
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())) { ... }
|
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(); } BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(f), "ISO-8859-1")); |
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants. Follow @BitterCoffey
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.