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

Understanding 7.5e9 in Java Constants

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)
9 views10 pages

Understanding 7.5e9 in Java Constants

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

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
[Link]( ) method as illustrated in below program.

Program:- Reading data from keyboard.


import [Link];
class Reading
{
public static void main(String args[])
{
DataInputStream input=new DataInputStream([Link]);
int intNumber=0;
float floatNumber=0.0f;
try
{
[Link]("Enter an integer");
intNumber=[Link]([Link]());
[Link]("Enter a floating point number");
floatNumber=[Link]([Link]()).floatValue();
}
catch (Exception e)
{
}
[Link]("intNumber="+intNumber);
[Link]("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.

Common questions

Powered by AI

Variable names in Java must not begin with a digit, must distinguish between uppercase and lowercase, should not be Java keywords, and should not include white space. Symbolic constants, while following the same naming rules as variables, are conventionally written in uppercase to enhance readability and differentiation from regular variables. Additionally, symbolic constants must be declared as final and cannot be reassigned a new value after their declaration .

Java uses two floating-point types, float and double, to handle real numbers. The float type represents single-precision, which is defined by appending 'f' or 'F' to the number (e.g., 1.23f). Double precision is the default for floating-point numbers in Java; no suffix is required for double precision numbers (e.g., 3.25E3). Floating-point numbers can be expressed in scientific notation, using an 'e' or 'E' to denote the exponent (e.g., 2.1565e2 means multiply 2.1565 by 10 to the power of 2).

Java forbids the use of embedded whitespace within numeric constants, such as numbers with spaces or commas (e.g., 3 000, 30.000) being illegal. This restriction ensures consistency and prevents misinterpretation of values by the compiler, maintaining programmatic integrity. However, it can impact code readability, especially with large numbers, which could become difficult to parse at a glance. Developers must use comments or formatting conventions for clarity .

Java's floating-point data types include a special value called NaN (Not-a-Number) to represent undefined or unrepresentable numerical results, such as the outcome of an operation like 0/0. Any arithmetic operation involving NaN as an operand will result in NaN. NaN is mainly used to handle scenarios where a valid number cannot be produced, ensuring program stability and ease of error checking .

Symbolic constants improve modifiability and understandability. They allow changes to be made to the constant values in one place, reducing the risk of error compared to making multiple changes across the code. Symbolic names improve the readability of the code by providing meaningful names over arbitrary numbers. They prevent unintentional changes to important fixed values because once defined, they cannot legally be reassigned within the code. This reduces potential misuse and errors while enhancing code maintenance and clarity .

Primitive data types in Java are basic types like byte, short, int, long, float, double, char, and boolean, which are not objects and have a predefined range and memory size. Non-primitive data types, such as arrays, classes, and interfaces, are derived types that can hold references to objects. For example, an int is a primitive type that holds whole numbers, whereas a class is a non-primitive type that defines objects with methods and fields .

Java's primitive data types, such as byte, short, int, and long for integers, allow programmers to choose the smallest appropriate type that accommodates the required value range. This optimizes memory usage and processing time because smaller data types require less memory and thus can be manipulated more rapidly than larger ones. For example, using a byte to store the number 50 instead of an int saves memory and can improve execution speed, as lighter memory operations are faster to perform .

Java supports three types of integer constants: Decimal, Octal, and Hexadecimal. Decimal Integer Constants consist of digits 0 through 9, optionally preceded by a minus sign (e.g., -341). Octal Integer Constants consist of digits from the set 0 to 7, prefixed with either 'o' or 'O' (e.g., O39). Hexadecimal Integer Constants use digits and letters A-F or a-f, prefixed by '0x' or '0X' (e.g., OX5).

Instance variables are defined inside a class but outside of any method, and they become part of an instance, storing unique values for each object created from the class. Class variables, declared using the static keyword in a class, are shared across all instances of the class, with only one memory location for the variable. Local variables are declared within a method or block, and they are only accessible within that method or block. They cease to exist once the method or block has completed execution .

The DataInputStream class in Java can read data from the keyboard using the readLine() method. This method reads input as a String, which must then be converted to the desired data type using wrapper classes like Integer.parseInt(). Exception handling is critical during this conversion and input process; hence, Java requires the use of try and catch blocks to manage potential IOExceptions or FormatExceptions that might occur, ensuring robust interactive input handling .

You might also like