Professional Documents
Culture Documents
Class 9 CH 4 Values and Datatypes
Class 9 CH 4 Values and Datatypes
2
4 5 7 9 10 11 12
4.1 INTRODUCTION
Chapter Outline
fundamentals
In any language, there are some
4.1 Introduction that you need to know before you can write evern
the most elementary programs. This chapter
4.2 Java Character Set
introduces Java fundamentals to you so that you
4.3 Tokens
You
4.4 Concept of Data Types may start writing your own Java programs.
will be learning about Java tokens such as
4.5 Variables
keywords, identifiers, literals, operators and separators
4.6 Constants along with data types, variables, constants,
operatorsand expressions. Let us now begin our
discussion with Java tokens. But before that let us
briefly know 'What is character set of Java ?
45
46
COMPUTER APPLICATIONS.
other sign.
represents
any letter, digit or any
Java uses the Unicode character set. Unicode is a two-byte character code set thas
characters representing almost all characters in almost all human alphabets and wei has
systems around the world including English, Arabic, Chinese and many more. writing
The first 128 characters in the lnicode character set are identical to the common AsCu
ISCII
character set. The second 128 characters are identical to the upper 128 characters of the ISo
Latin-1 extended ASCIl character set. It's the next 65,280 characters that present problems.
You can refer to a particular Unicode character by using the escape sequencelu followed bya
four digit hexadecimal number.
For example,
4.3 Tokens
In a passage of text, individual words and
punctuation
marks are called tokens or lexical-units. In fact,
every unit Token
that makes a sentence is token. Java has the
a
following
types of tokens The smallest
individual unit ina
Keywords Identifiers program is known as a Token.
Literals > Punctuators
Operators
4.3.1 Keywords
Keywords are the words that convey a special meaning to Keywords
the language compiler. These are reserved for special
purpose and must not be used as normal identifier names.
Keywords are the words that
convey special meaning
a
to the
The following character sequences are reserved for use asS language compiler.
keywords and cannot be used as identifiers:
abstract continue for new switch
NOTE The keywords const and goto are reserved words, even though they are
Words true, false and not currently used. true, false, and null might seem like keywords, but
null are not keywords they are actually reserved-words used as literals and cannot be used as
but reserved words.
identifiers.
4.3.2 ldentifiers
Identifiers are fundamental building blocks of a program and are used as the general
terminolo8y for the names given to different parts of the program viz. variables, objects,
classes, functions, arrays etc.
Identifier forming rules of Java state the following
Identifiers
Identifiers can have alphabets, digits and underscore
and doller sign characters. Identifiers are the names given
They must not be a keyword or boolean literal or null to identify different building
literal. blocks of a program such as a
variable, class, method etc.
They must not begin with a digit.
They can be of any length.
Java is case sensitive i.e., upper-case letters and lower-case letters are treated differently.
4.3.3 Literals
constants) are data items that arefized data lava zl
values. ava albrnn,
Literals (often referred to as
kinds of literals:
(i) Floating-literals ii) Bornlear literals
() Integer-literal
(iv) Character-literal (v) String-literal fviy The null literal
() Integer Literals
An integer nsan y
Integer literals are whole numbers without any fractional part. have at ieast ne
The method of writing integer constants has been specified in dig a
must o ConZiat
the adjacent box. decimal oim.it
Java allows three types of integer literals: contain either o r - ig
A number with o ignis
Decimal (base 10) assumed to be positve
Octal (base 8) Commas cannot appear in
an integer constant
Hexadecimal (base 16)
Thus number 12 will be written either as 12 (as decimal), 014 (as octal) and 0XC (as
hexadecimal).
The suffix1 or L andu or
U attached to any constant forces it to be
represented as a long and
unsigned respectively.
digits including a decimal point between digits. The rule for preceding it. A real literal
writing a real constarnt in fractional form is given in the adjacent with no sign is assumed to
box. be positive
VALUES AND
DATA TYPES 49
A real literal in exponent form consists of two parts : mantissa and exponent. For instance, 5.8
can be written as 0.58 x 10 = 0.58 EO01 where mantissa part is 0.58 (the part appearing before E)
and exponent part is 1 (the part appearing after E). E01 represents 10. The rule for writing a
real literal in exponent form is given in the box below.
adjacent box.
Java allows you to have certain nongraphic characters in character constants. Nongraphic
characters are those characters that cannot be typed directly from keyboard e.g., backspace, tabs,
carriage-return etc. These non-graphic characters can be represented by using escape
by backslash (\) followed by one or more
SEquences. An escape sequence is represented a
characters.
Following table (Table 4.1) gives a listing of escape sequences
50
COMPUTER APP
Table 4.1 Escape Sequences in Java PPLCATION
Escape Sequence
Nongraphic Character
Audible bell (alert)
Backspace
Formfeed
Newline or linefeed
Carriage Return
Horizontal tab
Vertical tab
Backslash
Single quote
Double quote
Question mark
on Octal number (On
represents the number in octal)
xHn Hexadecimal number (Hn
represents the number in
uHn Unicode character hexadecimal)
represented through its hexadecimal code Hn.
Null
In the above table, you see
canbe typed from the sequences representing \,," and ? also.
keyboard but when Though these characters
meaning and have a special purpose, used without escape sequence, these
carry a special
sequences should be used. however, if these are to be
typed as it is, then escape
The following are some
examples of char literals:
'a % 1' '\u03a9' "\uFFFF '\177 Q
VString Literals
Multiple Character' constants are treated as string-literals. The rule
for writing a
string-literal is given in the adjacent box. A A
string literal is a
string-literal is of class type String. sequence of zero or more
Following are legal string literals characters surrounded by
double quotes. Each
"abc" character may be repre-
size 6 bytes (each character takes 2 bytes) sented by an
escape
"ab" size 4 bytes ( \a is one character) sequence.
"Seema \'s pen" size 22 bytes (11 characters, 2 bytes each)
(la and \" are escape sequences)
4.3.5 Operators
Operators are special symbol that cause an action to take place.
The following 37 tokens are the operators in Java:
?
&& ++
&
Now depending upon your requirements for the decimal precision of the data, you can select
from float or double types.
For example, you can store the salary values of an employee using a data
NOTE variable of the float type. To store decimal values with a higher degree of
By default, Java precision, such as values calculated using the functions such as sin( ) and
assumes the fractional
sqrt(), you use the double datatype.
numbers to be of double
unless By default, Java treats fractional numbers as of double datatype, e.g., if you
datatype
specified. To explicitly write 0.234, it will be treated as a double value. To explicitly specify it to be
their type, use of float type, use suffix F or f. i.e., write 1.234f or 1.234F. Similarly if you
specify
suffixes F and D. use suffix d or D, it means double i.e., 1.234D or 1.234d means it is a
double value.
Following Table 4.5 lists the size and range of boolean datatype.
Range Remarks
Type Size Description
Logical or true or false. Useful in logic test
boolean Java reserves 8 bits but
only uses 1 bit. boolean values with if.
4.5 Variables
whose values
Variables represent named storage locations,
can be manipulated during program
run. For instance, to Variable
store name of a student and marks of a student during
a
A Variable is a named memory
locations.
program run, we require named storage location, which holds a data
Variables, called as symbolic variables, serve the purpose. value of a particular data type.
typevariablename;
where type is any Java data type and variablename is the name of the variable. A variablename is
identifier. Thus all rules of identifier naming apply to the name of a variable. Following
declaration creates a variable age of int type:
int age;
Following are some more examples of variable declarations
double pival;
fioat res;
The above declaration creates a variable
namely pival of type double and a variable namely res
of type float.
All above given definitions are simple definitions. A simple definition consists of a type
followed by a variable-name. When more than one identifier of a type is being defined,specifera
comma-separated list of identifiers may follow the type For specifier. example,
double salary, wage
int month, day, year;
long distance, area;
4.5.2 Initialization of Variables
A first value (initial value) may be specified in the detinition ofa variable. A variable with a
declared first value is said to be an initialised
variable. Java supports two forms of variable
initialization at the time of variable definition;
int val = 1001;
1. This type of initialization can take place either inside a method or inside a class; but in initial class the declaration
should also include keyword static eg,
static intval =1001;
AND DATA TYPES
VALUES 55
a Program on BlueJ
Writing
To write a program on Bluej, follow these steps. (refer to Sections 2.6.1 and 2.6.2) :
1. Open BlueJ and click New Project button on Project menu the left. (See below) and then
provide name for your project and click Create.
2 New Project
Bluel Lookn: Chap 14
Projectdit Tools View
prog14 1
New Project
Open Project Ctrl O Recent Iterms Then provide
Open Recent name for your
Open Non Blue).. project here
Computer
Close Ctrl+ W
Save Ctrl+S
Folder name: Program 1
Save Network Fles of Lype:Ales
Cance
2. In the new project window, click on New Class button on the left, provide class name and then
double-click the added class icon from the right pane. (see below)
2 Blue: Create New Class
2 Bluek Programl
ClassName
Project Edit Tools View Help Code
Class Type
New ClasS Cass 2Bluek Program
Abstract Cass Project Edit Tools View Help
Interface
Applet New ClasS
Compiie
Unit Test
Eum
Compile
Cancel Double click the
added class icon
3. The editor window will open. Here first delete all the comments i.e., the lines within. /
You can write your own comments if you want.
Now delete everything within the code lines:
4. Now the code window will look like the one shown on the figure below, left side. Now within
the curly braces, firstly write as shown below
void myMethod()
within which you can write your code (see figure below on the right side). You can give any
other identifier in place of identifier myMethod, if you want.
56 COMPUTER APPLICATIONS-X
Code
2Code GGbdsgeele2p
Class Edit Iools Options
Compiledo Cut Copy PasteFind.Close Source Gode
Comple Undo Cut Copy Paste Find..Close Source Code
chenged
Open Editor
NIC Name of Instance: first inherited from Object/
Compile first1:
First void myMethod)
Inspect Ok Cance
Remove nspect
firstt: First Remove
Program 4.1
Write a
program to print details about you i.e., your name and age using variables.
public class First
void display()
String name = "Rohan";
intage = 16;
My name is Rohan
My age is 16
VALUES AND DATA TYPES 57
Program 4.2
Write a program to print sum of three given numbers 1221, 2332, 3443
void myMethod(){
int num1, num2, num3, sum
num1 1221;
num2 2332;
num3 3443;
sum =
num1 + num2 + num3;
System.out.println ("3 given numbers are: ") ;
Output produced is:
System.out.printin ( num1);
System.out.printin ( num2 ); 3 given numbers are
1221
System.out.println ( num3); 2332
System.out.println ("Sum = "+sum);
3443
Sum = 6996
Program 4.3
Write a program to find the perimeter of a triangle with sides measuring 10 cm, 14 cm and 15 cm.
public class Calc
Output produced is
Perimeter of triangle with sides 10 cm, 14 cm and 15 cm is 39 cm
Program 4.4
Write a program to find the side of the square whose perimeter is 20 m.
void compute()
side =perm/4;
System.out.println("The side ofsquare with perimeter 20m, is "+ side +"m") ;
Output produced is
The side of square with perimeter 20 m, is 5.0 m
Numeric
Non-numeric Classes Iinterface Arrays
4.6- Constants
Often in a program you want to give a name to a constant
value. For example, you
might have a
fixed tax rate of 0.030 for goods and a tax rate of 0.020
for services. These are constants, because
their value is not going to change when the
program is executed. It is convenient to give these
constants a name.
VALUES AND DATA TYPES 59
This can be done as follows:
class CalculateTax
public void Calc() NOTE
The keyword final
final double GOODS_TAX =
0.030; before a variable
final double SERVICE_ TAX declaration, makes it a
=
0.020; constant. Henceforth, its
value can't be changed
in the program.
The reserved word final tells the compiler that the value will not change. The names of
constants follow the same rules as the names for variables. (Programmers sometimes use all
capital letters for constants; but that is a matter of personal style, not part of the language).
Once declared constants, their value cannot be modified eg, after declaring constant
GOODS_TAX, if you issue a statement like:
Advantages of Constants
There are two big advantages to using constants
1. They make your program easier to read and check for correctness.
2. If a constant needs to be changed (for instance, a new tax law changes the rates) all
you need to do is change the declaration. You don't have to search through your
program for every occurrence of a specific number.
Program 4.5
Write a program to calculate the distance of 1056 feet in terms of yards and miles. Given fixed values
are 1 mile = 1760 yards and 1 yard = 3 feet.
publicclass Conversion
void compute()
final double yard = 3.0; //1 yard = 3 feet
taxrate / 100;
System.out.println(Tax payable is Rs. " + tax );
Output produced is
Tax payable is Rs. 6820.0
LET US REVISE
The smallest individual unit in a
program is known as a token.
Java offers five tokens:
keywords, identifiers, literals, punctuators and
operators.
Keyword is a word carrying special meaning and purpose.
Identifiers are user defined names for different parts of
underscore and doller sign characters; must not be program. In Java, identifiers can have
keyword or boolean
alphabets, digits,
literal or null literal; must not
digit; and can be of any length. begin with a
Literals are data items with fixed values.
Java allows
following literals: integer-literal (Decimal, Octal, Hexadecimal); character-literal;
string-literal. floating-literal;
Data types are means to
identify the type of data and associated operations of
Java provides two types handling it.
of data types: primitive and reference data types.
Java supports
eight primitive data types : byte, short, int, long, float, double, char and boolean.
A variable is a named memory
location, which holds a data value of a
The region of program within which a variable is
particular data types.
accessible is called its scope.
Memory locations whose values cannot be changed within the
program are called constants.
Keyword final while declaring a variable, makes it a constant.
VALUES AND DATA TYPES
61
onceptual Questions
Section A: Objective Type Questions
1. Java uses
character set.
2 Smallest individual unit in a
is
program called
3. Which of the following is not
(a) class
a
keyword ?
(c) true
(b) void
(d) public
4. Which of the following is not a token ?
(a) keywords
(b) identifiers
()statement
5.
(d) operators
Identify the illegal identifier from the
following.
(a)CHK
(b) afy
(c) 20_to_50
6. Which of the following is invalid integer? (d)Ato Z
(a) 1934
(b) 0123
(c)OXFACE
d) 01934
7. 0.625E-3 is equivalent to
a) 0.625000 (b) 625.000
(c) 0.000625
(d) none of the above
8. Which of the following does not representa character literal ?
(a) 'a (b) 1
(c) \ a (d) "a"
9. Which of the following a primitive data type in Java ?
(a) array (b) class
(byte (d) Character
10. Which of the following is not an
integeral data type in Java ?
(a) short (b) long
(c) byte (d) double
11. Which of the following is the default initial value for a long datatype ?
(a) 0 () OL
(c) long 0 (d) all of the above
12. Which keyword turns a variable declaration into constant declaration ?
Ans. A type or
datatype represents a set of possible values. When we specify that a variahle k .
certain type, we are saying what values it can hold and what sa
operations can be performed on it. Wh
we say that an expression is of a certain type, you are saying what values the hen
For example, to say that a variable is of
expression can have.
int
type says that integer values in a certain
stored in that variable. range can he
3. One of the primitive types in Java is boolean. What is the boolean
used? What are its possible values ? type ? Where are boolean values
Ans. The only values of
type boolean are true and false. Expressions of type boolean are
places where true/false values are used in
expected.
4 What is a literal?
Ans. A literal is a
sequence of characters used in a program to represent a constant value.
example,'A' literal that represents the value A, of type char, and 17L is a literal that
is a F
number 17 as a value of type represents the
long. A literal is a way of writing a value, and should not be
with the value itself. confused
5. What does the computer do when it executes a variable declaration statement? Give an
Ans. A variable is example.
a box, location, in the computer's memory that has a name. The box holds a
or
value of some
specified type. A variable declaration statement is a statement such as
int x
which creates the variable x. When the
computer executes a variable declaration, it creates the box in
memory and associates a name (in this case, x) with that box. Later in the
be referred to by name. program, that variable can
6. Write a program that
computes payment for a proofreader who is paid @Rs60/- per page proofread.
The proofreader read 134
pages in first week, 217 pages in second week, 80 pages in third week and
145 pages in fourth week.
Ans.
int pages_read;
int amt;
void compute()
pages_read = 134 + 21780 + 145;
VALUES AND
DATA TYPES
63
amt = pages_read * 60;
7Write a program that computes tax for income of Rs 12,23,423. The income upto 3,00,000 is not
taxable and the tax is computed as 15% of the taxable income.
Ans.
public class TaxCalc
public static void main (String[] args)
double tax =
taxable
0.15; *
8. Write a program to calculate the scholarship earned by Satvik who gets Rs. 750 per month for 5
years.
Ans.
public class Calculate
void scholarship()
int sch_pm =750, yearly_sch =
0, Total_sch =0;
yearly_sch = sch_pm * 12;
9. An athlete takes 18 rounds ofa triangular park with sides as 30 m, 25 m and 35 m. Write a program to
determine the total distance covered by him.
Ans.
public class Calc
voiddistance()
int side1 = 25, side2 = 30, side3 35;
int one_round 0 , dist = 0;
one_round = side1 + side2 + side3;
KEYWORDS
Constant A data item that never changes its value during a program run.
Identifier Name given by for
part of the program.
user a
SSignment
11. How many types of integer constants are allowed in Java ? How are they written?
DATA TYPES
VALUES AND 65
12. What kind of program elenments are the following
13, 'a', 4.38925, "a", main () ?
13. What kind of constants are the following
14, 011, 0Xx2A, 17, 014, OXBC1 ?
14. What is a character constant in Java? How are nongraphic characters represented in Java ?
15. Why are characters \,'," and typed using escape sequences ?
16. Which escape sequences represent the newline character and null character?
17. What is meant by a floating constant in Java ? How many ways can a floating constant be
represented into ?
21. Arectangular piece of land measures 0.7 km by 0.5 km. Each side is to be fenced with 4 rows of wires.
Write a program to determine the length of the wire needed.
22. A student's school is at a distance of 5 km 350 m from her house. She travels 1 km 70 m on foot and the
rest by bus. Write a program to determine how much distance she travels by bus.
(Hint: Use constant, 1 km =1000 meters)