Data Types And Operations - School of Computing and ...
Data Types And Operations On Data
• Objectives
• To establish the difference between primitive data types and composite data types.
• To be able to classify the primitive data types.
• To differentiate between integral data type and floating point types.
• To know the data range for each primitive type.
• To know the storage requirement for each primitive type.
• To know the conditions for data conversion.
• To determine assignment assignability.
• To be able to evaluate arithmetic expressions, relational expressions, and logical 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 one does not understand data types, data values, and the amount of memory space required for each type of data.
The first half of the lesson introduces you to a comprehensive study of the fundamental data types and how they relate to writing programs in an object oriented form. The lesson begins by introducing us to the two broad categories of data types. These are described as primitive types and composite types. This section of the lesson discusses in detail the primitive types by their names, the amount of memory required to store data for each of them, and the operations that can be performed on each of them. The section closes with the discussion of what expressions are and how they are evaluated.
The second half of the lesson introduces you to the composite data types. The types that are discussed are arrays and classes. A brief introductory remark will be made about the concept of arrays. The lesson concludes with a study of Java’s fundamental classes as composite type.
Data Types
We established in the introduction that data is vital to a program. The data that is to be used by a program must be stored in primary memory in order for the processor to process it. The Java programming language specifies two categories of data values. One type of values is called primitive values. The other type is called composite values. Primitive types are the building blocks of the language. They are indigenous to the language. They do not have to be constructed. Composite types on the other hand are constructed from the primitive types; if they are not provided as supplement to the language, then the programmer will have to construct them.
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. Elements of each type require different amount of memory space to store the actual data value. For instance, if ten people are going on a journey and want to travel together, it would most likely require the use a minivan instead of a car; or if you want to study the molecular structure of an organism, then you would be better of using a microscope rather than a telescope. In terms of programming the programmer should pay attention to the size of the data value to be stored, and to instruct the machine how much space it must reserve for each data value. This will have a direct impact on the kind of manipulation that can be performed on the data value. Figure 3.1 shows the hierarchy of the data types.
Figure 3.1 Java data types.
Primitive Data Types
The primitive data types in Java falls into three categories. These are the integral types, the floating-point types, and the logical type. The integral type consists of two sub-types. These are the integer data types and the character type. We say integral type because we can represent elements of their kind by integer values.
Integral Types
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. Their names are 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 3.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 3.2 Java integer data types along with the storage requirements and range of values for each type
By default an integral value is an int, unless otherwise specified. For instance, the number 1024 falls within the range of integer values; hence, by default it 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.
Character Type
The character data type named char is any printable symbol found on the keyboard or certain sequences of characters forming one piece of instruction to the machine. In either case, each type requires 16 bits (2 bytes) of memory to store the char value. There are other arrangements to store character values. One popular scheme is called the ASCII set. It uses 8 bits (1 byte) store the data. This scheme can represent a maximum of 256 character values, but as you see Java can accommodate 65,536 character values. 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 letters A thru F represents 10 thru 15. Figure 3.3 shows the decimal range and the 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 3.3 Character data type, storage requirements and their decimal and Unicode ranges.
The Unicode character set comprises of ordinary characters and the escape sequence of characters. Ordinary 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.
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 |Decimal Value|Unicode |
| | | | |
|'\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 3.4 Character escape sequences, their meaning, integer and Unicode representations.
Floating Point Types – float, double
As mentioned earlier, floating-point numbers are primitive types. There are two floating-point data types in Java. These are called float and double. Floating points values are double by default. A numeric value may be appended with f or F to indicate that the number is a floating-point number. For instance, 1024F indicates to Java that this number must be treated as a floating-point number. Hence the numbers 1024.0 and 1024F are both floating-point numbers. Figure 3.5 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 3.5 Java floating-point data types along with storage requirement and range for each type.
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 relational and logical expressions are to be evaluated.
Declaring And Initializing Variables
In Java every variable must be declared before it can be used. The format for declaring any of these data types is as follows:
data_type identifier;
Where data_type is a valid data type and identifier is the name of the variable representing the type. Each declaration must terminate with a semicolon, unless you are specifying a series of variables, which are all the same type. In this case a comma must separate each variable; the last one must be terminated with a semi-colon.
Numeric Types – Integers and Floating-Point
The following are typical declarations for numeric variables:
byte aNumber;
int firstNumber;
float realNumber;
double bigNumber
long aLongNumber;
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 value 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 ----
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 = 6;
int firstNumber = 20;
float realNumber = 10F;
double bigNumber = 2.0E10;
long aLongNumber = 2L;
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, whether the value is an ordinary value or an escape sequence character. The following are typical ways of declaring and initializing character variables.
char digit_nine = '9';
char another_way = '\u0039';
char tab = '\t';
char newline = '\n';
char uppercase_A = ‘A’;
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, called more:
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 three examples are incompatible, as shown by the compiler error messages.
a) int x = 2.0 ; ----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.
b) short x = 150000; ----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.
c) boolean x = 0;
----Configuration: j2sdk1.4.1_02 ----
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) 1024
b) 1024.0
c) '\0041'
d) '\u0041'
e) '\\'
f) true
g) False
h) 1.024E10
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.
d) Declare a float variable called how_Is_It with 4. as its initial value.
e) 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 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.
Operators 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 three operations in this lesson.
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 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.
Integer arithmetic yields integer result. The first three operators ( +, -, * ) carry out the respective operation as they would be done in ordinary arithmetic. The division ( / ) does not have the usually arithmetic meaning. Instead, it defines the quotient of the division. The remainder is discarded. Similarly the modulus ( % ) defines the remainder from the division process. The quotient is discarded.
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.
The arithmetic operators and their respective operation are summarized in Figure 3. 6.
| | | | | |
|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.6 Java’s five arithmetic operators.
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 Operations on byte data values.
[pic]
ListiFigure 3.7 Arithmetic results on byte data.
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");
}
}
Listing 3.2 Operations on short data values.
[pic]
Figure 3.8 Results from arithmetic operations on short data value.
The operation on int data values produces in context either an int value, the number is too large, or execution error. Figure 3.9 shows the possible results from arithmetic operations on int data value.
| | | | | |
|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.9 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 generate the ArithmeticException message and halt the operation.
The data type float can be summarized as shown in Figure 3.10. 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.10 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. If this is the case consideration must be given to the following conditions:
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.
The result for the data value double is the same form as that of the float data type.
Unary Operators
The operators ( + ) and ( – ) are called unary operators when they precede a numeric value or a numeric identifier. The ( + ) operator does not present any 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.
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, the order evaluation may be altered based on any or all of the following criteria:
1. Unary operators. They have the highest priority. They are done first.
2. 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. 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 33 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.3 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. See Listing 3.4.
1. class short_
2. {
3. public static void main(String[] arg)
4. {
5. short s = 8;
6. s = s + 2;
7. }
8. }
Listing 3.4
----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) ;
Converting Algebraic Expression
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 Operations
There are six 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. 11 Summarizes these 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.11 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.5 shows the primitive types being compared. Notice that the compiler did not flag any syntax error. See result in Figure 3.12.
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. }
Listing 3.5
[pic]
Figure 3.12 Results from relational expressions.
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 = 200;
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 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 (||). Listing 3.6 shows the use of the logical operators. The corresponding output is shown in Figure 3.14.
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.6
[pic]
Figure 3.14
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.14 Line 26.
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.
-----------------------
User-defined
Classes
Class
Array
long
int
short
byte
float
boolean
Floating-Point
Integral Types
Composite Types
Primitive Types
Integers Type
Java Classes
(JDK1.4.2)
double Types
Character
Data types
char
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- chemistry webquest six major types of chemical reactions
- types of chemical reactions lab
- science test review 2
- safety in the science classroom assessment 4
- chapter 1 science skills
- class rules and expectations
- syllabus 9th grade physical science
- data types and operations school of computing and
- 7th grade science home hart county schools