Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Values and Data Types

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.

4.2 Java Character Set


A character set is a set of valid characters that a language can recognise. A character s

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,

\u00AE The copyright symbol


u0022 The double quote
\u00BD The fraction 1/2
\u0394 A The capital Greek letter delta

You can even use the full Unicode character


sequence to name your variables. However
chances are
your text editor won't be able to handle more than basic ASCII
very well.

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

assert default goto package synchronized


VALUES AND DATA
TYPES 47

boolean do if private this

break double implements protected throw

byte else import public throws

case enum instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

Const float native super while

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.

The following are some valid identifiers:

Myfile DATE9 7 77 Z2TOZ9 A_to_Z


MYFILE DS HJ13 JK isLetterorDigit
CHK FILE13 apepm $1_to_$10

The following are some invalid identifiers


DATA-REC contains special character NOTE
ie., other than A to Z, a to z and _or $) Java is case sensitive

29CLCT i.e., upper-case letters


|

Starting with a digit


and lower-case letters
break reserved keyword
are treated differently.
My.file contains special character.
48

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)

1. Decimal Integer Literals. An integer literal consisting of a sequence of digits is taken oa


decimalinteger constant unless it begins with 0
-17 are decimal integer literals.
(digit zero). For instance, 1234, 41, -
2. Octal Integer Literals. A sequence of digits starting with 0 (digit zero) is takem be
to an
oc
integer. For instance, decimal integer 8 will be written as 010 as octal integer.
(: 810 =10g) and decimal integer 12 will be written as 014 as octal
integer
(: 1210 =14,). But make sure that when an integer begins with 0, it must not contain
8 and 9 as these are invalid octal digits.
3. Hexadecimal Integer Literals. A sequence of digits preceded by Ox or 0X is taken to he ar
hexadecimal integer. For instance, decimal 12 will be written as 0xC as
hexadecimal
integer (::1210 C16). But with Hexadecimal constants only 0-9 and A-F can be used.
All other letters are illegal.

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.

(i) Floating Literals


Floating literals are also called real literals.
A real literal in fractional
Real literals are numbers having fractional parts. These may be form must have at least one
written in one of the two forms called fractional form or the digit before a decimal point
exponent form. and at least one digit after
the decimal point. It
A real literal in fraction form consists of signed or unsigned may
also have either + or sign-

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

The following are valid real literals in fractional form


2.0, 17.5,-13.0, -0.00625
Thefollowing are invalid real constants

(No decimal point)


7. (No digit after decimal point)
+17/2 (/-illegal symbol)
17250.26.2 (Two decimal points)
17,250.262 (comma not allowed)

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.

The following are the valid real literals in exponent form:


A real literal in exponent
form has two parts a 152E05, 1.52E07, 0.152E08, 152.0E08, 152E +8, 1520E04, -0.172E-3
mantissa and an exponent.
The mantissa must be either
The following are invalid real literals in exponent form:
an integer or a proper real
literal. The mantissa is 172.E5 (At least a digit must follow the decimal point)
followed by a letter E or e
()
and the exponent. The (i) 1.7E (No digit specified for exponent)
exponent must be an (i) 0.17E2.3 (Exponent can not have fractional part)
integer.
(io) 17,225E02 (No comma allowed)

() .25E-7 (No preceding digits before decimal point)

(in) Boolean Literals


The boolean type has two values, represented by the literals true and false, formed from ASCI
letters.
A boolean literal is always of type boolean. It is either boolean value true or boolean value false.

A character literal in Java


iv) Character Literals
must contain one character
A character literal is one character enclosed in single quotes, as and must be enclosed in
in 'z. The rule for writing character constant is given in the single quotation marks.

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)

(vi) The Null Literal


The null type has one value, the null reference, represented by the literal nul, which is formed
from ASCII characters. A null literal is always of the null type.
VALUES AND DATA TYPES
51
4.3.4 Separators
The following nine ASCII characters are the separators (punctuators) :

4.3.5 Operators
Operators are special symbol that cause an action to take place.
The following 37 tokens are the operators in Java:
?

&& ++

&

4.4 Concept of Data Types


Data can be of many
types eg, character, integer, real, string
etc. Any thing enclosed in single quotes represents Data Types
character data. Numbers without fractions
represent
integer data. Numbers with fractions represent real data Data Types are means to identify
and anything enclosed in double the type of data and associated
quotes represents a
string. Since the data to be dealt with are of many types, a operations of handling it.
programming language must provide ways and facilities
to handle all types of data.
Java like any other language provides ways and facilities Java Data Types
Primitive (or Instrinsic)
to handle different types of data by
providing data types. Reference
Java data types are of two types
Primitive datatypes come as a part of the language. Java provides
eight primitive datatypes,
which are: byte, short, int, long, float, double, char, boolea1.
Referencedatatypes are constructed from primitive data types. These are : classes, arrays
and interface. But their storage mechanism is different from primitive datatypes. We are
not going in details of reference data types here as it is beyond the scope of this book.
Let us now talk about primitive data types in details.
4.4.1 Primitive Datatypes

