Java String: Working with Strings in Java

Declaring and Initializing Strings in Java
Joining, Concatenating or Appending Strings in Java
Java Substring: Selecting Parts of Strings in Java
Java Array String: Joining Arrays of Strings
Java String Split: Splitting Strings Into Tokens
Java String Comparison: Comparing Strings in Java
Java Is String: How to Tell if an Object is a String
Java String Format: Format Strings Or Convert Numbers to Strings
Java Cast String: Creating Strings From Other Objects



Strings are very easy to use in Java. The main thing to watch out for is that appending to strings using the + operator isn't very efficient; it creates new string objects unnecessarily. For most programs this doesn't really matter; but if you're doing lots of string handling and speed is a concern, use StringBuffer (thread safe) or StringBuilder (not thread safe but slightly more efficient).

Also be aware that Java isn't the world's most efficient language for dealing with lots of text data. Perl or Python scripts will generally run much faster than a Java text-processing program.

And finally, don't forget to use .equals() to compare text in strings, not == (which compares objects, not text).

Declaring and Initializing Strings in Java



You can declare and initialize a string in Java using the String class.

String text = "Hello";
System.out.println(text);




Hello




Joining, Concatenating or Appending Strings in Java



The simplest way to join strings in Java is to use +. This works like you'd expect.

String text1 = "Hello";
String text2 = "Jim";
        
System.out.println(text1 + " " + text2);




Hello Jim




However, this isn't very efficient because every time you write a +, you're creating a new String object. For that reason, you might prefer to use StringBuilder, or the older thread-safe version, StringBuffer.

StringBuilder sb = new StringBuilder();
        
sb.append("Hello");
sb.append(" to");
sb.append(" you");
        
System.out.println(sb.toString());




Hello to you




Even better, since append() returns a reference to the StringBuilder object itself, we can write stuff like this, with the same effect:

StringBuilder sb = new StringBuilder();
        
sb.append("Hello")
.append(" to")
.append(" you");
        
System.out.println(sb.toString());




Java Substring: Selecting Parts of Strings in Java



You can obtain part of a string in Java using the substring method.

String substring(int beginIndex, int endIndex)

The endIndex here is optional; if omitted, you get the whole of the string after the beginIndex. Note, the substring you select does not include the character at endIndex itself. It includes all characters up to the endIndex.

The length of the selected substring is endIndex - startIndex.

Here are some examples.

String text = "The quick brown fox";
        
// Everything from index 4 onwards
System.out.println(text.substring(4));
        
// Index 0 up to but not including index 3.
System.out.println(text.substring(0, 3));




quick brown fox
The




Java Array String: Joining Arrays of Strings



Amazingly, there seems to be no method for joining arrays of strings in core Java, although such methods exist in various libraries. You can always roll your own. The following class declares just such a method and uses it to join an array of strings. You could easily adapt this to work with ArrayList or Vector or whatever.

package caveofprogramming.aquarium;

import java.util.*;

public class Test {
    public static String join(String[] strings, String glue) {
    
        StringBuilder sb = new StringBuilder();
        
        for(int i=0; i < strings.length; i++) {
            sb.append(strings[i]);
            
            if(i < strings.length - 1) {
                sb.append(glue);
            }
        }
        
        return sb.toString();
    }
    
    public static void main(String [] args) {

        String texts[] = {"Hello", "to", "you"};
        System.out.println(join(texts, " "));
    }
}




Hello to you




Java String Split: Splitting Strings Into Tokens



You can split a string into an array of tokens using the split(REGEX) method.

Let's take a look at some examples.

To split on whitespace (this also works for tabs):

String text = "The quick brown fox";
        
// Split on whitespace
String [] tokens = text.split("\s+");
        
for(int i=0; i < tokens.length; i++) {
    System.out.println(tokens[i]);
}




The
quick
brown
fox




Split an email address into parts:

String text = "someone@nowhere.com";

// Split on @ and .
// The double backslashes make this regular
// expression look more confusing than it is.
// We are escaping once for the sake of the
// regex, and again for the sake of Java.
String [] tokens = text.split("[\@\.]+");

for(int i=0; i < tokens.length; i++) {
    System.out.println(tokens[i]);
}





someone
nowhere
com




Java String Comparison: Comparing Strings in Java



To compare strings in java, use .equals, not ==.

== will tell you if two references refer to the same object. To test if two strings are identical, .equals does what you want.

The following program illustrates the point.

// Here's some text.
String text1 = "Hello there";

// Here's the same text.
String text2 = "Hello there";

// Here's a second reference to the 
// first string.
String text3 = text1;

// The first two strings are equal
// (contain the same text)
if(text1.equals(text2)) {
    System.out.println("text1 matches text2.");
}

// ... and in this case they are the same object, 
// which presumably is due to optimization by the
// virtual machine. DO NOT rely on this!!
if(text1 == text2) {
    System.out.println("text1 and text2 are the same object (oddly)");
}

// text2 and text3 ARE clearly the same object, however.
if(text2 == text3) {
    System.out.println("text2 and text3 are the same object.");
}




text1 matches text2.
text1 and text2 are the same object (oddly)
text2 and text3 are the same object.




Java Is String: How to Tell if an Object is a String



To check if an object is a String or not, use instanceof.

// Here's a string.
String text1 = "Hello there";

if(text1 instanceof java.lang.String) {
    System.out.println("It's a string!");
}




It's a string!




Java String Format: Format Strings Or Convert Numbers to Strings



If you just want to convert a number to a string in Java, it's very easy with toString(). You might have to wrap a primitive type like int in an object of type Integer or Double first.

// An int.
int count = 59;

// A float.
double cost = 57.59;

// Convert int to string and display.
System.out.println(new Integer(count).toString());

// Convert float to string and display.
System.out.println(new Double(cost).toString());




59
57.59




If you want more control over how your numbers are formatted, you need the static format() method.

This method works much like sprintf in C or Perl. Here's an example that formats various numbers.

// An int.
int count = 59;

// A float.
double cost = 57.59;

// Format the numbers together with some text.
// For 'cost', we make the entire number 7 characters
// wide (including the .); we left-pad with zeros
// and put two numbers after the decimal point.
String text = String.format("Count: %d, Cost: $%07.2f", 
    count, cost);

System.out.println(text);




Count: 59, Cost: $057.59




Java Cast String: Creating Strings From Other Objects



Don't forget, any time you want to turn an object into a string in java, just use the object's toString() method.

If one doesn't exist, or it doesn't do what you want, consider over-riding it.