4. Wrapper Classes

Lecture




  • Numeric Classes
  • Class boolean
  • Character Class
  • Class biglnteger
  • Class BigDecimal
  • Class Class

Java is a fully object oriented language. This means that everything in Java is represented by objects.

Eight primitive types violate this rule. They are left in Java because of the many years of habit of numbers and symbols. And it is easier and faster to perform arithmetic operations with ordinary numbers, and not with class objects.

But for these types in the Java language, there are corresponding classes — wrapper classes of primitive types. Of course, they are not intended for calculations, but for actions typical for working with classes — creating objects, transforming objects, obtaining the numerical values ​​of objects in different forms, and passing objects into methods by reference.

In fig. 4.1 shows one of the branches of the Java class hierarchy. For each primitive type there is a corresponding class. Numeric classes have a common ancestor - the abstract class Number , which describes six methods that return a numeric value contained in the class, reduced to the corresponding primitive type: bytevalue (), doubievalue () , floatValue (), intValue (), longValue (), shortValue () . These methods are overridden in each of the six numeric wrapper classes.

  4. Wrapper Classes

Fig. 4.1. Classes of primitive types

In addition to the equals method of comparing objects, redefined from the object class, all classes described in this chapter, except Boolean and class , have a compareTo () method that compares the numeric value contained in this object with the numeric value of the object, the argument of the compareTo () method. As a result of the method operation, an integer value is obtained:

  • 0 if the values ​​are equal;
  • a negative number (-1) if the numeric value in this object is less than in the object argument;
  • a positive number (+1) if the numeric value in this object is greater than the numeric value contained in the argument.

What is useful in wrapper classes?

Numeric Classes

In each of the six numeric wrapper classes, there are static methods for converting character strings of the string type that represent the number to the appropriate primitive type: Byte.parseByte (), Double.parseDouble (), Float.parseFloat (), Integer.parselnt (), Long. parseLong (), Short.parseShort () . The source string of string type, as always in static methods, is given as the argument of the method. These methods are useful when entering data into input fields, processing command line parameters, that is, everywhere where numbers are represented as strings of digits with plus or minus signs and a decimal point.

Each of these classes has static constants MAX_VALUE and MIN_VALUE , showing the range of numeric values ​​of the corresponding primitive types. In the Double and Float classes, there are also the constants POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN , which were discussed in Chapter 1, and the logical verification methods isNan () , isInfinite () .

If you know the binary representation of real numbers well, you can use the static floatTointBits () and doubieToLongBits () methods that convert real value to integer. A real number is given as a method argument. Then you can change the individual bits with bitwise operations and convert the changed integer back to real value using the intsitsToFioat () and longBitsToDouble () methods.

By using the static toBinaryString (), toHexString () and toOctalString () classes of the integer and Long classes, you can convert integer values ​​of types int and long , specified as an argument of the method, to a character string showing the binary, hexadecimal or octal number representation.

Listing 4.1 shows the use of these methods, and Fig. 4.2 shows the output of the results.

  4. Wrapper Classes

Fig. 4.2. Methods of numerical classes;

Listing 4.1. Numeric class methods

