0% found this document useful (0 votes)
8 views17 pages

Computer values and data type

The document discusses the character set and encoding in Java programming, explaining how characters, digits, and special symbols are represented in binary through encoding schemes like ASCII and Unicode. It describes the importance of tokens in Java, which are the smallest units of a program, and categorizes them into five types: reserved keywords, identifiers, literals, operators, and separators. Additionally, it outlines the rules for defining valid identifiers in Java.

Uploaded by

bholi83
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)
8 views17 pages

Computer values and data type

The document discusses the character set and encoding in Java programming, explaining how characters, digits, and special symbols are represented in binary through encoding schemes like ASCII and Unicode. It describes the importance of tokens in Java, which are the smallest units of a program, and categorizes them into five types: reserved keywords, identifiers, literals, operators, and separators. Additionally, it outlines the rules for defining valid identifiers in Java.

Uploaded by

bholi83
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/ 17

Values and D

ata Types
rHE CHARACTER SET
.,ike any other human ·
~ d ( readable I
or s tokens) and Senten anguage, program .
ces (statements) ming _languages also use Ch
. · aracters
.The character set . ,
characters that are ~a:ds~t of alphabets, letters and .
m Java langu age. some special
rhe smallest unit of Java Ian . .
rhese character set are defin::ge~s _the set of characters needed to ·t
n J p . y n1code character set - wn e Java tokens.
ava rogratnming, each d .
3asic Lexical Element. Each : ;ery character is considered as a single 1 .
>f different Java progr~""' ...... ~n lva ogram is set of statements and each stat exeme: i.e.,
......... u.1..u g exemes. ement 1s set

\ character set consists of Alphabets Di . .


► Alphabets ' gits and Special Characters
Uppercase: AB c
·················· ······ ·--····---- X Y Z
- z
· Lowercase: a b c ............ .................. ........ xy
► Digits
0123456789
► Special Characters
+ - ( ) { } [ ·] \ I / > < ; etc.

However, we all know that a computer c~ only understand binary language that is just
sequence of Os and ls. So how is it going to understand these alphabets, digits and
symbols? Here comes the concept of encoding. . _

Character Encoding
A character encoding tells the computer how to interpret raw zeroes and ones into real
characters by pairing numbers with characters. It's just like saying let's give a number
to capital 'A' that is 65 and 'B' 66 and so on upto Z. There can be similar corresponding
numbers to different l~tters, digits and symbols. Now these numbers can easily be converted
to binary number.
Words and sentences in text are created from characters and these characters are grouped
into a character set. There are many different types of character encodings, but the ones
We deal most frequently with are ASCII, 8_ - bit encodings, and Unicode-based encodings.

-------- ~~-~- ~~~~~ ==~=


To tal Co mp ute r Ap pli cat ion s - IX
Co de ti .
AS CI I (A me ric an Sta nd ard E r h or Inf orm at1 0n. Int erc han ge) is a cha rac ter -en cod ing
sch em e for rep res en tin is assigned
m
a nu mb er fro O 0 1 7 t l ng
It
Is
wa s
cha
the
rac ter
firs t
s as nu mb ers , wit h eac h let ter
cha
modern
rac ter enc odi ng sta nd ard . Mo st itiona1
ch ara cte r-e n d. ·
bas ed on ASCII, tho ug h the y sup po rt ma
ny add
Ing sch em es are
ch ara t I co
file , eac h alp hab eti c, nu me ric , or spe cia l cha rac ter is rep res ent ed
wi th c erbs: n_ an ASCII
a 7 - It bin ary nu mb er.
a pa rt of the
firs t dev elo ped an d pu bli she d in 196 3 by the X3 com mi tte e,
~S CI~ wa s
soc iat ion (ASA). Th e AS CII sta nd ard wa s firs t pu bli she d as ASA
Am en can Sta nd ard s As d 198 6.
h 10 ;rev isio ns of th~ sta nd ard bei ng pu bli she d bet we en 19 67 an
X3 .4- 19 63 , wit

Th e ASCII tab le is divided int o 3


different sec tio ns.
.
ab le, ·sy ste m cod es bet we en O ~d 31 .
► . No n Pr int er, Am eri can
CII , bet we en 32 an d 127 . Th is tab le ori gin ate s from the old
► Lo we r AS .
cha rac ter tab les . . / .
sys tem s, wh ich wo rke d on 7-b it s
Th is ~o rtio n is pr,ogratntQable; c~ ac ter
► Hi gh er ASCII ,· bet we en 12 8 an d 25
rat
5.
ing sys tem or prdgrEpn being use d. Fo
reign
are bas ed on the lan gu age of ope .
tiott. ..
let ter s are als o pl a~ in thi s sec

