0% found this document useful (0 votes)
16 views10 pages

Chapter 3

see

Uploaded by

Preksh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views10 pages

Chapter 3

see

Uploaded by

Preksh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Constants-Variables and Data Types

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

Numeric Constants Character Constants

Integer Real Character String


Constant Constant Constants Constant
s s s

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

Decimal Integer Constants


Decimal integer constants consist of a set of digits, 0 through 9, preceded by an optional
minus sign.

Examples:- 139, -341, 0, 654321


Note:- Embedded spaces, commas, and non-digit characters are not permitted between digits.

Examples:- 16 720, 30.000, $1000 (are all illegal numbers).


Octal Integer Constants
An octal integer constant consists of any combination of digits from the set 0 through 7,
with a leading o or O. some examples of octal integers are:

Examples:- O39, O465, o641, o23

Hexadecimal Integer Constants


A sequence of digits preceded by ox or OX is considered as hexadecimal integer (hex
integer). They may also include alphabets A through F or a through f. a letter A through F
represents the numbers 10 through 15.

Examples:- OX5, OX9E, oxbcd, oxa2


Note:- We rarely use octal and hexadecimal numbers in programming.

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.

Examples:- 0.0083, -0.75, 435.36


These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part, which is an integer. It is possible that the number may not
have digits before the decimal point or digits after the decimal point.

Examples:- 325., .93, -.53 (are all valid real numbers).


A real number may also be expressed in exponential (or scientific) notation. For example,
the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 102.
The general form is:

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.

Examples:- 0.53e4, 10e-2, 1.5e+5, 3.25E3, -1.3E-1


Note:- Embedded white (blank) space is not allowed, in any numeric constant.

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.

Single Character Constants


A single character constant (or simply character constant) contains a single character
enclosed within a pair of single quote marks. The character may be alphabet, digit, special
character and blank space.
Examples:- ‘3’, ‘Y’, ‘:’, ‘ ’
Note:- The character constant ‘5’ is not the same as the number 5. The last constant is a blank
space.

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.

Examples:- “Java Programming”, “”2013”, “GOOD MORNING”, “?...!”, “6+3”, “A”

Backslash Character Constants


Java supports some special backslash character constants that are used in output
methods. For example, the symbol ‘\n’ stands for newline character. A list of such backslash
character constants is given in below table. Note that each of them represents one character,
although they consist of two characters. These characters combinations are known as escape
sequences.

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.

A variable name can be chosen by the programmer in a meaningful way so as to reflect


what it represents in the program.

Examples:- average, height, total_height, classStrength etc.


As mentioned earlier, variables name may consist of alphabets, digits, the underscore ( _ )
and dollar character ($) subject to the following conditions:

1. They must not begin with a digit.


2. Uppercase and lowercase are distinct. This means that the variable Total is not same as total
or TOTAL.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
Data Types
Every variable in Java has a data type. Data types specify the size and type of values that
can be stored. Java language is rich in its data types. The variety of data types available allows
the programmer to select the type appropriate to the needs of the application. Data types in Java
under various categories are shown in below figure.

DATA TYPES IN JAVA

Primitive Non-Primitive
(Intrinsic) (Derived)

Numeric Non-Numeric Classes Arrays

Integer Character Interface

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

byte short int long

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.

TYPE SIZE MINIMUM VALUE MAXIMUM VALUE


byte One byte -128 127
short Two bytes -32,768 32,767
int Four bytes -2,14,74,83,648 2,14,74,83,647
long Eight bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807
It should be remembered that wider data types required more time for manipulation and
therefore it is advisable to use smaller data types, wherever possible. For example, instead of
storing a number like 50 in an int type variable, we must use a byte variable to handle this
number. This will improve the speed of execution of the program.

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 Types


Integer types can hold only whole numbers and therefore we use another type known as
floating point type to hold numbers containing fractional parts such as 28.31 and -3.654. There
ate two kinds of floating point storage in Java as shown in below figure. They are float and
double.

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.

TYPE SIZE MINIMUM VALUE MAXIMUM VALUE


Float 4 bytes 3.4e-038 3.4e+038
double 8 bytes 1.7e-308 1.7e+308

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.

Note:- A variable must be declared before it is used in the program.

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:

<Data Type> <Variable1>, <Variable2>, …………………., <VariableN>;

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;

Giving Values to Variables


A variable must be given a value after it has been declared but before it is used in an
expression. This can be achieved in two ways:
1. By using an assignment statement
2. By using a read statement

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’;

We can also string assignment as shown below:

x = y = z =0;

It is possible to assign a value to a variable at the time of its declaration. This takes the
form:

<Data Type> <VariableName> = <Value>;

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.

The following are valid Java statements:

float X, Y, Z; // Declares three float variables


int m=5, n=10; // Declares and initializes two int variables
int , n =10; // Declares m and n and initializes n

Read Statement
We may also give values to variables interactively through the keyboard using the
read.Line( ) method as illustrated in below program.

Program:- Reading data from keyboard.


import java.io.DataInputStream;
class Reading
{
public static void main(String args[])
{
DataInputStream input=new DataInputStream(System.in);
int intNumber=0;
float floatNumber=0.0f;
try
{
System.out.println("Enter an integer");
intNumber=Integer.parseInt(input.readLine());
System.out.println("Enter a floating point number");
floatNumber=Float.valueOf(input.readLine()).floatValue();
}
catch (Exception e)
{
}
System.out.println("intNumber="+intNumber);
System.out.println("floatNumber="+floatNumber);
}
}

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.

A constant is declared as follows:

<final> <Data Type> <Symbolic-Name> = <Value>;

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.

You might also like