class NumberTest {

public static void main (String [] args) {

int i = 0;

short sh = 0;

double d = 0;

Integer kl = new Integer (55);

Integer k2 = new Integer (100);

Double dl = new Double (3.14);

try {

i = Integer.parselnt (args [0]);

sh = Short.parseShort (args [0]);

d = Double.parseDouble (args [1]);

dl = new Double (args [1]);

kl = new Integer (args [0]);

} catch (Exception e) {}

double x = 1.0 / 0.0;

System.out.println ("i =" + i);

System.outjprintln ("sh -" + sh);

System.out.println ("d. =" + D);

System.out.println ("kl.intValue () =" + kl.intValue ());

System.out.println ("dl.intValue () '="' + dl.intValuei));

System.out.println ("kl> k2?" + Kl.compareTo (k2));

System.out.println ("x =" + x);

System.out.println ("x isNaN?" + Double.isNaN (x));

System.out.println ("x islnfinite?" + Double.islnfinite (x));

System.out.println ("x == Infinity?" +

(x == Double.POSITIVE_INFINITY));

System.out.println ("d =" + Double.doubleToLongBits (d));

System.out.println ("i =" + Integer.toBinaryString (i));

System.out.println ("i =" + Integer.toHexString (i));

System.out.println ("i =" + Integer.toOctalString (i));

}

}

The parseint () methods and class constructors require exception handling, so a try {} catch () {} block is inserted in Listing 4.1. Exception handling is covered in Chapter 16.

Class boolean

This is a very small class designed primarily to pass logical values ​​to methods by reference.

The Boolean constructor (String s) creates an object that contains the value true , if the string s is equal to " true " in any combination of letter registers, and false for any other string.

Boolean booieanvalue () returns a boolean value stored in an object.

Character Class

This class contains static constants and methods for working with individual characters.

Static method

digit (char ch, in radix)

translates the numeral ch of the number system with the base radix into its numeric value of the int type.

Static method

forDigit (int digit, int radix)

inversely converts the integer digit to the corresponding digit (type char ) in the radix base system.

The base of the number system must be in the range from Character.MIN_RADIX to Character.MAX_RADIX.

The tostring () method translates a character contained in a class into a string with the same character.

Static methods toLowerCase () , touppercase (), toTitieCase () return the character contained in the class in the specified register. The last of these methods is designed to correctly translate in four upper unicode codes that are not expressed in a single character.

Many static logic methods test various characteristics of the character passed as an argument to a method:

  • isDef ined () - ascertains whether a character is defined in Unicode;
  • isDigit () - checks if a character is a Unicode digit;
  • isidentifierignorable () - ascertains whether the character can not be used in identifiers;
  • isisocontroi () - determines whether a character is a control character;
  • isJavaidentifierPart () - determines if a character can be used in identifiers;
  • isjavaidentifierstart () - determines whether a character can start an identifier;
  • isLetter () - checks if a character is a Java letter;
  • IsLetterOrDigit () - Checks whether a character is a letter or a digit Unicode;
  • isLowerCase () - determines whether a lowercase character is written;
  • isSpaceChar () - finds out if a character is a space in the Unicode sense;
  • isTitieCase () - checks if a character is a title;
  • isUnicodeldentifierPart () - determines if a character can be used in Unicode names;
  • isunicodeidentifierstart () - checks if a character is a Unicode letter;
  • isUpperCase () - checks if the character is in upper case;
  • isWhitespace () - finds out if a character is whitespace.

The exact ranges of control characters, the concepts of upper and lower case, title character, whitespace characters, it is best to look at the Java API documentation.

Listing 4.2 demonstrates the use of these methods, and in fig. 4.3 shows the output of this program.

Listing 4.2. Character class methods in the CharacterTest program

class CharacterTest {

public static void main (String [] args) {

char ch = '9';

Character cl = new Character (ch);

System.out.println ("ch =" + ch);

System.out.println ("cl.charValue () =" +

c1.charValue ());

System.out.println ("number of 'A' =" +

Character.digit ('A', 16}};

System.out.println ("digit for 12 =" +

Character.forDigit (12, 16}};

System.out.printlnC'cl = "+ cl.toString ());

System.out.println ("ch isDefined?" +

Character.isDefined (ch));

System.out.println ("ch isDigit?" +

Character.isDigit (ch));

System.out.println ("ch isldentifierlgnorable?" +

Character.isldentifierlgnorable (ch));

System.out.println ("ch isISOControl?" +

Character.isISOControl (ch));

System.out.println ("ch isJavaldentifierPart?" +

Character.isJavaldentifierPart (ch));

System.out.println ("ch isJavaldentifierStart?" +

Character.isJavaldentifierStart (ch));

System.out.println ("ch isLetter?" +

Character.isLetter (ch));

System.out.println ("ch isLetterOrDigit?" +

Character.isLetterOrDigit (ch));

System.out.println ("ch isLowerCase?" +

Character.isLowerCase (ch));

System.out.println ("ch isSpaceChar?" +

Character.isSpaceChar (ch));

System.out.println ("ch isTitleCase?" +

Character.isTitleCase (ch));

System.out.println ("ch isUnicodeldentifierPart?" +

Character.isUnicodel IdentifierPart (ch));

System.out.println ("ch isUnicodeldentifierStart?" +

Character.isUnicodel IdentifierStart (ch));

System.out.println ("ch isUpperCase?" +

Character.isUpperCase (ch));

System.out.println ("ch isWhitespace?" +

Character.isWhitespace (ch)); }}

In the Character class, the Subset and UnicodeBlock classes are nested , and the Unicode class and another class, inputSubset , are extensions of the Subset class, as can be seen in Figure. 4.1. Objects of this class contain Unicode subsets.

