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.
/**
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);
}
}
$ $ 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. $
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.
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 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.
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. |
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);
}
}
$ $ 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. $
String str18=str11.replace(' ',"SUBSTITUTED"); //ErrorFor 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 $
String strAppendNumber="1"+6; // strAppendNumber is the string "16" not 7.