Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
4.
Data Types and Operations On Data
Objective
Objectives
To understand what data types are
The need to study data types
To differentiate between primitive types and reference types
To know the data range and storage requirements for each type
To know the conditions 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.
The first section of the lesson introduces you to a comprehensive study of the fundamental data types in
Java, and how they relate to programming. Like in anything else, it is important to conserve; against
background data values are divided into categories - primitive types and reference types. The section closes
with the discussion on expressions and how they are evaluated. The second part of the lesson introduces the
reference type. This includes some of the fundamental classes in Java.
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 the 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 different types.
Data types
Primitive types
Reference
types
Integral types
Floating Point types
boolean
Java classes
Integers
char
float
double
User defined classes
byte
int
short
long
Figure 4.1 Data types - primitive types and reference types
Primitive Type
In the field of computer science, like many other areas of life, conservation is a key ingredient for success;
hence the need for the different data types. Each type requires different amount of memory to store the
data. For instance, if two people are going on a journey and want to travel together, it would be more
conservative to use a car instead of a minivan. Not only that conservation is important, but relevancy as
well. Hence, if you want to study the molecular structure of an organism, then you would be better of using
a microscope rather than a telescope.
As was mentioned, 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 values do not have decimal values associated with them; hence, the concept of integral data
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 along with the storage requirements 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
to it the letter (l or L). That is, 1024L is a long. There is no abbreviation for byte or for short.
Floating Point Type
As mentioned earlier, floating-point numbers are primitive types. Java uses two floating-point types:called
float and double. A floating point value is double by default. Hence, the number 1024.0 is a double by
default. For it to be considered a float, you must append the letter f or F to it. That is, 1024F or 1024f
converts this number to a float rather than a double. Figure 3.2 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
32 bits (4 bytes)
-3.4 x 1038 to +3.4 x 1038
64 bits (8 bytes)
-1.7 x 10308 to +1.7 x 10308
float
double
Figure 4.3 Java floating-point data types along with storage requirement and range for each type
Character Type
The character data type named char is any printable symbol found on the keyboard or certain sequence of
characters forming one piece of instruction to the machine. In either case, the type char requires 16 bits (2
bytes) of memory to store the char value. There are other arrangements to store character values. This
scheme can accommodate a character set of up to 65,536 different characters. This arrangement is called
the Unicode character set. The Unicode character set can represent a wide variety of ideograms including
those form languages other the English language.
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 and the storage requirement and range of values
Character data value must be placed within single quotation mark. 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 mark.
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. Figure 3.4
shows a set of escape sequence characters, with their meaning, the decimal equivalence, and the Unicode
equivalence.
Escape
Sequence
Meaning
'\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'
Decimal Value
Unicode
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. Variables of boolean type are
declared the same way that a numeric variables and a character variables are declared.
Declaring And Initializing Variables
In Java every variable must be declared before it can be used, as we stated in chapter 2. The format for
declaring any of these new data types follow the same format as discussed then, that is:
data_type identifier;
Where data_type is a valid data type and identifier is the name of the variable. Each declaration must
terminate with a semicolon, unless you are specifying a series of variables, which case they are of the same
data type. In the latter case, a comma must separate each variable.
Numeric Types – Integers and Floating-Point
The following are typical declarations for numeric variables:
byte
aNumber;
int
firstNumber;
float
realNumber;
double
bigNumber
long
aLongNumber;
boolean
valid more;
After a variable has been declared, it may be assigned a value. The value that is to be assigned must be
compatible with the declaration. The format for assigning values is as follows:
destination_Variable = source_variable;
In order to assign a valuable to an identifier, one of two conditions must be satisfied.
1. The data value to be assigned must be within the range of the specified data type.
2. The identifier representing the destination variable must be of equal size or larger than the
identifier representing the source variable. If this condition is not satisfied, then we could try and
coerce the value to fit the destination variable by a method called casting. If this is done however,
then there is a high possibility that the value stored in the destination variable will not be accurate.
For instance, consider the following segment of code:
int x = 2;
byte y = x;
System.out.println(y);
This results in the following syntax error:
-----Configuration: j2sdk1.4.1_02 <Default>----
C:\istings\data_types\default_types.java:6: possible loss of precision
found : int
required: byte
byte y = x;
^
1 error
Process completed.
Now let us coerce the value of x to be a byte:
byte y = (byte)x;
Now this compiles fine and the output generated is 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.
A non-decimal data value is considered to be an integer unless it is qualified to be a long, in which case the
letter L or l must be appended to the numeric value. Similarly, a decimal value is by default a double,
unless it is qualified by appending the letter F or f to it, in which case the number is converted to fit the
space of a float.
ANumber
= 6;
firstNumber
= 20;
realNumber
= 10F;
bigNumber
= 2.0E10;
aLongNumber
= 2L;
Alternately, a numeric variable may be declared and initialized at once. The following example has the
same effect as if we had carried out the operations separately.
byte
aNumber
=
int
firstNumber
= 20;
6;
float
realNumber
= 10F;
double
bigNumber
= 2.0E10;
long
aLongNumber
= 2L;
The assignment to the following declaration will cause syntax error, because of the
assumed default values.
Character Type
The format for declaring a character variable is the same as the format for numeric variables. However, the
method of initializing character differs, in that the value that is being assigned to the identifier must be
enclosed within single quotation marks. The following are typical ways of declaring and initializing
character variables.
char digit_nine
= '9';
char another_way
= '\u0039';
char tab
=
char newline
= '\n';
char uppercase_A
= ‘A’;
'\t';
Boolean Type
The initialization of a boolean variable follows the similar pattern as a numeric variable and character
variable. The following is a valid way of declaring and initializing a boolean variable:
boolean more = true;
Where boolean is the data type, more is the name of the variable, and true is the data value that is
assigned to the variable.
Assignment Incompatibility
A variable can be initialized wrongly. That is, the value that is assigned to it might be of the wrong type. If
this happens the compilation process will fail. The following are incompatible as shown by the compiler
error messages.
a)
int x = 2.0 ;
b)
short x = 150000;
c)
boolean x = 0;
----Configuration: j2sdk1.4.1_02 <Default>---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 <Default>---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 <Default>----
C: \chapter3\unicodeChar.java:5: incompatible types
found : int required: boolean
boolean x = 0;
^
1 error
Process completed.
Notice that in each case the compiler tells you the type of data value you are trying to assign to the variable,
followed by telling you what data value is required to be assigned to the variable.
Exercises (3a)
1.
Give the data type for each of the following data values. If a value is invalid explain why you say that
it is invalid.
a)
b)
c)
d)
e)
f)
g)
h)
2.
For each of the following statements, do the following:
a)
b)
d)
e)
3.
Declare an integer variable called noOfPatrons, with an initial value of zero.
Declare a float variable called why_Is_It with initial value of 4.5.
Declare a float variable called how_Is_It with 4. as its initial value.
Repeat (b) and (c), but this time make the variable types be double.
What will happen if you attempt to compile each of the following lines of code?
a)
b)
c)
d)
e)
4.
1024
1024.0
'\0041'
'\u0041'
'\\'
true
False
1.024E10
int x = 25.0;
float x = 1.0;
byte x = 130;
char x = 128;
boolean x = 1;
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 would be 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 to 120 over 75 to 80 be normal reading. If you were to write a program to
represent these numbers, what is the smallest data type that could be used to represent these values?
Explain.
3.4 Reference Type
A composite 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. Composite types in Java 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 chapter 6.
Class
The concept of class is fundamental construct upon which Java is built. A class serves as a blueprint or a
template for a certain type of object. Against this background all data types other than the primitive type or
the array must be addressed in terms of a class. This is evident in the way that we use a class. For instance,
going back to the class areaAndCircumference. In order to use this class we had to declare variables of the
type:
areaAndCircumference circle1;
Notice that this declaration follows the definition of how to declare primitive data type. This construct
implies that the identifier areaAndCircumference is a type and circle1 is an identifier of that type.
3.5 Operator and Operations on Data
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 four operations in the book. We will study them one by one.
Arithmetic Operator and Operations
Arithmetic Operators
Java defines five binary arithmetic operators and two unary operators. The binary operators are used to
form what are called arithmetic expressions. The format of an arithmetic expression is as follows:
operand operator operand;
Where the operands are any valid identifier or actual data value, and operator is any of five arithmetic
operators. The arithmetic operators and their respective operation are summarized in Figure 3. 4.
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
18/2
9
%
Modulus operation
x%y
25 % 7
4
Figure 3.4 Java’s five arithmetic operators.
The result of an arithmetic expression will generate different type of numeric value, depending on the type
of operands. First let us consider the numeric integral types followed by the floating-point type. The first
three operators will attempt to carry out the respective operation, as it would be done arithmetically. In the
last two, if division by zero is attempted then the operation will not be carried through. The program would
generate what is called ArithmeticException (one word), and terminate, unless special arrangement is
made to handle the exception.
Arithmetic Operations on Integers and Floating-Point Types
The operation on byte data values produces in context either a byte data value or an int data value. Listing
3.1 summarizes the result from each of the operations.
class arithmetic_on_type_byte
{
public static void main(String[] arg)
{
byte
x1 = 60,
x2 = 50,
y1 = 127,
y2 = 127;
System.out.println("byte + byte = byte " + (x1 + x2));
System.out.println("byte + byte = int " + (y1 + y2));
System.out.println("\nbyte - byte = byte " + (-x1 - x2));
System.out.println("byte - byte = int " + (-y1 - y2));
System.out.println("\nbyte * byte = byte " + (x1 * 2));
System.out.println("byte * byte = int " + (y1 * y2));
System.out.println("\nbyte / byte = byte " + (y1 / x2));
System.out.println("byte % byte = byte " + (y1 % x2));
System.out.println("\nVerify each");
}
}
Listing 3.1
The operation on short data values produces in context either a short data value or an int data value.
Listing 3.2 summarizes the result from each of the operations.
class arithmetic_on_type_short
{
public static void main(String[] arg)
{
short x1 = 250,
x2 = 100,
y1 = 32767,
y2 = 1273;
System.out.println("short + short = short " + (x1 + x2));
System.out.println("short + short = int " + (y1 + y2));
System.out.println("\nshort - short = short " + (-x1 - x2));
System.out.println("short - short = int " + (-y1 - y2));
System.out.println("\nshort * short = short " + (x1 * 2));
System.out.println("short * short = int " + (y1 * y2));
System.out.println("\nshort / short = short " + (y1 / x2));
System.out.println("short % short = short " + (y1 % x2));
System.out.println("\nVerify each");
}
}
Figure 3.2
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
Operations
Result
Example
Actual
Result
int + int
int or
10000 + 1024
11024
number too large
2147483647 + 53
-2147483596
int or
10000 - 1024
8976
number too large
-2147483647 - 53
2147483596
int
1024 * 10000
10240000
number too large
1000000000 * 500
1783793664
int or
125 / 7
17
Arithmetic Exception
125/0
int - int
int * int
int / int
or
Correct
Result
2147483700
-2147483700
500000000000
No correct result
ArithmeticExcepti
on
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.
Notes about the data type int:
Addition, subtraction and multiplication operators will either produce a value that will fit the
memory space for int, or the value will exceed the maximum size of an int. In the latter case one
cannot predict what value will be stored.
The division operator generates the quotient from the division operation, if the denominator is
other than zero. The quotient is stored but the remainder is discarded. If the denominator is a zero
however, the actual division operation would not be performed, and this would result in what is
called an ArithmeticException that is generated by the compiler. If this happens and no
arrangement was made to handle the error, the program would terminate abnormally.
The modulus operator performs division operation too, however it is the remainder from the
division, which is stored, and the quotient is discarded. If the divisor is zero, then the compiler will
halt the operation and generate the ArithmeticException message.
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.
Result
float Operations
float or
float + float
Infinity
float - float
float or
-Infinity
float * float
float
or Infinity
-float * float
float
or
float / float
float or Infinity
-float / 0.0
-Infinity
0.0/0.0
NaN
float % float
float
–Infinity
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.
2.
3.
4.
Unary operators. They have the highest priority.
Parentheses. Sub-expressions that are determined by parentheses have the next level of priority.
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.
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.
d)
2+3–4+5
2+3–4*5
2 + (3 – 4 ) * 5
11 % 4 * 2 – 14/3 + (8 –2 * -3)
a)
2+3–4+5
Reason
5 -4+5
1+5
6
The operators have the same precedence level.
Calculation is done strictly from left to right.
Result.
a)
b)
c)
b)
2+3–4*5
2 + 3 – 20
5 – 20
-15
c)
2 + (3 – 4 ) * 5
2 + (-1) * 5
2–5
-3
d)
Multiplication has higher priority
The operators have the same precedence level.
Result.
Parentheses have higher precedence
Multiplication has higher priority
Result
11 % 4 * 2 – 14/3 + (8 –2 * -3)
11%4*2-14/3+(8 + 6)
11%4*2 – 14/3 + 14
3 *2 – 14/3 + 14
6 – 14/3 + 14
6 – 4 + 14
2 + 14
16
Unary (-) has highest precedence
Parentheses have nest highest precedence
Modulus, multiplication, and division have same
level of precedence. They are executed strictly from left to right.
Addition and subtraction will be done after.
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 data_types
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:
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 <Default>---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. All six
operators are binary operators. They are used in conjunction with primitive numeric types including 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
<=
Less than or equal to
x <= y
100 <= 200
>
Strictly greater than
x>y
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.
12.
13.
System.out.println("byte x = 20 != char z = 'y'" + "\t" +
(x != z));
System.out.println("byte x = 20 == long y = 20" + "\t" +
(x == y));
System.out.println("float b = 100.0F != double c = 100.0" + "\t" +
(b != c));
14.
15.
System.out.println("int a = 100 == double c = 100.0" + "\t" +
(a == c));
}
16. }
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.
10.
System.out.println("x == y " + (x == y));
System.out.println("x != z && x == y " + (x != z && x == y));
11.
12.
13.
14.
System.out.println();
System.out.println("x == z " + (x == z));
System.out.println("x == y " + (x == y));
System.out.println("x == z && x == y " + (x == z && x == y));
15.
16.
17.
18.
19.
System.out.println();
System.out.println("x == z " + (x == z));
System.out.println("x == y " + (x == y));
System.out.println("x == z || x == y " + (x == z || x == y));
System.out.println();
20.
21.
22.
System.out.println();
System.out.println("x == z " + (x == z));
System.out.println("x == y " + (x == y));
23.
System.out.println("(!(x == z || x == y)) " + !(x == z || x == y));
24.
25.
26.
27.
28.
29.
System.out.println();
boolean flag = x == z || x == y;
System.out.println("flag is " + flag);
}
30. }
Listing 3.xx
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
3.6 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
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.
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.
2.
3.
4.
5.
class testGetData
{
public static void main(String[] arg)
{
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.
10.
11.
System.out.println("Your name is: " + name + "\nYour age
is: " + x + "\nYou have $" + y);
}
}
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.
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.
Figure 3.31 Input dialog box when Line 6 of Listing 3.15 is called.
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.
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
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", JOptionPane.INFORMATION_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.
JOptionPane.INFORMATION_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",
JOptionPane.INFORMATION_MESSAGE);
14.
}
15. }
Listing 3.17
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";
s = s + "\nlet alone how much money he has";
15.
16.
17.
18.
19.
20.
JTextArea text = new JTextArea(s, 10, 20);
JScrollPane pane = new JScrollPane(text);
JOptionPane.showMessageDialog(null, pane, "Personal Data",
JOptionPane.INFORMATION_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.
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.
16.
17.
18.
19.
20.
21.
22.
23.
24.
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("0.00");
String s = "";
s = s + df.format(x);
JTextArea text = new JTextArea(s, 3, 5);
JScrollPane pane = new JScrollPane(text);
JOptionPane.showMessageDialog(null, pane, "Formatting numbers",
JOptionPane.INFORMATION_MESSAGE);
25.
26. }
}
Listing 3.19 Formatting decimal numbers.
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",
JOptionPane.INFORMATION_MESSAGE);
30.
}
31. }
Listing 3.20 Formatting local currency.
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", JOptionPane.INFORMATION_MESSAGE);
33.
}
34. }
Listing 3.21 Formatting number as percentage.
Figure 3.40 shows the output from Listing 3.21.
3.7 Pitfalls
3.8 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.
3.9 Programming Projects