  4. Wrapper Classes

Fig. 4.3. Character class methods in the CharacterTest program

Together with the wrapper classes, it is convenient to consider two classes for working with arbitrarily large numbers.

Class biglnteger

All primitive integer types have a limited range of values. There is no overflow in integer Java arithmetic, integers are given in modulus equal to the range of values.

In order to make it possible to perform integer calculations with any digit capacity, the Biglnteger class, stored in the java.math package, was introduced into the Java API. This class extends the Number class, therefore, the methods doubleValue (), floatValue (), intValue (), longValue () are redefined in it. The methods byteVaiue () and shortvalue () are not overridden, but are directly inherited from the Number class.

Actions with objects of the Biglnteger class do not lead to overflow, nor to modifying . If the result of the operation is large, then the number of digits simply increases. Numbers are stored in binary form with additional code.

Before performing the operation, the numbers are aligned in length by the propagation of the sign bit.

Six class constructors create a BigDecimai class object from a string of characters (number and digit signs) or from an array of bytes.

Two constants - ZERO and ONE - model zero and one in operations with objects of the Biglnteger class.

The toByteArray () method converts an object into an array of bytes.

Most methods of the Biglnteger class model integer operations and functions, returning an object of the Biglnteger class:

  • abs () - returns an object containing the absolute value of the number stored in the given this object;
  • add (x) is the operation this + x ;
  • and (x) is the operation of this & x ;
  • andNot (x) is the operation this & (~ x) ;
  • divide (x) - this / x operation;
  • divideAndRemainder (x) - returns an array of two objects of the class Biglnteger , containing the quotient and the remainder of this divided by x ;
  • gcd (x) is the largest common divisor of the absolute, the values ​​of the this object and the argument x ;
  • max (x) is the largest of the values ​​of the this object and the argument x ; min (x) is the smallest of the values ​​of the this object and the argument x ; mod (x) is the remainder of dividing the this object by the argument of the method x ;
  • modinverse (x) is the remainder of dividing the inverse of this object by the argument x ;
  • modPow (n, m) is the remainder of dividing this object raised to the power n by m ;
  • multiply (x) —the operation is this * x ;
  • negate () - change the sign of the number stored in the object;
  • not () is the ~ this operation;
  • or (x) - operation this | x ;
  • pow (n) is the operation of raising the number stored in the object to the power n ;
  • remainder (x) —operation this% x ;
  • shiftLeft (n) is the operation of this “n ;
  • shiftRight (n) is the operation of this ”n;
  • signum () is the function sign (x) ;
  • subtract (x) is the operation this - x ;
  • xor (x) is the operation this ^ x .

Listing 4.3 shows examples of using these methods, and fig. 4.4 shows the results of executing this listing.

