| Many programs deal with character strings so here we give a brief 
              introduction to the String 
              class in the core Java language. Although strings in Java are class 
              objects, in several ways they act like primitive types. 
              Note: You don't need to understand 
                the concepts of classes and objects yet to use Java strings. In 
                later chapters we discuss more details of the String 
                class.  The String 
              class makes creation and handling of strings quite easy and straightforward. 
              While one could create arrays of char 
              values, you will find it much simpler to use Java strings in most 
              cases.  As with other classes, you can create an instance 
              of a string with the new 
              operator but to make life simpler, it is not required. So either 
              of the following declarations will work:      String 
              str= new String("A string");     String 
              str1 = " and another string"; You can append one string to another with a simple "+" 
              operation (which is the only case in Java of overloading an operator, 
              that is, redefining its operation according to the type of operands). 
              For example,      String 
              str2 = str + str1;  which results in str2 
              holding:     "A 
              string and another string"; A very useful capability of the "+" 
              operator allows for default conversion of primitive type values 
              to strings. Whenever you "add" a primitive type value, 
              such as an int 
              value, to a string, the primitive value converts to a String 
              type and appends to the string. For example, this code     String 
              str1= "x = ";int i = 5;
 String str2 = str1 + 5;
 results in str2 
              holding "x 
              = 5". (This also works with boolean 
              type values, resulting in the strings "true" 
              and "false".) The String 
              class offers a large number of methods for accessing and manipulating 
              the characters in the string, but we will discuss these futher in 
              Chapter 10.     
                References & Web 
                  Resources  Latest update: Oct. 14, 2004 |