Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

1. Revising Basic of Java (1)

The document provides an overview of basic Java concepts, including its history, object-oriented programming principles, and fundamental programming structures. Key topics covered include classes, objects, encapsulation, inheritance, polymorphism, and the Java programming environment. It emphasizes the importance of understanding these concepts for effective Java programming and application development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

1. Revising Basic of Java (1)

The document provides an overview of basic Java concepts, including its history, object-oriented programming principles, and fundamental programming structures. Key topics covered include classes, objects, encapsulation, inheritance, polymorphism, and the Java programming environment. It emphasizes the importance of understanding these concepts for effective Java programming and application development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Revising Basic Java

Concepts

Chapter Outline 1.1 INTRODUCTION


Java is a popular Object Oriented programming
1.1 Introduction language that is used to build secure and
1.2 Object Oriented Programming powertul applications that run across multiple
1.3 Beginning with Java operating systems. The Java language offers
flexibility, scalability, and maintainability. The
Java programming language was developed by
James Gosling and Patrick Naughton for Sun
Microsystems Inc. in 1991, and it was later
acquired by Oracle Corporation.
You have learnt to work with Java in class DX
earlier. This chapter is going to revise the concepts
of Java that you learnt in previous class. After
going through this chapter, you can brush up
previous concepts learnt and then further your
knowledge of Java programming language.

1
COMPUTER APPLICATIONS-X
2

1.2 Object Oriented Programming


procedures for the solution of a probla. Abstraction
on the m
The programming approach that focuses emphasizes on the 'd abstractions
paradigm. This approach
known as procedural programming talk of anyt
rather than the 'data'. profession,
a problem in term ot classes and obios
bjects
The Object Oriented Programming paradigm views her talents,
are needed tor a particular situation/proble
1.e, it determines which classes and objects
characteristics and behavin >But w
context. Recall that an Object is an identifiable entity with some rollno,
that share common properties annd
and a class is a blueprint representing a group of objects > For ex
relationships. So OOP paradigm determines the classes and objects needed for the solutiono rollno,
a problem and thern provides a full set of operations for each class.
Thus, ther
and for ea
1.2.1 Elementary Concept of Objects and Classes
As you know that OOP programming paradigm views a problem in terms of objects and 2. Encop
classes. So, let us quickly revise what an object and a class 1s.
The wrapp
An Object can be thought of as an entity having a specific identity, specific characteristis known asa
and specific behaviour, e.g, 'Ceiling Fan that you see in your room is an object. Is are combi
characteristics are : it has three/four blades/wings, a motor, a mounting rod, may or no Java.
have remote-control feature etc. Its behaviour is : it works on electricity, it rotates air ata
EncapsulE
given speed (rpm)
implemer
The software objects have state and behaviour: methods
Their state is maintained through variables or data items. In software objects, values
of characteristics (data items) at any instant of time determine the state of the
object. 3. Mod
Their behaviour is implemented through functions The act of
generally called methods. property
Object & Class
A Class is a blueprint that represents a set of objects modules
that share common characteristics and behaviour, An Object is an entity with a
eg, "Honda City" is a class of cars, but a Honda City 4. Inhe
specific identity and having
Car having a particular registration number say specific characteristics and Inherita
DD-5938 is an object of this class type. specific behaviour. A Class is a another
Similarly,
"Dog" is a class, but a dog namely, "Leo blueprint representing a set ot which i
residing
with Gandhis, is an object of Dog class type. objects that share common
A
characteristics and behaviour
'AL
1.2.2 General Object Oriented Programming
Concepts A
Object oriented programming
paradigm involves the objects and classes and implements CE
solution on the basis of following
OOP concepts a fea

1. Data Abstraction 5. Pol


Data abstraction or sinply abstraction Polym
refers to the act of
including the background details representing essential features
or explanations.
Abstraction withou classes,
describes things in simple terms, hides the internal details pertor
according to your requirement,
eg, a
in 'switch board',
you only press certain switches and
its internal circuitry, it resus
is abstraction, which ensures that you connections etc., you
need to know only needn't know. This Concat
switch board without knowing the the essential things operate o opera
background details of to
switchboard.
Chapter 1
: REVISING BASIC JAVA CONCEPTS 3

Abstraction is always relative to the purpose or user. An object may have multiple
is abstractions depending upon the context. For instance, if we talk of a student object, we can
ing' talk of anything that belongs to her in the real world like her name, number of siblings, parents
profession, locality she lives in, marks obtained by her, her roll-number in the class, her medical history,
cts, her talents, her interests, her atwards, sports played by her etc.
em/ But when we talk of a student result tracking system, the abstraction for it would be : her
ur rollno, name, marks obtained etc.
NOTE
and For extra-curricular activities, the abstraction would be her :

of rollno, talents and awards. A different class is


defined to represent
Thus, there can be multiple abstractions for a real-world entity each abstraction of an
and for each abstraction, we define a class. object.

nd 2. Encapsulation
The wrapping up of data and functions (that operate on the data) into a single unit
(called class) is
known as encapsulation. The only way to access the data is provided by the functions (that
ics methods in
are combined along with the data). These functions are called member functions or
Its
ot Java.
ta Encapsulation is a way to implement data abstraction. Encapsulation hides the details of the
implementation of an object. Encapsulation enables access restriction to a class members and
methods by making them public, private or protected.
es 3. Modularity
Modularity is the
The act of partitioning a program into individual components is called modularity.
loosely coupled
property of a system that has been decomposed into a set of cohesive and
modules.

4. Inherifance
properties from
Inheritance capability of one class of things to inherit or derive capabilities or
is the
from the class Automobiles
another class, e.g., the class "Car' inherits some of its properties
Vehicles".
which inherits some of its properties from another class
A class from which another class inherits is called base
class or super class e8
>
'Automobiles' class is base class of class 'Car'
subclass or derived class eg, the
>And the class inheriting from another class is called inherits the common
Car a derived class of 'Automobiles class. A subclass
class is
are unique to it.
a features and additionally defines only those features that

5. Polymorphism
objects of several different
Polymorphism property by which the same message can be sent to
is a
depending on its class. The same operation is
classes, and each object can respond in a different way
it working upon, e,g., if you give 5 +7,
performed differently depending upon the data type is "ABC, the
7. And if you give 'A+ 'BC', it results into
it results into 12, the sum of 5 and
is able to distinguish between the two
concatenated strings. The same operation symbol'+ on.
operations (summation and concatenation) depending upon the data type it is working
COMPUTER APPLICATIONSx

1.3 Beginning with Java (io) Co


refers to some combination var
Java is both a programming language and a platform. Platform
ot hardware and system software e.g., operating system
Windows on Intel Core 19 or Linux giv
can
on AMD Ryzen or Skylake Xeon W etc. The Java Platform is a software platform that
computer EHelloWor
deliver and run highly interactive, dynamic and secure applications on networked
Ele
systems.
Byte Code

While most computer programs are platform dependent, i.e., they are very closely tied to the
Specific hardware and operating system they run on, Java apPplications are platform-
independent ie, they are not affected with changing platforms. Java solves the problem of
platform-independence by using byte code.
Contrary to ordinary compilers, the Java compiler does not produce native executable code
Comment des
for a particular machine. Instead it produces a special format called byte code. The Java Byte
code is interpreted by a special Java Interpreter for a specific platform. Actually this Java
interpreter is known as the Java Virtual Machine (JVM).

1.3.1 Anatomy of a Java Program 1.3.2 Java Fu


The most common Java programs are applications and applets. Applications are standalone A Java j
programs that can run independently of another program or application. Applets are similar statemer
to applications, but they don't run standalone, they are run inside another application such as progra
a web-browser.
A simple java program has following components or parts: Charac
) Comments. Comments are the explanatory text enclosed in
comments are only for the programmer, these are not part of the
... */ or follow /. The
Java us
charact
Java code and are
not executed. (see Fig. 1.1) system
(7) Class (es). A java program can have one or more
classes. A class defines functionality Keywa
of a specific type of objects. A class has variables and
methods inside it. There can be
multiple classes in a program but there has to be a Keywa
class that has the same name as
that of the Java program and this class contains the main() Special
called initial class. (refer Fig. 1.1) If there is method. This class is
only one class inside a java program
this class has to be the initial class, i.e., contains that
the main() method and bears the same
name as that of the program file.
(ii) Method main(). The entry point of every
Java application is its main
are multiple classes in a program, method. If there
the execution will begin from the initial
class containing main method. If class i.e., the
no main method is there,
no execution will take place.
(However, some specially NOTE
designed software like BlueJ, let
you run and test your
Java code even without main method, An initial class is the
BUT this is useful one that contains main()
only for learning purpose. A real life 1.3.2A Wor
application requires method inside it. The
a main method to run.)
program is given In a
See, the main method is declared same name as that of
the
as: its types
initial class and a
public static v01d main file the f
extension as .java. Each
Chapter 1
: REVISING BASIC JAVA CONCEPTS
combination (io) Code statements. The methods
inside classes contain functionality defined through
19 or Linux various statements of the code,
e.g, System.out.println statement will display the
rm given output on the terminal window. (refer Fig. 1.1)
that can
d computer
EHelloWorld- Notepad
Ele Edit Search Hep
This is the class name
/Progran HelloWorld.jaua
tied to the /class HellloWorld
Class containing
Execullon begins from main() is initial
platform- main mothod
class.
public static void nain (String
oroblem args[])
of
Systen.out-println(""He1lo Worldt*") ;
table code Print to standard output
device, generally monitor
Java Byte Comment delimiters

this Java L

Figure 1.1 Components of a Java Program.

1.3.2 Java Fundamentals


andalone A Java program is made up of many things such as keywords, identifiers, literals, expressions,
e
similar statements etc. Let us briefly talk about these fundamentals or the building blocks of Java
a such as programming language.

Character Set
7lI. The Java uses the Unicode character set. Unicode is a two-byte character code set that has
characters representing almost all characters in almost all human alphabets and writing
and are
systems around the world including English, Arabic, Chinese and many more.

ionality Keywords
can be
ame as Keywords are the words with special meaning associated with them. These are reserved for
special purpose and must not be used as normal identifier names. Some keywords of Java are:
lass is
m
that default T private this boolean do
same protected break double public byte else

return case int short try catch


there
e., void char long class float while
the
for new switch

"the above given is a partial list of Java keywords)


the
in()) 1.3.2A Working with Values
The NOTE
the n a Java program, you can work with various Smallest individual unit in a program is
its types of data values. These values can be either in called a token. Keywords, identifiers,
the form of literals/constants or named variables. literals, operators and punctuators are
file
Each value has a data type associated with it. tokens in a Java program.
APPLICATIONS-X
COMPUTER
6
For exampl
Java allows
Literals
data items that are fixed data values. doub
as constants) are int
Literals (often referred to
several kinds of literals: can be written in
decimal form long
numbers and
Integer literal are whole (starts with a zero,
e,g, 012) and You can as
) Integer literals. number e.g, 10), octal form
(starts with a non-zero OxC). dou
hexadecimal form (starts with a Ox, eg, fractional point or flo
Floating point literals are numbers with fractional form int
literals can be written either in
(i) Floating-point decimal points. These
the numbers having form, e,g, 0.36E-3. Constant
in exponent
eg, 0.00036 or by true and false. A Consta
(tii) Boolean literals.
These literals are represented
enclosed in single quotation A constar
literals. Single character or escape sequence
(io) Character literals.
e.g., 'a' and '\t are character Fi
marks makes a character literal make a
more characters enclosed in double quotation marks Now on,
or
() String Literals. One "T189" etc. but you
string literal, e.g, "abc", created
as null.
(vi) The null literal. The null literal
represent null reference and written value wi
ldentifiers where it
to various program units of Java.
Identifiers are the names given by the programmer 1.3.2B Data
packages and interfaces etc. ldentifier
Identifiers are the names of variables, methods, classes,
Each va
forming rules of Java state the following: type of
$ characters and can be of any
) Identifiers can have alphabets, digits,_underscore and support
length.
(ii) They must not be a keyword or Boolean literal or null literal.
ii) They must not begin with a digit.
(7D) Java is case sensitive i.e., upper-case letters and lower-case letters are treated differently. (ii)