  4. Wrapper Classes

Fig. 4.4. Methods of the Biglnteger class in the BiglntegerTest program

Listing 4.3. Methods of the Biglnteger class in the BiglntegerTest program

import Java.math.Biglnteger;

class BiglntegerTest {

public static void main (String [] args) {

Biglnteger a = new Biglnteger ("99999999999999999");

Biglnteger b = new Biglnteger ("88888888888888888888");

System.out.println ("bits in a =" + a.bitLength ());

System.out.println ("bits in b =" + b.bitLengthO);

System.out.println ("a + b =" + a.add (b));

System.out.println ("a & b =" + a.and (b));

System.out.println ("a & ~ b =" + a.andNot (b));

System.out.println ("a / b =" + a.divide (b));

Biglnteger [] r = a.divideAndRemainder (b);

System.out.println ("a / b: q =" + r [0] + ", r =" + r [l]);

System.out.println ("gcd (a, b) =" + a.gcd (b));

System.out.println ("max (a, b) =" + a.max (b));

System.out.printin ("min (a, b) =" + a.min (b));

System.out.println ("a mod b =" + a.mod (b));

System.out.println ("I / a mod b =" + a.modlnverse (b));

System.out.println ("alp mod b =" + a.modPow (a, b));

System.out.println ("a * b =" + a.multiply (b));

System.out.println ("- a =" + a.negate ());

System, out. println ("~ a =" + a.not ());

System.out.println ("a | b =" + a.or (b));

System.out.println ("a l 3 =" + a.pow (3));

System.out.println ("a% b =" + a.remainder (b));

System.out.println ("a" 3 = "+ a.shiftLeft (3)};

System.out.println ("a» 3 = "+ a.shiftRight (3));

System.out.println ("sign (a) =" + a.signum ());

System.out.println ("a - b =" + a.subtract (b));

System.out.println ("a l b =" + a.xor (b));

}

}

Notice that in the program in Listing 4.3 you need to import the Java.math package.

Big Decimal class

The BigDecimal class is located in the java.math package.

Each object of this class stores two integer values: the mantissa of a real number as an object of the class Biglnteger , and a non-negative decimal order of a number of type int .

For example, for the number 76.34862, the mantissa 7,634,862 will be stored in an object of the class Biglnteger , and order 5 as an integer of type int . Thus, the mantissa can contain any number of digits, and the order is limited by the value of the constant integer.MAX_VALUE . The result of an operation on objects of the BigDecimal class is rounded according to one of eight rules defined by the following static integer constants:

  • ROUND_CEILING - round to a larger integer;
  • ROUND_DOWN - rounding to zero, to a lower integer value;
  • ROUND_FLOOR - rounding to a smaller integer;
  • ROUND_HALF_DOWN - rounding to the nearest integer, average value is rounded to a smaller integer;
  • ROUND_HALF_EVEN - rounding to the nearest integer, the average value is rounded to an even number;
  • ROOND_HALF_UP - rounding to the nearest integer, average value is rounded to a larger integer;
  • ROUND_UNNECESSARY - it is assumed that the result will be integer, and rounding is not required;
  • ROUND_UP - rounding from zero, to a larger integer value.

There are four constructors in the BigDecimal class:

