Thursday 16 March 2017

Simple Type Wrappers - Java Tutorials ( Page - 2 of 2 )

The Methods Defined by Integer

byte byteValue( ):  Returns the value of the invoking object as a byte.

int compareTo(Integer i):  Compares the numerical value of the invoking object with that of i. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value. (Added by Java 2)

int compareTo(Object obj):  Operates identically to compareTo(Integer) if obj is of class Integer. Otherwise, throws a ClassCastException. (Added by Java 2)

static Integer decode(String str) throws NumberFormatException: Returns an Integer object that contains the value specified by the string in str.

double doubleValue( ):  Returns the value of the invoking object as a double.

boolean equals(Object IntegerObj):  Returns true if the invoking Integer object is equivalent to IntegerObj. Otherwise, it returns false.

float floatValue( ):  Returns the value of the invoking object as a float.

static Integer getInteger(String propertyName):  Returns the value associated with the environmental property specified by propertyName. A null is returned on failure.

static Integer getInteger(String propertyName, int default):  Returns the value associated with the environmental property specified by propertyName. The value of default is returned on failure.

static Integer getInteger(String propertyName, Integer default):  Returns the value associated with the environmental property specified by propertyName. The value of default is returned on failure.

int hashCode( ):   Returns the hash code for the invoking object.

int intValue( ):  Returns the value of the invoking object as an int.

long longValue( ):  Returns the value of the invoking object as a long.

static int parseInt(String str) throws NumberFormatException:  Returns the integer equivalent of the number contained in the string specified by str using radix 10.

static int parseInt(String str, int radix) throws NumberFormatException: Returns the integer equivalent of the number contained in the string specified by str using the specified radix.

short shortValue( ):  Returns the value of the invoking object as a short.

static String toBinaryString(int num):  Returns a string that contains the binary equivalent of num.

static String toHexString(int num):  Returns a string that contains the hexadecimal equivalent of num.

static String toOctalString(int num):  Returns a string that contains the octal equivalent of num.

String toString( ):  Returns a string that contains the decimal equivalent of the invoking object.

static String toString(int num):  Returns a string that contains the decimal equivalent of num.

static String toString(int num, int radix):  Returns a string that contains the decimal equivalent of num using the specified radix.

static Integer valueOf(String str) throws NumberFormatException:  Returns an Integer object that contains the value specified by the string in str.

static Integer valueOf(String str, int radix) throws NumberFormatException: Returns an Integer object that contains the value specified by the string in str using the specified radix.


The Methods Defined by Long

byte byteValue( ):  Returns the value of the invoking object as a byte.

int compareTo(Long l):  Compares the numerical value of the invoking object with that of l. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value. (Added by Java 2)

int compareTo(Object obj):  Operates identically to compareTo(Long) if obj is of class Long. Otherwise, throws a ClassCastException. (Added by Java 2)

static Long decode(String str) throws NumberFormatException:   Returns a Long object that contains the value specified by the string in str.

double doubleValue( ):  Returns the value of the invoking object as a double.

boolean equals(Object LongObj):  Returns true if the invoking long object is equivalent to LongObj. Otherwise, it returns false.

float floatValue( ):  Returns the value of the invoking object as a float.

static Long getLong(String propertyName):  Returns the value associated with the environmental property specified by propertyName. A null is returned on failure.

static Long getLong(String propertyName, long default):   Returns the value associated with the environmental property specified by propertyName. The value of default is returned on failure.

static Long getLong(String propertyName, Long default):   Returns the value associated with the environmental property specified by propertyName. The value of default is returned on failure.

int hashCode( ):  Returns the hash code for the invoking object.

int intValue( ):  Returns the value of the invoking object as an int.

long longValue( ):  Returns the value of the invoking object as a long.

static long parseLong(String str) throws NumberFormatException:   Returns the long equivalent of the number contained in the string specified by str in radix 10.

static long parseLong(String str, int radix) throws NumberFormatException: Returns the long equivalent of the number contained in the string specified by str using the specified radix.

short shortValue( ):   Returns the value of the invoking object as a short.

static String toBinaryString(long num):  Returns a string that contains the binary equivalent of num.

static String toHexString(long num):  Returns a string that contains the hexadecimal equivalent of num.

