Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

The Java Lesson 17: The String class

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

The Java Lesson 17

The String class


Overview

Java does not have a primitive data type for storing string data, such as "Java is fun". It does, however, provide an instantiable String class that may be used to construct String objects. Such objects encapsulate a constant string and numerous instance methods that support processing of the string.

The String class

  • Is part of the java.lang package. This package is automatically available so no import statement is needed to use the String class.

  • Is an extension of the Object class. This means a String is an Object and inherits all the features of the Object class. The implications of class inheritance will be covered in a later lesson.

Object

String
  • Is used to represents all string literals in Java.

A string literal, such as "abc", is implemented as an instance of the String class. It is placed in a memory area known as the literal pool. When two or more string literals have the same value, the compiler generates only one String object that is shared.

  • Has a large number of constructor methods. The most commonly used accepts a string literal as a parameter. For example,

String jobTitle = new String("clerk");

instantiates a String object having a value of "clerk" and assigns it to jobTitle. Whenever the keyword new is specified, a new object having its own memory space will be created in a memory area known as the heap as shown by this diagram:

Heap Space

Literal Pool

jobTitle

->

"clerk"

"clerk"

A new String object has been created on the heap that has the same string value as the String object in the literal pool. Any references involving jobTitle will access the object on the heap.

Because string literals are implemented as String objects, many programmers prefer to not create another object and simply assign the string literal to the object reference as follows:

String jobTitle = "clerk";

In this case, no heap space is used as shown by the following diagram:

Heap Space

Literal Pool

jobTitle

->

"clerk"

It is important to understand the difference between the two techniques.

  • Does not permit the value of its string to be changed. Once instantiated, a String object is immutable. It can, however, be shared. For example, consider the following statements:

String x = "abc";
String y = "abc";

Because the string literals are identical, the compiler creates one String object for "abc" in the literal pool. It is then assigned to both x and y.

  • Has several useful methods. Commonly used methods are:

Method

Usage

charAt()

Returns the character at the specified index within the string where the first character has an index of 0

compareTo()

Performs a case-sensitive comparison of the value of this string to the value of another String object to determine which comes first alphabetically

concat()

Concatenates the specified string to the end of this string to create another String object

equals()

Performs a case-sensitive comparison of the value of this string to the value of another String object to determine if they are equal

equalsIgnoreCase()

Compares the value of this string to the value of another String object with both strings viewed as having the same case

indexOf()

Returns the index of the first occurrence of a specified search character or substring within this string (overloaded)

lastIndexOf()

Returns the index of the last occurrence of a specified search character or substring within this string (overloaded)

length()

Returns the character length of this string

replace()

Replaces all occurrences of a specified character in this string with another character to create another String object

substring()

Extracts a substring from this string to create another String object

toLowerCase()

Converts all characters of this string to lowercase to create another String object

toUpperCase()

Converts all characters of this string to uppercase to create another String object

trim()

Removes all white space characters (spaces and TABs) from both ends of this string to create another String object

Many of these methods are overloaded to accept different parameter values. Also notice that methods that appear to modify the string actually return another String object (because String objects are immutable).

