CHAPTER 3 Data Types and Operations On Data



Data Types and Operations On Data

Objective

• To understand what data types are

• To understand the reason for studying data types

• To differentiate between primitive types and reference types

• To know the range and storage requirements for each data type

• To know the criteria for data conversion

• To know the permissible operations that can be performed on data

• To be able to evaluate expressions

Introduction

In any programming language the concept of data type is like what the bolts and nuts are to a piece of machinery. It is almost impossible to write any meaningful program, if you do not understand data types, data values, the amount of memory required for each type of data, and the permissible operations that can be performed on data.

Like anything else, conservation of the use of memory is important. In some former programming languages the idea of conserving memory as far as storing data is concerned was rarely considered. Hence, most addressed only two ways to store numeric values – int, for integers; and float, for floating point values. This gave rise to wasting of memory, especially when small values are to be stored; since the amount of memory set aside for each value, large or small, would be the same.

The first section of this lesson introduces you to a comprehensive study of the fundamental data types in Java, and how they relate to programming. It also focuses on the possible operations that can be performed on each type. The second part of the lesson introduces the reference type. This includes some of the fundamental Java classes, such as the String class and the Math class.

Data Types

We had established in the introduction that data is vital to a program. The data that a program uses must be stored in primary memory in order for the processor to handle it. The Java programming language specifies two broad categories of data. One type is called primitive and the other is called reference type. Primitive types are those values that are atomic and therefore cannot be decomposed into simpler types. Reference type on the other hand is constructed from the primitive types as well as from other reference types. Figure 4.1 shows a breakdown of the various categories of the types.

Figure 4.1 Data types - primitive types and reference types

Primitive Type

Let’s say two people are planning on going on a journey and want to travel together, it would be more conservative to use a car instead of a minivan. On average a car uses less petrol; a four-seater car would be half full, and seven-seater minivan would be two-seventh full. Not only that conservation is important, but relevancy as well. Hence, if you want to study the molecular structure of an organism, it would be more relevant to use a microscope rather than a telescope. So much so, it is important to use the appropriate data when programming.

As was mentioned earlier, Java classifies data into primitive type and reference type. The primitive types fall into three categories: the integral types, the floating-point types, and the boolean type. The integral type consists of two sub-types: the integer data types and the character type. Refer to Figure 4.1.

Integral Type

Integral data do not have decimal values associated with them; hence, the concept of integral types. Integral types are divided into two categories – integers and characters. There are four integer types - byte, short, int, and long.

Integers - byte, short, int, long.

The integer types are signed types, meaning that both negative and positive values are considered. Figure 4.2 shows the integer type, the amount of storage that is required for each type, and the range of values that each type can accommodate.

| | | |

|Data types |Storage Required |Range of Values |

| | | |

|byte |8 bits (1 byte) |-128 to +127 |

| | | |

|short |16 bits (2 bytes) |-32,768 to +32,767 |

| | | |

|int |32 bits (4 bytes) |-2,147,483,648 to +2,147,483,647 |

| | | |

|long |64 bits (8bytes) |-9223,372,036,854,775,808 to 9223,372,036,854,775,807 |

Figure 4.2 Java integer data types, the storage requirements, the and range of values for each type

By default an integer value is an int, unless otherwise specified. For instance, the number 1024 falls within the range of integer values; hence, by default is an int. To specify this number as a long you must append the letter (l or L) to it; as in 1024L, defines 1024, a long. There is no abbreviation for byte or for short.

Floating Point Type

As mentioned earlier, floating-point numbers are primitive types also. Java uses two floating-point types: float and double. A floating point value is double by default. Hence, the number 1024.0 is a double by default. For a decimal literal to be considered a float, you must append the letter f or F to it. That is, 1024F or 1024f the 1024.0 from a double to a float. Figure 4.3 shows the floating-point types, the amount of storage that is required for each type, and the range of values that each type can accommodate.

|Data type |Storage Required |Range of Values |

| | | |

|float |32 bits (4 bytes) |-3.4 x 1038 to +3.4 x 1038 |

| | | |

|double |64 bits (8 bytes) |-1.7 x 10308 to +1.7 x 10308 |

Figure 4.3 Java floating-point data types, the storage requirement and range of values for each type

Character Type

The character data type named char is any printable symbol found on the keyboard or certain sequence of characters called escape sequence. In either case, the type char requires 16 bits (2 bytes) of memory to store the char value. Java can accommodate up to 65,536 different characters. A char value can be represented decimal value in the range 0 to 65,536, or as Unicode character in the range ‘\u0000” to ‘\uFFFF’. Unicode characters are usually represented in base 16, where the digits for base 16 are 0 thru 9 and the letters A thru F. The letter as A thru F represents 10 thru 15. Figure 4.4 shows the decimal range and their equivalent Unicode range.

| | | | |

|Data Type |Storage Required |Decimal Range |Unicode Range |

| | | | |

|char |16 bits (2 bytes) |0 to 65,536 |\u0000 to \uFFFF |

Figure 4.4 Character types, the storage requirements and range of values

Character data value must be placed within single quotation marks. Hence the uppercase letter A, must be written as ‘A’. The digit 5 must be represented as ‘5’. There can be no more than one character within the quotation marks.

A portion of the Unicode character set called escape sequence, is reserved for certain controlling feature. Each escape sequence character is composed of a back slash followed by another character. For instance, we have seen the ‘\t’ for tab, and the ‘\n’ for new line. Figure 4.5 shows a set of escape sequence characters, with their meaning, the decimal equivalence, and the Unicode equivalence.

| |Meaning |Decimal Value |Unicode |

|Escape Sequence | | | |

| | | | |

|'\b' |Backspace |8 |'\u0008' |

| | | | |

|'\t' |Tab |9 |'\u0009' |

| | | | |

|'\n' |Line feed |10 |'\u000A' |

| | | | |

