1. Revising Basic of Java (1)
1. Revising Basic of Java (1)
Concepts
1
COMPUTER APPLICATIONS-X
2
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 :
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
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).
this Java L
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
<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.)
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.
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.
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).
!
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
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
<
OR Left to Right
Right to Left
? Shorthand for if..then..else
Right to Left
= +-= *= /= %= ^=Various shorthand assignments
Right to Left
&== <= >>= >>>= Various shorthand assignments
() 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.
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 {
into
Theoutput produced by above program is:
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. ") ;
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") ;
case <constant1> :
statement-sequencel
break
case <constant2> :statement-sequence2
break
case <constant3 :
statement-sequence3
break
) 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.
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)
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
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
:
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)
<
<
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
=
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
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.
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.
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 ;
) 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++) {
System.out.println( "WIN")
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
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 :
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
Ans. Output: 12
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=
+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);
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.
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
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
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") ;
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
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
KEYWORDS
Explicit Type Conversion User-defined type conversion.
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
5w+6z 1
1 2
.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--
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 <
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