0 ratings0% found this document useful (0 votes) 624 views40 pagesChapter 1 - Revising Basic Java Concepts
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
be crater
Chapter Outline
11 Introduction
1.2 Object Oriented Programming
113. Beginning with Java
Revising Basic Java
Concepts
1.1 INTRODUCTION
Java is a popular Object Oriented programming
language that is used to build secure and
powerful applications that run across multiple
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 IX
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.2
2 Object O'
1.2.1
riented Programming
ch that focuses on the Prot
yproa ‘ming paradigm. This ap)
cedures for the solution of a proble
proach: emphasizes on the mis
‘The programming aP: ‘doi
a es procedural program} oe
rather than the ‘data’. paradigm views a problem in term of classes and Obje
The Object Oriented Lee rrobjects are needed for a particular situation/probjny
ies it determing rin Object is an identifiable entity with some characteristics and behavioy
context. Recal a rueprint representing 2 group of objects that share common properties and
ae ps. $0 suey ign determines the classes and objects needed forthe okt
4 problem and then provides a full set of operations for each class.
Elementary Concept of Objects and Classes
‘As you know that OOP programming paradigm views a p'
classes. So, let us quickly revise what an object and a class is.
> An Object can be thought of as an entity having a specific identity, specific characteristics
and specific behaviour, e.g, ‘Ceiling Fan’ that you see in your room is an object. Its
characteristics are : it has three/four blades/wings, a motor, a mounting rod, may or not
have remote-control feature etc. Its behaviour is : it works on electricity, it rotates air ata
given speed (rpm).
The software objects have state and behaviour :
«= 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.
= Their behaviour is implemented through functions
generally called methods. rae)
" ec
A Class is a blueprint that represents a set of objects ‘
roblem in terms of objects and
Vv
that share common characteristics and behaviour, An Object is an entity with 3
eB, ‘Honda City’ isa class of cars, but a Honda City specific identity and having
Car having a particular registration number say specific characteristics and
rites is an object of this class type. Similarly, _ SPetiflc behaviour. A Clas st
Dee a class, but a dog namely, “Leo” residing blueprint representing @ soe
indhis, is an object of Dog class type. se that sar ae
aracteristics and beha’ ie
1.2.2 General Object Oriented Programming Conicepis
Object oriented programmin, Vv and implem
c 8 paradigm i ji
4 * ‘ Le invoh bd the objects and classes implements
‘I, Dota Abstraction
nations, 4 .
ode Ir a nay (Abstraction hides the intemal details
eet pee ich board’, you only press certain swith
Ht, Connections ete., you needn't know: TS
you need to know o
nk ;
e background details of iene things to operate
ard.
describes things in simple terms
according to your requirement, its:
is abstraction, which ensures that
switch board without knowing thREVISING BASIC JAVA CONCEPTS 3
Aimmecties & wbviies lative $9 fhe worpcee oF ua, An object may have multiple
abstractions depending upon the context. For instance, if we talk of a student object, we can
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 media history,
her talents, her interests, her awards, sports played by her ete.
= But when we talk of a student result tra
rollno, name, marks obtained etc.
> For extra-curricular activities, the abstraction ‘would be : her
rollno, talents and awards.
icking system, the abstraction for it would be ther
Thus, there can be multiple abstractions for a real-world entity
and for each abstraction, we define a class.
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
are combined along with the data). These functions are called member functions or methods in
Java.
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.
(3. Modularity
The act of partitioning a program into individual components is called modularity. Modularity is the
property of a system that has been decomposed into a set of cohesive and loosely coupled
modules.
4, Inheritance
Inheritance is the capability of one class of things to inherit or derive capabilities or properties from
another class, e.g., the class ‘Car’ inherits some of its properties from the class ‘Automobiles’
which inherits some of its properties from another class ‘Vehicles’.
> A dlass from which another class inherits is called base class or super class eg,
‘Automobiles’ class is base class of class ‘Car’
> And the class inheriting from another class is called subclass or derived class ¢.g., the
‘Car’ class is a derived class of ‘Automobiles’ class. A subclass inherits the common
features and additionally defines only those features that are unique to it.
5. Polymorphism
Polymorphism is a property by which the same message can be sent to objects of several different
classes, and each object can respond in a different way depending on its class. The same operation is
performed differently depending upon the data type it is working upon, e.g, if you give 5 +7,
it results into 12, the sum of 5 and 7. And if you give ‘A’ + ‘BC, it results into ‘ABC’, the
concatenated strings. The same operation symbol ‘+’ is able to distinguish between the two
operations (summation and concatenation) depending upon the data type it is working on.Byte Code
1.3.
COMPUTER ‘APPLICATIONS-X
1,3-- Beginning with Java on .
. amming language and a platform. Platform "fers fo some coning
Java is both a progré ‘oftware e.g., operating system Win lo fel Core i9 or
of hardware and system 50 vor otc. The Java Platform is a softoare platform thay a
a AMD Ryzen righty interactive, dynamic and secure applications on networked compe"
liver and run :
systems.
While most computer programs are platform dependent, i.c., they a vey Closely tied tothe
specific hardware and operating system they run on Java app! to oes platform,
independent i.e., they are not affected with changing platforms. Java solves the Problem of
platform-independence by using byte code. 4 , .
inary compilers, the Java compiler does not produce native executable code
Feralas nockive, tend it produce a special format called bytecode. The vay
code is interpreted by a special Java Interpreter for a specific platform. Actually this Java
interpreter is known as the Java Virtual Machine (JVM).
Anatomy of a Java Program
The most common Java programs are applications and applets. Applications are standalone
programs that can run independently of another program or application. Applets are similar
to applications, but they don’t run standalone, they are run inside another application suchas
a web-browser.
A simple java program has following components or parts :
() Comments. Comments are the explanatory text enclosed in /* ... */ or follow //. The
comments are only for the programmer, these are not part of the Java code and are
not executed. (see Fig. 1.1)
(i) Class(es). A java program can have one or more classes. A class defines functionality
of a specific type of objects. A class has variables and methods inside it, There can ®°
multiple classes in a program but there has to be a class that has the same name ®
that of the Java program and this class contains the main( ) method, This das
(ii) Method main( ), The entry point of eve
are multiple classes in a program, the e
class containing main method. If no m,
ry Java application is its main method. If the
xecution will begin from the initial class i#
ain method is there,
the
An initial class 1S x)
fone that contains may
See, the main method is declared as ;
public static void mainREVISING BASIC JAVA CONCEPTS 5
() Code statements. The methods inside classes contain functionality defined through
various statements of the code, ¢.g., System.outprintin statement will display the
given output on the terminal window. (refer Fig, 1.1)
CISIarenrs)
Class containing
‘main( ) is initial
class.
Execution bogins fam
‘main mettod
‘Systen.out .printin(“Hello World?");
Print to standard output
device, goneraly monitor
mbar he) ged
Figure 1.1 Components of a Java Program.
1.3.2 Java Fundamentals
A Java program is made up of many things such as keywords, identifiers, literals, expressions,
statements etc. Let us briefly talk about these fundamentals or the building blocks of Java
programming language.
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
systems around the world including English, Arabic, Chinese and many more.
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 :
default if private this boolean do.
Protected break double public byte else
return case int short try catch
void char long class, float while
for new switch
(“the above given is a partial list of Java keywords)
1.3.2A Working with Values
In a Java program, you can work with various ff smallest individual unit in a program is
types of data values. These values can be either in [called a token. Keywords, identifiers,
the form of literals/constants or named variables. [fliterals, operators and punctuators are
Each value has a data type associated with it, “COMPUTER We —_—_
“literals ts) are data items that are fixed data values. Java ag,
constant
Literals (often a to as —_
several kinds of literals : eee
i re whole nw ; 7
(i) Integer literals. ener eg., 10), octal ‘form (starts with a zero, eg,, 0) Ihe
rts with a non gee
on ocinal form (starts with a ox, sel * apen-vah beeteeg -
i ing-point literals Floating poin' n with f
(ii) ae sang decimal points. The con be written either in fractional forn
00 0.36E-3.
in exponent form, ¢.g., 0:
eg., 0.00036 or in exp eae
if i literals are represen
(iii) Boolean literals. These * ne
(jo) Character literals. Single character or escape sequence enclosed in single quotation
‘a a literals.
marks makes a character literal e.g., ‘a’ and ‘\t’ are character aa s.
(0) String Literals. One or more characters enclosed in double quotation marks make .
string literal, eg., “abe”, “T189” etc.
(vi) The null literal. The null literal represent null reference and written as null,
Identifiers are the names given by the programmer to various program units of Java
Identifiers are the names of variables, methods, classes, packages and interfaces etc. Identifier
forming rules of Java state the following :
(@ Identifiers can have alphabets, digits, _ underscore and $ characters and can be of any
_ length,
(i) They must not be a keyword or Boolean literal or null literal.
(ii) They must not begin with a digit.
(iv) Java is case sensitive i.e., upper-case letters and lower-case letters are treated differently.
Some legal Java identifiers are :
Myar, myvar, MYVAR, x, I, _myvar, $myvar, -9pins, andornot, i_am_a_long_name
Following identifiers are legal in java :
My Var // Contains a space
Shours // Begins with a digit
case // it is a keyword
atB-c // The
ee oy eas er hyphen are not legal characters for identifiers
Phe ds not a legal character for identifiers
And¬ I ki.
+4 ampersand is not a legal character for identifiers
Whenever you store
A .
identifi 7 values with a name i.e, in fi , 7
ler naming rules, ym form of a variable, you name it as Pe
A variable is a named
; ; Memory locati ii
Variable is declared as per folowing ms
; ee
h holds a data value of a particular data type 4REVISING BASIC JAVA CONCEPTS 7
For example,
double salary, wage 5 // two variables of double type declared
int month, day, year ; // two variables of int type declared
Jong distance, area ; // two variables of Long int type declared
You can assign initial value to a variable at the time of its declaration, e.g.,
double price = 1214.7057, discount = 0.12;
float x = 0.125;
int val = 13
Constants
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, ¢.g.,
final double TAXRATE = 0.25 ;
Now on, you will be able to use TAXRATE’s value in your program
but you will never be able to change its value again, because you
created it with keyword final, which means that this named
value will remain fixed for this name throughout the program
where it has been created.
Keyword final when used
with a declaration similar
to a variable, creates a
named constant,
1.3.2B Data Types
Each value that you use in a program has a data type. Data Types are means to identify the
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:
(i) 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.
(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 of an
object.
Various data types in Java are shown in following figure (Fig, 1.2.)
Data Types in Java
Primitive Types.
((ntrinsic or Fundamental) preference Iya
Non-numeric Classes | | interface | | Arrays
Integer | [Floating-point] [Character Boolean
= byte © oat © char boolean,
© short * double
* intCOMPUTER APPLICATIONS-X
(i) Primitive Data Types :
There are about eight primitive data types 1"
talk about these.
tmiti . These data types store
> Numeric Integral primitive types. wi both negative 28
integer values ie, whole numl Pa aise
well as positive numbers). There i four num
i : byte, short, int, and long.
a " it vm . Floating-point datatypes can store fractional numbers ie
o ing-poi es. | . . ”
eae avin dedeal ints. There are two floating point data types in Java : flog
aon precision of 6 digits) and double (provides precision of 15 digits). By defautt,
oye *
be assumes the fractional numbers to be of double datatype unless specified, 2, value
0.35 will be considered of double type by default to explicitly specify their type, you can
use suffixes f or F (for float) and d or D (for double).
> Character data type. The character datatype - char datatype of Java — is used to store
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.
Java. Let us briefly
You can use suffix | or,
with an integer to signify
long value.
(i) Reference Dota 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 a
primitive type, is a reference to (an address of) the value or set of values represented by the
variable (Fig: 1.3). A reference is called a pointer, or a memory address in other languages.
Figure 1.3 Reference datatype
‘reference is called a
pointer, or a memory address
in other languages. The Java
Programming language does
ot suppor the explicit use of
addresses like other
languages do. You use the
variable's name instead.
‘anol
or an array
There are two values associated with a syml
woe bolic variable : (i some
a ‘ le : (i) Its data value, stored at
which ie de nor Called roalue ) and (i) ts location value that is, the address in memory @t
Ata value is stored (called Toalue) eg, see belo
Memory Addresses
Ty yee NA tli i 1054
Data values of variable—p 10 =
Variables’ names ——y A :
c
Talue of A = 19
ae tvalue of C=25
Walue of C=1055aaa
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 with the memory address ie,, the location-value
(value). They do not store the actual 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 your program are processed as per the given
instructions. Various types of operations can be carried out on the data values. The operations
being carried out are represented by operators. Java provides a wide range of operators.
( Arithmetic Operators. These are +, -, *, / and % for arithmetic operations addition,
subtraction, multiplication, division and remainder calculation respectively.
(ii) Increment/Decrement Operators. These are ++ (increment operator) and -
(decrement operator) that increment or decrement a number. These operators,
however, work in two forms, prefix form - when used before the operand e.g., +a
and postfix form - when used after the operand, eg., a+.
> When used in prefix form, it follows the rule Change-then-use, ic, first the
variable value is incremented or decremented and then used in expression, ¢.g.,
int S=5, a= 105
S=St+a;
will evaluate as_§ = 5 + 11 (a is internally first incremented, becomes 11 and
then used), Thus $ stores 16 and a stores 11.
= 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, €..
int S=5, a= 10;
S=S+ate;
will evaluate as $=5+10 (a's value is first used and then incremented, a becomes
11) Thus $ stores 15 and a stores 11.
(iii) Relational Operators. These operators, also sometimes called comparison operators,
compare the values of two variables or literals etc. These are : >, <=, >=, <= !=.
(iv) Logical Operators. These operators are used to combine two or relational expressions
to make complex expressions for decision-making.
These are : && (And), | |(or) and ! (not).
(») 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
>>| opt >> op2 _| shift bits of opt right by distance op2 (signed shifting)
<< | opt << op2 __| shift bits of opt left by distance op2 (signed shifting)
>>>___| opt >>> op2 _| shift bits of opt right by distance op2 (unsigned shifting)reason oT
COMPUTER APPLICATIONS
a
10 ee
* and ~) work on individual bits of
‘These operators work as per following
it tors (6,
}) Bitwise Operators. Bitwise operators (
” pont and verform bit-by-bit operation.
a ther combination produces
i duces 1. Any of 0.
> ND (&) operations, pro :
i oe a pues, "ep produces 1, a8 does 0 XOR 1 (Al these operation
or ,
are commutative.) Any other combi
> For OR (|) operations, 0 ! 0 produces ;
> For complement (-) operations, the ~0 produces Lan
operator = assigns values to a
erators. The assignment
ily rs like new, instanceof, (dot), [ ], 2: etc,
1&1
ination produces 0.
0. Any other combination produces 1.
~1 produces 0.
(vii) Assignment, ?: and of
variable and there are some other operato’
The conditional operator, ?: works as :
expressiont ? expression? for true result : expression3 for false result
If expression! evaluates to true then expression2 is evaluated and taken as overall result
otherwise expression3 is taken and taken as overall result, ¢.3-,
evaluates to 9 because test expression 6 > 4 is true.
6>429:7
evaluates to 25 because test expression 4 == 9 is false, 0
4229710: 25
Java Shorthand Operators
Java offers special shorthands that simplify the coding of a certain type of assignment
statement. For example,
a=a+l0; canbe written as a t= 10;
The operator pair + tells the compiler to assign to a the value of a+ 10. This shorthand works
i all i binary operators in Java (those that require two operands). The general form of Java
shorthand is
var = var operator expression issameas var operator = expression
Following are some examples of Java shorthands :
means x=x-10
means x=x*S
means x=x/2
means X=EX%6
F,%
Operator Precedence and Associativity
“ete. are called arithmetic assignment operators.REVISING BASIC JAVA CONCEPTS 11
Here, addition and subtraction have the same precedence rating and soa and b are added and
then from this sum c is subtracted. Again, parentheses can be used to overrule the default
associativity, e.g,
x=a+(b-c);
However, the assignment and unary operators, are associated right to left, ¢..,
xte yen 5
is equivalent to
x= (y= (4D) 5
Table 1.2 : Operator Precedence and Associativity
Operator Notes Associativity |
vO Parentheses ( ) are used to group expressions ; a dot (.) is used | Left to Right |
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 | Right to Left |
of the named class or any of that class's superclasses |
new (type) The new operator is used for creating new instances of classes ; | Right to Left
() in this case is for casting a value to another type |
*/% Multiplication, division, modulus Left to Right
+e Addition, subtraction Left to Right |
> >> Bitwise left, right shift, and the zero fill right shift | Left to Right |
<> | Relational comparison tests | Left to Right
Equality not - equal to Left to Right |
& AND Left to Right |
“ XOR | Left to Right |
| oR | Left to Right |
8a Logical AND | Left to Right |
fl Logical OR Left to Right
2s Shorthand for if...then...else Right to Left
/=%= %= | Various shorthand assignments Right to Left |
-< Various shorthand assignments : ___| Right to Left |
1.3.2D_ Input in Java
Input is any information that is needed by your program to complete its execution. Most]
you input text via keyboard and other forms of input via other specific devices e.., for audi
input you need mic.
Text may be input in java in various ways, such as using java.io module (using BufferedReade
or DatalnputStream classes) or even via using Scanner class. Using a Scanner class for keyboar:
input is much easier for the beginners. Thus, in this section, we shall revise the input in Jav
using Scanner class.meen ES
12 COMPUTER APPLICATIONS-X
iit and substrings using regula,
text for primitive types and oe l
ions. It can obtain the text from sources such as a String oe aes a a file,
aaa ei ithat implements the Readable interface. The Scanner splits input Strings,
and any class that ae delimiters which by default consist of any white space. The tokens
or tokens, arat sy cw
can then be obtained as stings ot as primitive types. ent
n
To use Scanner class for input, you need to follow the steps given emer,
() Import java.util.Seanner class in your program, by giving following statement in the
beginning of the program :
import java.util.Scanner ;
Scanner is a class that can parse
elow :
(id) Create an object of Scanner class type by passing it argument as system.in so that it
connect to keyboard for input. Give following statement for this :
Scanner inp = new Scanner (System.in) 5
(ii) Using the Scanner object created in step (ii), read values using next__() methods, ie,
nextInt( ) for reading integers,
nextFloat( ) for reading floating-point numbers,
nextDouble() for reading double-precision numbers,
nextBoolean( ) for reading Boolean values, and
next( ) for reading Strings .
For example, the following code snippet shows how to read an integer from the keyboard :
Amport java.util.Scanner ; ‘
Scanner inp = new Scanner (System.in) ;
int i = inp.nextint () 3
| Program
Vrite a program to input three numbers and print their Output produced is :
1m of cubes, Enter Number 1: 3
import java.util.scanner; Enter Number 2 : 7
public class Input _ Enter Number 3 : 1
{ Three numbers are : 3, 7, 1
Public void sumcubes() { Sum of their cubes is : 371
Scanner inp = new Scanner (System. in) ; .
System.out.print("Enter Number 1: "); Enter Number 1 ; 5
int num = inp.nextint( ) ; Enter Number 2 : 6
System.out.print("Enter Number 2: ") ; Shier Nunber 3 3 7
int num2 = inp.nextInt( ) ; Three numbers are : 5, 6, 7
System.out.print("Enter Number 3 ; "); “Sum of their cubes is : 684
int num3 inp.nextInt( ) ;
Ant sum = (num * num * num) + (num *
System. out.printIn(*Three nunbers ar
System.out.printin("sum of their cubs
num * num2) +
re: "+ numa 4",
esis: "+ sum) ;REVISING BASIC JAVA CONCEPTS 13
1.3.2E Expressions
An expression in Java is any valid combination of operators, constants, and variables i.e, a legal
combination 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.
‘The expressions in Java can be of any type : arithmetic expression, relational (or logical) expression,
compound expression 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 ; if an expression has relational and/or Boolean operators, it is a Boolean expression.
_()) Arithmetic expressions.
Expression that use arithmetic operators are called Arithmetic expressions. Arithmetic
expressions containing all integer type operands are Pure integer expressions. An expression
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 arithmetic operators, an arithmetic expression may consist of Java's
mathematical functions that are part of Java standard library and are available through Math
class defined in java.lang package. You can use these math functions as per following syntax:
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)
cos(x) This function returns the cosine of the angle x in radians Math.cos(6)
tan(x) | This function returns the tangent of the angle x in radians | Math.tan(6)
asin(y) This function returns the angle whose sine is y Math.asin(6)
acos(y) This function returns the angle whose cosine is y Math.acos(6)
atan(y) This function returns the angle whose tangent is y Math.atan (6)
atan2(x, y) | This function returns the angle whose tangent is x/y Math.atana(5,2)
| pow(x, y) | This function returns x raised to y (x”) Math.pow(3,4)
exp) This function returns e raised to x (e*) Math.exp(4)
| log(x) This function returns the natural logarithm of x Math.log(5)
| sart(x) This function returns the square root of x Math.sqrt(16)
ceils) This function returns the smallest whole number greater than | Math.ceil(17.3)
or equal to x. (Rounded up)
floor(x) This function returns the largest whole number less than or | Math.floor(17.3)
equal to x (Rounded down)
rint(x) This function returns the truncated value of x Math.rint(17.99)
abs(a) This function returns the absolute value of a Math.abs(-17.9)
max(a, 6) | This function returns the maximum of a and 6 Math.max(13, 17)
min(a, 6) _| This function returns the minimum of @ and 6. | Math.min(13, 17)14
wad iis ey
COMPUTER APPLICATIONS-X
son 2+ Mb? = 40¢ wit be written in Java as :
For example, expression @*
(—b+Math.sqrt(b *b-4*a*c) y/(2*a)
ax?
ca
+ will be written in Java as :
d
Similarly, expression
(a * Math.pow(x, 2) +b) / (e* x +4)
While evaluating an arithmetic expression,
> if the expression is a pure expression (i.e, all operands are of same Bh) then the result of
the expression will also have same data type as that of the operands.
> if the expression is a mixed expression (ie, if the
data types of operands are different ), then the
operand with smaller datatype’s value will be
Promoted to bigger data type and then the a
expression will be evaluated and the overall result : ¥ ei
will have the data type same as the bigger data || ()
type in the expression. This is called internal or
implicit type conversion or coercion.
User can also change the datatype of
a value using type-cast operator ()
For example, expression (int) 3.2 will convert value to int datatype and thus value 3 will be
used (int cannot store fractions). Similarly, if x is an int variable storing 4, then expression
(double)x will change the datatype of x’s value to double and thus 4.0 will be used here. This
way of explicit type conversion is called type casting.
{Gi) Relational expressions
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!=b, p == etc. are relational expressions,
lil) Logical expressions —
Expressions that use logical operators (&&, || and !) to combine relational expressions to
Bake 4 complex expression are called Logical expressions.
For example, (x > y) && (y > z) is a logical expression.
Logical expressions are sometimes
also referred t¢ i i
(rior fis values which ae Boolean values, OUR eXPFeSsion as these result into
(iv) Boolean expressions.
The expressions that result into
expressions are combination of constant,
For example, following are examples of
xy
(a¥b) >= © &&(c <= d) OF 2) > (x12)
(-x) <(2-yyas 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 for
execution from multiple alternatives depending upon an expression’s truth value (i.e, a
condition-test). Java provides two types of conditional constructs : if and switch.
|. 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 :
The true section of if (gets executed if the
if (expression) eT ein tar
statement 1;
else The false section of if (gets executed ifthe
statenent 2; cm deathon alanis tfc}
If the expression evaluates to true the statement-1 (ie, the true section, containing a simple or
a block statement) is executed, otherwise, statement-2 (i.e., the false section, containing a
simple or a block statement) is executed. In an if-else statement, only the code associated with if
(ie, statement-1) or the code associated with else (ie., statement-2) executes, but never both.
[BALI Program 1.2
Write a Java Program that accepts a number in the range 1-99 and then displays if the entered number
is single digit or double digit number.
import java.util.Scanner 5
public class select {
public void test() {
Scanner inp = new Scanner (System.in) 5
int num ;
system.out.print("Enter a number (1..99) :
num = inp.nextInt();
if (num > @ && num <1@)
system.out.printIn("You entered a single digit number.") 5
else
System.out.printIn("You entered a double digit number.
}
The output produced by above program is :
Enter a number (1..99) : 3
You entered a single digit number.
ee
Enter a number (1..99) : 45 ]
You entered a double digit number. *
BodCOMPUTER ‘APPLICATIONS-X
16
i tion or/and in its fl
Nested Ifs if statement in its true sectior se secy
cent contains another ifs if statement. Following program uses 4 Hy
Ifanifstatement OM med as nest a)
such a statement is t
statement.
Wi] Progam 13
m 1.
Previous program (program 1
enters number beyond the given range 1
program so that it handles this situation i.e
the range 1.99. B
it user enters a number in tl ge uti
ZI arr Sbove program is not able to handle that. Mio
ic
er ty ay,
when users enters a number not in range 1,99.
import java-util.Scanner 3
public class select {
public void test() { ,
‘Scanner inp = new Scanner (System-in) 5
int num 5 a
system.out.print (“Enter a number (1.-99) :") 3
num = inp.nextInt()
if (num > @ && num < 12) 7
system.out.print1n("You entered a single digit number."
else
if (num >= 10 && num < 100)
Systen.out.printin("You entered a double digit number.
else
‘System.out.print1n("You entered number beyond the asked range.
}
The output produced by above program is :
Enter a number (1..99) : 9
You entered a single digit number,
a
Enter a number (1.,99) : 78
You entered a double digit nunber.
ee
Enter a number (1..99) : -4 x
Yow entered nunber beyond the asked rang
ee a
Enter a number (1, .99)
You entered nunber be
a
+ 999
Yond the asked range
A student is allow,
ed to take i classe:
© exam if he/she has attend, a :
and then prints ig a Student after o ee least 75% of the classes. Waite +f _
Tints if a student is eligible to tak is ° tee cee
Pi € exam or not.REVISING BASIC JAVA CONCEPTS 17
import java.util.Scanner ;
public class Eligibility {
public void Cale() {
Scanner inp = new Scanner(System.in) ;
int total_classes, attended ;
float att_perc;
System.out.print(“Enter total classes held : ") ;
total_classes = inp.nextInt();
System.out.print("Enter total classes attended : ") ;
attended = inp.nextInt();
att_perc = ( (float) attended / total_classes) * 100 ;
if (att_perc >= 75.0).
System.out.printin( "Eligible to take exam") ;
else
System.out.println("Low attendance ! Not Eligible to take exam") ;
}
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
|. 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 + statement-sequencel ;
break:
case 3 statement-sequence2 ;
break 5
case + statement-sequence3 ;
break 5
case : statement-sequence n-1;
break;
[ defautt + statement-sequence n ] ;
Clause enclosed in [ ] is
optional clauseCOMPUTER ‘APPLICATIONS-X
8 ‘ are matched against the values of the
its valu is found, the statement sex CONG
jon is evs match is fo quence qty
‘The expression is ¢' nn ben & ;
case statemen 88305;
specified in the ca5® SINE break sate
with that case is exerwte ached. The default sta
end of switch statemen' found. Ifthe Keabsence of RBEMEane a
gets executed when not atching case, in the absenck @ “followin, a
tothe next cas below the male Nr gefaut statement is |fllowing eases
break, this is called oe "no action takes place if all = 2 a cae
optional and, if it is mis eee
satches fil
[Bi] Program 15
Wi rogr tes a ese geometric shapes : Triangle, Rectangl
it lates areas of these 8 pe
rite a program that calcul le, par
fe i ference :
Gian li ses geometic shapes ae given here for your reference
Triangle Area =1x bxh where b = base and h = vertical height
2
Rectang idth and h= height
je Area = xh where w= wi ight
Parallelogram Area=bxh where b=base and ht= vertical height
Circle Area=ax1? where F= radius :
| Billipse Area = nab where it and b are semi-major and semi-minor aes,
import java.util.Scanner}
public class Area {
public void calcArea() {
Scanner inp = new Scanner(System.in) ;
System.out..printIn(“Area Calculation”);
System. out .println("1. Triangle") ;
System. out .print1n("2.Rectangle");
System. out. print1n("3.Parallelogran") ;
System.out. println("4.Circle");
System.out.printIn("5.Ellipse");
System.out.println("6. Exit");
System.out.print (“Enter your choice (1. +6):
int ch = inp.nextInt();
double area, base, ht, wid,
switch(ch) {
casei:
ry a, b;
fusten-out.print( “Enter base of triangle :
2ase = inp. nextDouble();
peat Out. print ("Enter height of triangle : ");
= inp.nextDouble();
area = 0.5 * base * hts // 1/2 *b+h i
System.out, a
breaky PT itIN("Area of triangle is : "sareat
case 2:
*xtDouble()
Out print (™
System,
Enter height of rectangle : ")5REVISING BASIC JAVA CONCEPTS 19
ht = inp.nextDouble();
area = wid * ht 3
System.out.printIn("Area of rectangle is
break;
+area+" sq units");
case 3: System.out.print("Enter base of parallelogram : ")
base = inp.nextDouble();
System.out.print("Enter height of parallelogram :
ht = inp.nextDouble( i
area = base * ht ;
system.out.printIn(“Area of parallelogram is : "+areat" sq units");
break;
case 4: system.out.print("Enter radius of circle : ");
r= inp.nextDouble() 5
area =3.14159*r*r; // pitr*r
system.out.println("Area of circle is : “+areat" sq units");
break;
case5: System.out.print("Enter minor axis of ellipse :
a= (inp.nextDouble() ) / 25
system.out print ("Enter major axis of ellipse : ");
b= (inp.nextDouble() ) / 2 5
area = 3.14159* a*b; // pitatb
system.out.printIn("Area of ellipse is : "+area+" sq units");
break;
case6: System.out.printIn("Exiting. .
break;
}
}
Sample runs of above program are shown below :
‘Area Calculation
L.tTriangle
2.Rectangle
3.Parallelogram
4.circle
5.Ellipse
6.Exit
Enter your choice (1..6) : 1
Enter base of triangle : 7
Enter height of triangle : 5
Area of triangle is : 17.5 sq units
Enter your choice (1..6) : 2
Enter width of rectangle : 4
Enter height of rectangle : 5
Area of rectangle is : 20.0 sq units
SS
Enter your choice (1..6) : 3
enter base of parallelogram : 4
Enter height of parallelogram : 5
Area of parallelogram is : 20.0 sq units
Lee ee eS annae
Enter your choice (1..6) : 4
enter radius of circle : 3.5
Area of circle is : 38.4844775 sq units
ess
Enter your choice (1..6) : 5
Enter minor axis of ellipse : 5
Enter major axis of ellipse : 7
‘Area of ellipse is : 27.4889125 sq unitsJON”
COMPUTER ‘APPLICAT!
20 4
1.3.26 Iterative Constructs JOO | sous allow a Set OF instructions to be perf
‘The iterative const oF HEAT filled: The tere sateen ate asc we
repeatedly unt as Ja provides three 1oOPINE statements : for loop, while toy, Pe
or looping
do-while loop.
|. The for Loop
‘The for loop i
gathered at the top of
‘The general-form (syntax)
‘on expression(s)3
. All its loo]
is the easiest to understand of the Java loops. P-contrl element .
the loop.
of the for loop statement #5
oc caruesatagatl test-expression ; update expression(s))
body-of-the-Lloop 3
() The initialization expression(s) is carried out ONLY ONCE before entering into the fo,
Joop, ie, when for loop begins execution.
(if) The test expression is next evaluated,
if it returns true, the for loop’s
body is executed and if it returns
{false then for loop terminates.
(iii) ‘The body of the loop contains either
one statement or a block con-
taining multiple Java statements. Unaste
The body of the loop gets executed teh
every time the test-expression 4
evaluates to true.
(io) The update expression(s) is per-
formed after execution of the body
of the loop and the steps step (iii)
onwards repeated.
— The exit
condition
True
The loop body
[Aly Program 1.6 Figure 1.4
Write a program t i ers in the r:
© calculate and print the sum of cubes of odd numbers i
the range 1.10.
Public class Loop {
Public void prncubes() {
Ant sum = @;
for (int i=2 546105 440 Te bay of th foro
sweeter, en?) “jut one cea
System.out. printin(*sum
} ‘Sum oF cub
es Of odd numbers between 1..10 is :* + su")!
Output produced is =
‘Sum of cubes of odd
© of odd numbers between 1.19 j
a 110 is = 1225,Saas - REVISING BASIC JAVA CONCEPTS
21
As you can see that above program uses a for loop that starts with initial value of i = 1;
iterates over the range 1..10 ; for every value of i < 10 (test-condition), it calculates the i? 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 :
sum4=(i*i*i);
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() {
int sum = @, cube = @ 5
for (int i= 1; i<10;i4=2) {
cube=(i*4*%4);
‘System.out.print1n("Cube of "+i +"
‘sum += cube 5
As there are multiple statements in
the body of this loop, the statements
are enclosed in { }, ie., the block of
statements
: "+ cube) 5
System.out.print1n("Sum of cubes of odd numbers till 1.."+i4": "+ sum) ;
Output produced is :
Cube of 1: 1
‘Sum of cubes of odd numbers til] 1 ..1: 1
Cube of 3: 27
‘Sum of cubes of odd numbers till 1 ..3: 28
Cube of 5: 125
‘Sum of cubes of odd numbers till 1 .
Cube of 7: 343
‘Sum of cubes of odd numbers til] 1 ..7: 496
Cube of 9: 729
153
Sum of cubes of odd numbers til] 1 ..9: 1225
Ul. The while Loop
The while loop of Java,
of a while loop is
while (test-expression)
o0p-body
In a for loop, the initialization
expression(s), test-expression and the
update expression(s) are optional,
i.e., you can omit any one, two or all
of them, depending upon your logic.
But the body of the loop must have at
least one statement in it.
iterates or repeats as long as the given test-condition is true. The syntax
“where the loop-body may contain a single statement, a compound statement or an empty statement.
The loop iterates while the test-expression evaluates to true. When the expression becomes
false, the program control passes to the line after the loop-body code.rh lial
COMPUTER APPLIC!
22 ‘4
“The usage form of while loop i Pa :
Initialization expression(:
while (test-expression) {
Joop-body
including update expression(s)
}
Hl] Program 1.8
Write a program that
taking input until a 0 (zero) is ent
tered by user. The pro;
displays the of a ae z Program should ey
red.
import java.util.Scanner 3
public class Sum {
public void calcSum() { .
tnt com 20, num = 1; // initial value is so that the condition is true initia
Scanner inp = new Scanner(System.in) 5 7
while (num I= @) {
system.out.print ("Enter number :
‘num = inp.nextInt();
sum = sum + num
}
System.out.print1n("Sum of numbers entered so far : "+ sum );
y
}
cape
we
Enter number : 3
Enter number : 6
Enter number : 2
1
4
Enter number :
Enter number :
Enter number : 0
‘Sum of numbers entered so far : 16
Il The do..while Loop
The do..while loop also works b
executes at le; i eo” i iti
do..while Toop. mice pled testeonditin ae is designed in such a way ane
executing loop-body, the test condition after executin, th ody ofthe op re E
otherwise loop terminates, "8 evaluated and if iti chp aye
The syntax of the do-while oe
do {
Statement1 ;
statement2 ;
loop is :
Futile (test-expressig )
mn);a -
REVISING BASIC JAVA CONCEPTS 23
Bl! Program 1.9
Write a program that inputs maximum 5 numbers and stops if 5 numbers have been entered or user
has entered a zero. It alsc prints the count of non-zero numbers entered.
import java.util.Scanner ;
public class count {
public void readwum() {
duced is :
‘nt count: = ej:rumn = © ; Output produced is
‘Scanner inp = new Scanner(System.in) 5 Enter a number : 6
do{ Enter a number : 8
System.out.print("Enter a number ; Enter a number : 2
num = inp.nextInt() ; Enter a number : 0 3
count++ 3 Total numbers entered :
} while(count < 5 && num I= @) ;
System, out.print1n("Total numbers entered :" + count);
}
+
|| Program 1.10
Write a program that inputs maximum 10 numbers but stops as soon as 4 even numbers have been
entered.
import java.util.Scanner ;
public class count {
public void readNum( ) {
int count = @, num = @, evenCount = @ ;
Scanner inp = new Scanner(System. in) ;
do {
System.out.print(“Enter a number :") ;
num = inp.nextInt() 5
count++ 5
if (num % 2 == 0)
evenCount++5
} while(count < 1@ && evenCount < 4) ;
System.out.print1n(“Total numbers entered : "+ count) ;
‘System.out.print1n("Total even numbers entered : “ + evenCount) ;
+
}
Output produced is :
Enter a.number : 5 Since for and while loops test the
Enter a number : 2 condition before entering into the
Enter a number : 7 loop, they are called entry-
Enter a number : 3 controlled loops. The do..while
Enter a number : 2 loop, on the other hand, tests the
Enter a number : 8 condition at the time of exit from
Enter a number : 4 the loop, this loop is called
Total numbers entered : 7 PEL copmtes loom
Total even numbers entered : 4COMPUTER APPLICATIONS"
24 cs
ii if a loop is call
IV. Nested For loops «a its body. This form o} led nes,
st oop may contain anoter 1OOP A ec efore the outer loop. V arity
‘nested loop, the inner ee “called nested for loop.
“a its body, .
another for loop in its bo iS that print some patterns using nested for loops,
Consider following exam
Program 1.11 ; TEE Sy 1s 4
BilPen 4 iangle of three Lines Jo Hiss) JooP. i heen
Write a program to print an inverte ing or is not
using “#”.
public class Nested {
public void prin()
{ inti=3, 5-65
for (3 4<55 i) 1
system. out.printIn()}
for (int k=j3k>isk--)
system.out.print("# ")3
id
BB Program 1.12
Write a program to print a triangle with numbers 1 to 4 in 4 rows using a nested for loop.
public class Nested {
public void prin( )
{
int 4, 35
for( i= 45 4 ce 4; +t) gue sce eat
for 5-455 iy 44) ( pero s
System. out. pris mt 2
Prints") 5 bie
System.out.printin() ; (123
y , 1234
}
}
EA Program 1.13
—_—__
Write a program to print a tr
langle with o4,
Id ni
Public cl, umbers
f ass Nested from 1 to 10 using a nested for looP-
Public vo}
{ id prin( )
int i, 4;= - REVISING BASIC JAVA CONCEPTS 25
Output produced is =
System.out.print(3 a
} 135
systen.out.printin(); aS oe
y 13579
+
V. The break and continue Statements
v
vvvvyv
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
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.
Java is a popular Object Oriented programming language that is used to build secure and powerful applications
that run across multiple operating systems.
‘An object is an identifiable entity with some characteristics and behaviour
A class is a blueprint representing a group of objects that share common properties and relationships.
Data abstraction refers to the act of representing essential features without including the background details or
explanations.
The wrapping up of data and functions (that operate on the data) into a single unit (called class) is known as
‘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.
The JVM compiler (javac) compiles the Java source code/program file (,java files) into byte code (.class files),
which can then be executed using Java interpreter program (java).
‘An initial class contains main function inside it. The program is given the same name as that of its initial class.
The building blocks of a program are classes, objects, methods, statements, expressions, variables etc.
Java offers two selection statements : if and switch.
Java offers three iterative constructs : for, while and do..while.
The break and continue are jump statements of java.COMPUTER ‘appLicATIONS-X
26
Conceptual Questions
Section A : Objective Type Questions
BE:
aracter set.
: eee in a program is called ——
3. Which of the following is not a token ? (a tahient (@ operators
(@) keywords ( identifiers
4. Identify the illegal identifier from the following. ome.50 (@ AtoZ
(@) CHK () oBye
5. Which of the following does not represent a character literal ?
@w ov (© ‘\a (@) “a
6. Which keyword tums a variable declaration into constant declaration ?
(@ const (® constant (0 final (@) fixed
7, ch 4=2 is equivalent to
(@ ch = chi2 (0) ch+2
(ch=+2 (@ none of the above
8, The Math class is part of which Java library package.
(@ java.util ( javaio (0 java.random (@ javalang
9, Which clause is optional in a switch statement ?
(@) switch () case (© default (@ none of the above.
10. Absence of which statement causes a fall-through in a switch statement.
(@) continue () break (0 stop (@ fal
u. Pie the itpait rela of an if statement can contain these many statements in it
/ : 5 (@) as many
co ve the following loops is mostly used for fixed number of iterations ?
(©) while o do-while
A a. none of the above
13. Po the following is not an entry controlled a
(c) while () do-while
(d) none of the above
14. Which of the following is an exit controlled loop ?
( for
(© while (®) do-while
15. Which of the following statements (@) none of the above
termi
eek males the complete execution of a loop ?
(0) terminate ©) continue
(@) System exit(o)eS REVISING BASIC JAVA CONCEPTS 27
ie aa
1, Using Java notation, provide the integer value zero, a string consisting of a zero, and the character
zero.
Ans.
™ the integer value zero 0
® string consisting of a zero : “0
the character zero : ‘0’
Section B : Subjective Type Questions
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 variable has a
certain type, we are saying what values it can 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 have.
For example, to say that a variable is of type int says that integer values in a certain range can be
stored in that variable.
3, What is a literal?
Ans. A literal 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 isa 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 of the expression is — p,
which would be positive. Do it :
using a conditional operator. (Do not use the mathematical function here).
Ans. p>0?p:-p
5. 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) 5
6. Given the following set of identifiers :
byte b; char ch ;
short sh ; int intval ;
Long longval ; float, fl ;
Identify the datatype of the following expressions :
(a) ‘a’ -3 (6) intoal * longval - ch (6) fl + longoal/sh
Ans.
(@) int because
ee;
P|
char int
es
int10.
o
because
Suppose x1 and x2 are two type double variables that you want to add as integers and asgring
integer variable. Construct a Java statement for doing so.
‘Ans, Assuming that target variable is res of type int.
res = (int) (x1 + x2)5
. What is casting, when do-we need it?
Ans, Casting is a form of conversion, which uses the cast operator to specify by a type nam
parentheses and is placed in front of the value to be converted. For example :
result = (float) total / count ;
They are helpful in situations where we temporarily need to treat a value as another type:
What will be the output of the following ?
‘System.out.println(1 +9 + “Super") ;
‘System.out.printIn("Hello" +24+3)5
Ans. 1@ Super
Hello 23
State the rules of operator Precedence,
Ans. All expressions are eval tat
the rules that govern the ordes nna an operator precedence hierarchy that
Operator (ype) 1, ana the maine ns te evaluated.
son i = Seman nder operator % are performed before + and -:
many methods with whi imple *
methods the square with which many simp!
trouble of erating an defined ag op eE TOOt, Tounding, trigo ie dogarith
ject, s they can be used irectly by the programme?REVISING BASIC JAVA CONCEPTS 29
12. 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...lse if combination allows
any kind of condition supporting all types of comparisons after each if.
13, 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 fest-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 test-condition for ending the loop is not tested until the body of the loop has been executed.
14. What are jump statements ?
Ans. The statements that cause unconditional control-transfer in program are called jump
statements. Two most common jump statements are break and continue.
15. What does a break statement do ?
Ans. A break statement terminates the current loop and proceeds to the first statement that
follows that loop. For example, the break statement in the following loop
for(int d=2;d eT + 10.0/1085
discount=
el: + 5.0/1005 sa
sf.
igiscountbill
, ee ) : ( bill * 5.0/100 ) ;
41 * 10.0/2 ;
i 2000 ) ? ( bi
(pill > ¥
discount =
19, Convert following
anti=23
goat loop into for loop.
d-d*23 :
systen.out-printin(d) 5
a (icse
} while (i <= 5) 5 ,
inti=1,d=53
for (3 1<= 55 i++)
d=d*23
system.out.printin(d) 5
}
20, Analyze the given program segment and answer the following questions +
for(inti=35;ice45 it) {
for(int j=2340;i-=2) {
for(j=255=
What is meant by im F
What do you mean by type castin
| What le el ic and db is a double variable 2
pe conversion ?
a icit
plicit and explicit fy st operator in Java ?
g ? What is type ca
type of the following expression if bh represents a byte variable, isang
variable, fl is a float variabl
_ What will be the resultant type of the
bh-iedb/fl-i* fl+db/ a /
following expression if flis a float variable and dbiss ny
variable ?
(int) (fl + db)
Determine the data type of the expression
ronda) (p+ nls )
+n) (long) (s + p)
If p is an int, ris a flat, qis a long and s is double.
. Determine the data type of the expression
2x+3y | 8p E
Sw +62" 5q
if xis int, y is long, w is float, z is double, p is short and q is long double.
State the value and type of each expression,
SSH eruUKR sR h@anceD
Math.abs(~5)-Math. abs(—7)
wath.abs(-1e-1) + Math. abs(-2e-2)
Math. sqrt(@.e¢64)
vath.sqrt(Math.pow(2.7, 2)
Nath.round(3.499)
Math.max(1.5e-2, .@95)
Math.ceil(4.ee2)
Math.min(5, 1.0)
Nath. floon(7.99)
Math. ceil(-2.73)
Math. pow(16, 0.25)
Math.pow(4, -2)
peat Pound( 49 +01
, 5
h.round(1.49) 4 a415.
16.
17.
18.
19.
REBBES
26.
27.
REVISING BASIC JAVA CONCEPTS 37
Write the following as Java expressions.
(@ Va? =o () rhx® -y6) © Snr (@\2*-11
‘A student incorrectly attempted to produce 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.
What is the significance of a break statement in a switch statement ?
‘What are iteration statements ? Name the iteration statements provided by Java.
‘What is meant by an entry-controlled loop ? Which Java loops are entry-controlled ?
What is meant by an exit-controlled loop ? Which Java loops are exit-controlled ?
What is the difference between a while and do-while loop ?
How many times is the loop body executed in a do loop, even if the test-condition is false ?
What is nested loop ?
Write a program to print pattern like :
1
21
w2 t
aa2%
54321
Write a program to print a pattern as :
ioves
1234
123
12
1
Write a program to print a pattern as :
1
1e
101
1010
1e101
Write a program to print a pattern as :
naeaA
comPuTER ‘ApPLICATION>
* senitive datatypes *
primitive .
ify the following 2 primitive oF POPPON 5 int (iv) classes
28, Classify the ew '
(i) char :
BEST”) 3
29. systen.out. print( - a
system. out.print1n( ‘oF Luck”) ove statements
the al
Chioose the correct option for the output of
(ii) BEST
(i BEST OF LUCK OF LUCK hes .
50. fd) Write a Java expression forthe flow *
~ ee?
: ab
J of y after evaluating the expression
y-> + —-ys when int y = 8
given below ?
(b) What is the valu
yie Hy +
(©) Give the output of the following =
(i Mathfloor (- 4.7)
(ii) Math.ceil(3.4) + Math.pow(2,3)
31. What are the values stored in variables 5 and rp ? {ICSE any
() double r, =Math.abs(Math.min(—2.83, -5.83)) 5
(i doubler, =Math.sqrt(Math.floor(16.3)) ;
32. (@ Name the operators listed below : [ICSE 209
O< (++ (i) && (iv)?
(b) State the number of bytes occupied by char and int data types.
(© Write one difference between / and % operator.
. Predict :
, = [ICSE 201
class Test {
Public static void main(String args|
cen ig ares[]) {
x=35
ye4;
Z=Math.sqrt(x* x+y # yy,
System.out.printIn(*z = " 4,
} z=" 42);
}
34, Predict the output :
class Power (
Public static voig
main(st
inte=5, resurt as ring args) F
result=1; 7?
ize;
while(e > 9) ¢
result #9.Ges
REVISING BASIC JAVA CONCEPTS 39
e-;
+
int n= result /2, p=i- 1)
System.out.print1n("2 to the power of" +14" is “+ result);
‘System.out.print1n("2 to the power of" + p+" is "+n);
+
35. Predict the output :
class FindFac {
public static void main(String args[]) {
for(int i= 25 i <= 100; i++) {
System.out.print("Factors of" +i+": "3
for(int j= 2; 5 10; i++)
System.out.println(i) ;
System.out.printIn(i * 4) ; [ICSE 2018}
37. Find the error
for(count = @, count < 5, count = count + 1)
System.out.printin(“This is count:" + count);
System.out.print1n("Done!"); -
38. Find the error :
x= 3;
yeas”
2 = math.power(x*x, y/2);
39. Find the error :
class Test {
Public static void main(String args[]) {
int x = 19;
if(x == 10) {
int y = 20;
System.out.printn("x andy: "+x+""4y);
x=y*2;
+
y = 100;
System.out.printin("x is " +x);
+40
RG
47.
49,
51
52.
53.
|. Write a program that input
‘COMPUTER ‘APPLICATIONS-X
ts if the given number is a multiple of both 3 and 5,
fe a characters and prints if the typed character is in uppercase oy
Write a program that inputs a number and tes|
: , igit or an alphabet
iia progam that inputs a character and prints ifthe user has typed a digi a
special character. 7 iven alphabet is a vowel or not,
it that inputs an alphabet and checks if the given alpha co
a : sansa that tekes a number and check ifthe given number is a 3 digit number or no
Ise if to determine)
= a program to input three number and print the largest of the three numbers.
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)
Write a program that prints the squares of 10 even numbers in the range 10 .. 100.
Write a program that inputs a number and checks if the given number is a palindrome. A number
that is equal to its reversed number is a palindrome number.
Write a program to input a number in the range 10 to 100 and check if it is a prime number,
Write a program to print following series of numbers: 2, 5, 8, 11, 14....
Write a program to print Fibonacci series : 0, 1, 1, 2, 3, 5, 8....
Write a program to print factorial of a given number.
Write a program to print Floyd’s triangle as shown below :
1
23
456
78910
11 12 13 1415