The Java String class (java.lang.String) is a class of object that represents a character array of arbitrary length. While this external class can be used to handle string objects, Java integrates internal, built-in strings into the language.
An important attribute of the String class is that once a string object is constructed, its value cannot change (note that it is the value of an object that cannot change, not that of a string variable, which is just a reference to a string object). All String data members are private, and no string method modifies the string’s value.
CONVERTING OBJECTS TO STRINGS
The String + operator accepts a non-string operand, provided the other operand is a string. The action of the + operator on non-string operands is to convert the non-string to a string, then to do the concatenation. Operands of native types are converted to string by formatting their values. Operands of class types are converted to a string by the method toString()
that is defined for all classes. Any object or value can be converted to a string by explicitly using one of the static valueOf() methods defined in class String:
String str = String.valueOf (obj);
If the argument to valueOf() is of class type, then valueOf() calls that object’s toString() method. Any class can define its own toString() method, or just rely on the default. The output produced by toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text representation of the object, nor is it meant to be parsed. These conversion rules also apply to the right-hand side of the String += operator.
CONVERTING STRINGS TO NUMBERS
Methods from the various wrapper classes, such as Integer and Double, can be used to convert numerical strings to numbers. This is often necessary for command line arguments where the parameter list is available to the main () method as a string array. The wrapper classes contain static methods ( such as parseInt() ) which convert a string to its own internal data type.
These can be used with class names rather than creating a separate object. Be aware that these particular conversion methods throw a NumberFormatException and must be used in the context of a try and catch block combination.
No comments:
Post a Comment