|'\r' |Carriage return |13 |\u000D' |

| | | | |

|'\f' |Form feed |12 |'\u000C' |

| | | | |

|'\\' |Backslash |92 |'\u005C' |

| | | | |

|'\''' |Double quote |34 |'\u0022' |

| | | | |

|'\'' |Apostrophe-quote |39 |'\u0027' |

Figure 4.5 Character escape sequences, their meaning, integer and Unicode representations.

Boolean Type

Java’s logical data type is called boolean. The set of values that represent the boolean data type is true and false. This data type is implemented when comparing primitive types. Boolean variables are declared the same way that numeric variables and character variables are declared.

Assignment Incompatibility

A variable can be initialized wrongly. That is, the value that is assigned to it might be of the wrong type. This situation gives rise to syntax errors. Figure 4.6 shows the compiler error messages when an attempt is made to compile the following statement.

int x = 2.0;

Figure 4.6 Error when you assign a floating point value to an integer variable

Figure 4.7 shows the syntax error for the statement: short x = 150000. The value 150000 is out of the range for the type short.

Figure 4.7 Error when value is outside the range of the type

The Boolean data type has only two values – true and false. If a value other than one of these two is assigned to a boolean variable, the result will be syntax error. Figure 4.8 show the syntax error that is generated when attempt is made to compile the following statement:

boolean x = 0;

Figure 4.8 Error - boolean value must be either true or false. No other value.

Consider the following segment of code:

int x = 2;

byte y = x;

This pair of statements looks fine at first glance, but on compiling it we discover that there is a subtle discrepancy which results in syntax error. See Figure 4.9. The second statement does not compile because the variable y is 8 bits wide, and the variable x is 32 bits wide; hence another case of assignment incompatibility.

Figure 4.9 Error due to assignment incompatibility

Let us coerce the value of x to be a byte:

byte y = (byte)x;

This statement compiles fine and y has the correct value, 2. If we change the value of x to 2550 and compile it before the coercion the same compilation error will be generated. When we apply the coercion and execute the code, result is –10.

Notice that in each case the compiler tells you the type of data value you are trying to assign to the variable, followed by what data value is required to be assigned to the variable.

Exercises (4a)

1. Give the data type for each of the following values. If a value is invalid explain why it is invalid.

a) 1024

b) 1024.0

c) '\0041'

d) '\u0041'

e) '\\'

f) true

g) False

2. For each of the following statements, do the following:

a) Declare an integer variable called noOfPatrons, with an initial value of zero.

b) Declare a float variable called why_Is_It with initial value of 4.5.

c) Declare a float variable called how_Is_It with 4.0 as its initial value.

d) Repeat (b) and (c), but this time make the variable types be double.

3. What will happen if you attempt to compile each of the following lines of code?

a) int x = 25.0;

b) float x = 1.0;

c) byte x = 130;

d) char x = 128;

e) boolean x = 1;

4. A company wishes to set up a computer network. The systems analysis proposes one of the following transmission media.

a) Twisted pair cable with transmission rate of 4 megabits per second.

b) Coaxial cable with a transmission rate of 500 megabits per second.

c) Optical cable with transmission rate of 3 gigabits per second.

What is the minimum data type would be required to represent each the speed of each of the transmission medium? Rationalize your answer.

5. In question 3, the analyst recommends a digital signaling that operates at 9,600 bits per second, what is the minimum data type required to represent the speed of the device? Explain.

6. A medical facility wishes to replace the current electronic monitoring device for measuring blood pressure. The current instrument gives normal reading to be 120/80 (read 120 over 80). The facility is requesting a range of 115/75 to 120/80 be normal reading. If you were to write a program to represent these numbers, what is the most appropriate data type to represent this range of values? Explain.

Operator and Operations on Data

Computers are known as number crunching machines. In order for them to crunch numbers, they need to perform operations on the numbers. In Java there are five types of operations that can be performed on primitive data values. These are arithmetic operations, relational operations, logical operations, bit-wise operations, and bit-shift operations. We will consider only the first three.

Arithmetic Operator and Operations

Java defines five binary arithmetic operators that are used to form arithmetic expressions. The format of an arithmetic expression is:

operand operator operand;

Where the operands are any valid identifier or literal numeric value, and operator is any of five arithmetic operators. The arithmetic operators and their respective operations are summarized in Figure 4.10.

| | | | | |

|Operator |Name |Algebraic form |Example |Result |

| | | | | |

|+ |Addition |x + y |25 + 15 |40 |

| | | | | |

|- |Subtraction |x + y |25 - 15 |10 |

| | | | | |

|* |Multiplication |x * y |18 * 2 |36 |

| | | | | |

|/ |Division |x / y |37/5 |7 |

| | | | | |

|% |Modulus operation |x % y |25 % 7 |4 |

Figure 4.10 Java’s five arithmetic operators

The first three operators (+ , - , * ) have the usual arithmetic meaning. The fourth operator ( / ), gives the quotient when applied to division. That is why 37/5 = 7, and not 7.4

[pic]

The last operator ( % ), gives the remainder when applied to division. Hence, 37%5 = 2.

[pic]

You may ask what the applicability of these two operators is. Consider for a moment the following situation:

If a task takes a worker 127 minutes to complete, how many hours and how many minutes did it take the person to complete.

If we were to program this, we would have to tell the computer precisely how to carry out the calculation. That is, the number of hours would be 127/60 = 2 hours, and 127%60 = 7 minutes.

Example

A small company wants you to write a program to figure out the number of boxes needed to ship book orders without wasting space. They have four types of boxes: extra large, large, medium and small, which can hold 25, 15, 5 and 1 book(s) respectively.

Write a Java program that accepts the number of books to be shipped and displays the number of boxes needed with their type. For example if the company wants to ship 81 books your output should be 3 big boxes, 1 medium box and 1 small box.

Figure 3.5 summarizes the difference for int data type only.

