Chapter 3
Chapter 3
Introduction
A programming language is designed to process certain kinds of data consisting of
numbers, characters and strings and to provide useful output known as information. The task of
processing data is accomplished by executing a sequence of instructions constituting a program.
These instructions are formed using certain symbols and words according to some rigid rules
known as syntax rules (or grammar). Every program instructions must conform precisely to the
syntax rules of the language.
Like any other language, Java has its own vocabulary and grammar. Here we will discuss
the concepts of constants and variables and their types as they relate to Java language.
Constants
Constants in Java refer to fixed values that do not change during the execution of a
program. Java supports several types of constants as illustrated in below figure.
JAVA CONSTANTS
Integer Constants
An integer constant refers to a sequence of digits. There are three types of integer
constants. They are:
1. Decimal Integer Constants
2. Octal Integer Constants
3. Hexadecimal Integer Constants
Real Constants
Integer numbers are inadequate to represent quantities that vary continuously, such as
distances, heights, temperatures, prices, and so on. These quantities are represented by numbers
containing fractional parts like 12.324. Such numbers are called real (or floating point) constants.
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The
exponent is an integer with an optional plus or minus sign. The letter e separating the mantissa
and the exponent can be written in either lowercase or uppercase.
Exponential notation is useful for representing numbers that are either very large or very
small in magnitude. For example, 7500000000 may be written as 7.5E9 or 75E8. Similarly,
-0.000000368 is equivalent to -3.68E-7.
String Constants
A string constant is a sequence of characters enclosed between double quotes. The
characters may be alphabets, digits, special characters and blank spaces.
CONSTANT MEANING
‘\b’ back space
‘\f’ form feed
‘\n’ new line
‘\r’ carriage return
‘\t’ horizontal tab
‘\’’ single quote
‘\”’ double quote
‘\\’ backslash
Variables
A variable is an identifier that denotes a storage location used to store a data value.
Unlike constants that remain unchanged during the execution of a program, a variable may take
different values at different times during the execution of the program.
Primitive Non-Primitive
(Intrinsic) (Derived)
Floating-Point Boolean
Integer Types
Integer types can hold whole numbers such as 123, -54, and 5639. The size of the values
that can be stored depends on the integer data type we choose. Java supports four types of
integers as shown in below figure. They are byte, short, int and long.
Integer
Note:- Java does not support the concept of unsigned types and therefore all Java values are
signed meaning they can be positive or negative. The table below shows the memory size and
range of all the four integer data types.
Note:- We can make integers long by appending the letter L or l at the end of the number.
Examples:- 123L or 123l
Floating Point
Float Double
The float type values are single-precision numbers while the double types represent
double-precision numbers. The table below gives the size and range of these two types.
Note:- Floating point numbers are treated as double-precision quantities. To force them to be in
singlprecision mode, we must append f or F to the numbers.
Examples:-1.23f and 7.56923e5F
Double-precision types are used when we need greater precision in storage of floating
point numbers. All mathematical functions, such as sin, cos and sqrt returns double type values.
NaN (Not-a-Number)
Floating point data types support a special value known as Not-a-Number (NaN). NaN is
used to represent the result of operations such as dividing zero by zero, where an actual number
is not produced. Most operations that have NaN as an operand will produce NaN as a result.
Character Type
In order to store character constants in memory, Java provides a character data type
called char. The char type assumes a size of 2 bytes but, basically, it can hold only a single
character.
Boolean Type
Boolean type is used when we want to test a particular condition during the execution of
the program. There are only two values that a boolean type can take: true or false. Boolean type
is denoted by the keyword boolean and uses only one bit of storage.
Note:- All comparison operators return boolean type values. Boolean values are often used in
selection and iteration statements. The words true and false cannot be used as identifiers.
Declaration of Variables
In Java, variables are the names of storage locations. After designing suitable variable
names, we must declare them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration (in the program) decides the scope of the variables.
A variable can be used to store a value of any data type. That is, the name has nothing to
do with the type. Java allows any properly formed variable to have any declared data type. The
declaration statement defines the type of variable. The general form of declaration of a variable
is:
Note:- Variables are separated by commas. A declaration statement must end with a semicolon.
Examples
int count;
float r, a, c;
double pi;
byte b;
char c1, c2, c3;
Assignment Statement
A simple method of giving value to a variable is through the assignment statement as
follow:
<Variablename> = <Value>;
Examples
initialValue = 0;
finalValue = 10;
yes = ‘Y’;
x = y = z =0;
It is possible to assign a value to a variable at the time of its declaration. This takes the
form:
Examples
int finalValue = 10;
char yes = ‘Y’;
double avg = 75.25;
Note:- The process of giving initial values to variables is known as the initialization. The ones
that are not initialized are automatically set to zero.
Read Statement
We may also give values to variables interactively through the keyboard using the
read.Line( ) method as illustrated in below program.
Output
Enter an integer
10
Enter a floating point number
25.7525
intNumber=10
floatNumber=25.7525
The readLine( ) method (which is invoked using an object of the class DataInputStream)
reads the input from the keyboard as a string which is then converted to the corresponding data
type using the data type wrapper classes.
Note:- We have used the keyword try and catch to handle any errors that might occur during
the reading process. Java requires this.
Scope of Variables
Java variable are actually classified into three kinds:
1. Instance Variables
2. Class Variables
3. Local Variables
Instance and class variables are declared inside a class. Instance variables are created
when the objects are instantiated and therefore they are associated with the object. They take
different values for each object. On the other hand, class variables are global to a class and
belong to the entire set of objects that class creates. Only one memory location is created for each
class variables.
Variables declared and used inside methods are called local variables. They are called so
because they are not available for use outside the method definition. Local variables can also be
declared inside program blocks that are defined between on opening brace “{“ and a closing
brace “}”. These variables are visible to the program only from the beginning of its program
block to the end of the program block. When the program control leaves a block, all the variables
in the block will cease to exist. The area of the program where the variable is accessible (i.e.,
usable) is called its scope.
We can have program blocks within other program block (called nesting) as shown in
below figure.
Block-1 Block-1
{
int x = 10;
{ Block-2
:
:
int m = 10;
:
:
}
{
: Block-3
:
int n = 20;
:
:
}
Each block can contain its own set of local variable declarations. We cannot, however,
declare a variable to have the same name as one in an outer block. In above figure, the variables
x declared in Block1 is variable in all the three blocks. However, the variable m declared in
Block2 is available only in Block2, because it goes out of the scope at the end of Block2.
Similarly, n is accessible only in Block3.
Note:- We cannot declare the variable x again in Block2 (This is perfectly legal in C and C++).
Symbolic Constants
We often use certain unique constants in a program. These constants may appear
repeatedly in a number of places in the program. One example of such s constants is 3.142,
representing the value of the mathematical constant “pi”. Another example is the total number
of students whose mark-sheets are analyzed by a “test analysis program”. The number of
student, say 50, may be used for calculating the class total, class average, standard deviation, etc.
We face two problems in the subsequent use of such programs. They are:
1. Problem in modification of the program
2. Problem in understanding the program.
Modifiability
We may like to change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of
calculations or the number 50 to 100 to process the test result of another class. In both the cases,
we will have to search throughout the program and explicitly change the value of the constant
wherever it has been used. If any value is left unchanged, the program may produce disastrous
output.
Understandability
When a numeric value appears in a program, its use is not always clear, especially when
the same value means different things in different places. For Example, the number 50 may
mean the number of student at one place and the “pass mark” at another place of the same
program. we may forget what a certain number meant, when we read the program some day
letter.
Assignment of a symbolic name to such constants frees us from these problems. For
example, we may use the name STRENGTH to denote the number of students and PASS_MARK
to denote the pass marks required in a subject. Constant values are assigned to these names at
the beginning of the program. Subsequent use of the names STRENGTH and PASS_MARK in
the program has the effect of causing their defined values to be automatically substituted at the
appropriate points.
Examples
final int STRENGTH =100;
final int PASS_MARK = 50;
final float PI = 3.14159;
Note:-
1. Symbolic names take the same form as variable names. But, they are written in CAPITALS to
visually distinguish them from normal variable names. This is only a convention, not a rule.
2. After declaration of symbolic constants, they should not be assigned any other value within
the program by using an assignment statement. For example, STRENGTH = 200; is illegal.
3. Symbolic constants are declared for types. This is not done in C and C++ where symbolic
constants are defined using #define statement.
4. They can not be declared inside a method. They should be used only as class data members
in the beginning of the class.