static String toOctalString(long num):  Returns a string that contains the octal equivalent of num.

String toString( ):  Returns a string that contains the decimal equivalent of the invoking object.

static String toString(long num):  Returns a string that contains the decimal equivalent of num.

static String toString(long num, int radix):  Returns a string that contains the decimal equivalent of num using the specified radix.

static Long valueOf(String str) throws NumberFormatException:  Returns a Long object that contains the value specified by the string in str.

static Long valueOf(String str, int radix) throws NumberFormatException:  Returns a Long object that contains the value specified by the string in str using the specified radix.


Converting Numbers to and from Strings

One of the most common programming chores is converting the string representation of a number into its internal, binary format. Fortunately, Java provides an easy way to accomplish this. The Byte, Short, Integer, and Long classes provide the parseByte( ), parseShort( ), parseInt( ), and parseLong( ) methods, respectively. These methods return the byte, short, int, or long equivalent of the numeric string with which they are called. (Similar methods also exist for the Float and Double classes.)

The following program demonstrates parseInt( ). It sums a list of integers entered by the user. It reads the integers using readLine( ) and uses parseInt( ) to convert these strings into their int equivalents.

  /* This program sums a list of numbers entered
     by the user. It converts the string representation
     of each number into an int using parseInt().
  */
  
  import java.io.*;

  class ParseDemo {
    public static void main(String args[])
      throws IOException
    {
      // create a BufferedReader using System.in
      BufferedReader br = new
        BufferedReader(new InputStreamReader(System.in));
      String str;
      int i;
      int sum=0;

      System.out.println("Enter numbers, 0 to quit.");
      do {
        str = br.readLine();
        try {
          i = Integer.parseInt(str);
        } catch(NumberFormatException e) {
          System.out.println("Invalid format");
          i = 0;
        }
        sum += i;
        System.out.println("Current sum is: " + sum);
      } while(i != 0);
    }
  }

To convert a whole number into a decimal string, use the versions of toString( ) defined in the Byte, Short, Integer, or Long classes. The Integer and Long classes also provide the methods toBinaryString( ), toHexString( ), and toOctalString( ), which convert a value into a binary, hexadecimal, or octal string, respectively.

The following program demonstrates binary, hexadecimal, and octal conversion:

  /* Convert an integer into binary, hexadecimal,
     and octal.
  */

  class StringConversions {
    public static void main(String args[]) {
      int num = 19648;

      System.out.println(num + " in binary: " +
                         Integer.toBinaryString(num));

      System.out.println(num + " in octal: " +
                         Integer.toOctalString(num));

      System.out.println(num + " in hexadecimal: " +
                         Integer.toHexString(num));
    }
  }

The output of this program is shown here:

  19648 in binary: 100110011000000
  19648 in octal: 46300
  19648 in hexadecimal: 4cc0


Character

Character is a simple wrapper around a char. The constructor for Character is

      Character(char ch)

Here, ch specifies the character that will be wrapped by the Character object being created.

To obtain the char value contained in a Character object, call charValue( ), shown here:

      char charValue( )

It returns the character.

The Character class defines several constants, including the following:

MAX_RADIX         The largest radix
MIN_RADIX           The smallest radix
MAX_VALUE         The largest character value
MIN_VALUE          The smallest character value
TYPE                       The Class object for char

Character includes several static methods that categorize characters and alter their case. They are shown in Table 14-7. The following example demonstrates several of these methods.

  // Demonstrate several Is... methods.

  class IsDemo {
    public static void main(String args[]) {
      char a[] = {'a', 'b', '5', '?', 'A', ' '};

      for(int i=0; i<a.length; i++) {
        if(Character.isDigit(a[i]))
          System.out.println(a[i] + " is a digit.");
        if(Character.isLetter(a[i]))
          System.out.println(a[i] + " is a letter.");
        if(Character.isWhitespace(a[i]))
          System.out.println(a[i] + " is whitespace.");
        if(Character.isUpperCase(a[i]))
          System.out.println(a[i] + " is uppercase.");
        if(Character.isLowerCase(a[i]))
          System.out.println(a[i] + " is lowercase.");
      }
    }
  }