cti ve of the
Sta nd ard pro vid es a un iqu e nu mb er for eve ry cha rac ter , irre spe
Th e Un ico de mo der n software
ice , app lic ati on or lan gua ge. It ha s bee n ado pte d by all
pla tfo rm , dev
tra nsp ort ed thr ou gh ma ny dif fer ent pla tfo rm s, dev ice s and
pro vid ers all ow ing to be
'
app lic ati on s wi tho ut cor rup tio n. major
fou nd ati on for the rep res ent ati on ofl ang uag es an d sym bo ls in all
Un ico de for ms the , lap top s, an d sm art ph on es plu s
the Int ern et
tem s, sea rch eng ine s, bro ws ers .
op era tin g sys CS S, JSO N, etc .).
Ls, HT ML , XM L,
an d Wo rld Wi de We b (UR

Th e Un ico de Character Se t . .
/
al'l
bit (2 byt e) ch ara cte r set wh ich ca n rep res en t alm ost all hum
Th e Un ico de is a 16- rld . Th is ch ara cte r set is use d
in Javs
itin g sys tem s aro un d the wo
alp hab ets _and wr .
pr og r~ g lan gua ge. . "'"'d
• ·ta1 cu•
rti f · · cro sof t, HP , D1g i
the co Ap ple , Mi
In the yea r 199
IBM cre ate d the
3
U. nso . um o co mp an ies su ch
set > usi
as
ng the ISO -10 64 6 sta nd ard . Th
eir aim was to
dar de ch ara cte r
pro du ce a sin gle s:o
d.
> All the cha rac ter s usedin th ~ 16-bit Un ieo de ch ara cte t eet occupy the sam e space•
V a lu es a n d D a ta
T yp es
I
r se t sh a r s It . . te r se t .
► T h is c h~ a ra c te e s fi rs t 2 5 6 al u e s With th e ISO-Latin ch ar ac and .
v .J
hi h
n s th e b a si s o f th e e . m g sy st em s su c h a s Windows 3
w c on e r o p er at
a rh
W in d o w s 9 5 . f
n to th e c h a ra c t ch t de ch ar ac te r se t
► In a d d it io e rs O th e A SC II se t,
ar ac e r rs . the U ni co
fin io n a l 6 5 2 8 0 d . . co d ed ch ar ac te
de e s a n a d d it P a rt ic u, la r U Is. ti n ct ,
► You c a n re fe r
to a rb · h
n ic o d. e c h a ra c te Y u s m g t elees ca p e se q u en ce i.e.
:
• o w ed b y a fo u r d ig it h x ad ec1mal n u m b er ; for examp
\ u fo ll e
.
\u00BD v2 The fraction 1/2
\u00AE mbol
® The copyright sy
\u0022 " The double quote
\u00BC V4 The fraction 1/4
✓ bol
\u221A Square Root sym
\u0041 A Capital A

ENC E .
ESCAPE S E Q U
n
g n al a n al te rn at iv e in te rp re ta ti o
e c h a r a c te r s a re u se d to si so called es ca p e se q u en ce s o r
E sc a p h a ra c te rs . T h ey
ar e al
a se ri e s
o f p e c o d e s.o f c
e sc a ial
es ca p e se q u en ce a n d h a s spec
is a n
r p re c e d e d b y a b a c k sl a sh (\ )
h a ra c te c o m p il e r.
In Ja v a , atoc th
m e a n in g e Java
em en t, th e co m piler in te rp re ts it
n t st at
u e n c e is e n c o u n te re d in .a p ri
W h en a n eto sc a p e se q g iv en b el o w:
ac co rd in g th e ta b le

u e n c e s a v a il a b le in J a v a are:
E sc a p e se q in t. ,er
rt s a ta b in th e te x t a t th is p o
\t In se in t. :7
a c k sp a c e in th e te x t a t th is p o
\b In se rt s a b p o
J

in t.

x t a t th is
n e in th e te
In se rt s a n ew li o in_t.
\n
ia g e re tu rn in th e te x t a t th is p
\r In se rt s a c a rr t.
rm fe ed in th e te x t a t th is p o in
\f In se rt s a fo th e te x t a t th is.r-p- oin. t.
h a ra c te r in
. gle q u o te c
\' In se rt s a sm
c te r in th e te x t a t tl µ s p o m t.
. b le q u o te c h a ra
\,, In se rt s a d o u in th e te x t a t th is p o in t.
c te r
k sl a sh c h a ra
In se rt s a b a c ce,
\\ e m u st u se th e es ca p e sequen
s w
t q u o te s w1't h in---- q u o te
we want to p u
F o r e x a m p le , if
o r q u o te s:
\ " , o n th e in te ri llo!\" to me .");
("She said \"He
System.ou
O u tp u
t.
t: S
p
h
n.
e
n tln
sa id

~ ~-----~ ~~
"Hello!" to m e .
~==
Toted Computer Applications - IX
TOKENS
In eve?' h~~ language (like English), there are words and symbols which have a predefineq
mearung. Similarly, all programming languages have a set of predefined words and symbol
In Java programming language we call them tokens. s.

Ja.\>'l. toke.na are the smallest units of a Java program that are used
by the Java compiler for constructing expressions and statements.

Java program is just collection of different types of tokens, comments, and white spaces.
There are five types of tokens in Java:
► Reserved Keywords
► Identifiers
► Literals
► Operators
► Separators

Reserved Keywords

Reserved keywords are the words th~t h.ave a special predefined


purpose in a Java program.

here are a few Java keywords listed.


abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while true false
null
Valu es and Dat a Typ es .

Ide ntif iers

be ass ign ed to var iabl es,


Ide ntif iers rep res ent nam es whi ch can
tify the m.
met hod s and clas ses to uni que ly iden
nam es are call ed iden tifie rs.
In Jav a the use r (pro gra mm er) def ined

An Ex am ple
public class Test
{
public static void main(String □ args)
{
int a= 20;
}
}
tifie rs nam ely :
In the abo ve Jav a cod e, we hav e 5 iden
► Tes t: cla ss nam e.
► ma in: me tho d nam e.
► arg s: var iab le nam e.
► a: var iab le nam e.
id",
wor ds like "pu blic ", "cla ss", "sta tic" , "vo
And all oth er pre def ine d wor ds are key
"Str ing" .

Nam ing Ru les for Jav a Ide nti fier s foll owe d,
d Jav a iden tifie rs. The se rule s mu st be
The re are cer tain rule s for def inin g a vali gua ges like
The se rule s are also vali d for oth er lan
othe rwi se we get com pile -tim e erro r.
C,C++. l... 'L
> J:.t r\CWe S('O Ce cha rac ters ([A-
ters for iden tifie rs are all alp han um eric
COY' l'nO"l:
► The onl y allo wed cha rac
der sco re). .
Z],[a-~J,[0-9)), '$'( dol lar sign ) and '_' (un er.
iden tifie r as it con tain s @' - spe cial cha ract
For exa mpl e "gee k@ " is not a vali d Jav a a
[0-91) . For exa mpl e, "12 3ge eks " is a not
► Ide ntif iers sho u ld n ot sta rt wit h dig itsf
vali d Jav a iden tifie r.
► Jav a ide ntif iers are cas e-s ens
itiv e.
le to use an
► The re is no lim it on .the
len gth of the iden tifie r but it is adv isab
opt imu m len gth of 4 - 15 lett ers only . is an
Wo rds can 't be use d as an iden tifie r. For exa mp le "int whi le= 20;"
► Res erv ed
d wor d.
inv alid stat em ent as whi le is a rese rve

The foll owi ng are som e vali d Ide ntif iers :



rollno emp loye e_n ame A_Z
BASICSAL Basicsal
$1 $A basicsal

A25833C678 _sto ck_ no AsialndiaOilCorporationEmployeeName


sum di
James $r4r emp loye es prog ram mer
- Total Computer Application s - IX
The followi ng are some invalid Identifiers:

Identifier name Reason why they are invalid


Student-ro ll-no Contains special character hyphen(-)
Employee. data Dot (.) cannot be a part of an identifier
-
9 only numeral cannot be an identifier
12345 ~nly num~rals cannot be an identifier
for reserverd keywords cannot be an identifier
8A Starting with a numeral

Literals or Constants
A literal or constant, in Java, .refers to a fixed value that does not change during th
-execution of the program. Java supports several types of constants.

Integer Real Character String Boolean

Decimal Octal Hexadecimal .

1. ·integer constant
Integer constant refers to sequence of numbers without decimal point. There are thn
types of integer constants - decimal, octal and hexadecimal.

A. Decimal integers (base 10)


They consist of combinatio n of digits O through 9 with or without negative sigr
This is the number system you use every day.
Example:
105 -245 0
B. Octal integer (base 8)
They consist of combinatio n of digits O through 7 with leading zero.
Example:
074 0 034
c. Hexadecim al integer (base 16) A t}iroti
They consist of combination of digits Othrough 9 and letter a through f or