By primitive datatypes, we mean fundamental datatypes offered by Java. Java supports


followingfour types of primitive datatypes
() Numeric Integral primitive types (i) Fractional primitive types
(ii) Character primitive types (iv) Boolean primitive types.
Let us learn more about these.
52 COMPUTER APPLICAT
CAION
0) Numeric Integral Types
The datatypes that are used to store numeric values fall under this Numeric Integral
sub-category i.e., numeric primitive datatypes. Types
byte
All integral numeric types store integer values i.e., whole numbers * int short
only.
long
The storage sizes and the range of values supported by numeric integral types is bei
in Table 4.2.

Table 4.2 Integer Primitive Datatypes


Type Size Description Range
byte 8 bits (1 byte) Byte-length integer -128 to + 127
short 16 bits (2 bytes)
Short integer 32,768 to +32,767
int 32 bits (4 bytes) Integer (about) -2 bilion to +2 bilion ie., -23 to 231 -1
Long 64 bits (8 bytes) Long integer (about) -10E18 to + 10E18 i.e., -2 to 263 -1

Please note that an l (small L) or L suffix on


NOTE of long datatype eg., 33L refers to a
integer means the integer is
an

Java does not


long integer having value 33. Thus, we
support can say that 33 is an int value but 33L is
a long value.
unsigned datatypes (i.e.,
only positive numbers). Depending upon your requirements, you can select appropriate datatype.
All numeric types in Consider this- you need to store your
Java can store negative What do you think should be the
phone no 27650000 in
your program?
as well as positive datatype ? Can
short datatype? Well, you need to store it in
store it in a
you byte or
int datatype. The
numbers. is that the number to be stored does
not fall into
reasorn being
and short types. ranges supported by byte
One more thing that you must know about datatypes that, all
store negative as well as
positive numbers.
datatypes are signed i.e., they can
(in) Fractional Numeric Types
The integral types covered above
could not have decimal values.
fractional numbers i.e., numbers having decimal Fractional datatypes can store
points. These are also called
floating-point
datatypes.
Following table displays various floating-point datatypes available in Java, along with their
ranges.
Table 4.3 Floating Point Primitive Datatypes
Type Size Description Range Remarks
float 32 bits Single-precision -3.4 E +38 to Precision up to 6 digits.
(4 bytes) floating point +3.4 E+38 Examples : currency, temperature, percentage, length.

double 64 bits Double-precision -1.7 E +308 to Precision up to 15 digits.


(8bytes) floating point 1.7 E+308 Examples: large numbers or high precision, such as for
a stronomy or subatomic physicCS.
VALUES AND DATA
TYPES 53

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.

(in) Character Types


The character datatype - char datatype of Java - is used to store characters.
The size of char datatype of Java is 16 bits as it can store Unicode characters. Following table
lists the size and range supported by a char datatype.

Table 4.4 Character Primitive Datatype

Size Description Range Remarks


Type
char 16 bits Single 0 to 65,535 Unicode characters (whereas other anguages use

character 1-byte ASCII text characters)


(2 bytes)
Examples: alphabets and numerals.

iv) Boolean Type


Another of the primitive datatypes is the type boolean. It is used to represent a single true/false
value. A boolean value can have only one of two values : true or false.

Following Table 4.5 lists the size and range of boolean datatype.

Table 4.5 Boolean Primitive 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.

Table 4.6 lists examples of various data items of different datatypes.

Table 4.6 Some Sample Data Values and their Types

Value Value Datatype Value Datatype


Datatype
87.363F float false boolean
178 int
8864L 26.77e3 double 22.34e2 double
Long
37.266 double char
boolean
37.266Ddouble true
COMPUTER APPLICATIONS-K
54

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.

4.5.1 Declaration of a Variable


The declaration of a variable generally takes the following form

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;

Here val is initialized with a first value of 1001. Following NOTE


are some more
examples of initialized variables: While naming variables,
double price 214.70, discount 0.12; make
fioat x = 0.27;
sure to follow
identifier naming rules
long val = 25L; and conventions.

Now consider the following example


program that declares
variables of different datatypes and prints their values.

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:

public class <classname>

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

public class Code


public clase Code
void myMe thod ()

Write your program-


code here within {} of
myMethod
changed

chenged

(Please note, this is done because,


function.) A function is in the form everything
we want Java to do, must be given inside a

<Java datatype> <functionname>()


/ java statements go here
And every function must be
inside a class definition as we did
5. To run this code, above in step 3.)
you need to first compile the class
of editór window. Then
in the main
by clicking the Compile button at the top
method using the project create an object of this class
and then u n the
object as explained in sections 2.6.6 and 2.6.7.

Right click the object and click on the


Blue: Create Objet method name to run the method.
First

new Firsto First

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;

System.out.println ("My name is " + name);


System.out.println "My age is " + age) Output produced is:

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

public class Test {

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

public void compute())

int side1 = 10, side2 14, side3 15;


int perimeter;
perimeter = side1 + side2+ side3;
System.out.printin("Perimeter oftriangle with sides 10 cm, 14 am and 15 anm is"+ perimeter + "em");

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.

public class Calc