Some legal Java identifiers are


MyVar, myvar, MYVAR, X, I, myvar, $myvar,_9pins, andornot, i_am_a_long_name
Variou
Following identifiers are legal in java :

My Var // Contains a space


9hours I/ Begins with a digit
case // it is a keyword
a+B-C // The plus and hyphen are not legal characters for identifiers
0' Neil // Apostrophe is not a legal character for identifiers
And&not I/ & i.e., ampersand is not a legal character for
identifièrs
Whenever you store a values with a name i.e., in form
of a variable, you name it as per Inte
identifier rules.
naming
by
Variables
sh
A variable is a named memory location, which int
holds a data value of a particular
variable is declared as per following syntax: data type. A lom

<type> <variablename>
Chapter 1
REVISING BASIC JAVA CONCEPTS
Javaallows
For exanmple,
ecimal double salary, wage // two variables of double type declared
g-, 012)form int month, day, year // two variables of int type declared
and long distance, area 1/ two variables of Long int type declared
You can assign initial value to a variable at the time of its declaration, e,g.,
al point double price = 1214.7057, discount = 0.12;
or
ional form float x = 0.0125;
int val = 13

Constants
quotation A Constant value represents a named value that remains fixed throughout an entire program.
A constant is declared in similar way as variable but with keyword final, e.g,
ks make final double TAXRATE = 0.25
a
Now on, you will be able to use TAXRATE'S value in your program NOTE
but you will never be able to change its value again, because you Keyword final when used
ll. with a declaration similar
created it with keyword final, which means that this named
value will remain fixed for this nanme throughout the program to a variable, creates a
named constant.
where it has been created.
of Java.
Identifier 1.3.2B Data Types
Each value that you use in a program has a data type. Data Types are means to identify the
e of any type of data and associated operations of handling it. Java provides many data types to
support various types of data. Java provides data types belonging to these two categories
() Primitive data types. These are basic datatypes provided by language and are not
based on any other datatypes. A primitive datatype is used to define and hold a value of
basic type in a named variable. These are also called fundamental datatypes of Java.
rently.
(i) Reference data types. These are derived datatypes that are created using the
primitive data types. A reference datatype is used to store the memory address ot an
object.
Various data types in Java are shown in following figure (Fig. 1.2.)

Data Types in Java


Primitive Types
(Intrinsic or Fundamental) Reference Types

Numeric Non-numeric Classes Interface Arrays

s per Integer Floating-point Character Boolean

byte float char boolean


short double
int
e. A long

Figure 1.2 Datatypes in Java.


COMPUTER APPLICATIONS-X

(0 Primitive Data Types Primitive


Let us brietly
There are about eight primitive data types in Java. NOTE reference
I (lvalue). T
talk about these. You can use suffix or L
types. These data types store with an integer to signify actual dat
>Numeric Integral primitive as
nteger values i.e., whole numbers only (both negative long value.
well as positive numbers). There are four numeric integral 1.3.2C Opera
types in Java byte, short, int, and long
:
The data
i.e.,
>Floating-point datatypes. Floating8 point datatypes can store fractional numbers instructio
numbers having decimal points. There are two floating point data types in Java :
float being car
By default
(provides precision of 6 digits) and double (provides precision of 15 digits). (1) Ar
Java assumes the fractional numbers to be of double datatype unless specified, eg, value su
0.35 will be considered of double type by default to explicitly specify their type, you can
(i) In
use suffixes f or F (for float) and d or D (for double).
(d-
Character data type. The character datatype - char datatype of Java is used to store
-

h
characters. A character can be any Unicode character that you can store using char type.
> Boolean data type. This data type (boolean) is used to represent a single true/false value.
A boolean value can have only one of two values: true or false.

(i) Reference Data Types


Broadly a reference in Java is a data element whose value is an address. Arrays, classes,
and
interfaces are reference types. The value of a reference type variable, in contrast to that of
primitive type, is a reference to (an address of) the value or set of values represented
by the
a
variable (Fig. 1.3). A reference is calleda pointe, or a memory
address in other languages.
A reference is called a
pointer, or a memory address
in other languages. The Java
programming objectName reference
language does
not support the explicit use of
addresses like other an object
languages do. You use the or an array
variable's name instead.
(ii)

Figure 1.3 Reference datatype (iv)

There are two values associated


with a symbolic variable: () Its
location in memory(called roalue ) data value, stored at some
and (i) its location value; (o)
which its data value is stored (called that is, the address in memory
lvalue), see e.g., below at
Memory Addresses
1051 1052 1053 1054
Data values of 1055
variable> 10
Variables names 25
A
C

rvalue of A =10
lvalue of A = 1052
rvalue of C=25
lvalue of C=1055
Chapter 1: REVISING BASIC JAVA CONCEPTS
9
Primitive data type operations deal only
with stored value ie., actual read-value (roalue). The
reference types on the other hand, deal
I or L (loalue). They do not store the actual
with the memory address i.c., the location-value
signify read-value, rather they store the address wherefrom
actual data is obtained.

1.3.2C Operators in Java


The data values that you store and use in
rs i.e., your program are processed as per the given
instructions. Various types of operations can be carried out on the data
float values. The operations
being carried out are represented by operators. Java provides a wide rangè of operators.
efault,
value ) Arithmetic Operators. These are +, , / and % for arithmetic operations addition,
u can subtracti0n, multiplication, division and remainder calculation respectively
(17) Increment/Decrement Operators. These are + (increment operator) and -
store (decrement operator) that increment or decrement a number. These operators,
pe. however, work in two forms, prefix form when used before the operand eg., ++a
and postfrix form when used after the operand, eg, a+.
-

alue.
When used in prefix form, it follows the rule Change-then-use, ie., first the
variable value is incremented or decremented and then used in expression, e,g.,
int S = 5, a = 10;
=
S S+++a
and will evaluate as S = 5 + 11 (a is internally first incremented, becomes 11 and
of a then used). Thus S stores 16 and a stores 11.
the
es. When used in prefix form, it follows the rule Change-then-use, ie, first the
variable value is incremented or decremented and then used in expression, eg
int S = 5, a = 10;
S S+a++
will evaluate as S =5+10 (a's value is first used and then incremented, a becomes
11) Thus S stores 15 and a stores 11.
(ii) Relational Operators. These operators, also sometimes called comparison operators,
compare the values of two variables or literals etc. These are: >, S5> h ,
(i0) Logical Operators. These operators are used to combine two or relational expressions
to make complex expressions for decision-making.
These are: && (And), 1| (or) and (not).
!

(o) Shift Operators. A shift operator performs bit manipulation on data


by shifting the
bits of its first operand right or left.

Table 1.1 Shift Operators

Operator Use Operation


shifting)
op1 >> op2 shift bits of op1 right by distance op2 (signed
shifting)
<< op1 << op2 shift bits of op1 left by distance op2 (signed
shifting)
op1 >>> op2 shift bits of op1 right by distance op2 (unsigned
10 COMPUTER APPLICATIONS-X

(&, 1, and-)work on individual bits of


(v7) Bitwise Operators. Bitwise operators Here, additiom
These operators work as per tollowing
operands and perform bit-by-bit operation. then from this
rules associativity,
1. Any other combination produces 0.
>For AND (&) operations, &1 produces
1
X =a+
1, as does 0 XOR 1. (All these operations
For XOR (^) operations, ^ 0 produces
1
However, the
produces 0.
are commutative.) Any other combination X + y
combination produces 1.
> For OR (1) operations, 0 0 produces Any other
0. 1

and -l produces 0. 1 is equivalent


> For complement ()operations, the -0 produces X+= (y
(vii) Assignment, ?: and other Operators. The assignment
operator = assigns values to a
variable and there are some other operators like new, instanceof,
(dot), [ ], ?: etc. Table 1.2: Operator F

The conditional operator, ?: works as


Operator
expression1 ? expression2 for true result expression3 for false result
:

If expressionl evaluates to true then expression2 is evaluated and taken as overall result
otherwise expression3 is taken and taken as overall result, eg,
insta
6>==4? 9:7 evaluates to 9 because test expression 6 4 is true.
==
4 9? 10: 25 evaluates to 25 because test expression 4 9 is false. new (type)
Java Shothand Operators
Java offers special shorthands that simplify the coding of a certain type of assignment /%
statement. For example,
a a + 10 can be Written as a + 10 >

The operator pair += tells the compiler to assign to a the value of a + 10. This shorthand works
for all the binary operators in Java (those that require two operands). The general form of Java
shorthand is
var = Var operator expression 1s same as var operator = expression

Following are some examples of Java shorthands:


=
X-= 10 means X X -
10 &&
x 5 =
means x x * 5
x /= 2 means X
=
x/ 2
=6 means X =X % 6
The operators +,-,* +-
5F% = etc. are called arithmetic assignment operators
Operator Precedence and Associativity
Operator precedence deternmines the order in 1.3.2D Input im
which sub-expressions are evaluated
expression. The precedence order of Java operators in an
is listed in table below. Input is a
determine the grouping of operands and operators Associativity rules
in an expression with more you input
operator of the same precedence. than one
input you
When the operations in an expression all
have the same precedence Text may
rules determine the order ot the operations. For rating, the associativity
most operators, the evaluation or Dataln)
right eg, is done left to
input is
X = a+b- C using Sca
Chapter 1
REVISING BASIC JAVA CONCEPTS 11
1
bits of
llowing Here, addition and subtraction have the same
precedence rating and so a and b are added and
then from this sumcis subtracted. Again, parentheses
can be used to overrule the detault
duces 0. associativity, e.g,
erations x = a+ (b -
c)
However, the assignment and unary operators, are associated right to lett, eg-
es 1. x+= y -= -~4 ;
is equivalent to
es to a x+ (y -= (-(4)))
?: etc. Table 1.2: Operator Precedence and Associativity

Operator Notes Associativity

O Parentheses () are used to group expressions; a dot () is used Left to Right


result for access to methods and variables within objects and classes;
and is used for arrays

. ++--!~instanceof Returns true or false based on whether the object is an instance


of the named class or any of that class's superclasses
Right to Left

alse. new (type) The new operator is used for creating new instances of classes Right to Left
O in this case is for casting a value to another type
Left to Right
ment */ % Multiplication, division, modulus
Addition, subtraction Left to Right

>> >>> Bitwise left, right shift, and the zero fill right shift Left to Right
<

Relational comparison tests Left to Right


works Left to Right
f Java = Equality not-- equal to
AND Left to Right

XOR Left to Right

OR Left to Right

Logical AND Left to Right


&&

Logical OR Left to Right

Right to Left
? Shorthand for if..then..else
Right to Left
= +-= *= /= %= ^=Various shorthand assignments
Right to Left
&== <= >>= >>>= Various shorthand assignments

1.3.2D Input in Java


an to complete its execution. Mostly
iles Input is any information that is needed by your program
specific devices e g., tor audio
one you input text via keyboard and other forms of input via other
input you need mic.
module (using BufferedReader
Text may be input in java in various ways, such as using java.io
ity class. Using a Scanner class for keyboard
or DatalnputStream classes) or even via using Scanner
to section, we shall revise the input in Java
input is much easier for the beginners. Thus, in this
using Scanner class.
12 COMPUTER APPLICATIONS-X

Scanner is a class that can parse text for primitive


types and substrings using regular 1.3.2E Expressions
a String object, an InputStream, a file
expressions. It can obtain the text from sources such as An expression
The Scanner splits input into substrings,
im

and any class that implements the Readable interface. combination o


of any white space. The tokens
or tokens, separated by delinmiters, which by default consist of the operatie
can then be obtained as strings or as primitive types. operators.
below
To use Scanner class for input, you ned to follow the steps given The expressio
) Import java.util.Scanner class in your program, by giving following statement in the compound expr
beginning of the program type. For inst
import java.util.Scanner expression; if a