- -
----=::;;;;;;,:;;:;;:= =:::;;;;;---;:/
Value s and Data Types
F with leadin g (zero x) Ox or (zero X) OX.
Exam ple:
OX7A4 OXa 0xA4

2. Real const ants


. .
Real const ant refers to seque nce of num b ers with · They can ·
· al pmnt.
d ecim be repres ented
in two forms: decim al notati on and .· a
. expon ential notati on.
A. Decim al notat ion
The decim al notati on has thr .
fractio nal part and can b ee parts the intege r part, the decimal point and the
· e used to repre sent numb ers.
Exam ple:
Valid Real Cons tants
2.15 -7.8 0.78 -111. 55555
Invalid Real Cons tants
9· (No nume ral after decim al .point)
99.32 0.34 (Two decim al points )
15,55 .890 (Com ma not allowed)
B. Expo nenti al n otati on
ing synta x
The expon ential notat ion is used to repres ent numb ers and has the follow

)
C mant issa e/E expo nent
-----=-----------
intege r .
The mant issa is eithe r a real numb er expre ssed in decim al notati on or an 2
I0 •
.The expon ent is an integ er with an option al + or - sign. Thus e2 mean s
Exam ple:
Valid R~al Cons tants in expon ent form 1
12e-2 -l.2E -4 10.10 E+5 10.E+ 5f .25e7
0.97e 4

