Using Strings in Java

As noted in the previous section a text string is a sequence of characters. Java provides several classes for handling strings. We have already seen one or two examples of the first of these, the String class. This is used to store string values that are immutable, that is to say, the data contained in the string does not change once it is assigned. The other two classes the StringBuilder class and the StringBuffer class allow the string data to be altered.

The StringBuffer class

The StringBuffer class is a synchronous class this is important for multithreaded applications. It means that different threads of a program can access and alter the StringBuffer objects data in an orderly fashion without corrupting the internal state of the object. (Multithreaded application have several parts of their program running concurrently.) One of the great advantages of Java is its strong support for multithreading.

The StringBuilder class

The StringBuilder class is an unsynchronous class, it is not designed to be used in multithreaded applications. It is, however, slightly more efficient than the StringBuffer since it doesn't need to coordinate access to its internal structures.

Basics of the Java String Class

The next program demonstrates some basics string operations in Java. The program consists of a single class called StringsJava. This class contains the main method which simply creates and displays a number of strings.
/**
This program demonstrates the Java String class
*/
class  StringsJava
{

 
public static  void main(String[] args)
  {
   
// String creation
   
   
String strFirstString ="This is a string.";
    String strSecondString = strFirstString;
    String strThirdString=
"Strings are sequences of unicode characters.";
    String strFourthString=
"So characters such as '\u03C0' can be used.";
    String strFifthString=
"To show a new line insert the \ncharacter.";
    String strSixthString= strFirstString+
" You can append strings using the + operator.";
   
    System.out.println
(strFirstString);
    System.out.println
(strSecondString);
    System.out.println
(strThirdString);
    System.out.println
(strFourthString);
    System.out.println
(strFifthString);
    System.out.println
(strSixthString);
   
 
}
}

To compile and run from the command line:
$ 
$ javac  StringsJava.java 
$ java  StringsJava
This is a string.
This is a string.
Strings are sequences of unicode characters.
So characters such as 'π' can be used.
To show a new line insert the 
character.
This is a string. You can append strings using the + operator.
$ 

Creating String objects

Declaring a variable makes it available to be used subsequently in the program. Java is a strongly typed language this means, among other things, that all variables must be declared before they are used. The simplest way to create a String object is to use the class name String followed by a reference variable name and assign a value to it. For example

String strFirstString = "This is a string."; //The simple way to create a string.
When the java compiler encounters a line such as this it creates a String Object containing associated text, in this case the, "This is a string." (without the quotes). The associated variable, in this case, strFirstString is called a reference. A reference doesn't store an objects data directly, rather, it stores the location or address of the object in memory.

String strSeventhString = new String("You can also create strings using the 'new' keyword."); //This way is not normally done for strings.
This code snippet demonstrates a second way of creating an object. In this example the "new" keyword is used to allocate a string object. The reference variable strSeventhString stores the address of the newly created String object. This technique is more commonly used to create mutable objects.

Code of the String object

The actual code for the String class is defined in java.lang.String and this is made available automatically to all Java programs. The code of the java.lang.String class is derived from a more general class called a java.lang.Object. This means that each Java String class has all the characteristics and properties of a Java java.lang.Object. The converse is not true, not every object is a String, indeed there are many different Objects in Java. The benefits of this arrangement will become clear in upcoming tutorials when we create our own classes and derive classes from them.

The string append operator +

The + operator when used between two strings creates a third string consisting of the concatenation of original strings.

Java strings consist of Unicode characters

Java strings are stored as sequences of Unicode (UTF-16) characters this makes it easy to append and embed Unicode characters into a string.

Double and single quotes

In Java literal strings are expressed in double quote characters, "". When the Java compiler encounters a sequence (possibly of zero length) of characters it creates a String object. This contrasts with literal characters which are expressed in single quotes.

The backslash symbol \

The backslash symbol, \, has a special meaning to the Java compiler. This symbol coupled with the character following it is used to apply string formating. In the above example the "\n" characters are used to insert a new line. The next table enumerates the effects of the backslash character.

The effects of the backslash symbol \ in Java
Characters Effect
\\ A single backslash character.
\\ A single backslash character.
\' A single quote character.
\" A double quote character.
\f A form feed character.
\n A new line character.
\r A carriage return character.
\t A tabulation character.
\x A Latin-1 character. Here x is a one digit octal number. This form is legal but not recommended.
\xx A Latin-1 character. Here xx is a two digit octal number. This form is legal but not recommended.
\xxx A Latin-1 character. Here xxx is a three digit octal number in 000 to 388 inclusive.
\uXXXX A Unicode (UTF-16) character. Here XXXX is a four digit hexadecimal number.

Manipulating Strings