() Create an object of Scanner class type by passing it argument as system.in so that it () Arithmeic
connect to keyboard for input. Give following statement for this: Expression t
Scanner inp = new Scanner (System. in) expressions co
containing orm
(in) Using the Scanner object created in step (i), read values using next ) methods, i.e.,
also be forme-
nextInt() for reading integers,
Using Mathe
nextFLoat () for reading floating-point numbers,
nextDouble() for reading double-precision or constants,
numbers,
from variable-
nextBoolean () for reading Boolean values, and
mathematica=
next () for reading Strings.
class defined
For example, the following code snippet shows how to read an integer from the keyboard: Math.
import java.util.scanners
Table 1.3 : Math Fu
Scanner inp = new Scanner (System. in) ;
int i = inp.nextInt () Functions
sin)
Program1.1 cos()
tan )
Write a program to input three numbers and print their asin(y)
Output produced is:
sum of cubes.
Enter Number 1: 3 acos()
import java.util. Scanner; Enter Number 27 atany)
public class Input Enter Number 3 1 atan2(x, y
Three numbers are: 3, 7, 1 pow x. y)
public void sumCubes () { Sum of their cubes is : 371
Scanner inp = new Scanner (System. in) ; exp)
System.out.print ("Enter Number 1: ") ; Enter Number 1 :5 log()
int numl = inp.nextInt () EnterNumber 2 6 sqrt()
System.out .print("Enter Number 2 : Enter Number 3: 7
") ; ceil(x)
int num2 = inp.nextInt ( ) ; Three numbers are: 5, 6, 7
System.out.print("Enter Number 3 : ") ; Sum of their
cubes is : 684 floor()
int num3 = inp.nextInt () ;
int sum = (num1 * numl numl) + (num2
num2 * num2) + (num3 * rint()
System.out.println("Three numbers num3 num3) ;
System.out.printlr("Sum are: "+ num1 +", + num2+",
"
"
abs(o)
+ num3)
of their cubes is: "+ sum) max(a, b

min(a, 0)
Chapter 1
REVISING BASIC JAVA CONCEPTS 13
regular
n, a file, 1.3.2E Expressions
strings, An epression in Java is any valid combination of operators, constants, and variables ie., a legal
tokens combinatiorn of Java tokens. An expression is made up of operands and operators. The objects
of the operation(s) are referred to as operands and the operations are represented through
operators.
t in The expressions in Java can be of any type: arithmetic expression, relational (or logical) expression,
the compound expressiom etc. Type of operators used in an expression determines the expression
type. For instance, if an expression is formed using arithmetic operators, it is an arithmetic
expression; it an expression has relational and/or Boolean operators, it isa Boolean expression.

that it () Arithmetic expressions


Expression that use arithmetic operators are called Arithmetic expressions. Arithmetic
expressions containing all integer type operands are Pure integer expressions. An expression
ds, i.e., containing only real numbers is called real expression. Sometimes a mixed expression can
also be formed which is a mixture of real and integer expressions.
Using Mathematical Library Methods. An arithmetic expression may contain numeric variables
or constants, or two or more numeric expressions joined by valid arithmetic operators. Apart
from variables, constants and arithraetic operators, an arithmetic expression may consist ot Javas
mathematical functions that are port cf java standard library and are available through Math
class defined in java.lang package. You can use these math functions as per following syntax
:

ard Math.function_name (argument list)


Table 1.3: Math Functions Available through Math Class

Functions Action Example


sin(x) This function returns the sine of the angle x in radians Math.sin(6)

This function returns the cosine of the angle x in radians Math.cos(6)


cos(x)
This function returns the tangent of the angle x in radians Math.tan(6)
tan()
This function returns the angle whose sine is y Math.asin(6)
asin(y)
This function returns the angle whose cosine is y Math.acos(6)
acos(y)
This function returns the angle whose tangent is y Math.atan (6)
atan(y)
This function returns the angle whose tangent is x/y Math.atan2 (5.2)
atan2(x, y)
y (x") Math.pow(3,4)
powx, y) This function returnsx raised to
Math.exp(4)
exp() This function returns e raised to x (e")
Math.log(5)
log) This function returns the natural logarithm of x
Math.sqrt(16)
sqrt() This function returns the square root of x
This function returns the smallest whole number greater than
Math.ceil(17.3)
ceil()
or equal to x. (Rounded up)
orMath.floor(17.3)
floor(x) This function returns the largest whole number less than
equal to (Rounded down)
Math.rint(17.99)
rint() This function returns the truncated value of x
Math.abs(-17.9)
This function returns the absolute value of
a
abs(a)
Math.max(13, 17)
max(a, b) This function returns the maximum of a andb
Math.min(13, 17)
min(a, b) This function returns the minimum of a and b.
APPLICATIONS-X
COMPUTER
14
-b+vb40C will be written in Java as 1.3.2F Conditiond
For example, expression 2a The conditic
a * c) )/ (2 * a) execution fi
(-b+ Math. sqrt (b * b-4*
condition-te
2 +b will be written in Java as:
Similarly, expression I. The it Statement
+d
An if stat
+
(a * Math.pow(x, 2) b) / (c
*x+ d) course-of-a-

While evaluating an arithmetic expression, It syntax is


same type) then the result of
the expression is a pure expression (i.e., all operands are of if (exp
if
the expression will also have
same data type as that of the operands. sta
(i.e., if the
if the expression is a mixed expression NOTE
else
), then the
data types of operands are different User can also change the datatype of
sta
will be
operand with smaller datatype's value a value using type-cast operator ()
promoted to bigger data type and then the as
If the expr
expression will be evaluated and the overall result (<target datatype) <value>
a block s
will have the data type same as the bigger data simple or-
type in the expression. This is called internal or 1.e., statem
implicit type conversion or coercion.
Program 1.2
Forexample, expression (int) 3.2 will convert value to imt datatype and thus value 3 will be
used (int cannot store fractions). Similarly, if x is an int variable storing 4, then expression Write a Java Prog
(double)x will change the datatype of x's value to double and thus 4.0 will be used here. This is single digit or
way of explicit type conversion is called type casting. impor
(i) Relational expressions publi
Expressions that establish the relation of two or more variables/values using relational
operators are relational expressions are called relational expressions.
For example, x> y, a l=b, p==r etc. are relational expressions.

i) Logical expressions
Expressions that use logical operators (&&, || and !) to combine
relational expressions to
make a complex expression are called Logical expressions.
For example, (x > y) && (y> z) is a logical expression.
Logical expressions are sometimes also referred
to as Boolean expression as these result
true or false values which are Boolean values. into
The ou
(iv Boolean expressions
Enter a numb
The expressions that result into false or true You entered
are called Boolean expressions.
expressions are combination of constants, variables The Boolean ======
and logical and relational operators.
Forexample, following are examples of some valid Boolean Enter a num
expressions You entered
x>y (y+ z) >= (x/ z)
(a+b) c
&&(c <= d) (y x) < (z y) -
-
Chopter 1
REVISING BASIC JAVA CONCEPTS
15
1.3.2F Conditional Constructs in
Java
The conditional constructs or selection
statements allow to choose the set-of-instructions tor
execution from multiple alternatives
depending upon an expression's truth value (1.e., a
condition-test). Java provides two types
of conditional constructs: if and switch.
I. The if Statement of Java
An if statement tests a particular
condition; if the condition evaluates to true, a
course-of-action is followed, else another course-of
action is followed.
It syntax is:
result of
The true section of if (gets executed if the
if (expression) condition evaluates to true)
statement 1;.
else The false section of if (gets executed if the
statement 2; condition evaluates to false )
type of
ator ()
If the expression evaluates to true the statement-1 (i.e., the true
section, containing a simple or
Lue> a block statement) is executed, otherwise, statement-2 (i.e.,
the false section, containing a
simple or a block staten ent) is executed. In an if-else statement, only the code
associated with if
(1.C., statement-1) or the code
associated with else (i.e., statement-2) executes, but never both.

Program 1.2
will be
ession Write a Java Program that accepts a number in the range 1-99 and then displays if the entered number
.
This is single digit or double digit number.

import java.util.Scanner
public class select {

public void test( ){


ional Scanner inp = new Scanner (System.in)
int num
System.out.print ("Enter a number (1..99) ");
num inp.nextInt );
if ( num > 0 8& num <10)
System.out.println ("You entered a single digit number. ")
S to else
System.out.println ("You entered a double digit number. ")

into
Theoutput produced by above program is:

Enter a number (1. .99) 3


You entereda single digit number.
an
Enter a number (1. .99) 45
YOu entered a double digit number.
APPLICATIONS-X
COMPUTER
16

in its false section, then


IHs
Nested import java.u
statement in its frue section o/and
Itan if statement oontains another if Following program
uses a nested if public class
as nested if statement. public
Such a statement is termed
vc

statement. Scan
int t
Program1.3 float
enters a number range 1..99. But if the user
in the Syste
1.2) assumes that user Modify above
P'revious program (program
above program is not able to handle that. 1..99. tota
given range, the not in range
enters number beyond the Syste
i.e, when users enters number
a
program so that it handles this situation attem
att
import java.util.Scanner if (;
public class select
public void test( else
Scanner inp = new Scanner (System. in)
int num
(1. .99) ")
System.out.print ("Enter a number
num = inp.nextInt ();
if ( num> e && num< 10) The output pre
System.out.println("You entered a single digit number. ") ;

else Enter total classes


if ( num >= 10 && num <
10e) Enter total classes
System.out.println("You entered a double digit number. ") s
Eligible to take
else
System.out.println("You entered number beyond the asked range. ") ; Enter total classe
Enter total classe
Low attendance !N

The output produced by above progranm is:


I1. The switch Statem
Enter a number (1..99) 9 The switch
YOu entered a single digit number. integer or cha
with that con
Enter a number (1..99) 78
YOu entered a double digit number. The syntax o
Switch (e=
Enter a number (1..99) : -4

YOu entered number beyond the asked range. Case

Enter a number (1..99): 999 case


YOu entered number beyond the asked range.
case

Program 14
Case
A student is allowed to take exam it he/she has
attended at least 75% of the classes.
that calculates the attendanceo of a student after Write a progran
obtaining details like total def
classes attended and then prnts if a student is classes held and total
eligible to take exam or
not.
Chapter 1
REVISING BASIC JAVA CONCEPTS 17
ion, then import java.util.scanner
ested if public class Eligibility {
public void Calc(O t
Scanner inp = new Scanner (System. in) ;
int total_classes, attended;
float att_perc;
he user System.out.print ("Enter total classes held : ") ;
y above total_classes = inp.nextInt ();
System.out.print("Enter total classes attended: ");
attended = inp.next Int () ;
att_perc = ( (float) attended/ total_classes)* 100
if (att_perc >= 75.0)
System.out.println ( "Eligible to take exam")
else
System.out.println("LOW attendance !
Not Eligible to take exan") ;

The output produced by above code is:

Enter total classes held : 340


Enter total classes attended 280
Eligible to take exam
======= ==============
Enter total classes held : 340
Enter total classes attended 210
Low attendance! Not Eligible to take exam

I1. The switch Statement of Java


The switch selection statement successively tests the value of an expression against a list of
integer or character constants, for equality ; when a match is found, the statements associated
with that constant are executed.
The syntax of switch statement is as follows:
switch (expression)

case <constant1> :
statement-sequencel
break
case <constant2> :statement-sequence2
break
case <constant3 :
statement-sequence3
break

case <constant n-1>: statement-sequencen-1; Clause enclosed in [] is


ram break; optional clause
[ default :statement-sequence n ]
otal
APPLICATIONS-X
COMPUTER
18
the values of the
constants
values are matched against
The expression is
evaluated and its statement sequence associated
case statements. When a match is found, the
specified in the thee
the break statement or
with that case is executed until statement Fall-Through
is reached. The default
end of switch statement control flows
found. If the case
gets executed when no match is case, in the absence of The fall of control to the
to the next case below the matching following cases of matching
default statement is
break, this is called fall through. The case, is called Fall-Through.
and, if it is missing, no action takes place if al
optional
matches fail.

Program 1.5 case


Rectangle, parallelogranm
of these geometric shapes: 1rangle,
Write a program that calculates areas
circle, and ellipse.
shapes are given here for your reference:
The formulas for areas of these geometric
where b = base and h
=
vertical height case
Triangle Area =xbxh
Rectangle Area = wx h where w = width and h = height
where b base andh = vertical height
=
Parallelogram Area =bxh
Circle Area = Tx r where r = radius
where a and b are semi-major and semi-minor axes.
Ellipse Area = nab
Cas
import java.util.scanners
public class Area
public void calcArea ()
Scanner inp = new Scanner (System.in);
System.out .println( "Area Calculation ") ;
System.out.println("1.Triangle"); Sample runs
System.out.println("2.Rectangle") ; Area cal culatiom
System.out.println ("3. Parallelogram"); 1.Triangle
System.out.println("4.Circle") ; 2.Rectangle
System.out.println("5. Ellipse ") ; 3.Parallelogram
System.out.println("6. Exit")
4.Circle
System.out.print("Enter your choice (1..6) : "); 5.Ellipse
int ch = inp.nextInt (); 6.Exit
double area, base, ht, wid, r, a, b; Enter your cho-
Switch (ch) { Enter base of
case 1: System.out .print ("Enter base of triangle: ") Enter height o
base inp.nextDouble () ; Area of triang
System.out.print ("Enter height of triangle: ")
ht inp.nextDouble () ; Enter your che
area = .5 * base * ht 1/ 1/2 *b*h Enter width of
System.out.println ("Area of triangle is: "+area+" sq Enter height
break; units "); Area of recta
case2: System.out.print ("Enter width of rectangle: =========
");
wid =inp.nextDouble();
System.out.print ("Enter height of
recttangle: ");
Chapter 1
REVISING BASIC JAVA CONCEPTS
constants 19
associated
ht inp.nextDouble();
area = wid * ht ;
System.out.println("Area of rectangle is: "+area+" sq units")
break;
to the case 3: System.out.print ("Enter base of parallelogram: ");
matching base = inp.nextDouble () ;
ough. System.out.print("Enter height of parallelogram: ");
ht inp.nextDouble();
area = base *
ht;
System.out.println ("Area of parallelogram is : "+area+" sq units");
break;
case4 System.out . print("Enter radius of circle : ");
lelogram, r = inp.nextDouble();
area = 3.14159 * r *rs // pi*r*r
System.out.println ("Area of circle is : "+area+" sq units ") ;
break;
case 5: System.out.print("Enter minor axis of ellipse: ");
a = (inp.nextDouble() ) /2
System.out.print("Enter major axis of ellipse: ");
=
b (inp.nextDouble() ) / 2
area = 3.14159 * a *b; // pi*a*b
axes. System.out.println ("Area of ellipse is: "+area+" sq units");
break;
case 6 System.out.println("Exiting... ");
break;

Sample runs of above program are shown below :

Area Calculation Enter your choice (1..6) : 3


1.Triangle Enter base of parallelogram:4
2.Rectangle Enter height of parallelogram 5
3.Paralllelogram Area of parallelogram is 20.0 sq units
4.Circle
5.E11ipse Enter your choice (1..6) 4
6.Exit Enter radius of circle 3.5
Enter your choice (1..6) 1 Area of circle is :38.4844775 sq units
Enter base of triangl 7 e:
Enter height of triang le :5 Enter your choice (1..6) : 5
Area of triangle is: 17.5 sq units Enter minor axis of ellipse : 5
Enter major axis of ellipse: 7
Enter your choice (1..6):2 Area of ellipse is: 27.4889125 sq units
Enter width of rectangl e :4
D: Enter height of rectang l e: 5
Area of rectangle is 20.0 sq units
COMPUTER APPLICATIONS-X
20

1.3.2G lferative Constructs Java in


allow a set of instructions to be performed As you can see tha
The iterative constructs or iteration statements statements are also called loops iterates over the ra
repeatedly until a certain condition is fulfilled. The iteration adds it to sum anc
or looping statements. Java provides three looping
statements for loop, while loop, and body of the loop o
do-while loop.
sum += (i*
I. The for Loop
are
Java loops. All its loop-control elements Program 1.7
The for loop is the easiest to understand of the
gathered at the top of the loop. Modify previous progran-
The general-form (syntax) of the for loop
statement is cubes till every odd numl
expression (s ); test-expression; update expression (s) ))

for (initialization public class Loop


body-of-the -loop public void pr
into the for int sum = E

) The initialization expression(s) is carried out ONLY ONCE before entering for (int i
loop, i.e., when for loop begins execution. cube =
(i) The test expression is next evaluated, Initialization Syste
if it returns true, the for loop's sum
expression(s)
body is executed and if it returns System
false then for loop terminates. False
(i) The body of the loop contains either Condition2
The exit
one statement or a block con- condition
Update True
taining multiple Java statements. expression(s)
The body of the loop gets executed Output produced is:
Statement 1
every time the test-expression Cube of 1: 1
The loop body
evaluates to true. Sum of cubes of odd
10) The update expression(s) is per- Statement2 Cube of 3: 27
Sum of cubes of odd
formed after execution of the body
Cube of 5: 125
of the loop and the steps step (ii) Sum of cubes of odd
onwards repeated. Figure 1.4 Cube of 7: 343
Sum of cubes of odd
Program 1.6 Cube of 9: 729
Sum of cubes of odd
Write a program to calculate and print the sum of cubes of odd numbers in the range 1..10.

public class Loop


public void prnCubes () { I1. The while Loop
int sum = 0; The body of this for loop contains
=
The while loop
+= JLust one statenment
for (int i 1;i< 10; i 2) of a while loo-
sum += ( i*i*i) ;
System.out .println("Sum of cubes of odd numbers between 1..10 is :" while (tes
+ sum)
loop-body

where the loop-body

Output produced is: The loop iter


Sum false, the pro
of cubes of odd numbers between 1..10 is: 1225
Chapter 1: REVISING BASIC JAVA CONCEPTS 21

rformed As you can see that above program uses a for loop that starts with initial value of i 1;
ed loops iterates over the range 1.10; for every value of i < 10 (test-condition), it calculates the and i
op, and adds it to sum and then updates the variable i's value with update expression as i+=2. The
body of the loop contains just one statement:
sum+= ( i*i*i)

ents are Program 1.7

Modify previous program to calculate and of odd numbers in the range 1.10. Also, print the sum of
cubes till every odd number in the range.
public class Loop
public void prnCubes () { As there are multiple statements irt
the body of this loop. the statements
int sum = 0, cube = 0 are enclosed in { }. i.e., the block of
the for
for (int i = 1; i < 10; i+ 2) {
Statemens
cube ( i *i*i)
System.out.println ("Cube of "
+ i+ "
: "
+ Cube) ;
sum+= Cube
system.out.println("Sum of cubes of odd numbers till 1.." +i+ "
: "+ sum) s

NOTE
In a for loop, the initialization
expression(s), test-expression and the
Output produced is
update expression(s) are optional,
Cube of 1: 1 1.e., you can omit any one, two or all
o body Sum of cubes of odd numbers till 1..1: 1 of them, depending upon your logic.
Cube of 3: 27 But the body of the loop must have at
Sum of cubes of odd numbers til1 1..3: 28 least one statement in it.
Cube of 5: 125
Sum of cubes of odd numbers til1 1..5: 153
Cube of 7: 343
Sum of cubes of odd numbers till11..7: 496
Cube of 9: 729
Sum of cubes of odd numbers till 1 ..9: 1225

II. The while Loop


is true. The syntax
The while loop of Java, iterates or repeats as long as the given test-condition
of a while loop is

while (test - expression)


loop-body
statement or an empty statement.
where the loop-body may contain a single statement, a compound

true. When the expression becomes


The loop iterates while the test-expression evaluates to
loop-body code.
false, the program control passes to the line after the
22 COMPUTER APPLICATIONS-X

The usage form of while loop is like Program 1.9


Initialization expression (S )
while (test-expression) Write a program that in
loop-body has entered a zero. It al
including update expression (s) import java.
public class=
public v
Program 1.8 int

Write a program that displays the sum of all numbers entered by


user. The program should keen Scan
do
taking input until a 0 (zero) is entered.
import Jjava.util.Scanner s

public class Sum


public void calcsum () w
int sum = 0, num =-1; // initial value is so that the condition is true initially Sys
Scanner inp = new Scanner (System. in)
while ( num != 0)
System. out.print ("Enter number: ") Program1.10
num = inp.nextInt ();
sum = Sum+ num Write a program that
entered.
System.out.println ("Sum of numbers entered so far: "+ sum ) import jav
public cl=
publi

Output produced is:


Enter number: 3
Enter number: 6
Enter number: 2
Enter number: 1
Enter number: 4
Enter number: 0
Sum of numbers entered so far : 16

I1. The do..while Loop


The do..while loop also works based on a condition but it is designed in such a
way so that it
executes at least once even if the test-condition is false. The reason behind it Output produced i
is that the
do..while loop evaluates the condition after executing the body of the loop. Enter a number
Everytime atter
executing loop-body, the fest condition is evaluated and if it is true, the loop body is Enter a number
re-executed
otherwise loop terminates. Enter a number
The syntax of the do-while loop is: Enter a number
Enter a number
do
Enter a number
statementl; a number
Enter
statement2 Total numbers
Total even nu
while (test-expression)
JAVA CONCEPTS 23
Chapter 1: REVISING BASIC

Program 1.9
stops if 5 numbers have been entered or
user
Write a program that inPuts maximum numbers and
5
count of non-zero numbers entered.
has entered a zero. t also prints the
import java.util.scanner
public class count
public void readNum () { Output produced is
int count = 0, num = 0 Enter a number
Scanner inp
=
new Scanner(System. in); 8
Enter a number
:

uld keep do { Enter a number: 2


System.out.print ("Enter a number: ");
Enter a number: 0
num inp.nextInt () 4
Total numbers entered:
count++
while(count 5 && num !=
< 0)
numbers entered"+ COunt) ;
System.out .println("Total
itially

Program 1.10
have been
Write a program that inputs maximum
10 numbers but stops as soon as 4 even numbers
entered.
import java.util.Scanner
public class count {
public void readNum() =
int count = 0, num = 0, evenCount 0
Scanner inp = new Scanner (System.in)
do
a number :
")
System.out .print("Enter
num = inp.nextInt() 3

count++5
if (num % 2 == 0)
evenCount++;
while(count 10 && even Count 4)
<
<

System.out.println("Total numbers entered:"+Count)


;
+evenCount) " ;
System.out.println ("Total even numbers entered:

that it NOTE
Output produced is
nat the Since for and while loops test the
e after Enter a number :5 condition before entering into the
loop, they are called
entry-
ecuted Enter a number:2 do.. while
Enter a number: 7
controlled loops. The
the
Enter a number:3 loop, on the other hand, tests
condition at the time of exit from
Enter a number :2
the loop, this loop is called
Enter a number:8 exit-controlled loop.
Enter a number:4
Total numbers entered: 7
4
TOtal even numbers entered
24 COMPUTER APPLICATIONS-XX

Chop
IV. Nested For loops
A loop may contain another loop in its body. This form of loop
a is called nested loop. In. for( i 1;ic
before the outer loop. When a for loop containe for( j 1
nested loop, the inner loop must terminate
called nested for loop. Syste-
another for loop in its body, it is
some patterns using nested for loops.
Consider following examples that print System.Ou

Program 1.11 NOTE


If in any loop, if the test-condition
Write a program to print an inverted triangle of three lines is missing or is not reachable, then
using "#" such a l0op will repeat endlessly V. The break and continue State
and hence is called endless loop or The break and continu
public class Nested { infinite loop. control flow of executio
public void prin()
=
int i = 3, j 6 The break statement
( <j; itt)
for i The break statement w
System.out println();.

=
for (int k j; k> i; k-) Output produced is : executed inside a loop
System.out .print("# ");
statement following th
## #
## The continue statemem
When a continue stat
statements in the bod
Program 1.12

Write a program to print a triangle with numbers 1


to 4 in 4 rows using a nested for loop.
LET US REVISE
public class Nested
public void prin( ) Java is a popular Object Ori
that run across multiple oper
e=
An object is an identifiable
int i, j
= Output produced is A is a blueprint repres
for( i 1; i <= 4; ++i) { class
for(j 1; j <=i; +j) { 1 Data abstraction refers to ti
1 2 explanations.
system.out.print (j+ "
*) ;
1 2 3 The wrapping up of data a
System.out.println () 12 3 4 encapsulation.
The Java Byte Code is a ma
independent of the compute
The JVM compiler Gavac)
which can then be execute
Program1.13 An initial class contains
m

The building blocks of a F


Write a program to print a triangle with odd numbers from 1 to 10 using a nested for loop. Java offers two selection
public class Nested Java offers three iterative
The break and continue
public void prin( )

int i, j
Chopter 1: REVISING BASIC JAVA CONCEPTS 25
loop. In a for( i 1; ice10; + 2 )
i Output produced is:
contains for( j 1; j <e i; j+ 2)
System.Out.print (j + ")

System.out.println(); 13 5
13 57
13 579
ondition
ole, then
ndlessly V. The break and continue Statements
loop or The break and continue statements are called jump statements as they jump the normal
control flow of execution.

The break statement


The break statement when used inside a switch, ends that case and when a break statement is
is: executed inside a loop, the loop is terminated and program control resumes at the next
statement following the loop.

The continue statement


When a continue statement is executed inside a loop, then from that point all remaining
statements in the body of the loop are skipped and loop proceeds with the next iteration.

LET US REVISE
powerful applications
Java is a popular Object Oriented programming language that is used to build secure and
that run across multiple operating systems.
An object is an identifiable entity with some characteristics and behaviour.
common properties and relationships.
A class is a blueprint representing a group of objects that share
features without including the background details or
Data abstraction refers to the act of representing essential
explanations.
on the data) into a single unit (called class) is known as
The wrapping up of data and functions (that operate
encapsulation.
The Java Byte Code is a machine instruction for a Java
processor chip called Java Virtual Machine. The byte code is
independent of the computer system it has to run upon.
code/program file (java files) into byte code (.class files),
The JVM compiler (javac) compiles the Java source
program (java).
which can then be executed using Java interpreter
it. The program is given the same name as that of
its initial class.
An initial class contains main function inside
variables etc.
objects, methods, statements, expressions,
The building blocks of a program are classes,
switch.
Java offers two selection statements: if and
iterative constructs: for,
while and do.. while.
Java offers three
statements of java.
The break and continue are jump
COMPUTER APPLICATIONS-X
26

onceptual Questions
Type Guestions
Section A: Objective 1. Using Java n=
zero.
Ans.
1. Java uses character set.
2. Smallest individual unit in a program is called the i
strin
3. Which of the following is not a tokern ?
the
(a) keywords (b) identifiers O) statement (d) operators
2. What is a t
Identify the illegal identifier from the following
Ans. A f
(a)_CHK (6) apyt 20_to_50 (d) A_to_Z
certain type
?
5. Which of the following does not represent a character literal we say that
(a) a ()a (d) "a For exa
6. Which keyword turns a variable declaration into constant declaration stored in th
(a) const (6) constant final (d) fixed 3. What is a l

7. ch + 2 is equivalent to Ans. A
(a) ch = ch+2 example, 4
(b) ch+2
number 17
() ch = +2 (d) none of the above
with the v
8. The Math class is part of which Java library package.
4. Construct
(a) java.util (b) java.io (c) java.random (d) java.lang positive, t
9. Which clause is optional in a switch statement ? zwhich wom

(a) switch (6) case (c) default (d) none of the above.
10. Absence of which statement causes a fall-through in Ans.
a switch statement.
(a) continue by break (c) stop 5. 1f the valh
(d) fall
11. By default, the if-part and else-part of an if statement can contain
these many statements in it.
(a) 2
b) 1 (c)5 (d) as many Ans.
12. Which of the following loops
is mostly used for fixed number of 6. Suppose
iterations ?
(a) for integer v
(b) do-while
(c)while (d) none of the above Ans.
13. Which of the following is not an
entry controlled loop 2
(a) for 7. Given tl
) do-while
(C)while
(d) none of the above
14. Which of the following is an exit controlled
loop?
(a) for
b) do-while
()while (d) none of the Identif
above
15. Which of the following statements terminates
the complete execution of
(oybreak a loop?
(6) continue
(c) terminate
(d) System.exit(0)
Chopter 1
REVISING BASIC JAVA CONCEPTS
27
Section B: Subjective Type
Questions
1. Using Java notation, provide the
integer value zero, a string consisting of zero,
zero. a and the character
Ans.
the integer value zero 0
string consisting of a zero: "0"
the character zero: "0
2. What is a type, as this term relates to
programming ?
Ans. A type or datatype represents a set
of possible values. When we specify that a
certain type, we are saying what values it can variable has a
hold and what operations can be performed on it. When
we say that an expression is of a
certain type, we are saying what values the expression can
For example, to say that a variable is of
have.
type int says that integer values in a certain range can be
stored in that variable.
3. What is a literall?
Ans. A
iteral is a sequence of characters used
in a program to represent a constant value. For
example, 'A is a literal that represents the value A, of type char,
and 17L is a literal that represents the
number 17 as a value of type long. A literal is a way of writing a value,
and should not be confused
with the value itself.

4. Construct an expression that is equal to the absolute value of a variable.


That is, if a variable p is
positive, the value of the expression is just p, but if p is negative, the value the
of expression is p -

which would be positive. Do it:


e. Using a conditional operator. (Do not use the mathematical function here).
Ans. p>0?p:-p
5. Ifthe value of basic= 1500, what will be the value of tax after the following statement is executed?
=
tax basic > 1200 ? 200:100 [ICSE 2019

Ans. 200
6. Suppose x1 and x2 are two double type variables that you want to add as integers and assign to an
integer variable. Construct a Java statement for doing so.
Ans. Assuming that target variable is res of type int.
res = (int) (x1 + x2) ;
7. Given the following set of identifiers:

byte b char ch
short shs int intval ;
Long longval; float, fl ;

Identify the datatype of the following expressions:


(a) 'a-3
(b) intoal *
longval - ch

) fl +longval/sh
COMPUTER APPLICATIONS-X
28

Ans.
(c) Identify
(a) int because and
(i) public
3
Ans.
char int (a) Operat
Operas
Lnt Unary
operat
(6) long because tor ex=
- (b) Short d
(intval *longval) ch
() ) p
int Long char (i)
(in)
long (io)

long
12. State the rules
because Ans. All exp
float the rules that g
fl (longval / sh) Operators
Any expres
float long short
The assign

long
13. What is the u
Ans. The
operations cat
float etc. As these 1
8. Suppose x1 and x2 are two type double variables that you want to add as integers and assign to an trouble of cre-
integer variable. Construct a Java statement for doing so. 14. Differentiate
Ans. Assuming that target variable is res of type int. Ans. An
res = (int) (x1 + x2) course-of-act
9. The switc
What is casting, when do we need it ?
or character
Ans. Casting is a form of conversion, which uses constant are
the cast operator to specify by a type name
parentheses and is placed in front of the value to in
be converted. For example: The if sta
result
(float) total / count it but switcl
They are helpful in situations where we 15. How is the
temporarily need to treat a value as
10. What will be the output
another type. Ans. The
of the following ?
section mus
System.out.println(1 +9 + "Super"); any kindo
System.out.println("Hello" +2+3) ; 16. What is th
Ans. 10 Super Ans. Bo
Hello 23 difference
11. (a) Writea difference betuween unary and binary do.whilel
operator. loop migh
b) Write the memory capacity (storage size)
of short and float data type since thete
in bytes.
Chapter 1
: REVISING BASIC JAVA CONCEPTS 29
(c) Identify and name the following tokens:
) public i) [ICSE 2019
'a' (ii)== (io)
Ans.
(a) Operators that act on one operand are referred to as Unary Operators while Binary
Operators act upon two operands.
Unary + or Unary increment/decrement operators are the examples of Unary
operator. While binary operator +, *, / and % are the examples of binary operators,
for example, (+) adds values of its operands.
(6) Short data type is of 2 bytes and float is of 4 bytes.
() () public Access Specifier in a class
(i)a character literal value
(ii)== a Relational operator
(io) the Curly braces, which are used for creating blocks, i.e., surrounding
the bodies of loops, methods and classes.
12. State the rules of operator precedence.
Ans. All expressions are evaluated according to an operator precedence hierarchy that establishes
the rules that govern the order in which operations are evaluated.
Operators (type). /, and tie remainder operator % are performed before +and.
Any expression in parentheses is evaluated first.
The assignment operator has a lower precedence than any of the arithmetic operators
13. What is the use of Math class of java library ?
Ans. The java.lang. Math class includes many methods with which many simple arithmetic
operations can be done like finding the square root, rounding, trigonometric and logarithm functions
etc. As these methods are defined as static, they can be used directly by the programmer without the
trouble of creating an object.
to an [ICSE 2019
14. Differentiate between if else if and switch-case statements.
Ans. An if statement tests a particular condition; if the condition evaluates to true, a
course-of-action is followed, else another course-of-action followed.
is
The switch selection statement successively tests the value of an expression against a list of integer
or character constants, for equality; when a match is found, the statements associated with that
me in constant are executed.
The if statement is more general and versatile statement as we can test any type of condition with
it but switch statement supports only equality comparison and that too with one variable.
15. How is the if.else if combination more general than a switch statement ?
Ans. The switch statement must be controlled by a single integer control variable, and each case
section must correspond to a single constant value for the variable. The if...else if combination allows
any kind of condition supporting all types of comparisons after each if.
16. What is the main difference between a while loop and a do.while loop ?
Ans. Both types of loops repeat a block of statements until some condition becomes false. The main
difference is that in a while loop, the test-condition is tested at the beginning of the loop, and in a
do..while loop, the test-condition is tested at the end of the loop. It is possible that the body of a while
loop might not be executed at all. However, the body of a do.. while loop is executed at least once
since the fest-condition for ending the loop is not tested until the body of the loop has been executed.
APPLICATIONS-X
COMPUTER
30
What are jump statements
?
in program are called jump
17.
that cause unconditional control-transter 22. Rewrite the follo
Ans. The statements statements are break and
continue.
statements. Two most common jump if (bi
? dis
What does a break statement do the first statement
18.
terminates the current loop and proceeds to t that else
Ans. A break statement di
follows that loop.
in the following loop
For example, the break statement Ans.
= d++) discom
for(int d 2; d<n;
23. Convert follow
isNotPrime = (n%d = 0);
; int i
if(isNotPrime) break
int
do
follows it.
stops the loop and executes the next statement that
is executed:
19. State the data type and value of res after the following
char ch = 9';
res Character . isDigit (ch) ; ICSE 2019
Ans.
Ans. Data type of variable res is boolean and its value is true. int
20. What is the value of x1 ifx =5 ? for
xl =++x x++ + --x - [ICSE 2017
Ans. Value off x1 will be 6, because
xl= +x -
X+ + -X
= 6 (x is first incremented to 6 and then used)
24. Analyze the
6 (firstly
value 6 is used and then x is incremented to 7)
+6 (x is first decremented to 6 and then used) for(in
fo
21. Convert the following if else if construct into switch case
=
If(var 1)
System.out.println ("good ")
else if(var == 2)
System.out.println ("better "); (a) How
else if(var == 3)
(6) Write
System.out.println ("best ") ;
else Ans. (
System.out.println("invalid"); (b
Ans. [ICSE 2018
switch (var) {
case 1: System.out.println 25. Predict th
case System.out.println ("good"); break
2: ("better ") break clas
case System.
3: out.println("best"); break;
default: System.out.println("invalid");
Chapter 1: REVISING BASIC JAVA CONCEPTS
alled 31
jump 22. Rewrite thefollowing using ternary
operator
if (bill 10000)
discount= bill * 10.0/100
ement
that else {
discount=bill * 5.0/100;
[ICSE 20181
Ans.
=
discount (bill>
( bill 10.0/10e ): (bill
1000e )?
5.0/100)
23. Convert following do-while loop into for loop.
=
int i 1;
int d = 5
do
d =
d* 2
. println
System.out (d) ;
it+
}while (i <= 5) ;
SE 2019] ICSE 2017]
Ans.
int i = 1, d = 5 ;
for ( <= 5; it+)
i
SE 20171 =
d d* 2
System.out.println(d) ;

n used)
24. Analyze the given program segment and answer the following questions:
ed to 7)
used) for(int i = 3 ;= i <= 4; i++) {

for (int j 2;j<i; j++) {

System.out.print (" ") ;

System.out.println( "WIN")

(a) How many times does the inner loop execute ?

(b) Write the output of the program segment. [ICSE 20171

Ans. (a) Inner loop executes 3 times in total (1 time for value i = 3 and 2 times for value i = 4)
(b) WIN
2018]
WIN

25. Predict the output:


class Test {
public static void main (String args [0)
{

int var = 10
double x = 10
System.out.println( "Original value of var: var)
"
+
APPLICATIONS-X
COMPUTER
32 Ch
;
of x: "+Xx)
System.out.println ("Original value
28. Predict the output:
var= var/ 4
class NoZeroDiv (
X=X/ 4 "+ var);
System.out.println( "var after division x);
:
public
"+ static vo
System.out.println( "x after division: int result
for(int i

result
Ans. if(i l=
original value off var :
10
Sy
original value of x
:
10.0
: 2
var after division
x after division 2.5 :

Give the output of the following code


:
26. Ans.
String P ="20", "19"; Q = 100/-2 is --5
int a = Integer .parseInt (P); 100/-1 is
int b = Integer. valueOf (Q 100/1 is 100
System.out .println (a+*+b) ;
[ICSE 2019 100/2 is 50
100/3 is 33
Ans. 2019 (as
"
- null string is in between) 100/ 4 is 25
100/5 is 20
output of the following code and mention how many times the loop will execute
?
27. Give the
29. Gire the output of the f
int i executed :
for(i 5 ;i=1; i--)
int a, b=
for (a 6,
if(i% 2 == 1)
continue if(a %b
System.out.print (i+" ");
bre
[ICSE 2019

Ans. Answer will be 4 2 System.out.

And the loop will execute 5 times. Ans. Output: 12


Explanation: Number of times
The loop control variable i: (Loop repeats for
-
is initialized with value 5 30. Predict the output
and tests against loop condition i>=1 NoB {
class
and updates every time as
i- i.e., decrements by value 1. public sta
int i;
Thus, it means the loop will execute for these values for(1
of i: 5, 4, 3, 2, 1 and will exit as soon as
becomes 0. Thus, the loop will execute 5 times but the
value of i will get printed only twice BECAU
of the following code inside loop body:
if(i % 2 == 1)
continue;
Thus, for i's values that yield remainder as 1
when divided by 2 (i.e., values
simply skip the rest of the loop body (that 5,3, 1), the control wil
contains the System.out.print( )) te
expression but for the values 4 and 2, the
values get printed and hence
and move to up
the output.
Chopter 1
: REVISING BASICJAVA CONCEPTS 33
28. Predict the output:
class NozeroDiv {
public static void main(String args
[) (
int result ;
for(int i -2; i< 6; i++) -
result =i!=0? 100/i0
if(i l= 0)
System.out .println ("100 /" +i+ "is" + result) ;

Ans.
100-2 is -50
100-1 is -100
100 1 is 100
CSE 2019]1 100 2 is 50
100/ 3 is 33
100/ 4 is 25
100/5 is 20
29. Give the output of the following program segment and also mention the number of times the loop is
executed
int a, b;
for (a = 6, b
=
4; a<= 24, a =
a +6)
if(a % b == 0)
SE 2019] break

System.out.println (a) ; ICSE 2017]

Ans. Output: 12

Number of times loop repeated: 2


(Loop repeats for values 6 and 12; for value 12 break gets executed and loop terminates)
30. Predict the output
class NoB {
public static void main (String args [0)
{

int 1
n asi for (i = 0; i <= 5; i+) {
AUSE switch (i) {
case 0: System.out.println (i + "is less than one") ;
case 1: System.out.println(i + "is less than two");
case 2: System. out.println (i + "is less than three");
case 3: System.out.println (i+ "is less than four");
l will case 4: System.out.println (i+ "is less than five");
odate
COMPUTER APPLICATIONS-X
34
System.out.println ();

Ans.
0 is less than one
0 is less than two
0 is less than three
0 is less than four
0 is less than five
1 is less than two Ans. The error
1 is less than three
1 is less than four int S=

1 is less than five calculates the summ


2 is less than th ree System.
2 is less than four
2 is less than five calculates s/4 to
result as integer.
3 is less than four So the cause of t
3 is less than five
33. Correct the code
4 is less than five
public cl=
31. Predict the output publi
class Mult {
public static void main (String args [])
int i, j;
for(i =0, 10; i<j; j =
itt, j-
System.out.println ("i and j: "
+ i +" "

+j);

Ans.
i and j:0 10
i and j :19
i and j : 2 8
i and j : 3 7
and j 4 6
32. Find the error. The following code
is not giving intended result the 34. Write a progr
average of four numbers 10, 11, 12, average of three numbers, eg
13 is 11.5 but it is Ans.
showing 11. Find out the reason.
import java.util.scanner; imp
public class ScannerInput ( cla
public void calcAvg()
Scanner input = new Scanner
(System.in)
System.out.print ("Enter
first number : ");
int a =
input.nextInt ();
Chapter 1: REVISING BASICJAVA CONCEPTS 35
System.out.print ("Enter second number: ");
int b input. next Int ();
System.out.print ("Enter third number: ");
int c= input.nextInt ();
System.out.print ("Enter last number: ");
int d = input.nextInt ();
int s (a +
b+c+ d) ;
System.out .println( "Average is "
+ S /4);

Ans. The error in above code is a logical error. The statement:

int s = (a + b+ c +d) ;

calculates the sum of four integers a, b, c, d and stores in an integer variable s. So, when the statenment
System.out .println ( "Average is" +S /4);

calculates s/4 to print average, then s, an integer when divided by another integer 4 will give the
result as integer. So it produces the result of s = (10 +11 +12 +13)/4 as 11, in place of 11.5.
So the cause of the erroneous result is the pure integer division expression s/4.

33. Correct the code of previous question so that it produces the correct result.
public class ScannerInput {
public void calcAvg () {
Scanner input = new Scanner (System. in);
System.out.print ("Enter first number: ")
int a = input.nextInt ();
System.out. print ("Enter second number : ") ;
int b input.nextInt ();
System.out.print("Enter third number: ");
int c = input. nextInt ();
System.out .print("Enter last number: ");
int d input.nextInt (); Corrected statement
double s = (a+b+c+d) ;
System.oút.println("Average is "
+ s /4);

Armstrong number.
34. Write a program to input a number and test if it is an
the
Ans.

import java.util. Scanner;


{
class ArmstrongNumber
public static void main(String args[)
digits 0;
int n, sum = 0, temp, remainder,
=

Scanner in
=
new Scanner (System. in) ;

a number: ") ;
System.out.println("Enter
COMPUTER APPLICATIONS-X
36
n in.nextInt ()
temp= n 36. Write a program to pri-
// Count number of digits
while (temp I= 0) { Ans. public clas=

digits++ public
temp = temp 16s int-
for

temp = n s

while (temp I= e)
remainder = temp 10
sum = sum+ power (remainder, digits)
temp =
temp 10

if (n == sum) 2 46 8
System.out. println (n + "is an Armstrong number. "); 2 46
else 2 4
System.out.println (n + "isn't an Armstrong number. ")
37. Using the switch-c
static int power (int n, int r)
(a) To generate

int c, p = 1;
for (c = 1; c <= r C++)
P P*n
return P

35. Write a program to input a number and print its reverse number.
(6) Display the_
Ans.
import java.util. Scanner;
class ReverseN{
public void rev()
int n, reverse = 0
Scanner in Scanner (System. in) ;
= new
Solution.
System.out.println("Enter number: ")
n = import ja
in.nextInt () Men
class
while(n!= 0)
publi
reverse =
reverse *
10
reverse = reverse + n% 10;
=
/l extracted digit added to reverse
n n/10,
extracted digit dropped from number
System.out.println("Reverse of the number
is" + reverse);
Chapter1: REVISING BASIC JAVA CONCEPTS
37
36. Write a program to print a reverse triangle with even
numbers from 2 to 8 using a nested for loop.
Ans. public class Nested
public void prin()
int i, j=
for( i 8; i>0; i -= 2)
=
for( j 2j=i; j+= 2 )
System.out.print (j+ * *)

System.out.println ();

2 4 6 8
2 6
2 4

37. Using the switch-case statement, write a menu driven program to do the following :
(a) To generate and print Letters from A to Z and their Unicode

Letters Unicode
A 65
B 66

90

(looping) statement:
(6) Display the following pattern using iteration

[ICSE 2019]
4 5

Solution.
import java.util.Scanner
class MenuDriven

public static void


main(String[ ]args)

Scanner kb
= new Scanner (System. in):
mber int choice;
do MENU")
System.out.println ("\t
Unicode of A to Z ");
System.out .println("1. See with digits")
System.out .println("2. Pattern
38 COMPUTER APPLICATIONS-X

System.out.print("Enter Your Choice (1 or 2): ")


choice kb.nextInt() 38. A tech number has eve
Switch(choice) sum of these halves is
case 1: System.out.println("Letters Unicode") ; tech numbers.
i++)
for (int i = 65 ; i <= 90; (char)i+ ": +i); "
Example:
System.out. println( Consider the numE
break;
Square of sum of
case 2: int k
=
for(int i 1; i <= 5; i++)

k 1 Ans.
for (int j = 1;j <=5s jt+)
class TechNum
if(j= i)
public sta

System.out.print (k) ;
k++ int fh
System

else
System.out.print (" ") ;

System.out. println( )

break
default: System.out. println ("Invalid choice") ;

}while (choice == 1 || choice == 2) ;

Sample output
Sample output 1: 4-digit
Sample output 2: 2025, 30=
MENU
MENU
1. See Unicode of A to Z
1. See Unicode of A to Z
2. Pattern with digits
2. Pattern wi th digits
Enter Your Choice (1 or 2):1
Enter Your Choice (1 or 2) :2
Letters : Unicode
1
A 65
12
KEYWORDS
B: 66
123
C: 67 Explicit Type Conversion
D 68 1234 by
Identifier Name given
12345
Implicit Type Conversion
Nested Loop A loop insi
W: 87
Token The smallest indin
X: 88
Type Casting Explicit cor
Y 89
Z 90
Chapter 1
REVISING BASIC JAVA CONCEPTS 39
38. A tech number has even number of digits. the
If number is split in two equal halves, then the square OJ
sum of these halves is equal to the umber itself. Write
a program to generate and print alt
tech mumbers. foir u
[ICSE 2019]
Example:
Consider the number 3025
Square of sum of the halves of 3025=(30+25)

(55)
= 3025 is a tech number.

Ans.
class TechNum

public static void main(String []args)


{

int fh, sh, sum_sqr


System.out.println ("4-digit Tech numbers ane:")
for (int i= 1000 i <= 9999; i++) //Taking 4 digit numbers only

fh i/10e
sh i% 100
sum_sqr = (int) Math.pow( (fh+sh) , 2) ;
if(sum_sqr == 1)
System.out.print (i+", ") ;

Sample output 1

4-digit Tech numbers are:")


2025, 3025, 9801,

KEYWORDS
Explicit Type Conversion User-defined type conversion.

ldentifier Name given by user for a part of the program.


implicit Type Conversion Type conversion automatically carried
out by the compiler.

Nested Loop loop inside body of another loop statement.


A

Token The smallest individual unit in a program.


ype Casting Explicit conversion of an operand to a specific type.
COMPUTER APPLICATIONS-X
40

SSign ment d
e
Math.sqrt (Mat
Math.round (3.
f Math.max(1.Se
1. What is meant by token Name the tokens available in Java.
?
8 Math.ceil(4.6
2. What are keywords ? Can keywords be used
as identifiers ? h Math.min(-5,
?
rule(s) of Java i Math.floor(7
3. What is an identifier ? What is the identifier forming
Math.ceil(-2
4. What kind of program elements are the following? k Math.pow(16,
)
13, 'a, 4.38925, "a", main( 1 Math.pow(4,
What kind of constants are the following?
m Math.round (1
5.
14, 011, OX24, 17, 014, OXBC1 n Math.round(
Write the following as
Java? How are nongraphic characters represented in Java
? 15.
6. What is a character constant in
7. Write an equivalent Java expressions for the following expressions: (a) va-
(i) ya +b 16. A student incorrectly
6 (int)Mat

3x +5y 8xy 3/2 Correct the error in e


(ii) a +b>=b" +a (Gio)

5x +3y 2yx 17. What is the significa


8. What is meant by implicit and explicit type conversion ? 18 What are iteration st
9. What do you mean
19. What is meant by an
by type casting ? What is type cast operator in Java ?
20. What is meant by a
10. What will be the resultant type of the following expression if bh represents a byte variable, i is an i 21. What is the differen
variable, fl is a float variable and db is a double variable?
22. How many times is
bh-i+db / fl -i * f1+ db / i 23. What is nested loop
11. What will be the resultant type of the following expression if fl is a float variable and db is a double 24. Write a program to
variable ?

(int) (fL + db)


12. Determine the data type of the expression 3
3
100(1-pa)_(p+/s 5 43
(q+) (long)(s + P)) 25. Write a program
Ifp is an int, r is a float, q is a long and s is double. 1 2 3
13. Determine the data type of the expression 1 23
1 2
1 2

5w+6z 1

if x is int, y is long, w is float, z is double, p is short 26. Write a program


and q is long double.
14. State the value and type of each expression. 1
10
a Math. abs (-5)-Math. abs (-7) 1
b Math. abs (-le-1) + Math.abs (-2e-2) 10
Math.sqrt(0. 0064)
Chopter 1
REVISING BASIC JAVA
CONCEPTS
41
d Math.sqrt(Math.pow(2.7,
e 2)
Math.round (3.499)
Math.max(1.5e-2,
0.095)
Math.ceil(4.002)
h Math.min(-5, 1.0)
Math.floor (7.99)
Math.ceil(-2.73)
k Math.pow(16, e.25)
1 Math.pow(4, -2)
m Math.round(1.49+0.1)
n Math.round(1. 49) +0.1
? 15. Write the following as Java expressions.

(a) va?-b (b) x-y) (d)1-1


16. A student incorrectly attempted to produoe a
random value in the range 1.6 using the expression
6*(int)Math.random () +1
Correct the error in expression above to
get the desired result.
17. What is the significance of a
break statement in a switch statement ?
18. What are iteration statements ?
Name the iteration statements provided by Java.
19. What is meant by an entry-controlled
loop? Which Java loops are entry-controlled ?
20. What is meant by an exit-controlled loop ?
s an Which Java loops are exit-controlled ?
int
21. What is the difference between a while and do-while loop ?
22. How many times is the loop body executed in a do
loop, even if the test-condition is false ?
23. What is nested loop?
double 24. Write a program to print pattern like:
1
2 1
3 1
4 3 2 1
5 4 3 2 1

25. Write a program to print a pattern as


1 2 3 4 5
1 2 3 4
1 2 3

1 2

26. Write a program to print a pattern as:

.01
1010
1010 1
APPLICATIONS-X
COMPUTER
42
Chopte
27. Write a program to print a pattern as
34. Predict the output:
class Power (
public static void=
int e- 5, resul
result-1;
i-e
>
while(e 0)
result
e
28. Classify the following as primitive
or non-primitive datatypes
(in) int (iv) classes ICSE 2018 int n = result
(i7) arrays
) char System.out.pr
29 System.out.print ("BEST") ; System.out.pr
System.out.println ("OF LUCK") ;
Choose the correct option for the output of the above statements
35. Predict the output
) BEST OF LUCK (i) BEST
OF LUCK [ICSE 2018) class FindF ac {
public static vo
30. (a) Write a Java expression for the following:
for(int i 2
System.
3x+2 for(int
a+b
ifC
(6) What is the value of y after evaluating the expression given below ?

+y +y--
y+= +--y; when int y = 8
(C) Give the output of the following:
) Math.floor (-4.7)
(i) Math.ceil (3.4) + Math.pow(2,3) 36. Give the output of the fo
31. What are the values stored in variables and r2 ? executed:
[ICSE 2018
double r Math. abs (Math.min (-2.83, -5.83))
=
int i;
(i) double r = Math.sqrt (Math.floor (16.3))
for (i 5;i:
System.out
32 (a) Name the operators listed below : System.out.pr
[ICSE 2017)
)< (i) ++ (ii) && (iv) ? 37. Find the error
=
(b) State
the number of bytes occupied by char for(count 0
and int data types.
(C) Write one difference System.out.pr
between/ and % operator.
33. Predict the output: System.o
class Test { (ICSE 20171 38. Find the error
public static void main(String args X= 3;
[]) {
double x, y, z; y = 4;
X = 3; Z = math.power (
y =4;
39. Find the error
z = Math.sqrt (x * x+ y *
y);
System.out.println("z " class Test {
=
+z) ;
public stat-
int x=
-
Chapter 1: REVISING BASIC JAVA CONCEPTS 43
34. Predict the output:
class Power {
public static void main(String args [])
int e = 5, result, i;
result = 1;
i =
e
while(e > 0) {
result *= 2 ;
e--

2018) int n = result /2, p i -


1;
System.out.println ("2 to the power of" + i + "
is "+ result) ;
System.out.println ("2 to the power of" +p + "
is "+ n)

35. Predict the output:


2018] class Fin c
public static void main(String args []) {
for (int i = 2; i <= 100; i++) {
System. out.print("Factors of" + i+ ": ");
for (int j = 2; j <ij j++)
== 0) System.out.print (j *); "
if((i%j)
System.Out.printIn);

the loop is
36. Give the output of the following program segment and also mention how many times
executed
2018]
int
for (i = 5; i> 10; i++)
System.out .println (i) ;
[ICSE 2018
System.out.println(i * 4) ;
D17]
37. Find the error
for(count 5, Count = COunt + 1)
=
0, count <

System.out.println( "This is count: + Count)


"

System.out.println( "Done !");


17] 38. Find the error:
x = 3;
y= 4;
Z
=
math.power (x*X, y/2);
39. Find the error:
{
class Test
args 0) (
public static void main(String
int x = 10;
44 COMPUTER APPLICATIONS-X

if(x == 10) {
int y= 20;
System.out.println("x and y: "
+ x +" "+y)
x = y *
2

y= 100;
System.out.println ( "x is "
+ x);

40. Write a program that inputs a number and tests if the given number is a multiple of both 3 and5.
41. Write a program that inputs a characters and prints if the typed character is in uppercase or

2
lowercase.
42. Write a program that inputs a character and prints if the user has typed a digit or an alphabet or
special character.
43. Write a program that inputs an alphabet and checks if the given alphabet is a vowel or not.
44. Write a program that takes a number and check if the given number is a 3 digit number or not
(Use if to determine)
45. Write a program to input three number and print the largest of the three numbers.
46. Write a program that takes a number and check if the given number is a 3 digit number
or not
(Use a loop to determine) Chapter Ourline
a
47. Write program that prints the squares of 10 even numbers in the range 10.. 100.
48. Write a program that inputs a number and checks if the
given number is a palindrome. A number 2.1 Introducton
that is equal to its reversed number is a palindrome number. 2.2 What is an Object ?
49. Write a program to input a number in the range 10 to 100 2.3 What is a Class?
and check if it is a prime number.
50. Write a program to print following series of numbers: 2, 5, 8, 2.4 Significance of Classes
11, 14....
51. Write a program to print Fibonacci series : 0, 1, 1, 2, 3, 5, 2.5 Creating and Using Obje
8....
52. Write a program to print factorial of a given number. 2.6 Objects as Instance of C
53. Write a program to print Floyd's triangle as shown below :

2
456
7 8 9 10
11 12 13 14 15

You might also like