Invali d Real Cons tants in expon ent form


2.SE (No nume rals specif ied after expon ent)
10.SE 4.8 (Expo nent can not have decim al part)
20,55 5E4 (Com ma not allowed)

3. Character const ant

A single chara cter enclo sed withi n single quote s is called chara cter
const ant.

'E' '$' '+' ''


Exam ple: '5'
cter const ants.
Java allows you to have certai n graph ic and non-g raphic chara cters in chara
ly from keybo ard
Non-g raphic chara cters are those chara cters that ~anno t be typed direct
Total Comput er Applica tions - IX
~
hie charact ers can be represe nted by
e.g., tabs, carriage return etc. These non-gra p 'l¼::
escape sequenc es.
Certain graphic charact ers like single quotes p, double quotes (") ~ave spe~ ~
to the com p1-1er th us th ey cannot be printed directly they can hbe pnnted by usmg eSc;.,i
. . h' t .
sequenc es. We have studied escape sequenc e ear11er 1n t 1s c ap er.

4. String Consta nts

A sequenc e of c.haract ers enclose d within double quotes is called


string constan t.

Example:
"Hai" "Java program ming" "1998"

5. Boolean Consta nts


The Boolean constan ts can have only two types of value i.e., true or false. True and fah
are the reserved words of Java languag e.

Operat ors
Java operato rs are the mathem atical symbols used to perform mathem atical and logic
operatio ns among two or more variable s or literals called operand s. There are many t:yJx
of operato rs availabl e in Java such as: Arithme tic Operafo rs, Relation al Operato rs, Logic
Operato rs, Bitwise Operato rs, Assignm ent Operato rs etc. We shall study them in deta
later in this book.

Separa tors
Separat ors help define the structur e of a program. The separato rs used in Java are as follow

Separa tors in Java


Symbol Name Usage
() Parenth eses Method signatu res to contain lists of argume nts .
Express ions to raise operato r precede n ce.
Narrow ing convers ions.
Loops to contain express ion s to be evaluat ed
{} Braces Declaration of types .
Blocks of statemen ts
Array initialis ation. ~

[] Brackets Array declara tion.


Array value referenc ing ---
Semicolon Termina te stateme n ts
'
In the fo r stateme nt to separat e the initialis ation code, the
express ion, and the update code.
S£ 1*' =--
Value s and Data Types

-- Colon
Comm a
After loop varia bles i.e., for nami ng loops.
To separ ate argum ents or variab les in decla ration s.
_c:

- '
Period To separ ate packa ge name s from sub-p ackag es and type
name s, and to separ ate a field or meth od from a reference
variab le. - ' .. .·

-
vARJABLES

Variable is name of reserv ed area alloca ted in me_mory.

of data it holds , the we


The amou nt of memo ry alloca ted to a variab le is defined by the type
in Java. As the name
explicitly define the data typ~ by using some keywords of data types
defined by the nami ng
suggests the value of the vanab le can chang e. The variable name is
of the identi fiers.
rules of identifiers, as we have alrea dy studi ed that a variable is one

Declaring a Varia ble


gener al form of variable
In Java, all varia bles must be decla red before they can be used. The
declaration is given below:

syntax:

__
(..__ty _al_u_e]_;_ _ _ _ _ _ _ _ _ _ _ ___;;_:__ _ _)
pe_id_e_n_tifi_·_e_r_[=v
of a class or interf ace,
Where, the type is one of Java' s primi tive data types, or the name
the identifier is the name of the variab le.
type using assig nmen t
The variable can be initia lised by assig ning a value of compatible
comm a opera tor.
operator. More than one varia ble of a type can be decla red using
lization.
Look at sorpe exam ples given below of varia ble decla ration and initia

e.g. int age = 20; II declare int variable age and assigning 20 as its initial value
int x,y,z; II declares three ints x ,y and z in a single statement. ·
char section = '/\ ; II declares and initialize a char variable and stores A as its value.
float price = 398.50f; II declare and initialize a decimal value in float variable
String name = "SGC"; II declare and in

Example: Supp ose there is a memo ry locati on 110, 111 and


112 in main memory.

B c.
A
I 23 I 44
111 112
110

have assig ned


In this example there are three memo ry locati ons 110, 111 and 112, now we ned
we have assig
the name to th~se varia bles as A, B and C respectively. And the value
three varia bles.
them is 2, 23 and 44, now the value can be chang ed for any of the

- • > .
-- -- ----.
_ __ _ _ __ _ __:.:: .::.:.eo,n
int A = 2;
Tota l
a.~t icat
iottS - JX,.- - - - -
put err ~~~ r~- ----
.:..-- --- - ,, hich is of type "in\\ -
a vari able n a111ed the
"A VI
dat a type int late r.
hav
The stat eme nt above mea ns we " " in it.e crea ted will disc uss the
We
i.e., inte ger and it hold s the value 2
·
DAT A TYP ES rnpi ler hoW rnu ch Space this ...1:"
variab1~
t tell the Jav a co d"ff eren t dat a typ es nee d uu1erent
While dec larin g a vari ab1e we hav e o
data type s are us ed as 1
. urpo se
will occ upy . For t h is P
amo unt of memory space. . 1 can
ible valu es a van ab e
- -A - - - - . defined as the~:e:t~o:f~p~o_s_s_ __ _
data type is _ _ _ _ _ _~ -
hold.
es of data type s.
In Jav a ther e are basi·cally two typ
► Primitive data type
► Non-primitive data type
Data Type
I
*
Primitive Non-Primitive

I
i .i String
Bool
ean Numeric
I Arra y
i i
Integral Complex data structure
Character

i I
char i
Integer
i
Floating point

true false

int short int long float double


Prim itiv e Dat a Typ e

Primitive dat a typ es or fun dam en tal dat a typ


es are pre def ined d a t a
types provided by a prog ram min g lang uag e to
stor e dat a in a var ia ble.
Jav a has different primitive data type s , all of
whi ch rep rese nt diff eren t vaiu es a variable
can acce pt in a prog ram . The se can be clas sifie
d in fou r gro ups :
1. Inte ger, : Inte gers are who le num ber s wit
h no frac tion al par t, suc h as 10 , 2 , -5·
and O. This grou p incl ude s byte , sho rt, int, and
whole-valued sign ed num bers . lon g dat a typ es. Inte ger type is fol
Values and Data Types
- 2. Floating-point numbers: A number having fractional part is a floating-point
number. For example 3.14, 2.0, -10.5 are flo.a ting-point numbers. The floating
point numbers can be written in decimal notation or in exponential notation. For
example, 179.5102 can be written as l..795101E02. This group includes float and
double data types, which represent numbers with fractional precision.
3. Characters: This group includes char data type. It stores characters, such as letters
and digits. It is large enough to represent the entire range of basic symbols.
4. Boolean: This group includes boolean data type, which is a special type for
representing true/false values.

1. Integers
Java defines four integer types: byte, short, int, and long. All these are signed positive as
well as negative values. Java does not support unsigned positive only integers. The width
and ranges of integer types are given in the table below.

Type Width in Bits Range


long 64 - 2 63 to 2 63 - 1
int 32 - 2 3 1 to 2 31,- 1
short 16 -32,768 to ?,2,767
byte 8 -128 to 127

Let us look at each integer type.


I. byte
The smallest integer type is byte. It is a signed 8-bit type. Its range is from-12~ to
127. Byte variable is declared using the byte ~eyword. For example, the followmg
statement declares a byte variable called b. ·
byte b;
II. short
The data type short is a signed 16-bit type. It is declared using short keyword, as
given below.
short abc;
DI. int
Data type int is the most commonly used inte~er type. It is a signed 32-bit type.
The int type is declared using int keyword as given below.
int ctr;
IV. long .
The d ata type 1ong l·s a signed 64-bit type and is used
.
when int type is not large
d d 1 . bl f
enough to h old the desired value. The long keyword 1s use to ec are vana es o
Total Computer Ap pli cat ion s
- IX
type long. For example, the cod • below co mp ute s the nu mb er of
m ile ~t
e
light will travel in a specified nu given
mb er of days.
long days;
long seconds;
long distance;
//approx. speed of light in miles per
int ~ghtspeed = 186000; second
days= 1000; //number of days for which distance
is to be calculated
seconds = days * 24 * 60 * 60;
//days converted to seconds
distance = lightspeed * seconds;
//computes distance travelled
· en above the variable dis tan
In the co de giv , ce will sto re res ult 16O704000OO
miles which can only be sto .
red in a long type va na • · t typ 0oo
ble an d no t 1n an m ·
e vanable.
2 . Fl oa tin g-P oin t Types
Floating-point nu mb ers are als
o known as real nu mb ers , i.e
precision. There are two types ., nu mb ers wi th fractionai
of floating-point types: ~oat_ an
single an d double precision nu d double. Th ese represe~t
mb ers respectively. Their wi dth
the table given below: an d ran ge s are shown lil

Type Width in By tes Range


float 4 -3·:4: x 10 -3 8 to 3.4 x 10 38
double '
8 . · · · , 1.7~~1Q ---3Q& tO 1.7 X 10 30 8
"
Let us look at eac h floating-point
type.
I. float
The type float specifies a single
-precision value. It us es 32 -bi
precision is faster on some pro ts of sto rag e. Single
cessors an d tak es ha lf as mu ch
Type float is us efu l wh en da ta sp ac e as double.
with fractional pa rt is req uir ed
large degree of precision. For exa bu t do no t need a
mple, float ca n be us ed wh en rep
in rup ee s an d pa isa s. The typ res en tin g amount
e float is de cla red us ing float ke
yword.
II. do ub le
The type double specifies a doub
le-precision value. It us es 64 -bi
precision is faster tha n single pre ts of storage. Double
cision on some mo de m pro ce sso
mathematical calculations. The rs optimised for
double keyword is us ed to decla
type. Look at the example code re variables of double
given below, wh ich ca lcu lat es
are a of a circle.
double pi, r, area; //variables declared
r = 8.8; //radius initialized
pi= 3.14156; //value of pi set
area = pi * r * r; //computes area of circle
·The variable are a will store the
va lue 243. 28 24 06 4. Th e res ult
ca n be stored only in a floating , be ing a real number,
-point type variable.
Da ta in double ca n be rep res en
ted as 3.1 4d or 3.1 4D or O. 31
... !),314E2 or 314 .28E-2 wh ere E2 4e l or
repreaenta 10 2, E-2 represen
ts 10 -2 .
Values and Data Types