  • BigDecimal (Biglnteger bi) - the object will store a large integer bi, the order is zero;
  • BigDecimal (Biglnteger mantissa, int scale) - set by the mantis mantissa and non-negative scale object; if the scale order is negative, an exception is thrown;
  • BigDecimal (double d) - the object will contain a real number of double precision d ; if the value of d is infinite or NaN , then an exceptional situation arises;
  • BigDecimal (String val) - the number is specified by the character string val , which must contain a record of the number according to the Java language rules.

When using the third of the listed constructors, an unpleasant feature noted in the documentation arises. Since a real number during binary translation is usually represented by an infinite binary fraction, when creating an object, for example, BigDecimal (0.1) , the mantissa stored in the object will be very large. It is shown in Fig. 4.5. But when creating the same object with the fourth constructor, BigDecimal ("0.1") , the mantissa will simply equal 1.

The Class overrides the methods doubleValue (), floatValue (), intValue (), longValue () .

Most methods of this class model operations with real numbers. They return an object of class BigDecimal . Here, the letter x denotes an object of class BigDecimal , the letter n is an integer value of type int , the letter r is a rounding method, one of the eight constants listed above:

abs () is the absolute value of the this object;

add (x) is the operation this + x ;

divide (x, r) is the operation this / x , rounded off using the r method;

divide (x, n, r) is the operation this / x with a change in the order and rounding by the method r ;

max (x) is the largest of this and x ;

min (x) is the smallest of this and x ;

movePointLeft (n) —shift left by n digits;

movePointRight (n) - right shift by n digits;

multiply (x) - the operation this * x ;

negate () - returns an object with the opposite sign;

scale () - returns the order of numbers;

setscaie (n) - controls the new order n ;

setscaie (n, r) - establishes a new order n and rounds the number, if necessary, according to the method r ;

signumo - the sign of the number stored in the object;

subtract (x) - this operation - x ;

toBiginteger () - rounding the number stored in the object;

unscaiedvalue () —returns the mantissa of a number.

Listing 4.4 shows examples of using these methods, and fig. 4.5 - output results.