The operation on int data values produces in context either an int value, the number is too large, or execution error.

| | | | | |

|Integer | | |Actual |Correct |

|Operations |Result |Example |Result |Result |

| | | | | |

|int + int |int or |10000 + 1024 |11024 | |

| | | | | |

| |number too large |2147483647 + 53 |-2147483596 |2147483700 |

| | | | | |

|int - int |int or |10000 - 1024 |8976 | |

| | | | | |

| |number too large |-2147483647 - 53 |2147483596 |-2147483700 |

| | | | | |

|int * int |int or |1024 * 10000 |10240000 | |

| | | | | |

| |number too large |1000000000 * 500 |1783793664 |500000000000 |

| | | | | |

|int / int |int or |125 / 7 |17 | |

| | | | | |

| |Arithmetic Exception |125/0 |ArithmeticException |No correct result |

| | | | | |

|int % int |int or |125 % 7 |6 | |

| | | | | |

| |Arithmetic Exception |125 % 0 |ArithmeticException |No correct result |

Figure 3.5 The possible values generated by the arithmetic operators on int values.

The data type float can be summarized as shown in Figure 3.6. Notice that in all cases the operation yields a float value or if not, it produces the identifying word Infinity, or in the case of 0.0 / 0.0 it produces the description NaN, meaning Not A Number.

| | |

|float Operations |Result |

| | |

| |float or |

|float + float | |

| |Infinity |

| | |

|float - float |float or |

| | |

| |-Infinity |

| | |

|float * float |float or Infinity |

| | |

|-float * float |float or –Infinity |

| | |

|float / float |float or Infinity |

| | |

|-float / 0.0 |-Infinity |

| | |

|0.0/0.0 |NaN |

| | |

| | |

|float % float |float |

Figure 3.6 The possible values generated by the arithmetic operators on float values.

Arithmetic expressions can be more complex than the examples given above. Usually the result from an arithmetic expression gets stored in a variable. When this is the case consideration must be given to:

a) The size of the value that is generated, and

b) The data type of the variable that will be receiving the value calculated.

If conditions (a) and (b) are not compatible, then the compilation process will fail. Java checks for type compatibility at compilation time.

Unary Operators

The operators + and – are called unary operators when they precede a numeric value. The ( + ) operator does not present any dramatic change to the number; however, the ( – ) operator changes the value of the variable by reversing its sign. For instance, let x = 10, then –x = -10 .

Similarly, if x = -10, then – x = 10.

The ( + ) operator leaves the number in its original state.

Rules Governing Arithmetic Operations

Arithmetic Expressions

An arithmetic expression is a finite sequence of operands; an arithmetic operator separates each operand. An identifier, or a constant, or the actual data value can represent the operands. In general, arithmetic expressions are evaluated from left to right. However, this order evaluation may be altered based on any or all of the following criteria:

1. Unary operators. They have the highest priority.

2. Parentheses. Sub-expressions that are determined by parentheses have the next level of priority.

3. Multiplication, division and modulus operation. These have priority next to the level of parentheses. In addition, if there is a sequence of these operators, where they have equal priority, evaluation is done strictly from left to right.

4. Addition and subtraction have the lowest level of priority. They have equal priority with one another. If there is a sequence of them, the expression or sub-expression is evaluated strictly from left to right

Example 3.1 Evaluate the following expressions.

a) 2 + 3 – 4 + 5

b) 2 + 3 – 4 * 5

c) 2 + (3 – 4 ) * 5

d) 11 % 4 * 2 – 14/3 + (8 –2 * -3)

a) 2 + 3 – 4 + 5 Reason

5 - 4 + 5 The operators have the same precedence level.

1 + 5 Calculation is done strictly from left to right.

6 Result.

b) 2 + 3 – 4 * 5

2 + 3 – 20 Multiplication has higher priority

5 – 20 The operators have the same precedence level.

-15 Result.

c) 2 + (3 – 4 ) * 5

2 + (-1) * 5 Parentheses have higher precedence

2 – 5 Multiplication has higher priority

-3 Result

d) 11 % 4 * 2 – 14/3 + (8 –2 * -3)

11%4*2-14/3+(8 + 6) Unary (-) has highest precedence

11%4*2 – 14/3 + 14 Parentheses have nest highest precedence

3 *2 – 14/3 + 14 Modulus, multiplication, and division have same

6 – 14/3 + 14 level of precedence. They are executed strictly from left to right.

6 – 4 + 14 Addition and subtraction will be done after.

2 + 14

16 Result

When evaluating arithmetic expressions, one must be mindful of the data type of each operand. Failure to observe the rules might result in loss of data, arithmetic overflow or underflow (result exceed the allowable limit), or undefined value, or infinite value being generated. Listing 3.1 shows how erroneous values can be generated if due care is not taken when writing arithmetic expressions.

1. class DataTypes

2. {

3. public static void main(String[] arg)

4. {

5. double fahrenheit = 42.0;

6. double centigrade = 5/9*(fahrenheit - 32.0);

7. System.out.println(centigrade);

8. }

9. }

Listing 3.1 Integer division can result in loss of data.

The code above is syntactically sound, however, the result is 0.0. On closer examination of Line 6 shows, that the operands 5 and 9 are both integers. The result from the integer division is the quotient 0; the remainder is discarded. You can avoid this by casting (coercing) either the operands to at least a float, and this solves the problem. That is, modify Line 6 to be:

Centigrade = [pic]

double centigrade = (float)5/9*(fahrenheit - 32.0);

In this case integer 5 is converted to floating-point 5.0. This guarantees a floating-point division.

1. class short_

2. {

3. public static void main(String[] arg)

4. {

5. short s = 8;

6. s = s + 2;

7. }

8. }

Listing 3.2

----Configuration: j2sdk1.4.1_02 ----

C:\ listings\listing3_1\short_.java:6: possible loss of precision

found : int

required: short