3. c haractel'.S
d~tatype used to store charac ters is char. Java uses Unicode to repres ent
111 Java, the repres ent all
characters. Umcode d7fines a complete intern ationa l charac ter set that can
The range of
the characters found in all huma n langua ges. Java char is a 16-bit type.
ter s known
char is Oto 65,535. There are no negative chars. The standa rd set of charac
as ASCII, ranges from 1 to 127. For example, look at the code given below.
char ch1, ch2;
ch1 = 89; //ASCII and Unicode for Y
ch2 = 'Z'; //Character Z stored in variable
ch1 = ch1 +1; //ch1 stores 90, ASCII and Unicode for Z

4 , Boolean
two possib le
J ava has a simple type, called boolean, for logical values . It can have only
requir ed by
values, true or false. It is the type return ed by all relational opera tors . or
keyword. The
conditional expres sions. The boolea n type is declared using the boolea n
program code given below demo nstrat es the boolean type.
boolean b1, b2;
b1 = true;
b2 = false;

Creat ing a Strin g


a word in a
We have learnt how to create chara cter variables. But we may need to store
ive type.
variable. The String type is used to declare a smt}g variable. String is not a primit
be assign ed
Rather, String define s an object of class String. A quoted string const ant can
tb String variable. Java suppo rts String to allow it to act simila r
to a primit ive data type.
For example, look at the code below.
String str = "This is a string";