The next program demonstrates some basic string manipulation using the String class. The important points to note in this example are: Firstly, that because the String class is immutable, any methods that change a string provide their result as a returned String. The original String object is unchanged. In order to make use of the returned String it is assigned to a new String object (or passed in to some method). Secondly, to use the a method in a String object we a reference variable to that String object and the dot '.' operator followed by the method's name. For example :
String str7=str6.toUpperCase();

/**
This program demonstrates the Java String class.
It shows conversion from integer, floating point and boolean types, case conversion, character
and string replacement.
*/
class  MoreStringsJava1
{

 
public static  void main(String[] args)
  {
   
// String creation
   
int iAnInteger=32;
   
double dADouble =10.0/7.0;
   
boolean bABoolean= true;
   
   
//Primitive types can be converted to strings automatically.
   
String str1 ="The value iAnInteger is "+iAnInteger;
    String str2 =
"The value of dADouble is " +dADouble;
    String str3 =
"The value of bABoolean is "  +bABoolean;

   
//The trim method removes leading and trailing white spaces.
   
String str4 ="  \t \t  Leading and trailing\twhite spaces can be removed. \t \t    ";
    String str5 = str4.trim
();
   
   
//The case of text can be changed.
   
String str6= "The case of strings can be changed and substrings can be extracted.";
    String str7=str6.toUpperCase
();
    String str8=str6.toLowerCase
();

   
//Substrings can be extracted.
   
String str9=str6.substring(25);
    String str10=str6.substring
(29,45)+ "and added to";
   
   
//Substrings and characters can be replaced.
   
String str11="Characters and substringes can be replaced.";
    String str12=str11.replace
(' ','-');
    String str13=str11.replace
("replaced","SUBSTITUTED");
   
   
    System.out.println
(str1);
    System.out.println
(str2);
    System.out.println
(str3);
    System.out.println
(str4);
    System.out.println
(str5);
    System.out.println
(str6);
    System.out.println
(str7);
    System.out.println
(str8);
    System.out.println
(str9);
    System.out.println
(str10);
    System.out.println
(str11);
    System.out.println
(str12);
    System.out.println
(str13);
     
 
}
}

To compile and run from the command line:
$ 
$ javac  MoreStringsJava1.java 
$ java  MoreStringsJava1 
The value iAnInteger is 32
The value of dADouble is 1.4285714285714286
The value of bABoolean is true
                  Leading and trailing  white spaces can be removed.                
Leading and trailing    white spaces can be removed.
The case of strings can be changed and substrings can be extracted.
THE CASE OF STRINGS CAN BE CHANGED AND SUBSTRINGS CAN BE EXTRACTED.
the case of strings can be changed and substrings can be extracted.
e changed and substrings can be extracted.
anged and substrand added to
Characters and substringes can be replaced.
Characters-and-substringes-can-be-replaced.
Characters and substringes can be SUBSTITUTED.
$ 

Method overloading

The replace method used in the above program, is an example of method overloading. Here, the String class provides two replace methods. The first of these expects two character parameters to be passed, the second expects two String parameters to passed. The Java compiler identifies the correct version of the replace method based on type of the parameters used. Because there is no replace method defined in the String class that has a char for its first parameter and a String for its second, attempting to use the replace method in this way will result in a compile time error of "cannot find symbol".
 String str18=str11.replace(' ',"SUBSTITUTED"); //Error  
For example if the above the above code snippet were in a Java program called MoreStringsJava1Bad on line 39 upon compiling we would have:
MoreStringsJava1Bad.java:39: cannot find symbol
symbol  : method replace(char,java.lang.String)
location: class java.lang.String
                String str18=str11.replace(' ',"SUBSTITUTED");                                ^
1 error
$ 

Converting from primitive types to string types

When converting from primitive data types the + operator is string append not arithmetic addition.
String strAppendNumber="1"+6; // strAppendNumber is the string "16" not 7.  

Summary

  • The String class is immutable, that is its data can't be altered.
  • The StringBuilder and StringBuffer classes are mutable.
  • Reference variables are used to store the location of a String in memory.
  • The Sting objects methods are executed via the reference variable using the dot operator.
  • The String class is derived from the Object class.
  • String methods can return other strings.
  • The + operator concatenates two strings.
  • The eight primitive types can be converted to String types automatically.
  • The String class provides methods for, replacing, changing case, trimming and many other frequently needed operations.
  • Methods can be overloaded, so that the same method name is used in different contexts.


Previous Basic arithmetic operations in Java Next More Strings in Java

Custom Search

Tutorial
Your First Java Program
Primitive data types in Java
Basic arithmetic operations in Java
Using Strings in Java
More Strings in Java
The Java if statement
Loops in Java
The entire content of this site is subject to copyright.