Section 3.4. Primitive Data Types

   

3.4 Primitive Data Types

Java defines eight primitive data types, each of which reside in one of four main types. These main types are shown in Table 3.3.

Table 3.3. Four Main Primitive Data Types

Data Type

Purpose

Integral

Storing regular numbers

Floating Point

Storing decimal point numbers

Textual

Storing single text characters

Logical

Storing boolean values

These data types are called primitive because they are the only things in Java that are not objects. We will now look at each of them in particular.

3.4.1 Integral Data Types

There are four types of integral data: byte , short , int , and long . These data types are used to store numbers requiring between 8 and 64 bits for storing their values. The default value of an int variable is . Table 3.4 shows the range, length, and example values for each type.

Table 3.4. Integral Data Types

Data Type

Range

Length

Example Values

byte

“128 to 127

8 bits

“36

125

short

“32,768 to 32,767

16 bits

30,005

“42

int

-2,147,483,648 to 2,147,483,648

32 bits

-100

1,904,800,257

long

-9,223,372,036,854, 775,808 to 9,223,372,036,854,775,807

64 bits

-1,493,665,740,948L

119L

One thing you may notice about the long data type is that the numbers in the example are followed with an L . This notation is used when specifying literal values for a number of type long . The compiler can assume that your literal is an int , and not a long , if you do not specifically indicate this using the L as a suffix to your number as shown.

Probably the most commonly used of the integral types is int . There are a number of situations that call for a long , however, such as representing the population of the earth, the national debt, and so forth. There is generally no need to get too picky about which integral data type to use; even if you expect your numeric value to never exceed, say, 100, you're probably just as well off storing an int . A good example is probably human life span: while it might seem clever to represent this value as a byte , it is possible for people to live to be older than 127 years (a very few people already have). RAM space is cheap ”far less expensive than the time required to go back and retool a program insufficiently typed.

One benefit to the Java types is that their ranges do not change from system to system. This is a stark distinction to C and C++ programs, which are subject to overflow problems when porting from one platform to another. That is, specifying an integer in C or C++ program refers to whatever the length of an integer is on the target platform. On a 16-bit processor an integer is (you guessed it) 16 bits, but it can be 32 bits in 32-bit Windows programs on a more recent Intel processor. That can cause problems for data, which would not be truncated, but rather wrapped ”creating potentially disastrous results.

3.4.2 Floating Point Types

Java specifies two floating point data types: float and double . A floating point type is a number stored with a decimal place. There are a couple of things to note about these types. First of all, the highest and lowest possible values cannot be specified because of the decimal place. The accuracy of the number is variable depending on its magnitude, which could be very large or very small depending on where the decimal is placed. The default value for both floating point type variables is 0.00 .

As with a long , you should specify a float by placing an F after the literal value; otherwise , the compiler will treat it as a double . Table 3.5 shows the range, length, and example values for each type.

Table 3.5. Floating Point Types

Data Type

Range

Length

Example Values

float

6 “7 significant decimal digits

32 bits

3.8E6F

double

15 significant decimal digits

64 bits

“222

2.0E10

888,777,666,555.444

Note

If you are interested in the use of "e" in numbers, it is engineering notation for an irrational number representing the base of the natural system of logarithms, having an approximate numerical value of 2.7182818284. It was first used in the mid 17th century and has been calculated to 869,894,101 decimal places. So, 4.5E6 is another way of writing 4.5*10 6 .


Floating point numbers in Java follow the IEEE 754 specification. This standard includes positive and negative signed numbers, positive and negative zeros, positive and negative infinities, and a special value referred to as NaN (Not a Number). NaN is used to represent the result of an invalid operation (such as trying to divide by zero) or another non-numeric result. Java's Double and Float wrapper classes have an isNan() method for testing variables.

It is probably most common to choose double when a floating point number is required. This is because a float , like a short , is often not significant enough for many situations.

It is possible to convert between types in Java, which we will see how to do later. For now, it is pertinent to our discussion of data types and their reserved storage space to note certain behavior, which is noted briefly in IntCast.java .