s = s + 2;

^

1 error

Process completed.

Although the result of the expression is within the allowable limit, the digit 2 is occupying an integer space. Now if we coerce the 2 to be recognized as a byte; i.e,

s = s + (short)2 ;

the compiler generates the same message. The way to get around this is to cast the entire expression. That is,

s = (short)(s + 2) ;

Another common feature concerning arithmetic expression is to convert algebraic expressions into equivalent Java expressions. For example, given the following algebraic expression, convert it into a Java arithmetic expression.

s = s0 +v0t + ½ gt2

In carrying out this exercise, you should convert each term in the expression into an identifier. In the actual code you should specify the data type for each identifier named. The following are equivalent arithmetic expression, in which the value of the expression is assigned to the identifier s.

s = s0 + v0 * t + g * t * t / 2.0;

or

s = s0 + v0 * t +1.0/2 *g * t * t ;

or

s = s0 + v0 * t +0.5 *g * t * t ;

or

s = s0 + v0 * t + (float)1/2 *g * t * t ;

Relational Operator and Operations

There are six binary relational operators in Java that you can use to form Boolean expressions. They are used in conjunction with primitive numeric types and the character type to form simple conditional expressions. Figure 3. 7 Summarizes the operators, their meaning and their associated operation.

| | | | |

|Operator |Operation |Usage Pattern |Example |

| | | | |

|< |Strictly less than |x < y |100 < 200 |

| | | | |

| 100 |

| | | | |

|> = |Greater than or equal to |x >= y |200 >= 100 |

| | | | |

|== |Is equal to |x == y |200 == 100 |

| | | | |

|!= |Not equal to |x != y |200 != 100 |

Figure 3.7 Relational operators and their meanings.

Relational Expressions

Relational expression, sometimes referred to as simple conditional expression, refers to an expression that combines two primitive data types, each separated by a relational operator. The result from evaluating the expression is one of the boolean values, true or false. The general form of simple conditional statements is:

Left_Operand Relational_Operator Right_Operand

Where:

Left_Operand and Right_Operand are the primitive type that are to be tested, and

Relational_Operator is one of the six relational operators.

The expression is evaluated from left to right. There is no incompatibility between data types. For example, Listing 3.xx shows the primitive types being compared. Notice that the compiler did not flag any syntax error. See result in Figure 3.xx.

1. class relational

2. {

3. public static void main(String[] arg)

4. {

5. byte x = 20;

6. long y = 20;

7. char z = 'y';

8. int a = 50;

9. float b = 100.0F;

10. double c = 100.0;

11. System.out.println("byte x = 20 != char z = 'y'" + "\t" +

(x != z));

12. System.out.println("byte x = 20 == long y = 20" + "\t" +

(x == y));

13. System.out.println("float b = 100.0F != double c = 100.0" + "\t" +

(b != c));

14. System.out.println("int a = 100 == double c = 100.0" + "\t" +

(a == c));

15. }

16. }

[pic]

Figure 3.xx

The last line of output at first might look wrong, but you must remember that floating-point values are not stored the same way as integers are stored. Integers are stored precisely; where as floating-point values are stored as approximation. That is the reason for this seemingly incorrect result.

Just like how we can store the value calculated from an arithmetic expression in a variable of its kind, we can also store the value calculated from a relational expression in a Boolean variable. The format for doing so is as follows:

boolean id = relational_expression.

For example consider the following segment of code:

int x = 20;

double y = 20;

boolean flag = x == y;

Note, the relational expression is first evaluated, and the value to which it is evaluated is assigned to the Boolean variable flag. In this case the value true is assigned to the variable flag.

Logical Operator and Operations

Java has three logical operators. They are logical-AND, logical-OR, and logical-NOT. Logical operators AND, and OR, are binary operators. They combine relational expressions to form logical expressions, sometimes called compound expressions. The evaluation of an expression is carried out from left to right, and the result that it yields is a Boolean value. The Logical-NOT simply negates the result of a relational expression or the result of a logical expression.

Figure 3.8 summarizes the logical operators and their associated operations.

| | | | |

|Operator |Meaning |Usage Pattern |Example |

| | | | |

|&& |Logical-AND |Condition1 && Condition2 |200 < 100 && ‘m’ > ‘M’ |

| | | | |

||| |Logical-OR |Condition1 || Condition2 |200 < 100 || ‘m’ > ‘M’ |

| | | | |

|! |Logical-NOT |!(Condition) |!(200 < 100) |

Figure 3.8 Logical operators

Rules Governing Logical Operations

• The logical-AND operator (&&) produces true if both conditions are true and false otherwise. In addition, if one of the conditional expressions is false before the entire expression is evaluated, the entire logical expression terminates, in which case the result is false.

• The logical-OR operator ( || ) produces true if either conditions is true, or both conditions are true; and false otherwise.

• The logical-NOT operator negates a the result of a condition, it produces true if the original operation is false and vise versa.

Logical Expressions

Logical expressions sometime referred to as logical expressions operate with relational expression. As mentioned earlier, the Logical_AND and the Logical_OR are binary operators. They simply test one simple conditional expression against another, the result of which is one of the Boolean values. The general form of compound conditional statements is:

Conditional_Expression Logical_Operator Conditional_Expression

Where:

Conditional_Expression are the simple conditional expressions that are to be tested, and

Logical_Operator is either the logical-AND (&&), or the logical-OR (||).

1. class logical

2. {

3. public static void main(String[] arg)

4. {

5. byte x = 20;

6. long y = 20;

7. char z = 'y';

8. System.out.println("x != z " + (x != z));

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

10. System.out.println("x != z && x == y " + (x != z && x == y));

11. System.out.println();

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

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

14. System.out.println("x == z && x == y " + (x == z && x == y));

15. System.out.println();

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

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

18. System.out.println("x == z || x == y " + (x == z || x == y));

19. System.out.println();

20. System.out.println();

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

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

23. System.out.println("(!(x == z || x == y)) " + !(x == z || x == y));

24. System.out.println();

25.

26. boolean flag = x == z || x == y;

27.

28. System.out.println("flag is " + flag);

29. }

30. }

