Thursday, December 3, 2009

Java Number Operations


Working With Numbers

Crunching numbers is a central task for many programs. In fact, the desire to automate number operations was the motivation that drove the invention of digital computers decades ago. In this tutorial we will learn how to work with numbers in Java, including arithmetic, conversions, and other numeric operations. Java Number Types

Most computer languages have both integers and floating point numbers. Java has the following primitive number types

Integer Floating Point
byte float
short double
int
long
 
  • Each integer and float type is composed of one or more bytes of memory. (See Java Variables.) For integers, the number of bytes of storage determines how large the number can be (its magnitude). For floating point numbers, the number of bytes of storage also determines the maximum scale of the number; in other words, how many decimal places of accuracy can be represented.

    As you can see, since float and double can only be represented to a certain number of decimal places, many floats and doubles will be slightly inaccurate. When this built-in inaccuracy could affect your calculations, you can instead use BigDecimal to represent a floating point number.

  • Java Arithmetic

    Programming arithmetic in Java is no different from using a graphing calculator—or pencil and paper, for that matter.

    Examples:

 int result = 5 + 5;
result = 5 - 5;
result = 5 * 5; //multiplication
result = 5 / 5;
result = 5 % 5; //modulus division

Order of Precedence

The order of precedence of the arithmetic operators is identical to that of mathematics. As in algebra, the use of parentheses '()' can be used to change the default order of precedence. The following are usage examples for arithmetic-related operators, grouped by their order of precedence.

Highest precedence ++/-- postfix operators and parentheses '()':

 int a = 55;
int c = a++; //c == 55, a == 56
c = a--; //c == 56, a == 55
int d = (49 + 1) * 2 //the parentheses change the precedence

As you can see, the postfix operators return their value, then increment/decrement themselves.

Next highest precedence ++/-- prefix operators:

 int a = 55;
int c = ++a; //c == 56, a == 56
c = --a; //c == 55, a == 55

The prefix operators, on the other hand, increment/decrement themselves first. Then, they return their new value.

Next highest precedence is the (type) cast operator:

 int a = (int)55.55f; //force a float into an int variable
short c = (short)a; //force an int into a short variable

Next highest precedence is the standard multiplicative operators, * / %.

 int a = 2 * 2; //a == 4
int b = 2 / 2; //b == 1
int c = 5 % 2; //c == 1

Next highest precedence is the standard additive operators, + -.

 int a = 2 + 2; //a == 4
int b = 2 - 2; //b == 0

Last in order of precedence, we have the standard assignment operator '=' and the shortcut assignment operators '=op' where op is another operator such as * / % + -, etc. These shortcut operators allow you to apply an operator and assign the result in one step.

Examples:

 int result = 10;
result += 10; //result == 20, the sum of result and 10
result /= 5; //result == 4, the quotient of result divided by 5

Numeric Type Conversions

When you assign a value to a variable of a different type (say, int to short or float to double), one of two things will happen. The value will be implicitly cast (converted) to the new type if it is a widening conversion. If it is a narrowing conversion, a compiler error will be thrown.

When going from an int and long value to a float or double, the value will be implicitly converted. If you want to go from a float or double to an int or long, however, you'll need to use an explicit cast. Be aware that this will truncate the decimal portion of the float or double.

Examples:

 //Widening conversions
int a = 123123123;
float b = a; //ok
long c = a; //ok
 //Narrowing conversions
long a = 123123L
int b = a; //compiler error
int c = (int)a; //ok
 long d = 123123123123L
int e = (int)d; //loss of magnitude

Converting Between Numbers and Java Strings

  • Very commonly, especially in Web applications, numbers need to be converted to Strings, and vice versa. An HTML form only deals with one data type—text. When the text is posted to a Java servlet, the servlet will often convert the text values to numbers for calculations or for persisting to a database.

  • Java String to Number Conversion

    To convert a Java String to a number, you need to parse it using the appropriate primitive "wrapper" class, e.g. java.lang.Integer.

    Example:

 String s = "100";
int i = java.lang.Integer.parseInt(s);

Number to Java String Conversion

There are several ways to convert from a number to a Java String. The first is to concatenate the number with an empty String using the '+' operator. The second is use the appropriate "wrapper" class's toString().

Examples:

 float price = 23.99f;
String priceStr = "" + price;

Number Wrapper Classes

In "Converting Between Numbers and Java Strings" you saw the use of the primitive wrapper classes to parse Java Strings and to convert numbers to Java Strings via toString(). Each primitive data type has a corresponding wrapper class located in the java.lang package.

Treat Primitives as Objects

The wrapper classes are primarily used to store primitive data types in objects so they can be handled by classes that only work with objects. For example, the Java Collections API has many data structure classes such as ArrayList and HashMap that only work with objects—in order to store a primitive number in one of these collections, you must first wrap it.

Example:

 ArrayList list = new ArrayList();
int age1 = 25;
int age2 = 20;
list.add(new Integer(age1)); //wrap age1 in Integer
list.add(new Integer(age2)); //wrap age2 in Integer

Autoboxing

Prior to Java 5.0 Tiger, a developer had to manually convert primitives to wrappers and vice versa. One of the syntactic shortcuts added in Java 5.0 was autoboxing (automatically converting primitives to wrappers) and auto-unboxing (automatically converting wrappers to numbers).

To autobox, simply assign a primitive value to an appropriate wrapper object. To auto-unbox, assign a wrapper object reference to an appropriate primitive variable. The compiler takes care of the plumbing.

 Integer a = 55; //autobox int to Integer
float f = new Float(22.5f); //auto-unbox Float to float
long l = a; //auto-unbox Integer to long
  • Math Class

    No, this section does not refer to Mr. Johnson's ninth grade algebra class but, instead, to java.lang.Math, which provides methods for basic numeric operations beyond simple arithmetic. Powers, rounding, square roots, maximums, and minimums are a few of the operations it handles. We will look at two typical uses of Math.

  • Computing Square Roots

    Since Math.sqrt() is static, you don't have to create an instance of Math in order to call it.

    Example:

 double d = 16.0;
double r = Math.sqrt(d); //r == 4.0

Rounding Numbers

If you have a floating point number that must be rounded "half up," then you can use Math.round(). If you need more complex rounding logic, you should use BigDecimal.

Example:

 int a = Math.round(25.4f); //a is set to 25
int b = Math.round(25.5f); //b is set to 26
In this tutorial, we reviewed the fundamentals of working with numbers in Java. This, of course, is just the beginning. In future tutorials we will examine BigDecimal, BigInteger, and random number generation.

0 comments:

Post a Comment

 

JAVA INTRODUCTION Blak Magik is Designed by productive dreams for smashing magazine Bloggerized by Ipiet © 2008