The output from this program is shown here:

  a is a letter.
  a is lowercase.
  b is a letter.
  b is lowercase.
  5 is a digit.
  A is a letter.
  A is uppercase.
  is whitespace.


Various Character Methods

static boolean isDefined(char ch):  Returns true if ch is defined by Unicode. Otherwise, it returns false.

static boolean isDigit(char ch):  Returns true if ch is a digit. Otherwise, it returns false.

static boolean isIdentifierIgnorable(char ch):  Returns true if ch should be ignored in an identifier. Otherwise, it returns false.

static boolean isISOControl(char ch):  Returns true if ch is an ISO control character. Otherwise, it returns false.

static boolean isJavaIdentifierPart(char ch):  Returns true if ch is allowed as part of a Java identifier (other than the first character). Otherwise, it returns false.

static boolean isJavaIdentifierStart(char ch):  Returns true if ch is allowed as the first character of a Java identifier. Otherwise, it returns false.

static boolean isLetter(char ch):  Returns true if ch is a letter. Otherwise, it returns false.

static boolean isLetterOrDigit(char ch):  Returns true if ch is a letter or a digit. Otherwise, it returns false.

static boolean isLowerCase(char ch):  Returns true if ch is a lowercase letter. Otherwise, it returns false.

static boolean isMirrored(char ch):  Returns true if ch is a mirrored Unicode character. A mirrored character is one that is reversed for text that is displayed right-to-left. (Added by Java 2, version 1.4)

static boolean isSpaceChar(char ch):  Returns true if ch is a Unicode space character. Otherwise, it returns false.

static boolean isTitleCase(char ch):  Returns true if ch is a Unicode titlecase character. Otherwise, it returns false.

static boolean isUnicodeIdentifierPart(char ch):  Returns true if ch is allowed as part of a Unicode identifier (other than the first character). Otherwise, it returns false.

static boolean isUnicodeIdentifierStart(char ch):  Returns true if ch is allowed as the first character of a Unicode identifier. Otherwise, it returns false.

static boolean isUpperCase(char ch):  Returns true if ch is an uppercase letter. Otherwise, it returns false.

static boolean isWhitespace(char ch):  Returns true if ch is whitespace. Otherwise, it returns false.

static char toLowerCase(char ch):  Returns lowercase equivalent of ch.

static char toTitleCase(char ch):  Returns titlecase equivalent of ch.

static char toUpperCase(char ch):  Returns uppercase equivalent of ch.


Character defines the forDigit( ) and digit( ) methods, shown here:

      static char forDigit(int num, int radix)
      static int digit(char digit, int radix)

forDigit( ) returns the digit character associated with the value of num. The radix of the conversion is specified by radix. digit( ) returns the integer value associated with the specified character (which is presumably a digit) according to the specified radix. Another method defined by Character is compareTo( ), which has the following two forms:

      int compareTo(Character c)
      int compareTo(Object obj)

The first form returns 0 if the invoking object and c have the same value. It returns a negative value if the invoking object has a lower value. Otherwise, it returns a positive value. The second form works just like the first if obj is a reference to a Character. Otherwise, a ClassCastException is thrown. These methods were added by Java 2.

Java 2, version 1.4 adds a method called getDirectionality( ) which can be used to determine the direction of a character. Several new constants have been added which describe directionality. Most programs will not need to use character directionality. Character also defines the equals( ) and hashCode( ) methods.

Two other character-related classes are Character.Subset, used to describe a subset of Unicode, and Character.UnicodeBlock, which contains Unicode character blocks.


Boolean

Boolean is a very thin wrapper around boolean values, which is useful mostly when you want to pass a boolean variable by reference. It contains the constants TRUE and FALSE, which define true and false Boolean objects. Boolean also defines the TYPE field, which is the Class object for boolean. Boolean defines these constructors:

      Boolean(boolean boolValue)
      Boolean(String boolString)

In the first version, boolValue must be either true or false. In the second version, if boolString contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will be false.


The Methods Defined by Boolean

boolean booleanValue( ):  Returns boolean equivalent.

boolean equals(Object boolObj):  Returns true if the invoking object is equivalent to boolObj. Otherwise, it returns false.

static boolean getBoolean(String propertyName):  Returns true if the system property specified by propertyName is true. Otherwise, it returns false.