Listing 3.xx

[pic]

Figure 3.xx ….

Just like how we can store the value calculated from arithmetic and relational expressions in a variable of its kind, we can also store the value calculated from a logical expression in a Boolean variable. See Figure 3.xx Line 26.

Unary Operator and Operations

Reference Type

A reference data type is any data type that is composed of primitive data types as its based type. In other words, it is an aggregate of primitive types. Reference types are the array data structure and the class data type. In this section we will briefly discuss the concept of array. We will and we will discuss the class type to the extent of the fundamental classes of Java.

Array

An array is a contiguous set of storage locations set aside to hold one type of data. Array is simply a means where by we can store values of the same type by using one generic name. The list of items are stored linearly, hence the items can be accessed by their relative position in the list.

Arrays are regarded as real objects in Java. Storage space is not allocated for an array during compilation time, but rather during execution time. This means that the declaration alone does not imply that memory is allocated. The concept will be discussed fully in lesson 6.

Class

The concept of class is the fundamental construct upon which Java is built. As we have discussed, class serves as a blueprint or a template for objects. Against this background all data types other than the primitive type or the array must be addressed in terms of class. This is evident in the way that we use a class. For instance, going back to the class Book, in order to use this class we had to declare variables of the type:

Book b1;

Notice that this declaration follows the definition of how to declare primitive data type. This construct implies that the identifier Book is the type and b1 is a variable of the type Book.

7 Input and Output Operations

There are three other important operations that are performed on data. These are input operations, output operations, and formatting operations. We have been generating outputs already, but we have not formally addressed the issue. We will address these three items in this section. The section begins with a study of the input operations, followed by the output operations, and finally, the formatting operations.

Input Operations

The Scanner Class

JOptionPane Class

Java input/output system is very complex. To the extent of its complexity, keyboard input is not directly supported. There are three principal ways by which a program can be supplied with data. They are as follows:

1. Through the command line at the DOS prompt. This method requires you to know about array containing string, values, and how to manipulate these arrays. So far we have not studied arrays, so we will differ this method until we have studied the concept of files and text stream classes, by which time we would have covered arrays.

2. The second approach is to use System.in, which is used to represent standard input; i.e., entering data from the keyboard. In order to use this method one has to be acquainted to some degree about the concept of Exception. In addition, you will need some knowledge about the concept of the classes that deal with text files.

3. This third method may be the simplest. In addition, we have sufficient knowledge to appreciate what goes on here. For this third method we will use the class JOptionPane for the package javax.swing. As a matter of fact, we can use it along with the wrapper classes to build a class solely for reading data. There might be one or two disadvantages using this method, but these disadvantages are minor comparing to trying to understand the other two methods at this early stage of the game. Before we actually start using the JOptionPane class let us look at its characteristics and its capabilities.

JOptionPane class is a utility class that is used to create various dialog panes or windows. You can use it to create input and output dialog boxes. A dialog box is normally used as a temporary window to receive data from the keyboard or to display information. This class can be used to four kinds of standard dialogs, namely:

• Message dialog shows a message and waits for the user to click OK.

• Confirmation dialog shows a question and ask for confirmation such as OK or Cancel.

• Option dialog shows a question and gets the user’s response from a set of options.

• Input dialog shows a question and gets the user’s input from a text field, a combo box, or list.

The class contains several forms of constructors, but there are also several class methods that can be used to achieve the same results. The general construct of these class methods are as follows:

showXXXXDialog(parameter_list)

Where XXXX is any of the four types. In this section we will be concerned with the input dialog type.

As was mentioned, the input dialog box is used to receive input from the user. We will specifically use it to capture text from the keyboard when the text is typed in the text field. Listing 3.12 shows how an input dialog box is created, and Figure 3.28 shows the dialog box and the parts of the input dialog box that is created.

1. import javax.swing.JOptionPane;

2.

3. class optionPane

4. {

5. public static void main(String[] arg)

6. {

7. String str = JOptionPane.showInputDialog("Read data");

8. }

9. }

Listing 3.12 line 7 shows how the dialog box is created.

Notice that in order to use the JOptionPane class you must import it into your code, because it is not a part of the lang package. Line 1 shows the import statement. Line 7 of the code shows how the showInputDialog class method is called. In addition, notice that the value that this method returns is a string value, no other data type!.

System’s message Your Message

[pic]

System’s Icon Accept option Reject option Text field

Figure 3.28 Parts of the JOptionPane input dialog box .

Now that we know about the input dialog box, let us use the same code (Listing 3.12) to enter a value, say the value 123.45. To us this is a floating-point value, but when read by the dialog box it will be returned as a string value. See Figure 3.29.

[pic]

Figure 3.29 The value 123.45 typed into the text field of the JOptionPane input dialog box.

When the OK is clicked, the value is stored in the variable str, Line 7 of Listing 3.12. That is:

String str = JOptionPane.showInputDialog("Read data");

str = 123.45

Convert String To Primitive Type

A string value of appropriate characters can be converted to the appropriate numeric data value and character value. Recall that the wrapper classes can be used to carry out the conversion. For instance, the string value 123.45 can be converted say to a double value by using the class method parseDouble from the wrapper class Double. Listing 3.13 Line 9 shows how this can be achieved.

1. import javax.swing.JOptionPane;

2.

3. class convert_string

4. {

5. public static void main(String[] arg)

6. {

7. String str = JOptionPane.showInputDialog("Read data");

8.

9. double x = Double.parseDouble(str);

10. }

11. }

Listing 3.13 Converting string value to double value.

