[go: up one dir, main page]

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

Adobe Scan 11 Apr 2025

The document outlines the revision of the Class IX syllabus focusing on Java programming, covering topics such as packages, input/output operations, and error types. It includes questions and answers about Java concepts, syntax, and examples of Java programs for practical understanding. Additionally, it provides exercises for students to implement their knowledge through coding tasks.

Uploaded by

angelinjeffrin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views25 pages

Adobe Scan 11 Apr 2025

The document outlines the revision of the Class IX syllabus focusing on Java programming, covering topics such as packages, input/output operations, and error types. It includes questions and answers about Java concepts, syntax, and examples of Java programs for practical understanding. Additionally, it provides exercises for students to implement their knowledge through coding tasks.

Uploaded by

angelinjeffrin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Chapter 1 Revision of Class IX Syllabus

Part V(a)
Introduction to Java

IV. Write short answers:


1. What is meant by a package? Give an example.
Ans. Package is a collection of classes such that each class includes different
built-in functions. For example: java.io
2. Name a Java package which is imported by default.
Ans. java.lang
3. Writeapackage that is used for input/output operations in Java.
Ans. java.io is used for input/output operations in Java.
4. Explain the significance of the following Java library packages.
Ans. (a) java.lang in Java that contains classes and
It is one of the built-in packages
interfaces of the Java programming language. The lang package
(primitive data type), Math
contains classes such as Boolean, Integer
(exponerntial, logarithm, square root),
etc. which are considered the
building blocks of a Java program.
(b) java.io helps the user to perform all the
input
It contains the classes that
streams also support all
data types,
output operations. These
execute the I/O operations.
characters, files, etc. to fully
(c) java.math mathematical methods
classes which provides various
It contains the max(),
calculations. Some of them include min( ),
to work on math
cos( ), tan( ), etc.
avg(), round( ), sin( ), machine. Explain.
is called Java Virtual into
5. (a) Java
interpreter
Byte code as input and converts it
Machine takes generated by
Ans. Java Virtual a time. This Byte code can be
line at Kotlin,
Machine Code one
any JVM language like Scala,
written in Machine.
compiling source code interpreter is called Java Virtual
Hence, Java
etc. not just Java. programs.
Name two ways of writing Java
(b) programs are:
ways of writing Java
Ans. Two
" Java Application
" Java Applet
programming
6. Define the terms: written in a high level code.
set of statements source
Ans. (a) Source code: A C++, Python, etc. is called as language.
language like Java, low level programming
code is a a sequence of
Os and
Machine code: Machine are written as
(b) code,the
instructions
processor.
the
In machine understood and executed by
1s. It is directly