int hashCode( ):  Returns the hash code for the invoking object.

String toString( ):  Returns the string equivalent of the invoking object.

static String toString(boolean boolVal):  Returns the string equivalent of boolVal.
(Added by Java 2, version 1.4)

static Boolean valueOf(boolean boolVal):  Returns the Boolean equivalent of boolVal.
(Added by Java 2, version 1.4)

static Boolean valueOf(String boolString):  Returns true if boolString contains the string “true”
(in uppercase or lowercase). Otherwise, it returns false.

Simple Type Wrappers - Java Tutorials ( Page - 1 of 2 )

As we mentioned in Part I of this book, Java uses simple types, such as int and char, for performance reasons. These data types are not part of the object hierarchy. They are passed by value to methods and cannot be directly passed by reference. Also, there is no way for two methods to refer to the same instance of an int. At times, you will need to create an object representation for one of these simple types. For example, there are enumeration classes discussed in Chapter 15 that deal only with objects; to store a simple type in one of these classes, you need to wrap the simple type in a class. To address this need, Java provides classes that correspond to each of the simple types. In essence, these classes encapsulate, or wrap, the simple types within a class. Thus, they are commonly referred to as type wrappers.


Number

The abstract class Number defines a superclass that is implemented by the classes that wrap the numeric types byte, short, int, long, float, and double. Number has abstract methods that return the value of the object in each of the different number formats. That is, doubleValue( ) returns the value as a double, floatValue( ) returns the value as a float, and so on. These methods are shown here:

      byte byteValue( )
      double doubleValue( )
      float floatValue( )
      int intValue( )
      long longValue( )
      short shortValue( )

The values returned by these methods can be rounded.

Number has six concrete subclasses that hold explicit values of each numeric type:
Double, Float, Byte, Short, Integer, and Long.


Double and Float

Double and Float are wrappers for floating-point values of type double and float, respectively. The constructors for Float are shown here:

      Float(double num)
      Float(float num)
      Float(String str) throws NumberFormatException

As you can see, Float objects can be constructed with values of type float or double. They can also be constructed from the string representation of a floating-point number. The constructors for Double are shown here:

      Double(double num)
      Double(String str) throws NumberFormatException

Double objects can be constructed with a double value or a string containing a floating-point value.

The methods defined by Float are shown in Table 14-1. The methods defined by Double are shown in Table 14-2. Both Float and Double define the following constants:

MAX_VALUE                          Maximum positive value
MIN_VALUE                            Minimum positive value
NaN                                           Not a number
POSITIVE_INFINITY              Positive infinity
NEGATIVE_INFINITY            Negative infinity
TYPE                                         The Class object for float or double


The Methods Defined by Float

byte byteValue( ):   Returns the value of the invoking object as a byte.

static int compare(float num1, float num2):  Compares the values of num1 and num2. Returns 0 if the values are equal. Returns a negative value if num1 is less than num2. Returns a positive value if num1 is greater than num2. (Added by Java 2, version 1.4)

int compareTo(Float f):   Compares the numerical value of the invoking object with that of  f. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value. (Added by Java 2)

int compareTo(Object obj):   Operates identically to compareTo(Float) if obj is of class Float. Otherwise, throws a ClassCastException. (Added by Java 2)

double doubleValue( ):   Returns the value of the invoking object as a double.

boolean equals(Object FloatObj):   Returns true if the invoking Float object is equivalent to FloatObj. Otherwise, it returns false.

static int floatToIntBits(float num):    Returns the IEEE-compatible, single-precision bit pattern that corresponds to the num.

float floatValue( ):   Returns the value of the invoking object as a float.

int hashCode( ):   Returns the hash code for the invoking object.

static float intBitsToFloat(int num):  Returns float equivalent of the IEEE-compatible, single-precision bit pattern specified by num.

int intValue( ):   Returns the value of the invoking object as an int.

boolean isInfinite( ):   Returns true if the invoking object contains an infinite value. Otherwise, it returns false.

static boolean isInfinite(float num):  Returns true if num specifies an infinite value. Otherwise, it returns false.

boolean isNaN( ):   Returns true if the invoking object contains a value that is not a number. Otherwise, it returns false.

static boolean isNaN(float num):   Returns true if num specifies a value that is not a number. Otherwise, it returns false.

long longValue( ):   Returns the value of the invoking object as a long.

static float parseFloat(String str) throws NumberFormatException:  Returns the float equivalent of the number contained in the string specified by str using radix 10. (Added by Java 2)

short shortValue( ):   Returns the value of the invoking object as a short.

String toString( ):   Returns the string equivalent of the invoking object.

static String toString(float num):   Returns the string equivalent of the value specified by num.

static Float valueOf(String str) throws NumberFormatException:  Returns the Float object that contains the value specified by the string in str.


The Methods Defined by Double

byte byteValue( ):   Returns the value of the invoking object as a byte.

static int compare(double num1, double num2):   Compares the values of num1 and num2. Returns 0 if the values are equal. Returns a negative value if num1 is less than num2. Returns a positive value if num1 is greater than num2. (Added by Java 2, version 1.4)

int compareTo(Double d):  Compares the numerical value of the invoking object with that of d. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value. (Added by Java 2)

int compareTo(Object obj):   Operates identically to compareTo(Double) if obj is of class Double. Otherwise, throws a ClassCastException. (Added by Java 2)

static long doubleToLongBits (double num):  Returns the IEEE-compatible, double-precision bit pattern that  corresponds to the num.

double doubleValue( ):  Returns the value of the invoking object as a double.

boolean equals(Object DoubleObj):   Returns true if the invoking Double object is equivalent to DoubleObj. Otherwise, it returns false.

float floatValue( ):   Returns the value of the invoking object as a float.

int hashcode( ):   Returns the hash code for the invoking object.

int intValue( ):   Returns the value of the invoking object as an int.

boolean isInfinite( ):   Returns true if the invoking object contains an infinite value. Otherwise, it returns false.

static boolean isInfinite(double num):   Returns true if num specifies an infinite value. Otherwise, it returns false.

boolean isNaN( ):  Returns true if the invoking object contains a value that is not a number. Otherwise, it returns false.

static boolean isNaN(double num):   Returns true if num specifies a value that is not a number. Otherwise, it returns false.

static double longBitsToDouble (long num):   Returns double equivalent of the IEEE-compatible, double-precision bit pattern specified by num.

long longValue( ):   Returns the value of the invoking object as a long.

static double parseDouble(String str) throws NumberFormatException:  Returns the double equivalent of the number contained in the string specified by str using radix 10. (Added by Java 2)

short shortValue( ):  Returns the value of the invoking object as a short.

String toString( ):   Returns the string equivalent of the invoking object.

static String toString(double num):   Returns the string equivalent of the value specified by num.

static Double valueOf(String str) throws NumberFormatException:  Returns a Double object that contains the value specified by the string in str.


The following example creates two Double objects—one by using a double value and the other by passing a string that can be parsed as a double:

  class DoubleDemo {
    public static void main(String args[]) {
      Double d1 = new Double(3.14159);
      Double d2 = new Double("314159E-5");

      System.out.println(d1 + " = " + d2 + " -> " + d1.equals(d2));
    }
  }

As you can see from the following output, both constructors created identical Double
instances, as shown by the equals( ) method returning true:

  3.14159 = 3.14159 –> true


Understanding isInfinite( ) and isNaN( )

Float and Double provide the methods isInfinite( ) and isNaN( ), which help when manipulating two special double and float values. These methods test for two unique values defined by the IEEE floating-point specification: infinity and NaN (not a number). isInfinite( ) returns true if the value being tested is infinitely large or small in magnitude. isNaN( ) returns true if the value being tested is not a number.

The following example creates two Double objects; one is infinite, and the other is not a number:

  // Demonstrate isInfinite() and isNaN()
  class InfNaN {
    public static void main(String args[]) {
      Double d1 = new Double(1/0.);
      Double d2 = new Double(0/0.);

      System.out.println(d1 + ": " + d1.isInfinite() + ", " 
                         + d1.isNaN());
      System.out.println(d2 + ": " + d2.isInfinite() + ", " 
                         + d2.isNaN());
    }
  }

This program generates the following output:

  Infinity: true, false
  NaN: false, true


Byte, Short, Integer, and Long

The Byte, Short, Integer, and Long classes are wrappers for byte, short, int, and long integer types, respectively. Their constructors are shown here:

      Byte(byte num)
      Byte(String str) throws NumberFormatException

      Short(short num)
      Short(String str) throws NumberFormatException

      Integer(int num)
      Integer(String str) throws NumberFormatException

      Long(long num)
      Long(String str) throws NumberFormatException

As you can see, these objects can be constructed from numeric values or from strings that contain valid whole number values.

The methods defined by these classes are shown in Tables 14-3 through 14-6. As you can see, they define methods for parsing integers from strings and converting strings back into integers. Variants of these methods allow you to specify the radix, or numeric base, for conversion. Common radixes are 2 for binary, 8 for octal, 10 for decimal, and 16 for hexadecimal.

The following constants are defined:

MIN_VALUE               Minimum value
MAX_VALUE             Maximum value
TYPE                           The Class object for byte, short, int, or long


The Methods Defined by Byte

byte byteValue( ):   Returns the value of the invoking object as a byte.

int compareTo(Byte b):   Compares the numerical value of the invoking object with that of b. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value.(Added by Java 2)

int compareTo(Object obj):   Operates identically to compareTo(Byte) if obj is of class Byte. Otherwise, throws a ClassCastException. (Added by Java 2)

static Byte decode(String str) throws NumberFormatException:  Returns a Byte object that contains the value specified by the string in str.

double doubleValue( ):  Returns the value of the invoking object as a double.

boolean equals(Object ByteObj):   Returns true if the invoking Byte object is equivalent to ByteObj. Otherwise, it returns false.

float floatValue( ):  Returns the value of the invoking object as a float.

int hashCode( ):  Returns the hash code for the invoking object.

int intValue( ):   Returns the value of the invoking object as an int.

long longValue( ):  Returns the value of the invoking object as a long.

static byte parseByte(String str) throws NumberFormatException:   Returns the byte equivalent of the number contained in the string specified by str using radix 10.

static byte parseByte (String str, int radix) throws NumberFormatException: Returns the byte equivalent of the number contained in the string specified by str using the specified radix.
    

short shortValue( ):   Returns the value of the invoking object as a short.

String toString( ):   Returns a string that contains the decimal equivalent of the invoking object.

static String toString(byte num):   Returns a string that contains the decimal equivalent of num.

static Byte valueOf(String str) throws NumberFormatException:  Returns a Byte object that contains the value specified by the string in str.

static Byte valueOf (String str, int radix) throws NumberFormatException:  Returns a Byte object that contains the value specified by the string in str using the specified radix.



The Methods Defined by Short

byte byteValue( ):   Returns the value of the invoking object as a byte.

int compareTo(Short s):  Compares the numerical value of the invoking object with that of s. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value. (Added by Java 2)

int compareTo(Object obj):   Operates identically to compareTo(Short) if obj is of class Short. Otherwise, throws a ClassCastException. (Added by Java 2)

static Short decode(String str) throws NumberFormatException:   Returns a Short object that contains the value specified by the string in str.

double doubleValue( ):   Returns the value of the invoking object as a double.

boolean equals(Object ShortObj):   Returns true if the invoking Integer object is equivalent to ShortObj. Otherwise, it returns false.

float floatValue( ):   Returns the value of the invoking object as a float.

int hashCode( ):   Returns the hash code for the invoking object.

int intValue( ):   Returns the value of the invoking object as an int.

long longValue( ):   Returns the value of the invoking object as a long.

static short parseShort(String str) throws NumberFormatException:  Returns the short equivalent of the number contained in the string specified by str using radix 10.

static short parseShort (String str, int radix) throws NumberFormatException: Returns the short equivalent of the number contained in the string specified by str using the specified radix.


short shortValue( ):  Returns the value of the invoking object as a short.

String toString( ):   Returns a string that contains the decimal equivalent of the invoking object.

static String toString(short num):   Returns a string that contains the decimal equivalent of num.

static Short valueOf(String str) throws NumberFormatException:  Returns a Short object that contains the value specified by the string in str using radix 10.

static Short valueOf (String str, int radix) throws NumberFormatException:  Returns a Short object that contains the value specified by the string in str using the specified radix.

String Methods Added by Java 2, Version 1.4 & StringBuffer - Java Tutorials

String Methods Added by Java 2, Version 1.4

Java 2, version 1.4 adds several methods to the String class. These are summarized in the following table.


boolean contentEquals(StringBuffer str):   Returns true if the invoking string contains the same string as str. Otherwise, returns false.

CharSequence, subSequence (int startIndex, int stopIndex): Returns a substring of the invoking string, beginning at startIndex and stopping at stopIndex. This method is required by the CharSequence interface, which is now implemented by String.

boolean matches(string regExp):  Returns true if the invoking string matches the regular expression passed in regExp. Otherwise, returns false.

String  replaceFirst(String regExp, String newStr):   Returns a string in which the first substring that matches the regular expression specified by regExp is replaced by newStr.

String replaceAll(String regExp, String newStr):   Returns a string in which all substrings that match the regular expression specified by regExp are replaced by newStr.

String[ ] split(String regExp):   Decomposes the invoking string into parts and returns an array that contains the result. Each part is delimited by the regular expression passed in regExp.

String[ ] split(String regExp, int max):   Decomposes the invoking string into parts and returns an array that contains the result. Each part is delimited by the regular expression passed in regExp. The number of pieces is specified by max. If max is negative, then the invoking string is fully decomposed. Otherwise, if max contains a non-zero value, the last entry in the returned array contains the remainder of the invoking string. If max is zero, the invoking string is fully decomposed.

Notice that several of these methods work with regular expressions. Support for regular expression processing was added by Java 2, version 1.4 and is described in Chapter 24.




StringBuffer

StringBuffer is a peer class of String that provides much of the functionality of strings. As you know, String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. Java uses both classes heavily, but many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded + operator.


StringBuffer Constructors

StringBuffer defines these three constructors:

      StringBuffer( )
      StringBuffer(int size)
      StringBuffer(String str)

The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.


length( ) and capacity( )

The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms:

      int length( )
      int capacity( )

Here is an example:

  // StringBuffer length vs. capacity.
  class StringBufferDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("Hello");

      System.out.println("buffer = " + sb);
      System.out.println("length = " + sb.length());
      System.out.println("capacity = " + sb.capacity());
    }
  }

Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations:

  buffer = Hello
  length = 5
  capacity = 21

Since sb is initialized with the string “Hello” when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.


ensureCapacity( )

If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity ( ) has this general form:

      void ensureCapacity(int capacity)

      Here, capacity specifies the size of the buffer.


setLength( )

To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is shown here:

      void setLength(int len)

Here, len specifies the length of the buffer. This value must be nonnegative. When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost. The setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer.


charAt( ) and setCharAt( )

The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here:

      char charAt(int where)
      void setCharAt(int where, char ch)

For charAt( ), where specifies the index of the character being obtained. For setCharAt( ), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer.

The following example demonstrates charAt( ) and setCharAt( ):

  // Demonstrate charAt() and setCharAt().
  class setCharAtDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("Hello");
      System.out.println("buffer before = " + sb);
      System.out.println("charAt(1) before = " + sb.charAt(1));
        sb.setCharAt(1, 'i');
        sb.setLength(2);
        System.out.println("buffer after = " + sb);
        System.out.println("charAt(1) after = " + sb.charAt(1));
    }
  }

Here is the output generated by this program:

  buffer before = Hello
  charAt(1) before = e
  buffer after = Hi
  charAt(1) after = i


getChars( )

To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form:

      void getChars(int sourceStart, int sourceEnd, char target[ ],
                              int targetStart)

Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.


append( )

The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types and for Object. Here are a few of its forms:

      StringBuffer append(String str)
      StringBuffer append(int num)
      StringBuffer append(Object obj)

String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together, as shown in the following example:

  // Demonstrate append().
  class appendDemo {
    public static void main(String args[]) {
      String s;
      int a = 42;
      StringBuffer sb = new StringBuffer(40);

      s = sb.append("a = ").append(a).append("!").toString();
      System.out.println(s);
    }
  }

The output of this example is shown here:

  a = 42!

The append( ) method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokes append( ) on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString( ) to turn the modifiable StringBuffer back into a constant String. All of this may seem unreasonably complicated. Why not just have one string class and have it behave more or less like StringBuffer? The answer is performance. There are many optimizations that the Java run time can make knowing that String objects are immutable. Thankfully, Java hides most of the complexity of conversion between Strings and StringBuffers. Actually, many programmers will never feel the need to use StringBuffer directly and will be able to express most operations in terms of the + operator on String variables.


insert( )

The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is the inserted into the invoking StringBuffer object. These are a few of its forms:

      StringBuffer insert(int index, String str)
      StringBuffer insert(int index, char ch)
      StringBuffer insert(int index, Object obj)

Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object. The following sample program inserts “like” between “I” and “Java”:

  // Demonstrate insert().
  class insertDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("I Java!");

      sb.insert(2, "like ");
      System.out.println(sb);
    }
  }

The output of this example is shown here:

  I like Java!


reverse( )

You can reverse the characters within a StringBuffer object using reverse( ), shown here:

      StringBuffer reverse( )

This method returns the reversed object on which it was called. The following program demonstrates reverse( ):

  // Using reverse() to reverse a StringBuffer.
  class ReverseDemo {
    public static void main(String args[]) {
      StringBuffer s = new StringBuffer("abcdef");

      System.out.println(s);
      s.reverse();
      System.out.println(s);
    }
  }

Here is the output produced by the program:

  abcdef
  fedcba


delete( ) and deleteCharAt( )

Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and deleteCharAt( ). These methods are shown here:

      StringBuffer delete(int startIndex, int endIndex)
      StringBuffer deleteCharAt(int loc)

The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex–1. The resulting StringBuffer object is returned.

The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.

Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:

  // Demonstrate delete() and deleteCharAt()
  class deleteDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("This is a test.");

      sb.delete(4, 7);
      System.out.println("After delete: " + sb);

      sb.deleteCharAt(0);
      System.out.println("After deleteCharAt: " + sb);
    }
  } 

The following output is produced:

  After delete: This a test.
  After deleteCharAt: his a test.


replace( )

Another method added to StringBuffer by Java 2 is replace( ). It replaces one set of characters with another set inside a StringBuffer object. Its signature is shown here:

      StringBuffer replace(int startIndex, int endIndex, String str)

The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.

The following program demonstrates replace( ):

  // Demonstrate replace()
  class replaceDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("This is a test.");

      sb.replace(5, 7, "was");
      System.out.println("After replace: " + sb);
    }
  }

Here is the output:

  After replace: This was a test.


substring( )

Java 2 also added the substring( ) method, which returns a portion of a StringBuffer. It has the following two forms:

      String substring(int startIndex)
      String substring(int startIndex, int endIndex)

The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at startIndex and runs through endIndex–1. These methods work just like those defined for String that were described earlier.


StringBuffer Methods Added by Java 2, Version 1.4

Java 2, version 1.4 added several new methods to StringBuffer. They are summarized in the following table.


CharSequence subSequence(int startIndex,  int stopIndex): Returns a substring of the invoking string, beginning at startIndex and stopping at stopIndex. This method is required by the CharSequence interface, which is now implemented by StringBuffer.

int indexOf(String str):  Searches the invoking StringBuffer for the first occurrence of str. Returns the index of the match, or –1 if no match is found.

int indexOf(String str, int startIndex):  Searches the invoking StringBuffer for the first occurrence of str, beginning at startIndex. Returns the index of the match, or –1 if no match is found.

int lastIndexOf(String str):   Searches the invoking StringBuffer for the last occurrence of str. Returns the index of the match, or –1 if no match is found.

int lastIndexOf(String str, int startIndex):   Searches the invoking StringBuffer for the last occurrence of str, beginning at startIndex. Returns the index of the match, or –1 if no match is found.


Aside from subSequence( ), which implements a method required by the CharSequence interface, the other methods allow a StringBuffer to be searched for an occurrence of a String. The following program demonstrates indexOf( ) and lastIndexOf( ).

  class IndexOfDemo {
    public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("one two one");
      int i;

      i = sb.indexOf("one");
      System.out.println("First index: " + i);

      i = sb.lastIndexOf("one");
      System.out.println("Last index: " + i);
    }
  }

The output is shown here.

  First index: 0
  Last index: 8