Basic Constructs of JAVA
Basic Constructs of JAVA
Constructs of
2 Java
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Describe the importance of data type and variable in Java;
2. List the primitive data types in Java;
3. List the rules of naming a variable in Java;
4. Describe an assignment;
5. Describe boolean operators and relational operators; and
6. Explain about operator precedence.
X INTRODUCTION
What is a computer program? A program is a sequence of instructions that a
computer can execute to perform a task. There are two basic blocks of
programming - data and instructions - and to work with data, you need to
understand variables and data types; to work with instructions, you need to
understand control structures and subroutines (methods). This topic will focus
on how variables, data types and related concepts can be implemented in Java.
TOPIC 2 BASIC CONSTRUCTS OF JAVA W 17
2.1.1 Integer
The integer type of data is used for numbers that do not have decimals. Negative
values are also allowed. Java prepares four types of integer data, namely, int,
short, long and byte. The storage size and value range for each of this data type is
shown in Table 2.1:
In many cases, the int type data is the most practical. If the integer value used
is too large, for example, in representing the income of PETRONAS, the most
appropriate data is long0 The byte and short data type are for the use of
specific applications such as keeping files at a lower level or a larger array if the
storage space is insufficient.
In Java language, the range for the integer data type does not depend on the
machine where the Java code is executed. Unlike Java, in C or C++ language, the
int data type is different according to the machine. For the 16 bytes processor
such as the 8086, the int cell size is 2 bytes while for the 32 bytes processor such
as the Sun SPARC, the cell size is 4 bytes. For the Intel Pentium processor, the
integer data type depends on the operation system: for DOS and Windows 3.1,
the integer cell size is 2 bytes and when using the 32 bytes processor on Windows
95 or Windows NT, the cell size is 4 bytes.
18 X TOPIC 2 BASIC CONSTRUCTS OF JAVA
As the range for all types of Java data is fixed, the Java program will produce the
same results if run on any machine. This makes it easier for programmers who
wish to transfer their codes from one machine to another or between the
operational systems on the same platform.
The long type of numerical integer has the L suffix (for example 2412345600L).
The hexadecimal numbers have the initial 0x (for example 0xA9B9). Take note
that Java does not have the type of data with an unsigned descriptor as in C.
2.1.2 Real
The real data type or floating point represents numbers that have the decimal
parts. There are two types of real data types, namely, float and double. The
storage size and value range for each of these data is shown in Table 2.2 below.
Storage
Type Minimum Value Maximum Value
Capacity
float 32 bit 3.40282347E+38F 1.40239846E-45F
double 64 bit 1.797693134862+31570E+308 4.9406545645841246544E-324
The name double is used because the number from this type has two times the
precision of the float type numbers. Sometimes, it is called the variable with
double precision. In many applications, the double type is picked to represent
real numbers. This is because the float data type can only represent 7
meaningful digits (decimals). The precision of limited float data is insufficient
in most cases. One of the reasons for using it is when there is a need for quick
processing or when the real number count that needs to be stored is large.
The real number from the float type has the F suffix, for example 75.43F. The
floating point number without the suffix F such as 75.43 would be considered
double0 This is because the double data type is the default data that represents
real numbers in Java. This is different from C language that uses vjg float as
its default data type.
We could also add the D suffix to represent double type numbers. All the
floating point data types follow IEEE 754 specifications. An overflow occurs
when the range error takes place and an underflow occurs when the zero
division operation takes place.
TOPIC 2 BASIC CONSTRUCTS OF JAVA W 19
2.1.3 Characters
The character data type is represented by char0"Vjg"ukping"qrgp"kpxgtvgf"ukip"(Â)
is used to show character constant. As an example,
The char data type follows the Unicode coding scheme. Unicode was created to
facilitate the programmer in dealing with non-Roman characters. As the Unicode
was invented to handle all characters existent in all the written languages in the
world, the cell size is 2 bytes. This size allows character representation of up to
65,536 compared to the ASCII/ANSI code, which is the 1 byte code and only
allows 255 character representation. Until recently, only 35,000 character codes
were used.
Java has also allowed us to use the escape sequence for special characters as
shown in Table 2.3 below.
Although Java allows any Unicode character in the Applet or Java applications,
the question whether that character can be displayed on the Applet or console
depends on the support provided. For example, we cannot display the Kanji
character (a type of Japanese writing) on a machine that operates using Windows
95 US version.
2.1.4 Boolean
Boolean types have two values: true and false. These literals are typed
without quotes, but they represent values, not variables. Boolean-valued
expressions are used extensively in control structures and to test the mantic
expressions. Boolean values can also be assigned to variables of type boolean.
Boolean data type does not exist in C language. However, the non-zero value is
used to represent true and zero for false. In C++, a data type called bool is
used. It, too, can take either the true or false value. As C++ has a history that
relates closely to C, therefore, the exchange between the Boolean value and
integer is allowed. This means that the integer value can still be used to test a
signal. But in Java, the exchange of the boolean value and integer is not
allowed, even by using the casting operation. The following is an example of the
use of the Boolean data type to represent the status of a room.
class Test1 {
public static void main (String args[]){
boolean dark;
dark = true;
while (dark) {
System.out.println(“Switch on lights”);
dark = false;
}//while
}//main
""Ä11class
TOPIC 2 BASIC CONSTRUCTS OF JAVA W 21
ACTIVITY 2.1
SELF-CHECK 2.1
At the end of this section, you should be able to list the types of data that could
be used in developing a Java program and differentiate the four data types that
have been discussed. In the subsequent section, we will learn how to name and
declare a variable with the appropriate data type.
22 X TOPIC 2 BASIC CONSTRUCTS OF JAVA
Figure 2.1: Memory location showing the name and value of variables age
Figure 2.2: Memory location showing the name and value of variables age and name
A variable in Java is designed to hold only one particular type of data; it can
legally hold that type of data and no other. The compiler will consider it to be a
syntax error if you try to violate this rule. In the previous section, you have
learned data types that can be used in a Java program. This section will describe
how to name variables to be used according to Java specification.
Remember: Declaring a variable will involve data type and variable name.
This is important because if you fail to properly declare the right variable, the
Java program will be unable to be compiled and executed.
TOPIC 2 BASIC CONSTRUCTS OF JAVA W 23
There is also a style in naming the variable, especially if that name consists of
several words. The rule discussed above does not allow empty space characters
to be used to separate words. The most popular among the programming
community is by starting the first word with a small letter and using the capital
letter to start the next word. Character Â_Ê is not selected even though it does not
break the above rules. Below is an example of the name of variable:
student_name,total_marks,price_perunit
24 X TOPIC 2 BASIC CONSTRUCTS OF JAVA
ACTIVITY 2.2
data_type name_variable;
class Test2 {
public static void main (String args[]){
byte presentStatus;
int n;
long distanceInInches;
boolean stillStudying;
char grade;
}//main
}//class
Each declaration ought to end with Â;Ê because the declaration is a complete Java
statement. We can also declare several variables in a line such as the following
example:
class Test3 {
public static void main (String args[]){
int x, y, z;
boolean haveEaten, sleepy;
}/main
} //class
TOPIC 2 BASIC CONSTRUCTS OF JAVA W 25
class Test4 {
public static void main (String args[]){
long distanceInInches; /* distance between earth and
sun */
boolean stillStudying; //informs present status
char grade; / * grade for programming
course */
}//main
}//class
2.2.3 Constant
The variable whose value is always constant, meaning it does not change, is
known as a constant. The reserved word final is used in this constant declaration
as in the following format:
The reserved word public shows that the constant declared can be accessed and
used by any method in class where it is declared even in other classes. The word
static means that this constant has not accomplished any operation on other
objects. The word final means the value for the constant is permanent and cannot
be changed by any other Java statement.
class Test5 {
public static void main (String args[]){
class Test6 {
public static void main (String args[]){
2.2.4 Comment
As in other programming languages, comments in Java do not appear in the
output of the program. Java has three ways to write comments, which are:
class Test7 {
public static void main (String args[]){
class Test8 {
public static void main (String args[]){
Answer the following questions to test your knowledge of what you have
learned in this topic.
ACTIVITY 2.3
SELF-CHECK 2.2
State whether the variables below are valid or otherwise. For the
variables that are invalid, please state the following reasons:
(a) nameLength
(b) Name_length
(c) Import
(d) 43650BBB
(e) BBB43650
(f) touch&go
(g) touch-and-go
(h) 2nd
(i) break
(j) OUM
After reading through this section, you should be able to declare a variable with
the appropriate data type. You should also be able to differentiate the three types
of comment and how to use them.
28 X TOPIC 2 BASIC CONSTRUCTS OF JAVA
variable = expression;
Here, expression refers to data or its computation whereas variable is any name
of variable that has been declared. The expression can consist of any variable,
constant, expression or a combination of the three that is linked by the operator
such as +, -, /, * and others that can produce a value.
discount = 100;
The variable in this assignment statement is discount, and the expression is the
number 100. The computer executes this assignment statement by putting the
number 100 in the variable discount, replacing whatever was there before.
Now, consider the following assignment statement, which might come later in
the same program:
newPrice=oldPrice-discount;
TOPIC 2 BASIC CONSTRUCTS OF JAVA W 29
class Test9 {
public static void main (String args[]){
int age; //declaration of int variable
char sex; //declaration of the char variable
boolean status; //declaration of the boolean
age = 10; // assigned value 10 for age
gender = ‘M’; // assigned character ‘M’ for sex
status = false; //status has value false
}//main
}//class
Java allows both declaration and giving initial value to be executed on the same
line. For example:
class Test10 {
public static void main (String args[]){
The declaration of the variable can be placed anywhere in the code so long as it is
declared before the variable is used. However, a variable can only be declared
once in a method. The contents of the variable may change based on the last
assigned expression and it has only one value.
The same principle applies to integer types: int, short. and byte0
The value assigned to the ringgit is 100. Changing the floating point value to int
would cut off the decimal portion of the float point value. If we wish to round up
a floating point number to the nearest integer, use the Math.round method:
The sum assigned to the ringgit is 1010 Note that the use of the casting
operation"*int+ is still needed. This is because the value returned by the round
method is a long type, and a long value can only be changed to int value with the
casting operator.
The Java compiler will not give any warning if we try to change a certain number
from one type to another, which is outside the target type range. Therefore, a
good programming practice is by testing whether the intended value to be
changed is within the target type range before change can be made.
Java allows the change in value of a particular variable from one type to another
without the casting operation following the sequence below:
and
char int
A value of a type that occurs earlier in this list can be converted automatically to
a value that occurs later. For example:
int A;
double X;
short B;
A = 17;
X = A; // Acceptable; A is converted to a double
B = A; // illegal; no automatic conversion
// from int to short
Source: David J. Eck, 2006
In some cases, you might want to force a conversion that would not be done
automatically. For this, you can use casting. For example:
int A;
short B;
A = 17;
B = (short)A; // Acceptable; A is explicitly type cast to a value of type short
Source: David J. Eck, 2006
32 X TOPIC 2 BASIC CONSTRUCTS OF JAVA
You can do casting from any numeric type to any other numeric type. However,
you should note that you might change the numeric value of a number by type-
casting it. You can also type-cast between the type char and the numeric types.
The numeric value of a char is its Unicode code number. For example,
(char)97 is 'a', and (int)'+' is 43 (Source: David J. Eck, 2006).
SELF-CHECK 2.3
class Error {
public static void main (String[ ] args){
width = 15
area = length * width;
System.out.println(„Area is „ + area);
}
}
You now know how to give an initial value to a variable and perform binary
operations to numerics with different data types without losing data. In the next
section, you will learn in detail on operators and operator's operation that
involve numeric values.
2.4 OPERATOR
In developing a program, we will use mathematical operations to do the
calculation. In this topic, you will be exposed to arithmetic operations,
assignment, increment and decrement that could be used in a Java program.
2.4.1 Arithmetic
Table 1.5 below shows the operator and operation used in Java. The operation for
this operator is the same as in C language.
Operator Operation
+ Addition
Subtraction
* Multiplication
/ Division
% Residue (modulo)
The / operator refers to the integer division if both operands are integers. This
means that the results obtained are integers. If otherwise, the division is division
of real numbers. The % operator meanwhile refers to the integer residue. Look at
the examples shown in Table 2.6 below:
Operation Result
5/2 2
5.0 / 2 2.5
5.0 / 2.0 2.5
5 / 2.0 2.5
5%2 1
34 X TOPIC 2 BASIC CONSTRUCTS OF JAVA
= no = 7 no = no 7
*= no *= 7 no = no * 7
/+ no / = 7 no = no / 7
%= no % = 7 no = no % 7
This operation will change the value of the variable. Therefore, it cannot be done
on a constant, for example 7++. See several examples below:
class Test11 {
public static void main (String args[]){
int i = 1;
int j = 1;
int x = 7-++i;//the value of x is 5, and i becomes 2
int y = 7–j++;//the value of y is 6, and j becomes 2
}//main
}//class
Note that the values of x and y are different even though the original value of i
and j are the same. This is because in the third statement, the value of i is added
by 1 first before subtracting from 7, while in the last statement the original value
of j is subtracted from 7 and then only added by 1. The use of the addition and
reduction operator in the statement can cause confusion which is difficult to
trace. Therefore, the use of this operator is not encouraged in statements such as
the examples shown above. However, it can be used in cases such as follows:
int n = 0;
n++; //alternative to n = n+ 1;
These operators can be used to compare values of any of the numeric types. They
can also be used to compare values of type char.
Boolean expressions are used intensively in loop and branch statements. But you
can also assign boolean-valued expressions to boolean variables, just as you can
assign numeric values to numeric variables.
By the way, the operators == and != can be used to compare boolean values. This
is occasionally useful. For example, can you figure out what the following
program does?
class Test12 {
public static void main (String args[]){
int age = 30, height = 40;
boolean status;
status = ((age > 20) == (height > 55));
}//main
}//class
Relational operators <, >, <=, and <= are cannot be used to compare values of
type String.
Please remember that Java uses different symbols for assignments and
equivalence tests. Assignments use the symbol Â=Ê while equivalence tests use the
symbol Â==Ê. For example, the value *;"?"?"8+"is false. Java avoids the possibility
of the occurrence of errors arising from the use of the symbol Â=Ê at places where
the symbol Â==Ê is used.
If you use several operators in one expression, and if you don't use parentheses
to explicitly indicate the order of evaluation, then you have to worry about the
precedence rules that determine the order of evaluation.
TOPIC 2 BASIC CONSTRUCTS OF JAVA W 37
Table 2.10 below shows the priority level of the numeric operator including
relations.
Operators on the same line have the same precedence. When they occur together,
unary operators and assignment operators are evaluated right to left, and the
remaining operators are evaluated left to right.
For example, A*B/C means (A*B)/C, while A=B=C means A=(B=C). Let us see
more examples below.
2 + 4/2
2+2=4
(Note: 4/2 will be evaluated first as the operator / has higher priority than
operator +)
38 X TOPIC 2 BASIC CONSTRUCTS OF JAVA
(2 + 4)/2
6/2=3
(Note: The operands and operator in the parentheses will be evaluated first as
parentheses have the highest priority. Thus, 2 + 4 in the parentheses will be
evaluated first and the result will be divided with 2)
In Java, the boolean operator "and" is represented by &&. The && operator is used
to combine two boolean values. The result is also a boolean value. The result is
true if both of the combined values are true, and the result is false if either of
the combined values is false. For example, "(x == 0) && (y == 0)" is
true if and only if both x is equal to 0 and y is equal to 0.
The boolean operator "or" is represented by ||. The expression "A || B" is true
if either A is true or B is true, or if both are true. "A || B" is false only if
both A and B are false.
The && and II operators are evaluated using a shortcut method. This means in
evaluating the following statement:
If the statement or the A value variable has been evaluated as false, therefore the
statement or B value variable need no longer be evaluated to obtain the overall
value of that statement.
test = !test;
will reverse the value of test, changing it from true to false, or from false to
true.
SELF-CHECK 2.4
Statement Value
(a) 4 + 5.0 * 6
(b) (4 + 5) * 6
(c) 4+5/6
(d) (4 + 5) / 6
(e) 4+5%3
(f) (4 + 5) % 3
(g) 9%2*7/3
(h) 5.0 / 2 * 3 % 2
2. What are the values of j and k after the statement below has been
executed? Assume that value j is 5 and value k is 7 before the
statement is accomplished.
(a) k + = j;
(b) k = j++;
(c) k * =++ j*2;
(d) k / = 25 * j ;
(e) k % = j 3;
40 X TOPIC 2 BASIC CONSTRUCTS OF JAVA
In conclusion, you should have recognised the operators that could be suitably
used with arithmetic operations that will be used in a particular Java program.
x To work with data, you need to understand variables and data types which
are the focus of this topic.
x Like other programming languages, Java is rich with various constructs that
should be understood by students.
x This topic has discussed basic Java constructs that should be known by
students to enable them to write a Java program that is complete and free
from errors.
Boolean Expression
Boolean Operator Relational Operator
Data Types Variable