  4. Wrapper Classes

Fig. 4.5. Methods of the BigDecimal Class in the BigDecimalTest Program

Listing 4.4. Methods of the BigDecimal Class In the BigDecimalTest Program

import java.math. *;

class BigDecimalTest {

public static void main, (String [] args) {

BigDecimal x = new BigDecimal ("- 12345.67890123456789");

BigDecimal y = new BigDecimal ("345.7896e-4");

BigDecimal z = new BigDecimal (new Biglnteger ("123456789"), 8);

System.out.println ("| x | =" + x.abs ());

System.out.println ("x + y =" + x.add (y));

System.out.println ("x / y =" + x.divide (y, BigDecimal.ROUND__DOWN));

System.out.println ("x / y =" +

x.divide (y, 6, BigDecimal.ROUND_HALF_EVEN));

System.out.println ("max (x, y) =" + x.max (y));

System.out.println ("min (x, y) =" + x.min (y));

System.out.println ("x" 3 = "* x.movePointLeft (3));

System.out.println ("x" 3 = "+ x.mpvePQintRight (3));

System.out.println ("x * y =" + x.multiply (y));

System.out.println ("- x =" + x.negate ());

System.out.println ("scale of x =" + x.scale ());

System.out.println ("increase scale of x to 20 =" + x.setScale (20));

System.out.println ("decrease scale of x to 10 =" +

x.setScale (10, BigDecimal.ROUND_HALF__UP));

System.out.println ("sign (x) =" + x.signum ());

System.out.println ("x - y =" + x.subtract (y)};

System.out.println ("round x =" + x.toBiglnteger ());

System.out.println ("mantissa of x =" + x.unscaledValue ());

System.out.println ("mantissa of 0.1 = \ n =" +

new BigDecimal (0.1) .unscaledValue ()); }}

Let's give one more example. Let's write a simple calculator that performs four arithmetic operations with numbers of any size. It works from the command line. The program is shown in Listing 4.5, and examples of using a calculator are shown in Fig. 4.6.

Listing 4.5. Simplest Calculator

import Java.math. *;

class Calc {

public static void main (String [] args) {

if (args.length <3) {

System.err.println ("Usage: Java Calc operand operator operand");

return;

}

BigDecimal a = new BigDecimal (args [0]);

BigDecimal b = new BigDecimal (args [2]);

switch (args [l] .charAt (0)) {

case '+': System.out.println (a.add (b)); break;

case '-': System.out.println (a.subtract (b)); break;

case '*': System.out.println (a.multiply (b)); break;

case '/': System.out.println (a.divide (b,

BigDecimal.ROUND_HALF_EVEN)); break;

default: System.out.println ("Invalid operator");

}

}

}

Why multiplication symbol - an asterisk - is enclosed in fig. 4.6 in quotes? Unixoids understand this, but for others we will give a brief explanation.

  4. Wrapper Classes

Fig. 4.6. The results of the calculator

This is a feature of the operating system, not a Java language. The string entered from the keyboard is first viewed by the command shell (shell) of the operating system, and the asterisk for it is an instruction to substitute all the names of files from the current directory into this place. The shell will do this, and the Java interpreter will get a long line from it, in which instead of the asterisks there are filenames separated by spaces.

The asterisk in quotes is understood by the shell as a normal character. The command shell removes quotes and passes the Java interpreter what is needed.

Class Class

The Object class, which is at the head of the Java class hierarchy, represents all the objects that operate in the system and is their common wrapper. Any object can be considered an instance of the class Object .

A class named class represents the characteristics of the class of which the object is an instance. Он хранит информацию о том, не является ли объект на самом деле интерфейсом, массивом или примитивным типом, каков суперкласс объекта, каково имя класса, какие в нем конструкторы, поля, методы и вложенные классы.

В классе class нет конструкторов, экземпляр этого класса создается исполняющей системой Java во время загрузки класса и предоставляется методом getciass() класса object , например:

String s = "Это строка";

Class с = s.getClass();

Статический метод forName(string class) возвращает объект класса class для класса, указанного в аргументе, например:

Class cl = Class.forName("Java,lang.String");

Но этот способ создания объекта класса class считается устаревшим (deprecated). В новых версиях JDK для этой цели используется специальная конструкция — к имени класса через точку добавляется слово class :

Class c2 = Java.lang.String.class;

Логические методы isArray(), isIntetface(), isPrimitive() позволяют уточнить, не является ли объект массивом, интерфейсом или примитивным типом.

Если объект ссылочного типа, то можно извлечь сведения о вложенных классах, конструкторах, методах и полях методами getoeciaredciasses() , getdeclaredConstructors(), getDeclaredMethods(), getDeclaredFields() , в виде массива классов, соответствейно, Class, Constructor, Method, Field . Последние три класса расположены в пакете java.lang.reflect и содержат сведения о конструкторах, полях и методах аналогично тому, как класс class хранит сведения о классах.

Methods   getClasses(), getConstructors(), getlnterfaces(), getMethods(), getFieids() возвращают такие же массивы, но не всех, а только открытых членов класса.

Метод getsuperciass() возвращает суперкласс объекта ссылочного типа, getPackage() — пакет, getModifiers() — модификаторы класса В битовой форме. Модификаторы можно затем расшифровать методами класса Modifier из пакета Java.lang.reflect .

Листинг 4.6 показывает применение этих методов, а рис. 4.7 — вывод результатов

Листийс 4.6 tМетоды класса Class в программе ClassTest

import java.lang.reflect.*;

class ClassTest{

public static void main(String[] args)(

Class с = null, c1 = null, c2 = null;

Field[] fld = null;

String s = "Some string";

с = s.getClass();

try {

cl = Class.forName("Java.lang.String"); // Старый стиль

c2 = Java.lang.String.class; // Новый стиль

if (!c1.isPrimitive())

fid = cl.getDeclaredFields(); // Все поля класса String

}catch(Exception e){}

System.out.println("Class c: " + c);

System.out.println("Class cl: " + cl);

System,out.println("Class c2: " + c2);

System.out.printlnt"Superclass c: " + c.getSuperclass());

System.out.println("Package c: " + c.getPackageO);

System.out.printlnf"Modifiers c: " + c.getModifiers());

for(int i = 0; i < fid.length; i++)

System.out.println(fld[i]);

}

}

Методы, возвращающие свойства классов, вызывают исключительные ситуации, требующие обработки. Поэтому в программу введен блок try{} catch() {} . Рассмотрение обработки исключительных ситуаций мы откладываем до главы 16.

  4. Wrapper Classes

Fig. 4.7. Методы класса Class в программе ClassTest


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Object oriented programming

Terms: Object oriented programming