void compute()

double side, perm 20;


58 COMPUTER APPLICATIONS-X

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

Initial Values of Variables


Every variable in a program must have a value before it is used in an expression:
Each class variable, instance variable, is initialized with
or array component a default
value when it is created

Type Initial value


byte o (Zero) of byte type
short of short type
o (Zero)
int 0
long OL
float 0.0f
double 0.0d
char null character i.e., "\u0000
boolean false
All reference types null

Please note that the local variables i.e., the variables


you define inside a method (or a block
statement) are not initialized by default. You have to give them initial value
explicitly.
Following Fig. 4.1 summarizes various datatypes in Java
DATA TYPES
IN JAVA
Primitive
Gintrinsic or Fundamental) Reference

Numeric
Non-numeric Classes Iinterface Arrays

Integer Floating-point| Character Boolean


byte float char .boolean
short .double
int
long

Figure 4.1 Datatypes in Java.

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:

final double TAXRATE=0.25


The keyword final makes a variable as constant i.e., whose value can not be changed during
program execution. Consider the following program that declares and uses two constants.

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:

GOODS_TAX =0.050; /lerror

it will cause an error, as the value of constants cannot be modified.

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

finaldouble mile 1760; // 1 mile = 1760 yards

double dist_feet 1056, dist_mile = 0, dist_yard = 0 ;


dist_yard = dist_feet/yard;

dist_mile = dist_yard/ mile;


60 COMPUTER APPLICATIONS-X
System.out.println(" 1056 feet are equal to "+ dist_yard + "yards")
System.out.printin(" 1056 feet are equal to "+ dist_mile + "miles");

Output produced is:


1056 feet are equal to
352.0yards
1056 feet are equal to 0.2miles
Program 4.6
Write a program to calculate tax for a taxable income of R 3,10,000, if tax rate is fixed at 2.2%.
public class Calculate {
void calcTax() {
final double taxrate =
2.2;
double income 310000, tax = 0;
tax income *
=

taxrate / 100;
System.out.println(Tax payable is Rs. " + tax );

Output produced is
Tax payable is Rs. 6820.0

NOTE In Java, wherever you use multiple data


types in single expression, Java will convert the
types of participant values to make them of same data type. The
conversion requires you to understand process of type
shall talk about Type Conversion in expressions and before that operators. Hence, we
details
operators, expressions and of course Type
in coming
chapter where we talk about
Conversion:).

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 ?

(a) const (b) constant


) final (d) fixed
62 COMPUTER APPLICATIONS
Section B: Subjective Type Questions
1. Using Java notation, provide the integer value zero, a string consisting of a zero, and the e.
zero. characte
Ans.
the integer value zero 0
string consisting of a zero: "0"
thecharacter zero: '0
2. What is type, as this term relates to programming ?
a

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.

public class PayCheck

int pages_read;
int amt;
void compute()
pages_read = 134 + 21780 + 145;
VALUES AND
DATA TYPES
63
amt = pages_read * 60;

System.out.println("For "+ pages_read +" pages, amount payable is Rs."+ amt);

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 income 1223423;


double taxable = income 300000;

double tax =
taxable
0.15; *

System.out.println("Forincome of Rs."+ income +" tax payable is Rs." + tax);

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;

Total sch = yearly_sch * 5;


System.out.println("Total scholarship earned in 5 years is Rs. " + Total_sch) ;

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;

dist = one_round * 18;

System.out.println("Total distance covered (in meters): " + dist);


64 COMPUTER APPLICATIONSN
10. Write a program to compute the contribution of a school to a charity fund if one branch ofha.
contributed 35500 every year to it for last 12 years and another branch of the school has
contributed 18500 for last 8 years.
Ans.
public class Calc
{
void contribution( )

intcontri1 = 35500, contri2 = 18500;


int Total_contri = 0;
Total _contri = contri1 * 12 + contri2 * 8;

System.out.printin("Total contribution Rs. "+ Total_contri);

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

Keyword Reserved word having special meaning and purpose.


Literal Constant
Token The smallest individual unit in a program.

SSignment

1. What is meant by token ? Name the tokens available in Java.


2. What are keywords? Can keywords be used as identifiers?
3. What is an identifier? What is the identifier forming rule of Java ?
4. An identifier can start with the underscore "_". True or False.
5. Is Java case sensitive ? What is meant by the term 'case sensitive' ?
6. An identifier in Java can begin with a digit or letter. True or False.
7. All special characters are allowed in Java identifiers. True or False.
8. Which of the following are valid identifiers and why/why not:
Data_rec, _data, 1 data, data 1, my.file, asm, switch, goto, break ?
9. What are literals? How many types of integer literals are available in Java?
10. What is an integer constant ? Write integer forming rule of Java.

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 ?

18. Write the following real constants into exponentform:


23.197, 7.214, 0.00005, 0.319.
19. Write the following real constants into fractional form
0.13E04, 0.417E-04, 0.4E-05, 0.123E02
20. Write a program to determine the length of the wooden strip required to frame a photograph of
length and breadth 32 cm and 21 cm respectively.

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)

You might also like