17
(c) Byte code: Java compiler converts Java source
code into an
intermediate
binary code called Byte code. This Byte
executed directly by the processor. It needs to be code can'tbe
machine code for its execution. converted into
7. What is BlueJ? What are the features of Blue)?
Ans. Blue) is an integrated development
environment (DE) for the Jaya
programming language. It is a Windows based application for Java, It
uses conmpiler as well as interpreter to convert
code. source code intO machine
Features of Blue):
" It uses a menu driven approach to
carry out various tasks.
" It supports graphical user interface.
" It facilitates easier
debugging.
8. Write down the syntax of output
Ans. We commonly use two output statement in Java with an example.
statements in Java.
() Syntax: System.out.println(<output value>);
This statement displays the values on the
printing the value, it places the cursor at the output screen. After
start of the next line.
So the next printing happens at the start of the next line.
For example:
int a =10, b = 15;
System.out.println(a);
System.out.println(b);
Output:
10
15
(i) Syntax: System.out.print(<output
This statement also prints data on themesSsage>);
line. After printing the value, the output screen but on the same
the end of the printed value. So cursor remains on the same line at
the next printing starts in the
line just after the end of the previous same
For example: printed value.
System.out.print("JVM stands for"):
System.out.print(Java ");
System.out.print("Virtual ");
System.out.print("Machine");
Output:
JVM stands for Java Virtual Machine
9. What is meant by Java
reserved words? Name five Java
which are commonly used reserved words
Ans. In Java, a reserved word is ain Java programming.
word
language. Moreover, the reserved that has a pre-defined meaning in
words the
variables, methods, cannot be used as names for
are also known as classes or any other identifier. The reserved words
keywords.
Five commonly used Java reserved
char. words are public, class, int, double,

18 Teacher'e
10. Differentiate between the
output statements System.out.println( ) and
System.out.print(0.
Ans. The differences are:
System.out.println(0 System.out.print( )
It displays the output of the t
displays the output of the
program and the cursOr moves to program
the next line. but the cursor remains at
the end of thedata in the same line.
Next printing takes place from the Next printing
next line. takes place fron the
same line.

11. A Java program uses a Compiler as well as an


Ans. Java compiler compiles Java source code to Byte Interpreter. Explain.
code. The Byte code
can not runon the processor directly as the processor only understarnds
Machine Code. This task is perfornmed by Java Virtual Machine (JVM)
which takes this Byte code as input and converts it into Machine Code
line by line. So, VM acts as an interpreter for converting Byte code to
Machine Code. In this way, a Java program uses bothacompiler as well
as an interpreter.
Chapter 1 Revision of Class IX Syllabus
Part V(b)
Input in Java

III. Explain the following functions:


1. Integer.parselnt(in.readLine());
Ans. This is an input function of the InputStreamReader class that accepts an
integer value at the time of execution.
2. (char)(in.read( );
Ans. This is an input function of the InputStreamReader class that accepts a
character at the time of execution.
3. next);
Ans. The next( ) function is an input function of the Scanner class that accepts
a word at the time of execution.
4. public static void main(int b);
Ans. This is one of the methods to accept an integer value fromn the user at
the time of executiorn to the main( ) function using function argument.
5. nextLine( ):
Ans. The nextLine( ) function is an input function of the Scanner class that
accepts a string including spaces at the time of execution.
IV. Answer the following:
1. What are the different ways to give input in a Java program?
Ans. Java provides the following ways to give input in a program:
" Using Function Argument
" Using InputStreamReader class
" Using Scanner class
" Using Command Line Arguments
2. What is the use of the keyword 'import' in Java programming?
Ans. The keyword 'import' is used to imnport built-in and user-defined
packages into our Java programs.
For example: import java.util.*;
It will provide the facility to avail the Scanner class to perform various
tasks in Java programming.
3. What is a Run Time error? Explain with an example.
Ans. The errors that occur during the execution of the program primarily due
tothe stateof the program which can only be resolved at run time are
called Run Time errors.
Refer the following code:
import java.util.*;
class Sample
public staticvoid main(String args[)

20
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int n= in.nextlnt();
double ans = Math.sqrt(n);
System.out.println("Result = + ans);

}
The above program will work for all positive values of n, entered by
the user. When the user entersa negative number, a run time error will
occur. As we know that the square root of a negative number cannot be
determined. So, it is a run time error.
4. What are the different types of errors that take place during the execution
of a program? Name them.
Ans. Logical errors, Syntax errors and Runtime errors occur during the
execution of the program.
5. Give twodifferences between Syntax error and Logical error.
Ans. The differences are:
Syntax Error Logical Error
Syntax errors Occur when we Logical errors occur due to our
violate the rules of writing the mistakes in the programming logic.
statements of the programming
language.
Program is unable to compile and Program compiles and executes but
execute. does not give the desired output.

V. Unsolved Java Programs:


the election day,
0.1 In an election, there are two candidates X and Y. On
vote for X. Write a
80% of the voters go for polling, out of which 60%
program to take the number of voters as input
and calculate:
" number of votes received by X
"number of votes received by Y
Prog. import java.util.*;
public class Polling

public static void main(String args[)

Scanner in = new Scanner(System.in);


long tvoters, voters, xvoters, yvoters; voters: ");
System.out.print("Enter the number of
tvoters = in.nextLong );
Voters =Math.round(0.8 * tvoters);
Xvoters =Math.round(0.6 * voters);
yvoters = voters- xvoters;
System.out.printin("Total Votes: " +t tvoters):
System.out.println("Votes received by X: " +
xvoters);
System.out.println("Votes received by Y:" +
yvoters);

Input inJava 21
shopkeeper offers 10% discounttonthe printed price of a mobile
Q.2 A
However, a customer has topay 9% GST on the remaining amount. phone.
Writo
a program in Javato calculate the amount to be paid by the
taking printed price as an input. customer
Prog. import java.util.";
public class Phone

public static void main(String args[|)


Scanner in =new Scanner(System.in);
double mp, dis, gst, price;
System.out.print("Enter the Marked Price: ");
mp=in.nextDouble( ):
dis = mp*0.1;
price =mp-dis;
gst = price0.09;
System.out.println("'Price after 10% discount and 9% GST:" +
(price+gst);

Q.3 Write a program to input time in seconds.


converting it into hours, minutes and seconds.
Display the time after
Sample Input: Time in seconds: 5420
Sample Output: 1 Hour 30 Minutes 20 Seconds
Prog. import java.util.*;
public class Time
public static void main(String args])
{
Scanner in = new Scanner(System.in);
int time, hrs, min, sec;
System.out.print("Time
time =
in seconds: ");
in.nextlnt( );
hrs =time/3600;
min = (time %3600)/60;
sec = (time % 3600) % 60;
System.out.printin(hrs+" Hour"+min+" Minutes" +sec+"
Seconds");
Q.4 The driver took a
drive to
the evening, he drove a town 240 km at a speed of 60 km/h. Later in
back at 20 km/h less than the
a program to calculate: usual speed. Write
" the total time taken
by the driver
" the average speed
[Hint: average speedduring the whole
= total distance /journey
total timel

22 Teacher's Manual Understanding


ubliwstatwvd nnaintrin; angsl)
int dist = 40. s = 0, s p =speed-20;
lvt tine_mah time_eturn, totall tiìme, avg speed:
time wh= dist spe:
time ium= dist spd:
twtal tine = time_mch+ time_rturn:
Vg s =(dist)total time:
Sstemout.println("Total time:" + total_time);
Sstemout.println'Average speed:"+ avg_speed);

numbers. Display the numbers


Q.3 Write a pngram to input two unequalvariables without using a third
atter siwapping their values in the
variable.
Sample Input: a = 76, b = 65
Sample Output: a= 65, b= 76
Prog. inport java.util.";
publicclass Swap
public static void main(String args[)
Scanner(System.in);
Scanner in = new
int numl, num2;
System.out.println("Enter two unequal numbers:");
System.out.print("Enter first
number: ");
numl = in.nextlnt( );
System.out.print("Enter second number: "):
num2 = in.nextInt( );
num2)
if (numnl == Input! Numbers are equal."):
System.out.println("Invalid

else
num2;
numl=num1 +
num2;
num2 = numl -
num2;
num1 = numl-

swapping first number: "+ numl);


System.out.println("After
swapping second
number: " + num2);
System.out.println("After

years at the rate of


6%, 8%
for 3
invested
amount of money is Write a program to
calculate:
Q.6 Acertain compounded annually.
and 10% per annum years.
"the amount after 3
interest after 3 years. an input.
" the compound (Principal) as
Accept certain
anmount of money (R2/ 100))T * (1 + (R3 / 100)) and
(R1/ 100))T *(1 +
[Hint:A = P*(1 +
CI=A- P] Input in Java 23
Prog. import java.util.";
public class Interest

public static void main(String argsll)


Scanner in = new Scanner(System.in);
int p, rl=6, r2=8, r3=10;
double amt, ci;
System.out.print("Enter the principal: ");
p=in.nextInt( );
amt = p*(1+(r1/100)*(1+(r2/100)*(1+(r3/100);
ci = amt- p;
System.out.println("Amount after 3 years:" +amt);
System.out.println("Compound Interest:" +ci);

Q.7 The co-ordinates of twO points A and Bon a straight line are given as
(x1, yl) and (x2, y2). Write a program to calculate the slope (m) of the
line by using formula:
Slope =(y2 - y1) / (x2-x1)
Take the co-ordinates (x1, yl) and (x2, y2) as input.
Prog. import java.util.";
publicclass Slope
public static void main(String args[|)
Scanner in =new Scanner(System.in);
int x1, y1, x2, y2;
float slope;
System.out.print("Enter x coordinate of point A: ");
x1 = in.nextlnt( );
System.out.print("Enter ycoordinate of point A: ");
yl = in.nextint( ):
System.out.print("Enter xcoordinate of point B: ");
x2 = in.nextlnt( );
System.out.print("Enter ycoordinate of point B: ");
y2 = in.nextInt( ):
slope =(y2- y1) / (x2-x1);
System.out.printin("Slope of line: "+slope);

Q.8 A dealer allows his customers a discount of 25% and still gains 25%.
Write a program to input the cost of an article and display its selling
price and markedprice.
Sample Input: 600
Sample Output: Selling Price =750
Marked Price = 1000

24 Teacher's Manual Understanding Computer Applications with BlueJ- X


Prog. import java.util.";
public class MP_SP

public static void main(String argsl])


Scanner in =new Scanner(System.in);
int cp, dis = 25, pp= 25;
double sp, mp;
System.out.print("Enter cost price: ");
cp =in.nextlnt( );
sp= (100 +pp)/100.0)*cp;
mp = (100.0/(100 - dis))"sp;
System.out.printBn("Selling Price:" +sp);
System.out.printn("Marked Price:" +mp):

Input in Java 25
Chapter 1 Revision of Class IX Syllabus
Part VI

Mathematical Library Methods

V. Explain the following functions:


1. Math.random()
Ans. It returns a positive double value, greater than or equal to 0.0 and less
than 1.0.
2. Math.pow()
Ans. It returns the value of the first argument raised to the power of the second
argument. The return type of thismethod is double.
3. Math.cbrt( )
Ans. It returns the cube root of its argument as a double type value.
4. Math.log( )
Ans. It returns the natural logarithm of its argument. It always returns a
double data type value.
VI. Distinguish between:
1. Math.ceil( )and Math.floor( )
Math.ceil( ) Math.floor( )
It returns the next higher double It returns the lower double type
type value, greater than or equal value, less than or equal to the
to the argument. argument.
double a =Math.ceil(65.5); double b = Math.floor(65.5);
Output: 66.0 Output: 65.0
2. Math.rint( ) and Math.round( )
Math.rint( ) Math.round( )
This function returns the nearest |It rounds
off its
integer of a given fractionalnearest integer argument to the
and returns its
number. The return data type will value as long type, irrespective of
always bedouble. its argument (int, float or double).
double a = Math.rint(1.5);
double b =Math.rint(2.5); long a =Math.round(1.5);
Both will result in a value of 2.0 long b = Math.round(2.5);
The first will have a value of 2 and
second will have a value of 3.
VII. Unsolved Java Programs:
Q.1 Write aprogram to calculate the value
1/a' +2/' +3/c of the given expression:
Take the values of a, b and cas input from
the result of the expression to its nearest the console. Finally, display
whole number.

26
Prog. import java.util.";
publicclass Expression
public static void main(String argsll)
Scanner in = new Scanner(System.in);
int a,b, c;
double ans;
System.out.print("Enter the value of a: ");
a = in.nextint( );
System.out.print("Enter the value of b: ");
b= in.nextlnt( );
System.out.print("Enter the value of c: ");
c= in.nextInt( );
ans =(1/Math.pow(a,2) +(2/Math.pow(b,2) +
(3/Math.pow(c.2);
long round_ans =Math.round(ans);
System.out.println("Result roundedto whole number:" + round_ans);

Pythagorean
0.2 For every natural number m>1;2m,m²-1 and m²+1 form a
triplet. console to display a
Write a program to input the value of 'm' through
Pythagorean Triplet!.
Sample Input: 3
Then 2m=6, m²-1-8 and m²+1=10
Thus 6, 8, 10form a Pythagorean Triplet.
Prog. import java.util.*;
public class PIriplet

public static void main(String argsl)

int m, f_Triplet, s_Triplet, th Triplet;


Scanner in = new Scanner(System.in);
System.out.print("Enter the value of m: ");
m = in.nextInt( );
if (m < 2)
System.out.printn("Invalid Input! mshould be
greater than 1");

else

f_Triplet =2*m;
s_Triplet = (int)(Math.pow(m,2)-1);
th_Triplet = (int)(Math.pow(m,2) +1);
System.out.println("Pythagorean Triplets are:");
System.out.println("First Triplet: "+f_Triplet);
System.out.println("Second Triplet: "+s_Triplet);

Mathematical Library Methods


27
Sstem ot println Thrd Irnplet th Triplet).

Q3 Wnte aogram to inputa number. Calculate its square root and cube
Finallv. displav the result bv rounding it off.
Sample Input: 5
Square root of 5= 2.236067
Rounded fom= 2
Cube root of 5 = 1.7099759
Rounded form= 2
Prog. import java.util.",
public class Roots

public static void main(String args|)


Scanner in = new Scanner(Svstem.in):
int num;
double sqrt_val, cbrt_val;
long rd_sqrt, rd_cbrt;
Sstem.out.print("Enter anumber: ");
num =in.nextlnt( ):
sqrt _val = Math.sqrt(num);
cbrt_val = Math.cbrt(num);
rd sqrt =Math.round(sqrt_val);
rd_cbrt =Math.round(cbrt_val);
System.out.println("Square root of" + num +"="+ sqrt_val);
System.out.println("Rounded form =" + rd_sqrt);
System.out.println(Cube root of "+num +=" +cbrt_val);
System.out.println("Rounded form =" + rd _cbrt);

Q.4 The volume of a sphere is calculated by using formula:


V=2,3
3 7
Write aprogram to calculate the radius of a sphere by taking its volume
as an input.
3
Hint: radius = 3volume.
4 22
Prog. import java.util.";
publicclass Sphere
public static void main(String args[|)
anner in =new Scanner(System.in);
System.out print("Enter volune of sphere: ");
double y innextDouble),
doubler- Math cbn(v *(3/4 0)(7/22.0);

28 teatter's Matiual Uderstarnding Conputer Applications with BlueJ X


System.out.println("Radius of sphere =" + r);

Q.5 A trigonometrical expression is given as:


tan A-tan B
1+tanA*tanB
Write aprogram to calculate the value of the given expression by taking
the values of angles A and B (in degrees) as input.
22
Hint: radian= degree
\7+180
Prog. import java.util.";
publicclass Trigono_Exp
publicstatic void main(String args[)
Scanner in =new Scanner(System.in);
double ang_A, ang_B, ang_Arad, ang_Brad, num, denom, exp;
System.out.print("Enter angle Ain degrees: ");
ang_A in.nextDouble( );
System.out.print("Enter angle Bin degrees: ");
ang B= in.nextDouble( );
ang Arad = (22 *ang_A)/(7*180);
ang_Brad = (22 * ang_B)/(7*180);
num =Math.tan(ang_Arad)- Math.tan(ang Brad);
denom =1+ Math.tan(ang Arad) * Math.tan(ang_ Brad);
exp = num/denom;
System.out.println("Value of expression="+ exp);

Q.6 The standard form of quadratic equation is represented as:


ax² + bx +c= 0
where d= b² 4ac, known as 'Discriminant' of the equation. value of
Write a programn toinput the values of a, b and
c. Calculate the
discriminant and display the output.
Prog. import java.util.*;
public class Quadratic

publicstatic void main(String args[])


Scanner in = new Scanner(System.in);
int a, b, c;
doubled;
System.out.print("Enter the value of a: "):
a= in.nextInt( );
System.out.print("Enter the value of b:"):
b= in.nextlnt( );
System.out.print("Enter the value of c: ":

29
Mathematical Library Methods
C= innextint( ):
d =Math pow(b,2) -(4"a');
System out printIn("Discriminant = "+d);

Q.7 The sum of first nodd natural numbers can be calculated as n', where.
n is the number of odd natural terms.
For example,
Sum= 1+3+5+7: number of odd natural terms =4
Therefore, Sum= 4'=16
Write aprogram to input number of odd natu°al termsand display the
sum of the given series:
(a) 1+3 +5+ +29 +31
Prog. import java.util.";
publicclass Sum
publicstatic void main(String args[)
Scanner in =new Scanner(System.in);
int n,sum;
System.out.print("Enter the number of terms of the series: ");
n = in.nextInt( );
Sum = n*n
System.out.printn("1+3+5+. +29+31 ="+sum);
}
(b) 1+3+5+7+ .+47+ 49
Prog. import java.util.";
publicclass Sum
public static void main(String argsl])
Scanner in = new Scanner(System.in);
int n,sum;
System.out.print("nter the number of terms of the series: "):
n= in.nextint( );
Sum = n*n
System.out.println("1+3+5+. +47+49 ="+sum);

Q.8 Write a program to input the sum. Calculate and display the compound
interest in 3 years, when the rates for the successive years arer1%, r2%
and r3% respectively.
Hint: A=P ++
100/ 100 100/ CI=A-P

30 Teacher's Manual Udorstanding Computer Applications with BueJ X


Prog. import java.util.";
public class Interest

publicstatic void main(String args[|)


Scanner in = new Scanner(System.in);
int p, rl, r2, r3;
double amt, ci;
System.out.print("Enter the principal: ");
p=in.nextInt( );
System.out.print("Enter the rate rl: ");
rl= in.nextlnt( );
System.out.print("Enter the rate r2: ");
r2= in.nextInt( );
System.out.print("Enter the rate r3:");
r3 = in.nextlnt( );
amt = p*(1+(r1/100))*(1+(r2/100))*(1+(r3/100));
ci= amt-p;
System.out.println("Amount after 3 years: " + amt);
System.out.printin("Compound Interest: " + ci);
Chapter 1 Revision of Class IX Syllabus
Part VII
Conditional Statements in Java

IV. Convert the following constructs as directed:


1. switch case construct into if-else-if.
switch (n)
case 1:
s=a+b;
System.out.println("Sum="+s);
break;
case 2:
d=a-b;
System.out.printh(Difference="+d);
break:
case 3:
p=ab;
System.out.println(Product=+p);
break;
default:
System.out.println("Wrong Choice!");
Ans. if (n ==1)
S =a+ b:

System.out.println("Sum="+s);
else if (n ==2)
d=a-b;
System.out.println("Difference="+d);
else if (n ==3)

p=a*b;
System.out.println("Product="+p);
else

System.out.printin("Wrong Choice!");

32
2. if-else-if construct into switch case:
if(var==1)
System.out.println("Distinction");
else if(var==2)
System.out.println("First Division");
else if(var==3)
System.out.println("Second Division");
else
System.out.print1n("invalid");
Ans. switch (var)
case 1:
System.out.println("Distinction");
break;
case 2:
System.out.println("First Division");
break;
case 3:
System.out.println("Second Division");
break;
default:
System.out.println("invalid");

V. Answer the following questions:


Explain.
1. What is meant by 'conditional' statement?
program are executed is known as
Ans. The order in which the statements of a
program are executed from
control flow. By default, the statements ofa
programs require to modify this
top to bottom, but most of the times our condition. So, the statements
some
top to bottom approach, based on
program are known as conditional
that help us to alter the flow of the
statements.
System.exit(0)?
2. What is the significance of execution of the program by ignorning
Ans. The System.exit(0) terminates the program.
the Java Virtual Machine, exxecuting the current
For example: number, if the user enters a negative
number
To find the square root of a
the square root of the number.
In such
then it is not possible to find
situation,we can use System.exit(0)
to terminate the program.
statement? Justify.
necessary to include default case in a switch included to
3. Is it optional in a switch statement. It is
Ans. The 'default' case is an match in the
situation when none of the case values
take care of the
switch block for agiven value of control variable.

Conditional Statements in Java 33


intn
sIVithn)

Sstem out println(Value ot control variable is (0) zero");

Sstemout println(Value of controlvariable is I);

Sstemout.println(Value of control variable is 2");


detault:
Srstem.out println("Valueof control variable is greater than 2");
Even if we donot include the detault case, the program is syntactically
Ornt butwe will not get any output when value of controlvariable is
other than 0, l or 2.
4. What will happen if reak' statement is not used in a switch case?
Explain.
Ans. lna switch case, the use of break statement is an optional. The omission
of break statement will lead to fall through where program execution
continues into the next case and onwards till end of switch statement is
reached.
5. When does 'Fall through' occur in a switch statement? Explain.
Ans. In case a break statement is not used at the end of each switch case
block, the controlenters into the nextcase and onwards till end of switch
statement is reached. Thiscondition is said to be fall through.
6. What is a compound statement? Give an example.
Ans. Two or more statements can be grouped together by enclosing them
between opening and closing curly braces. Such a group of statements
is known as a compound statement.
For example:
if (numl <num2)

System.out.println("First nunmber is less than the second number"):


num1 =10;
num2 = 20;
System.out.println("The value of first number is" +numl):
System.out.println("The value of second number is" +num2);
7. Explain if-else-if construct with an
Ans. The if-else-if construct is used to testexample.
multiple
a deision. It provides multiple branching of conditions and then take
control statements.

34 Teacher 's Manual Understanding Computer


Applications with BlueJ X
For example:
if (marks < 35)
System.out.println("NoGrade awarded");
else if (nmarks < 60)
System.out.println("Grade Cawarded");
else if (marks < 80)
System.out.println(Grade Bawarded");
else if (marks < 95)
System.out.println("Grade Aawarded");
else
System.out.println("Grade A+ awarded");
8. Give two differences between the switch statement and the if-else
statement.
Ans. The differences are:
switch if-else
The switch statement can only test, The if-else can test for any boolean
ifthe expression is equal to any of expression such as less than,
its control variable. greater than, equal to, not equal
to, etc.
It is a multiple branching flow of It is abi-directional flow of control
control statement. statement.

VI. Unsolved Java Programs:


Q.1 A triangle is said to be an 'Equable Triangle, if the area of the triangle is
equal to its perimeter. Write a program to enter three sides of a triangle.
Check and print whether the triangle is equable or not.
its area
For example,a right angled triangle with sides 5, 12 and 13 has
and perimeter both equal to 30.
Prog. import java.util.";
public class Equable'Triangle

public static void main(String args[|)


Scanner in = new Scanner(System.in):
double a, b, c, p, s,ar;
System.out.println("Enter the three sides of a triangle:");
System.out.print("Enter the first side: "):
a = in.nextDouble( ):
System.out.print("Enter the second side: ");
b= in.nextDouble( ):
System.out.print("nter the third side: ");
c= in.nextDouble();
p=a+b+ c;
S=p/ 2;
ar = Math.sqrt(s *(s - a)
*(s -b) *(s - c));
ifSystem.out.printin("Equable
(ar == p) Triangle");

in Java 35
Conditional Statements
else
Svstem out printn(Not an tquable Iriangle");

Q.2 Aspval twodigit number is such that when the sum of its digits js
added to the product of its digits, the result is equal to the original two.
digit nunmber.
Tor cramplc: Consider the number 59.
Sum of digits = 5 +9= 14
Product of digits =5*9 =45
Total of the sum of digits and product of digits = 14 +45 =59
Write aprogram to accept atwo-digit number. Add the sum of its digits
to the product of its digits. If the value is equal to the number input,
display the message 'Special 2 - digit number" otherwise, display the
message "Not a special two-digit number".
Prog. import java.util.*;
public class Sp_Number
publicstatic void main(String args||)
Scanner in = new Scanner(System.in);
int num, num1, digitl, digit2, dsum, dprod, gsumn;
System.out.print("Enter a 2-digit number: ");
num = in.nextInt( );
if (num<10 | | num > 99)

System.out.println("nvalid input!");
System.exit(0);
numl = num;
digitl = num %10;
digit2 = num / 10;
dsum = digitl +digit2;
dprod =digitl *digit2;
gsum = dsum + dprod;
if (gsum == num)
System.out.println("Special 2-digit number");
else

System.out.println("Not a special 2-digit number");

36
O.3 The standard form of quadratic
equation is given by: ax? + bx + c = 0,
where d= b²4ac, is known as discriminant
of the roots of the equation that determines the nature
as:
Condition Nature
if d >= 0 Roots are real
if d<0 Roots are imaginary
Write a program to determine the nature and the roots of
a
equation, taking a, b, c as input. Ifd=b²-4ac is greater thanquadratic
to zero, then display "Roots are real", otherwise display or equal
"Roots are
imaginary". The roots are determined by the formula as:
-b+b² - 4ac -b-b-Aac
r1 = r2 =
2a 2a
Prog. import java.util.*;
publicclass QuadRoots
public static void nmain(String args[])
Scanner in = new Scanner(System.in);
int a, b, c;
double d, rl, r2;
System.out.print("Enter a: ");
a = in.nextInt( );
System.out.print("Enter b: ");
b= in.nextlnt( );
System.out.print("Enter c: ");
c= in.nextInt( );
d= Math.pow(b, 2) -(4*a*c);
if (d >=0)
System.out.println("Roots are real.");
rl =(b + Math.sqrt(d) / (2*a);
r2 = (-b- Math.sqrt(d)) / (2 *a); equation are:");
System.out.println("Roots of the
System.out.println('r1 ="+r1);
System.out.println("r2 ="+r2);

else
System.out.println("Roots are imaginary.");

Conditional Statements
in Java 37
Q.4 An air-conditioned bus charges fare for the passengers based on the
distance travelled as per the tariff are given below:
Distance Travelled Fare

Up to l0 km Fixed charge 80
11 km to 20 km Z6/km
21 km to 30 km Z5/km
31 km and above 74/km
Design a program to input distance travelled by the passenger. Calculate
and display the fare to be paid.
Prog. import java.util.*;
public class BusFare

public staticvoid main(String argsl)


Scanner in =new Scanner(System.in);
int dist, fare;
System.out.print("Enter distance travelled: ");
dist = in.nextInt( );
fare =0;
if (dist <= 0)
fare =0;
else if (dist <= 10)
fare = 80;
else if (dist <= 20)
fare = 80 + (dist -10) *6;
else if (dist <= 30)
fare = 80 + 60 + (dist - 20) * 5;
else if (dist > 30)
fare = 80 + 60 + 50 + (dist -30) *4;
System.out.printin("Fare =" +fare);

Q.5 An ICSE school displays a notice on the


school notice board regarding
admission in Class XI for choosing stream according
obtained in English, Maths and Science in Class 10 Council to the marks
Examination.
Marks obtained in different subjects
Stream
Eng, Maths and Science >= 80%
Pure Science
Eng and Science >= 80%, Maths >= 60%
Bio. Science
Eng, Maths and Science >= 60%
Commerce
Print the appropriate stream
allotted to acandidate. Write a
accept marks in English, Maths and Science from the console.program to

38 Teacher's Manual Understanding


Computer Applications with BlueJ -X
Prog. import java.util.*;
public class Admission

public static void main(String args[])


Scanner in = new Scanner(System.in);
int eng, maths, sci;
System.out.print("Enter marks in English: ");
eng = in.nextInt( ):
System.out.print("Enter marks in Maths: ");
maths = in.nextInt( );
System.out.print("Enter marks in Science: ");
sci = in.nextInt( ):
if (eng >=80 && sci >=80 &&& maths >=80)
System.out.printn("Pure Science");
else if (eng >=80 &&& sci >= 80&& maths >= 60)
System.out.println("Bio. Science");
else if (eng >= 60 && sci >= 60 && maths >= 60)
System.out.println("Commerce");
else
System.out.printin("Can not allot stream");

}
Q.6 A bank announces new rates for Term Deposit Schemes for their
Customers and Senior Citizens as given below:

Term Rate of Interest Rate of Interest


(General) (Senior Citizen)
7.5% 8.0%
Up to 1 year
8.5% 9.0%
Up to 2 years
9.5% 10.0%
Up to 3 years
10.0% 11.0%
More than 3 years
whose age is 60
The sernior citizen rates are applicable to the customers
sum (p) in term deposit
years or more. Write a program to accept the displays the
scheme, age of the customer and the term. The program
information in the following format:
Interest earned Amount Paid
Amount Term Age
Deposited
XXX XXX
XXX XXX
XXX

Prog. import java.util.";


publicclass BankLDeposit

publicstatic void main(String args[])


Scanner in = new Scanner(System.in):

Conditional Statements in Java 39


int sum, age;
double term, interest, amt;
System.out.print("Enter sum: ");
Sum= in.nextInt():
System.out.print("Enter age: ");
age = in.nextInt( );
System.out.print("nter term: ");
term = in.nextDouble( );
interest= 0.0;
if (age < 60)
if (term <=1)
interest = (sum *7.5 *term)/100;
else if (term <= 2)
interest= (sum * 8.5 * term)/100;
else if (term <=3)
interest = (sum *9.5 *term)/100;
else
interest= (sum * 10.0 * term)/100;
else

if (term <= 1)
interest =(sum * 8.0 * term)/100;
else if (term <= 2)
interest= (sum *9.0* term)/100;
else if (term <=3)
interest= (sum *10.0 *term)/100;
else
interest= (sum *11.0 *term) / 100;
amt = sum + interest;
System.outprintln(Sum Deposit"+"\e'+Term"'+"\t'+"Age"+"\e+ "hterest"+"\"+"Amount");
System.out.println(sum +"\t\e"+ term +"\t"+age+"\E"+interest+"\t\e"+amt);

Q.7 A courier company charges differently for


'Express' booking based on the weight of the'Ordinary'
parcel as
booking and
given below: per the tariff
Weight of parcel Ordinary booking
Up to 100gm Express booking
80
100
101 to 500 gm 7 150
200
501 gm to1000 gm 210 250
More than 1000gm 7 250 300
Write aprogram to input weight of a parcel and
ordinary and 'E for express). type of booking (O' for
Calculate and print the charges accordingly.
40 Teacher's Manual Urnderstanding
Computer Applications with BlueJ- X
Prog. import java.util.*:
public class Courier
public static void main(String
args)
double wt, charge;
char ch;
Scanner in =new
Scanner(System.in);
System.out.print("Enter
wt=in.nextDouble( ): weight of parcel: ");
Systern.out.print("Enter
ch = in.next( ).charAt(0); type of booking 'O' or 'E:");
charge = 0;
if (ch = 'O)

if (wt <= 0)
charge =0;
else if (wt <= 100)
charge = 80;
else if (wt <= 500)
charge = 150;
else if (wt <= 1000)
charge = 210;
else
charge = 250;

if (ch = 'E')
if (wt <=0)
charge 0;
else if (wt <=100)
charge = 100;
else if (wt <= 500)
charge = 200;
else if (wt <= 1000)
charge = 250;
else
charge = 300;

System.out.println("Parcel charges =" + charge);

Statements in Java 41

You might also like