538 Strings and (Free web design) Characters Chapter 10 10.2 Fundamentals

538 Strings and Characters Chapter 10 10.2 Fundamentals of Characters and Strings Characters are the fundamental building blocks of Java source programs. Every program is composed of a sequence of characters that when grouped together meaningfully is interpreted by the computer as a series of instructions used to accomplish a task. A program might contain character constants. A character constant is an integer value represented as a character in single quotes. As we stated previously, the value of a character constant is the integer value of the character in the Unicode character set. For example, ‘z’ represents the integer value of z, and ‘n’represents the integer value of newline. See Appendix D for the integer equivalents of these characters. A string is a series of characters treated as a single unit. A string may include letters, digits and various special characters, such as +, -, *, /, $and others. A string is an object of class String. String literals or string constants (often called anonymous String objects) are written as a sequence of characters in double quotation marks as follows: “John Q. Doe” (a name) “9999 Main Street” (a street address) “Waltham, Massachusetts” (a city and state) “(201) 555-1212″ (a telephone number) A Stringmay be assigned in a declaration to a Stringreference. The declaration String color = “blue”; initializes Stringreference colorto refer to the anonymous Stringobject “blue”. Performance Tip 10.1 Java treats all anonymous Strings with the same contents as one anonymous String object that has many references. This conserves memory. 10.3 StringConstructors Class String provides nine constructors for initializing String objects in a variety of ways. Seven of the constructors are demonstrated in Fig. 10.1. All the constructors are used in the StringConstructors application s mainmethod. Line 25 instantiates a new String object and assigns it to reference s1, using class String s default constructor. The new Stringobject contains no characters (the empty string) and has a length of 0. Line 26 instantiates a new String object and assigns it to reference s2, using class String s copy constructor. The new Stringobject contains a copy of the characters in the String object sthat is passed as an argument to the constructor. 1 // Fig. 10.1: StringConstructors.java 2 // This program demonstrates the String class constructors. 3 4 // Java extension packages 5 import javax.swing.*; 6 Fig. 10.1 Demonstrating the Stringclass constructors (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Leave a Reply