15-01-2013, 02:47 PM
Strings, Inheritance, Polymorphism, Arrays, and Exceptions
Strings.ppt (Size: 123.5 KB / Downloads: 26)
Strings and String Processing
String
Java strings are sequences of Unicode characters. For example, the string "Java\u2122" consists of the five Unicode characters J, a, v, a, and ™.
String e = ""; // an empty string
Immutable Strings
Objects of the String class are immutable. If you examine the JDK documentation for the String class, you’ll see that every method in the class that appears to modify a String actually creates and returns a brand new String object containing the modification. The original String is left untouched.
String Input and Output
The Scanner class is not suitable for reading a password from a console since the input is plainly visible to anyone. Java SE 6 introduces a Console class specifically for this purpose. To read a password, use the following code:
Console cons = System.console();
String username = cons.readLine("User name:");
char[] passwd = cons.readPassword("Password: ");
String Format
The Formatter class functionality is handled by the Formatter class in the java.util package
Format specifiers
To control spacing and alignment when data is inserted, you need more elaborate format specifiers.
Here’s the general syntax:
%[argument_index$][flags][width][.precision]conversion
Format specifiers
%[argument_index$][flags][width][.precision]
Width: control the minimum size of a field. The Formatter guarantees that a field is at least a certain number of characters wide by padding it with spaces if necessary
Precision: is used to specify a maximum
precision has a different meaning for different types.
For Strings, the precision specifies the maximum number of characters from the String to print.
For floating point numbers, precision specifies the number of decimal places to display (the default is 6), rounding if there are too many or adding trailing zeroes if there are too few.
Since integers have no fractional part, precision isn’t applicable to them and you’ll get an exception if you use precision with an integer conversion type