prev | TOC | next

Strings in Java


The String class is commonly used for holding and manipulating strings of text in Java programs.  It is found in the standard java.lang package which is automatically imported, so you don't need to do anything special to use it.

In its simplest form, you use the String class by typing some text surrounded by double quotes.  This is called a String literal.

"This is a Java String"

Anywhere you need a String object, you can type a String literal as in:

Console.println("Hello there!");

Concatenation

Strings are special types of objects in that you can add them together using the "+" operator and get a longer string that is a concatenation of the two.  Thus, the code:

String name = "Bill";
String introduction = "Hello there, my name is " + name;
Console.println( introduction );

will print

Hello there, my name is Bill

on the console.

String representation of Objects

All Java objects implement the method toString() which returns a String object that best "describes" that object.  For example, if you can print out a red color object using

Color color = new Color( 255, 0, 0 );
String colorStr = color.toString();
Console.println( colorStr );

This will printout:

java.awt.Color[r=255,g=0,b=0]

In this case you do not even need to explicitly call toString().  The println() method has a version that takes an Object as its argument.  This version will implicitly call toString() for you and print the result.

This implicit conversion to a String also happens when concatenating a String object with another object type.  For example, you could type:

Color color = new Color( 255, 0, 0 );
String str = "My color looks like: " + color;
Console.println( str );

And you would get the following on the console:

My color looks like: java.awt.Color[r=255,g=0,b=0]

String API

You will find the complete String API here.  It would probably be useful for you to at least scan the API to see what other interesting things you can do with Strings.  There are methods for:

  • getting the character at a given position within the string -- charAt()
  • seeing if a character or string exists within a string -- indexOf()
  • getting the number of characters in a string -- length()
  • extracting a substring from a string -- substring()