Non-Primitive Data Type


and seque nce
Non-primitive data type are the data type made up with the combi nation s
s, String s
of multiple variab les of primitive data types. Non-primitive data types are Array
_and other complex data struct ure.

Solve d· Exam ples


ization
Q 1. Program which displa ys declar ation of variable of int data type and initial
of a variable.
Ans. class P1
{
static void main()
{
int a; //declaring variable.
a= 10; //initialization of variable
Total Computer Applications - IX
System.out.println( a); -
}
}

Q 2. Program showing use of char data type to store characters.


Ans. class P2
{
static void main()
{
//corresponding integer value for X
char c1 = 88;
char c2 = 'Y';
System.out.print("c1 & c2 : ");
System.out.println(c1 +" "+ c2);
}

} . _ 90 and a-z(97-122)
Note: Every character has an mteger value. A-Z (65 )

Q 3. Program which shows storage of String values.


Ans. class P4
{
static void main()
{
String a = "Java is programming language";
System.out.println(a);
} }

Q 4. Program which shows storage of float values.


Ans. class P7
{
static void main()
{
float a = 5.555f; //max no. of digits supported is 7 but precision is 6
System.out.println(a);
} }

fit is written as float a = 5.555 will give rise to compile tune (


like 5.555 is of double data type to. make it float you have to I
F.

Closer Look at Literals


00
We already kn_ow that a data item, which does not change its value during the executi
of a program, 1s called a literal or a conatant. Let us look at them in detail.
Value s and Data Types
(a) Integer constan~s are whole numb ers witho ut a fractional part. Exam ples are 1, 4,
and 78 .. Intege r hter~ ~ create an int value . An intege r literal can be
assign ed to a
long vm:ab le by exphc1tly telling the compi ler that the iiteral value is of
type long by
appen ding upper case Lor lower case 1 to it.
(b) Character co~st ant is enclo sed in single quote s. Nong raphic
chara cters can be
repres ented using escap e chara cters, which are repres ented by a backs lash(\
) followed
by one or more chara cters. We have alread y studie d them earlie r in this
chapt er.
(c) Float ing-p oint const ants are called real const ants, as they are
decim al values with a
fractio nal part. They can be repres ented in either stand ard or scientific
notati on. The
standar~ notati on consi sts of a whole numb er comp onent followed by a decim
al point
and then the fracti onal comp onent . E.g. 23.7, 0.008 97, and 3.141 59.

The scien tific notati on uses a stand ard-n otatio n: ·floatin g-poin t
numb er plus a suffix that ·specif ies a power ·o f 10 by which the
numb er is .to be multip lied. The expon ent is indica ted by an 'E' or
'e' followed by a positi ve or negati ve decim al numb er. E.g. 6.022 E23
and 31415 9E-05 .

(d) Boolean const ants can take only two value s ~rue and false. These
value s .do not
conve rt to any nume rical repres enta~ on. They can only be assigr led to
a vanab le of
type boole an.
(e) String const ants are a seque nce of chara cters enclos ed in doubl e quote
s. E.g. "Hello
World", "Doub le \n lines" . The escap e seque nces given in the table work
the same way
inside string litera ls. It is impor tant to note that in Java string must begin
and end on
the same line.
The following progr am show s the use of escap e seque nce chara cters in
String literal .
class P7
{
static void main()
{
String a; . . '"
a = "Java is programming language \n developed by \t \' James Gosling\
;
System.out.println(a);
}
}
Output : Java is a progr ammi ng langu age
II developed by 'James Gos 1·mg '
Type Conv ersio n
1


.
·
The proce ss of conve rting one pnmi·tive type to anoth er is called
.
type conve rsion.
The two types of conve rsion suppo rted in Java are:
.
1. Implic it conve rsion; and
2. Explic it conve rsion.

!-=~ ==-=;;;;;_;;;;;;;;;;;;.;;;;;;-=• ~~..;.;..;;...~-----~_;;;;.;


To tal Co mp ute r Ap pli ca tio ns
- IX
.
1. Im pli cit Co nv ers ion or Wid ing or Auto111atfc Co nv er sio n or COERCION
. . . en
. h co nv ers ion of on e pri mi
~
Im pli cit co nv ers ion is t e . tiv .
e typ e to oth er co mp ati ble Prh
typ e do ne by the Ja va co mp ile . h t rog ram me r's int erv en tio n. nitiv
r wi t ou P t
.
Im pli cit co nv ers ion b d un de r tw o co
ca n e on e nd iti on s:
-
l. Two typ es are co mp ati ble .
2. Th e de sti na tio n typ e is lar ge
r tha n so urc e typ e.

Ex am ple :
int a= 5;
double b = a;
System.out.println(b );
He re va lue in a is of int eg er typ
e an d ge ts rea dil y co nv ert ed
typ e is lar ge r tha n so urc e typ e to do ub le as the de sti na ti01
In ca se of an ex pre ssi on , the co
nv ers ion follows the fol low ing
1. Re su lta nt typ e de pe nd s on rul es:
the da ta typ e of the lar ge st op
2. If an ex pre ssi on co nta ins int era nd .
eg er an d flo at va lue the res ult
will be flo at typ e. an t typ e of expressi01
3. If ~ ex pre ssi on co nta ins ch
ara cte r an d int eg er the res ult
an t wi ll be of int eg er type
Ex am ple 1:
int i; 'i/ r res ult an t typ e wi ll be flo
at wh ich when
su btr ac ted wi th do ub le da ta
float f; typ e wi ll res ult
in do ub le da ta typ e
do ub led ;
do ub le an s = i / f - d;
System.out. println( ans);

Ex am ple 2:
long a = 1OOL; 'a + r res ult an t typ e wi ll be flo
at.
float f = 5.5f; Note: he re tho ug h lon g ha s 64
bit siz e an d float
flo at an s = a + f; ha s 32 bit siz e bu t the res ult
is flo at be cau se
System.out.println(ans); it is mo re pre cis e.

Ex am ple 3:
int a= 3; He re wh en we ad d a wi th b, as
ev ery ch ara cte r I
ch ar b = 'C'; va lue ha s nu me ric rep res en tat
ion , C ha s ASCII I
int an s = a + b;
va lue 67 so res ult an t va lue wi
ll be 70 .
System.out.prif!tln(ans);

2. Ex pli cit Co nv er sio n or Na


rro wi ng or Ty pe Ca sti ng
Co nv ers i~n fro m o~ e pri mi tiv
e typ e to an oth er typ e us ing
pro gra m is do ne us ing pro gra typ ec ast op era tor '{) ' in a Jav!l
mm er' s int erv en tio n. It is als o
Ex pli cit co nv ers ion ca n be do cal led na rro wi ng conversiotl·
ne un de r tw o co nd itio ns:
1. Two typ es are inc om pa
tib le.
Values and Data Types
2. The destination
. type is less than the source type.
Syntax used:
( (target datatype) value
"------.:.._..:._--=-=... _ _ _.:____ ___,;;,,;;,,.,__ )
Examples:
1. char a= 'A';
int x = (int) a;
System.out.println(x); //output will be 65.
2. long a= 500;
int x = (int) a;
System.out.println(x); //output will be 500
3. double a = 5.5;
int x = (int)a;
System.out.println(x); //output will be 5

Program which shows char variables behaving like integers.


class P3
{
static void main()
{
char c;
c='X';
System.out.println("variable c contains :" + c);
c++; . //increments c using++ increment (unary) operator.
System.out.println("c now contains :" + c);
}
}

SUMMARY
~ The character set is a set of alphabets, letters and some special characters that are
valid in Java language.
~ A character encoding tells the computer how to interpret raw zeroes and ones into
real characters.
~ The Unicode Standard provides a unique number for every character, irrespective of
platform, device , application or language.
~ Escape characters (also called escape sequences or escape codes) in general are used
t o signal an alternative interpretation of a series of characters .

You might also like