Consult Java API documentation for more details.

  • Has special support for concatenation and conversion of primitive data types to their string equivalent within the Java language. Whenever the '+' sign is coded after a string literal or a String object reference, it means that the second operand is to be converted to a string (if it isn't one already) and appended to the first string to create a new String object. That is why you have been able to code statements such as

System.out.println("Value is " + xyz);

The second operand (xyz) is converted to a string and appended to "Value is ". The resulting string is then passed to the println() method to be displayed. The following would also have worked:

String temp = "Value is " + xyz;
System.out.println(temp);

  • Can trap unwary programmers who incorrectly test two strings for equality. The correct way to test for equality is to use the equals() method. For example, if stringA and stringB are String class objects, you should test them for equality by coding either of the following expressions:

stringA.equals(stringB)

or

stringB.equals(stringA)

A common mistake is to code the expression

stringA == stringB

which compares the object references and NOT the objects they reference. The following code, for example, would say that the objects have different values:

String x = "abc";
String y = new String("abc");
if (x == y)
System.out.println("They have the same value");
else
System.out.println("They have different values");

Because x references the object in the literal pool and y references an object on the heap, x and y are not equal even though the strings they reference have identical values.

The following code would say that the objects have the same value:

String x = "abc";
String y = new String("abc");
if (x.equals(y))
System.out.println("They have the same value");
else
System.out.println("They have different values");

Sample program

The following program uses some methods of the String class to count the number of times a specified character appears within a string entered by the user.

public class App {
public static void main(String[] args) {

// Variables for holding input data.

String buffer;
char find;
String again;

// Loop to process one string search request.

do {

// Prompt for and read input data.

Utility.separator(50, '~');
System.out.print("Enter the string to be searched: ");
buffer = Keyboard.readString();
System.out.print("Enter the character to be counted: ");
find = Keyboard.readChar();

// Local variables used in searching and counting.

int fromIndex = 0;
int foundIndex;
int count = 0;

// Loop to find and count all occurrences of the character
// within the string.

do {

// Search for the next occurrence of the character. The search
// will begin at the location specified by fromIndex.

foundIndex = buffer.indexOf(find, fromIndex);

// If the character was found, increment the counter and set
// fromIndex to continue the search at the next character position.

if (foundIndex >= 0) {
count++;
fromIndex = foundIndex + 1;
}
} while (foundIndex >= 0); // Continue looping if character is found.

// Display how many characters the string contains and how many
// times the search character occurs within the string.

Utility.skip();
System.out.println(" The string has " + buffer.length() + " characters");
System.out.println(" '" + find + "' occurs " + count + " time(s)");

// Ask the user if they want to search another string.

Utility.skip();
System.out.print("Again? ("YES" or "NO"): ");
again = Keyboard.readString();
} while (again.equalsIgnoreCase("YES")); // Loop as requested
}
}

Notes:

  1. The sample declares a String object reference (buffer) for the string to be searched and a char variable (find) for the character to be found. Values for these are read from the user. Note that the readString() method of my Keyboard class returns a String object.

  2. To count how many times the character occurs within the string, a loop is performed that relies on the indexOf() method. This String class method returns either the index of the next occurrence a specified character within a string, or -1 if the specified character is not found. The program's loop begins the search at the first character location (it has an index of 0). If the search character is found, it is counted and the search resumes at the next character position. Otherwise, the loop ends.

  3. After counting the number of occurrences of the search character, the results of processing the string are displayed. The length() method of the String class provides an easy way to display the number of characters in the string.

  4. In asking the user if they want to process another string, a String object is read and assigned to again. Its value is tested using the equalsIgnoreCase() method so that they can reply "YES" in any form of capitalization to continue.

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

Review questions

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following code? The line numbers are for reference purposes only.

1
2
String x = "abcdefg";
System.out.println("Value is: " + x.charAt(3));
  1. Compilation will fail at line 1

  2. Compilation will fail at line 2

  3. Compilation will succeed but a runtime error will occur

  4. Compilation will succeed. The message "Value is: c" will be displayed.

  5. Compilation will succeed. The message "Value is: d" will be displayed.

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following code? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
String x = "abc";
String y = new String(x);
String z = y;
if (z.equals(x))
System.out.println("They are equal");
else
System.out.println("They are different");
  1. Compilation will fail at line 2

  2. Compilation will fail at line 3

  3. Compilation will fail at line 4

  4. Compilation will succeed. The message "They are equal" will be displayed.

  5. Compilation will succeed. The message "They are different" will be displayed.

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following code? The line numbers are for reference purposes only.

1
2
String x = new String("abcde");
System.out.println("Result: " + x.substring(x.length() - 2));
  1. Compilation will fail at line 1

  2. Compilation will fail at line 2

  3. Compilation will succeed but a runtime error will occur

  4. Compilation will succeed. The message "Result: de" will be displayed.

  5. Compilation will succeed. The message "Result: cde" will be displayed.

  1. Assume that x is the object reference of a String object having the string value "abc". What value will the string have after executing the following statement?

x.toUpperCase();

  1. The statement will not compile

  2. The statement will compile but a runtime error will occur

  3. "abc"

  4. "Abc"

  5. "ABC"


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy