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.

No comments:

Post a Comment