3.4.3 IntCast.java

 /*  File: chp3.IntCast Purpose: Show primitive integral conversion Date: 4 14 02 Author: E Hewitt */ public class IntCast { public static void main (String [] args) { double y = 3.14;         // make a double int x = (int)(y);        // convert to int double z = x;            // assign new double the int's value System.out.println("y: " + y + ", x: " + x + ", z: " + z);     } } 

When compiled and run, this program outputs

 y: 3.14, x: 3, z: 3.0 

The integer, as expected, loses the decimal place. An int cannot hold a floating point, but the number can be used as an int with loss of precision. Other types of conversion are not possible, however, even if it seems they should be allowed. Making the following modification to the above code produces a program that will not compile:

 int x = (int)(y);  long z = 3L; int i = z; 

The compiler will complain that it found a long when it needed an int . That means that Java does not want to compile the program and possibly lose important data for the variable. Recall that z , as a long , is 64 bits, while an int holds 32 bits ”which should be enough room to store the value "3." Even though zeros (empty place holders) are the only thing populating all of the remaining int bits, Java doesn't know that, and throws a compile-time error. Data type conversion will be covered in more detail in later chapters.

There has been some contention in different versions of Java between making floating point variables absolutely precise and increasing performance. On the one hand, it can be very important to have totally precise (reproducible) floating point data. On the other hand, maintaining such precision all the time can result in a severe performance degradation, which is especially costly when typical programs don't require it. For this reason, the strictfp keyword was created to protect the integrity of floating point operations. strictfp can be applied to a class or method by the programmer; declaring a class or a method as strictfp means that all of the instructions carried out inside its body must maintain strict floating point computational processes. For example, a main method would be declared strictfp like this:

 public static strictfp void main(String[] args) { .... 

Such precision is often only necessary for programs in which very careful mathematical precision is important, and is not likely to be a concern.

3.4.4 Textual Type

The textual type char is reserved for single Unicode character values. That is, you can assign a variable of type char the value "a," but not the value "ab." A value requiring more than one character requires creating a String . A char value is assigned with single quote marks, in contrast to a String object, which is assigned with double quote marks. The default value of a char is the Unicode symbol \u0000 .

Note

A String is a primitive type in C and C++, but it is a class in Java.


The char is an unsigned 16-bit type, and as such it is possible to use mathe-matical operators (that is, treat it like an int in some situations). The ASCII character set corresponds to the first 127 values in the Unicode character set. So in Java we can write a simple loop that prints out the entire English alphabet:

3.4.5 alphabet.java

 /*  File: chp3.alphabet.java Purpose: print English alphabet Author: E Hewitt */ public class alphabet { public static void main(String[] args) {     char letter = 'a';     int x, y;     y = 90;     for (x = 64; x < y; x++) {         System.out.print(letter + ",");         letter++; //increment the counter } } } 

alphabet.java prints the letters a “z with each letter followed by a comma.

3.4.6 Unicode in Java

Because Java fully supports the Unicode character set, it is theoretically possible to represent any Unicode value from within a Java program. However, that does not necessarily mean that your platform (or browser) will be able to render it correctly. This is most commonly a consideration when dealing with internationalization issues.

Note

Until ColdFusion MX, ColdFusion did not offer native Unicode support, and unless you were writing international applications that required support for languages such as Korean or Chinese, it may not have become much of an issue for you.


Unicode is referred to as a double-byte character set, because it uses 16 bits to store character data, unlike the 8-bit ASCII with only 128 characters. Unicode is therefore capable of storing 65,535 different values, often expressed as hexadecimals from u\0000 to u\FFFF .

3.4.7 UnicodeDemo.java

 /*    File: chp3.UnicodeDemo.java   Author: E Hewitt   Purpose: demos how to work with Unicode characters        and shows some useful ones  */ public class UnicodeDemo {     public static void main (String[] args){         // Unicode for a space         String space = "\u0020";         StringBuffer sb = new StringBuffer().append("hello").append(space).append("world");         // using the Unicode symbols directly         // in the string         System.out.println(sb.toString());         // result: hello world         // a list of handy Unicode chars         System.out.println("Yen: \u00a5");         System.out.println("Pound: \u00a3");         System.out.println("Cents: \u00a2");         System.out.println("Paragraph: \u00b6");         System.out.println("mu: \u00b5");         System.out.println("1/4th: \u00bc");     } } 

The above program may print out characters correctly or incorrectly, depending on whether your platform supports them. The point is simply to see how to reference the Unicode set under slightly different circumstances.

Note

It is sometimes necessary to escape Unicode characters, as you have no doubt had to do in ColdFusion with the pound sign: <cfoutput><font color = ##336699> . In Java, Unicode characters need to be escaped too.


For more information on Unicode, visit www.unicode.org.

3.4.8 Logical Type

The boolean type has two possible values: true and false , used in evaluation of a logical condition. The default value of a boolean variable is false .

Note

In ColdFusion (and in C++ for that matter), numbers can be used to represent boolean values: 0 can be equivalent to false , and 1 (or other non-zero ) is equivalent to true . The purpose for this is to ensure that Java programmers do not perform an assignation when they meant to check for equivalency.


The following bit of code demonstrates a simple use of the logical type.

3.4.9 booleanTest.java

 /*  File: chp3.booleanTest.java Purpose: demonstrate use of boolean type Author: E Hewitt */ public class booleanTest {   public static void main(String [] args) {   boolean isCurrent = true;   if (isCurrent) { System.out.println("isCurrent is true");       }   else {       System.out.println("isCurrent is false");     }   } } 

This code simply outputs isCurrent is true to the command line. The following code produces an equivalent result: if(isCurrent == true) . Two equal signs are used, as in JavaScript, to check for the same value. In addition to assigning a variable of boolean type literally, boolean variables can also store the results of decisions. For instance, you can write if(numberOf-Employees > 50) .

Note

You cannot use eq , is , gte , or similar expression phrases as you can in ColdFusion. As we will see in a moment, checking for equivalency in Java is somewhat more complicated than it is in ColdFusion because of how objects are stored in memory. We will examine this when we start looking at objects.



   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net