Surely we could write our programs and insert pairs of statements as in Lines 7 and 9 of Listing 3.13. This might become unsightly after a while. What we could do is to write a service class that can be used to read the data. As a service class we make the methods class methods, similar to what the class math has done. An application program could then refer to this service class to fetch data of any kind. Listing 3.14 shows a partial definition of this class. The remaining types will be left as an exercise.

1. import javax.swing.JOptionPane;

2.

3. class getData

4. {

5. static String str;

6.

7. static double getDouble(String s)

8. {

9. str = JOptionPane.showInputDialog(s);

10. return Double.parseDouble(str);

11. }

12.

13. static int getInt(String s)

14. {

15. str = JOptionPane.showInputDialog(s);

16. return Integer.parseInt(str);

17. }

18.

19. static String getWord(String s)

20. {

21. return JOptionPane.showInputDialog(s);

22. }

23. }

Listing 3.14 Shows a partial definition of a service class that reads data using the class JOptionPane along with the wrapper classes.

Listing 3.15 shows a test class that utilizes the service class getData.java. Notice how the methods are called in Lines 5 – 7.

1. class testGetData

2. {

3. public static void main(String[] arg)

4. {

5. int x = getData.getInt("Type an integer value");

6. double y = getData.getDouble("Type a double value");

7. String name = getData.getWord("Enter a Name");

8.

9. System.out.println("Your name is: " + name + "\nYour age

is: " + x + "\nYou have $" + y);

10. }

11. }

Listing 3.15 The test class testGetData.java.

Figure 3.30 shows the state of the input dialog box after the data value has been entered in the text field. This figure was generated when Line 5 of Listing 3.15 has been executed. This line of code invokes the class method in Listing 3.14, Lines 13 – 17.

[pic]

Figure 3.30 Input dialog box when Line 5 of Listing 3.15 is called.

Figures 3.31 and 3.32 are generated on the similar fashion as the previous figure.

[pic]

Figure 3.31 Input dialog box when Line 6 of Listing 3.15 is called.

[pic]

Figure 3.32 Input dialog box when Line 7 of Listing 3.15 is called.

The following, Figure 3.33 shows the output from the program.

[pic]

Figure 3.33 Output from the program.

If we take this approach then this class can be used whenever data is need to be read. In this case we will not have to write code for reading data again, but rather, we use this existing code.

Output Operations

We have seen output operations in previous lessons, this time we will look at output operations using the JOPtionPane class. As we said earlier this class has several constructors, however we can use the showMessageDialog class method to achieve the same result. The general for of the showMessageDialog is shown in Figure 3.34.

System’s information icon

The output displayed

[pic]

Title you want System’s confirm button

Figure 3.34 The general form of the showMessageDialog.

1. import javax.swing.JOptionPane;

2.

3. class output_pane

4. {

5. public static void main(String[] arg)

6. {

7. JOptionPane.showMessageDialog(null, "Your \noutput string",

"Your title", RMATION_MESSAGE);

8. }

9. }

Listing 3.16 Shows the class that produced the message dialog in Figure 3.34.

Notice in Figure 3.14 Line 7 certain keywords and constants.

• null signifies that this dialog box does not part of any frame or dialog box.

• Your \noutput string the string value that is to be displayed in the message dialog box.

• Your title the title you want to give to the output.

• RMATION_MESSAGE declares what type of dialog box this is. Notice the letter cases. They must be written as shown here.

Notice also that in this context System.out.print(ln) is not used, instead it is the string value that must be stated. The string may be represented by a variable as shown in Listing 3.17.

1. import javax.swing.JOptionPane;

2.

3. class output_pane

4. {

5. public static void main(String[] arg)

6. {

7. int x = getData.getInt("Type an integer value");

8. double y = getData.getDouble("Type a double value");

9. String name = getData.getWord("Enter a Name");

10.

11. String s = "Your name is: " + name + "\nYour age is: " + x +

"\nYou have $" + y;

12.

13. JOptionPane.showMessageDialog(null, s, "Personal Data",

RMATION_MESSAGE);

14. }

15. }

Listing 3.17

[pic]

Figure 3.35 Using showMessageDialog to display the output from a program.

In the above situation the value that is passed to the method must be a string. What this means is that you must be able to construct the string before calling the method. This requires you to know the format of the output ahead of time, and be able to use the sting concatenation features along with tabs, new line, and space to make the entire string.

The above method has one major disadvantage; i.e., if the string is very long then the dialog box will also be very long maybe spanning more than one page. An enhancement to this feature is to place the text in a scrolling window. This is how it works. Let us imagine that we have a photograph that we want to frame, but the picture is much larger than the frame. Suppose we could do the following, we would solve the problem. That is,

1. Place the picture on a backing paper whose size would be determined.

2. Place the backing paper containing the in a pane that is scrollable, so that we can scroll down or pan across to see the picture.

3. Finally, get a box and cut an opening in it so that the picture can be viewed from it. Place the scrollable frame in a box with the picture facing the viewer.

This approach could solve the problem posed above. In terms of programming we will follow the same analogy. That is:

1. A text area from the class JTextArea would represent the backing paper. This text area would contain the string, and its size; i.e., the number of visible rows and columns.

2. A scrollable pane from the class JScrollPane would represent the scroll pane.

3. Finally, place the scrollable pane in showMessageDialog method.

That is it!

Listing 3.18 shows how carry out this exercise. The first thing that you must do is to import the JTextArea class and the JScrollPane class. Both classes are from the javax.swing package. See Lines 2 and 3.

1. import javax.swing.JOptionPane;

2. import javax.swing.JTextArea;

3. import javax.swing.JScrollPane;

4.

5. class output_pane

6. {

7. public static void main(String[] arg)

8. {

9. int x = getData.getInt("Type an integer value");

10. double y = getData.getDouble("Type a double value");

11. String name = getData.getWord("Enter a Name");

12.

13. String s = "Your name is: " + name + "\nYour age is: " + x +

"\nYou have $" + y;

14. s = s + "\nThat other person does not remember his name\nnor

his age";

15. s = s + "\nlet alone how much money he has";

16.

17. JTextArea text = new JTextArea(s, 10, 20);

18. JScrollPane pane = new JScrollPane(text);

19.

20. JOptionPane.showMessageDialog(null, pane, "Personal Data",

RMATION_MESSAGE);

21. }

22. }

Listing 3.18 Creating a scroll pane.

In Listing 3.18 notice the following:

1. In Line 17 the string variable s is used to create the text area object (the backing paper for the string value). In addition the size of the text area is specified; i.e., 10 rows and 20 columns of text must be visible at all times.

2. In Line 18 the text area object is used to build a scrollable pane object.

3. Finally, in Line 20, the scroll pane object replaces the string field in the showMessageDialog method.

See Figure 3.36 for the output generated from the program.

[pic]

Figure 3.38 Shows the output in a scrollable text area of the showMessageDialog box.

Formatting the Output

Formatting numbers as decimal to a given number of decimal places, or as currency, or as percentage is of paramount importance when generating output. There is no easy default way of generating these in Java. A few classes and some methods are involved here. Numbers are formatted using the java.text.NumberFormat class. This class has several methods for formatting and parsing numbers. This class allows you to format numbers for different natural languages. Your program code is independent of the conventions for decimal points, thousands separator, or currency unit. These issues can be specified using the NumberFormat class. Usually we specify a locale; that is, the country for which the format must be made. In addition, we must specify the format to apply to the number and also the digit pattern to apply to the number.

Formatting Floating-Point Numbers

In order to format floating-point numbers there are two class that must be imported. They are:

java.text.NumberFormat, and

java.text.DecimalFormat

See Listing 3.19 Lines 5 and 6. Once the classes are imported we must do the following:

1. Get a number format instance. Here we will use the NumberFormat.getInstance() method. This is the default instance method. See Listing 3.19 Line 14.

2. Cast this number format instance to a decimal format. See Listing 3.19 Line 15.

3. Set the pattern for which we want the number to be formatted. That is, the number of decimal places, any trailing zeroes, or if a leading zero is to be applied. See Listing 3.19 Line 16. In this case the pattern describes a number that has at least one digit left of the decimal point and two to the right of the decimal point. If there are not sufficient digits then zero(s) will take the place. In addition, the digits to the right of the decimal point may experience rounding.

4. Line 19 shows how the format method is applied to the variable containing the value that is to be formatted.

Listing 3.19 shows how the number 123.4567 is formatted to two decimal places.

1. import javax.swing.JOptionPane;

2. import javax.swing.JTextArea;

3. import javax.swing.JScrollPane;

4.

5. import java.text.NumberFormat;

6. import java.text.DecimalFormat;

7.

8. class number_format

9. {

10. public static void main(String[] arg)

11. {

12. double x = 123.4567;

13.

14. NumberFormat nf = NumberFormat.getInstance();

15. DecimalFormat df = (DecimalFormat)nf;

16. df.applyPattern("0.00");

17.

18. String s = "";

19. s = s + df.format(x);

20.

21. JTextArea text = new JTextArea(s, 3, 5);

22. JScrollPane pane = new JScrollPane(text);

23.

24. JOptionPane.showMessageDialog(null, pane, "Formatting numbers",

RMATION_MESSAGE);

25. }

26. }

Listing 3.19 Formatting decimal numbers.

[pic]

Figure 3.39

Formatting Currency

The formatting of currency follows the same pattern as formatting floating-point numbers. As was said earlier, numbers are formatted according to the country or locale. Java makes provision for a number of monetary representations. The class java.util.Locale specifies those countries. In order to format currency, do the following:

1. Import the class java.util.Locale. See Listing 3.20 Line 7. This is optional. However, if it is not imported Java will use the default locale found on the computer that is being used.

2. Adopt a locale value. In our case we get the US format. See Line 19.

3. Get the currency format for the locale. See Line 20.

4. Finally, apply the format. See Line 24.

Listing 3.20 shows how to format US dollar currency.

1. import javax.swing.JOptionPane;

2. import javax.swing.JTextArea;

3. import javax.swing.JScrollPane;

4.

5. import java.text.NumberFormat;

6. import java.text.DecimalFormat;

7. import java.util.Locale;

8.

9. class dollar_format

10. {

11. public static void main(String[] arg)

12. {

13. double x = 123.4567;

14.

15. NumberFormat nf = NumberFormat.getInstance();

16. DecimalFormat df = (DecimalFormat)nf;

17. df.applyPattern("0.00");

18.

19. Locale local = Locale.US;

20. NumberFormat cf = NumberFormat.getCurrencyInstance(local);

21.

22. String s = "";

23. s = s + df.format(x);

24. s = s + "\n\n" + cf.format(x);

25.

26. JTextArea text = new JTextArea(s, 3, 5);

27. JScrollPane pane = new JScrollPane(text);

28.

29. JOptionPane.showMessageDialog(null, pane, "Formatting currency",

RMATION_MESSAGE);

30. }

31. }

Listing 3.20 Formatting local currency.

[pic]

Figure 3.40 Formatting currency.

Formatting Percentage

Percentage formatting is not much different from the other two types of formatting. The only difference here is to get a percentage instance as shown in Listing 3.21 Line 20 and Lines 25 shows how the format method is called.

1. import javax.swing.JOptionPane;

2. import javax.swing.JTextArea;

3. import javax.swing.JScrollPane;

4.

5. import java.text.NumberFormat;

6. import java.text.DecimalFormat;

7.

8. class percentage_format

9. {

10. public static void main(String[] arg)

11. {

12. double x = 123.4, y = 246.8, p = 123.45678;

13.

14. NumberFormat nf = NumberFormat.getInstance();

15. DecimalFormat df = (DecimalFormat)nf;

16. df.applyPattern("0.000");

17.

18. NumberFormat cf = NumberFormat.getCurrencyInstance();

19.

20. NumberFormat pc = NumberFormat.getPercentInstance();

21.

22. String s = "";

23. s = s + "Express y to three places of decimal .... " +

df.format(x);

24. s = s + "\nExpress y in currency format ................... " +

cf.format(x);

25. s = s + "\nExpress x as a percentage of y .............. " +

pc.format(x/y)

26. + "\nExpress p to three places of decimal.... " + df.format(p)

27. + "\nExpress p in currency format .................. " +

cf.format(p);

28.

29. JTextArea text = new JTextArea(s, 6, 25);

30. JScrollPane pane = new JScrollPane(text);

31.

32. JOptionPane.showMessageDialog(null, pane, " Decimal, Currency &

Percentage Format", RMATION_MESSAGE);

33. }

34. }

Listing 3.21 Formatting number as percentage.

Figure 3.40 shows the output from Listing 3.21.

[pic]

8 Pitfalls

9 Chapter Summary

In this chapter you have learned about variables, data types, and operations on data Most importantly, you should have learned the following:

• The conventions that are use to name variables:

• Each variable must be declared before it can be used.

• Java primitive data types and composite types. The primitive type includes numeric types, which includes integer and floating-point types; character types; and boolean types.

• The integer types are: byte, short, int, long. The corresponding storage requirements for each of these types are 1 byte, 2 bytes, 4 bytes, and 8 bytes, respectively. The default for an integer value is int.

• Java floating-point types are float and double. The default of a floating-point number is a double. The storage requirements are 4 bytes and 8 bytes, respectively.

• The character type, char, is a 2 bytes Unicode representation.

• The third and final primitive data type is the boolean, which has values true or false.

• There are two composite types in Java, namely: array and string. Arrays are used to house more than one data values of the same type. Individual elements are accessed by use of the index. A string stores a fixed number of characters that cannot be changed. You can create an array of string objects.

• You can know the number of items that are in an array by using the string operator length.

1. class Math

2. {

3. double distance, height;

4.

5. public Math(String x, String y)

6. {

7. distance = Double.parseDouble(x);

8.

9. height = Double.parseDouble(y);

10. }

11.

12. double findAngle()

13. {

14. double x = Math.atan(height/ distance);

15.

16. return Math.round(Math.toDegrees(x));

17. }

18.

19. double lineOfSight()

20. {

21. double x = Math.pow(height, 2) + Math.pow(distance, 2);

22. return Math.sqrt(x);

23. }

24. }

Listing 3.10

In the test class we have made use the string method substring to extract the numeric string representations. See Figure 3.11 Lines 8 and 9. Finally Line 18 shows one way of converting a double to the next integer value equal to or larger than the value itself.

1. class TestMath

2. {

3. public static void main(String arg[])

4. {

5. String distance = "Distance from foot of cliff 200";

6. String height = "Height of cliff is 40 meters";

7.

8. distance = distance.substring(28);

9. height = height.substring(19,21);

10.

11. System.out.println("Distance of boat from foot of cliff is: " + distance);

12. System.out.println("The height of the cliff is: " + height);

13.

14. math m = new math(distance, height);

15.

16. System.out.println("The angle of elevation is: " + m. findAngle() + " degrees");

17.

18. System.out.println("The line of sight is " + (int)Math.ceil(m.lineOfSight()) + " meter");

19. }

20. }

Listing 3.11.

[pic]

Figure 3.27

10 Programming Projects

-----------------------

Data types

Primitive types

Reference types

Floating Point

Integral types

boolean

double

Integers

byte

short

long

int

float

-----Configuration: j2sdk1.4.1_02 ----

C:\istings\data_types\default_types.java:6: possible loss of precision

found : int

required: byte

byte y = x;

^

1 error

Process completed.

User defined classes

Java classes

char

Boolean types

Character

Configuration: j2sdk1.4.1_02 ----

C:\chapter3\unicodeChar.java:5: possible loss of precision

found : double required: int

int x = 2.0;

^

1 error

Process completed

Configuration: j2sdk1.4.1_02 ----

C: \chapter3\unicodeChar.java:5: possible loss of precision

found : int required: short

short x = 150000;

^

1 error

Process completed

Configuration: j2sdk1.4.1_02 ----

C: \chapter3\unicodeChar.java:5: incompatible types

found : int required: boolean

boolean x = 0;

^

1 error

Process completed.

1. public class PackingBooks

2. {

3. static final int XTRA_LARGE_BOX = 25,

4. LARGE_BOX = 15,

5. MEDIUM_BOX = 5,

6. SMALL_BOX = 1;

7.

8. public int books;

9. public int big, large, medium, small;

10.

11. PackingBooks(int books)

12. {

13. this.books = books;

14. }

15.

16. void determineBoxes()

17. {

18. big = books/ XTRA_LARGE_BOX;

19. books = books % XTRA_LARGE_BOX;

20.

21. large = books/LARGE_BOX;

22. books = books % LARGE_BOX;

23.

24. medium = books/MEDIUM_BOX;

25. small = books % MEDIUM_BOX;

26.

27. total = xlarge + big + medium + little;

28. }

29.

30. int getBigBox()

31. {

32. return big;

33. }

34.

35. int getLargeBox()

36. {

37. return large;

38. }

39.

40. int getMediumBox()

41. {

42. return medium;

43. }

44.

45. int getSmallBox()

46. {

47. return small;

48. }

49. }

class TestPacking

{

public static void main(String [] arg)

{

Packing pack = new Packing(127);

pack.calculate();

System.out.println(pack.getXLarge() + " extra large boxex\n"

+ pack.getLarge()

+ " large boxex\n" + pack.getMedium()

+ " medium boxes\n" + pack.getSmall()

+ " small box\n" + pack.getTotal()

+ " total boxes\n") ;

}

}

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download