Skip to main content
ICT
Lesson A10 - The String Class
 
Main   Previous Next
 

A. The String Class page 3 of 17

  1. Groups of characters in Java are not represented by primitive types as are int or char types. Strings are objects of the String class. The String class is defined in java.lang.String, which is automatically imported for use in every program you write. We’ve used String literals, such as "Enter a value" with System.out.print statements in earlier examples. Now we can begin to explore the String class and the capabilities that it offers.

  2. So far, our experience with Strings has been with String literals, consisting of any sequence of characters enclosed within double quotation marks. For example:

    "This is a string"
    "Hello World!"
    "\tHello World!\n"

    The characters that a String object contains can include escape sequences. This example contains a tab (\t) and a linefeed (\n) character.

  3. A second unique characteristic of the String class is that it supports the "+" operator to concatenate two String expressions. For example:

    sentence = "I " + "want " + "to be a " + "Java programmer.";

    The "+" operator can be used to combine a String expression with any other expression of primitive type. When this occurs, the primitive expression is converted to a String representation and concatenated with the string. For example, consider the following instruction sequence:

    PI = 3.14159;
    System.out.println("The value of PI is " + PI);

    Run Output:

    The value of PI is 3.14159

    To invoke the concatenation, at least one of the items must be a String.

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.