Chapter 4 Coding Unit
Chapter 4 Coding Unit
Question 1
Which of the following is a valid comment in Java language?
1. /*comment*//
2. /* comment
3. //comment
4. */ comment */
Answer
//comment
Reason — In Java, the comment statements are written using double slash (//).
Question 2
Which of the following is used to enclose a set of statements to form a compound statement
in Java program?
1. Parenthesis
2. Brackets
3. Curly brackets
4. All of them
Answer
Curly brackets
Reason — A set of two or more statements placed within curly brackets and executed
together is called compound statement.
Note — Here, there is a misprint in part (3). Curly bracket has been misprinted as square
brackets.
Question 3
Which of the following operators is essentially required while writing if statement?
1. Arithmetic
2. Relational
3. Bitwise
4. All of them
Answer
Relational
Reason — In if statement, to test whether a condition is true or not, Relational operators are
used.
Question 4
Due to which of the following errors, a program does not provide correct result although it
has no grammatical mistake?
1. Logical
2. Syntax
3. Type mismatch
4. None of the above
Answer
Logical
Reason — Logical error occurs when the logic is incorrect. Thus, the program does not
produce the desired result although it is syntactically correct and compiles and executes fine.
Question 5
A Java statement is given as:
if((a!=b)&&(a==c))
Which of the following statements is true?
Answer
Both (a) and (b)
Reason — The if condition checks that a and b are unequal and a and c are equal. Both these
conditions should be true then only if statement will execute. If a and b are unequal and a
and c are equal then b will either be the smallest number or the greatest number.
Question 6
Which of the following logical operators results in true when all the connecting conditions
are true?
1. !
2. ||
3. &&
4. !=
Answer
&&
Reason — Logical AND results in true when all the connecting conditions are true.
Question 1
Question 2
In assignment, the data values are readily available in Java program.
True
Question 3
Question 4
In a decision making program, 'if' checks whether the condition is true or false.
True
Question 5
You can't assign data values in the main( ) function.
False
Question 6
In an if-else statement, the condition is to be defined only with if and not with else.
True
Predict the output of the given snippets, when executed
Question 1
int x = 1,y = 1;
if(n>0)
{
x=x+1;
y=y+1;
}
What will be the value of x and y, if n assumes a value (i) 1 (ii) 0?
Answer
Output
(i) When n is 1:
x is 2 and y is 2
(ii) When n is 0:
x is 1 and y is 1
Explanation
Question 2
int b=3,k,r;
float a=15.15,c=0;
if(k==1)
{
r=(int)a/b;
System.out.println(r);
}
else
{
c=a/b;
System.out.println(c);
}
Output
Syntax Error
Explanation
There are 2 syntax errors in this program:
1. Variable k is not initialized with any value before using it in the if check.
2. The statement float a=15.15 has a syntax error. We are trying to assign a
double literal to a float variable. The correct statement will be float
a=15.15f.
Question 1
class public
{
public static void main(String args{})
{
int a=45,b=70,c=65.45;
sum=a+b;
diff=c-b;
System.out.println(sum,diff);
}
}
Answer
Corrected Program
class A //1st correction
{
public static void main(String args[]) //2nd correction
{
int a=45,b=70;
double c=65.45; //3rd correction
int sum=a+b; //4th correction
double diff=c-b; //5th correction
System.out.println(sum + " " + diff); //6th correction
}
}
Question 2
class Simplify
{
public static void main(String args[])
{
int a,b,c,d;
a=10,b=5,c=1;
c=2a+2b;
d=(a+b)2;
p=c/d;
System.out.println(c , d , p);
}
}
Answer
Corrected Program
class Simplify
{
public static void main(String args[])
{
int a,b,c,d;
a=10;b=5;c=1; //1st correction
c=2*a+2*b; //2nd correction
d=(a+b) / 2; //3rd correction
int p=c/d; //4th correction
System.out.println(c + " " + d + " " + p); //5th correction
}
}
Case-Study Based Question
Question 1
It is possible that the user may not be able to write an error-free program at one
go. Due to this reason, debugging is significant. Debugging is used to eliminate
errors from a program. Some of the examples describing the errors are given
below:
(b) The user has applied multiplication sign, instead of division sign.
(c) Sum of p and q is to be divided by their difference using the statement p+q/p-q.
(d) While writing a Java statement, the user forgot to terminate the statement using
semicolon.
Answer
1. Runtime error
2. Logical error
3. Logical error
4. Syntax error
Question 1
Write the syntax of 'if' statement.
Answer
OR
if(condition)
{
Statement 1
Statement 2
:
:
Statement n
}
Question 2
What is a compound statement? Give an example.
Answer
A set of two or more statements which are executed together and are placed within
curly brackets { } is called compound statement.
For example,
int n=5;
if(n>0)
{
System.out.println(n);
n=n-1;
}
In this snippet, the statements System.out.println(n); and n=n-1; are
compound statements as they will be executed only when the condition of if is true.
Question 3
Define the following:
(a) Normal flow of control
Answer
1. if statement
2. if-else statement
3. if-else-if statement
Question 4
Write down the syntax of the following with reference to Java Programming:
(a) to accept an integer value using main( )
(b) to accept a fractional number using main( )
Answer
Question 5
What are the different types of errors that may occur during the execution of a
program?
Answer
Logical errors and Run-Time errors occur during the execution of the program.
Question 6
Distinguish between Syntax error and Logical error.
Answer
Syntax Errors occur when we violate the rules of Logical Errors occur due to our
writing the statements of the programming
language. mistakes in programming logic.
Question 7
Answer
In if-else construct, the user defines the statements to be executed when the
condition results in true or false. If the given condition results in true, the
statements in the 'if' block are executed and if the given condition results in false,
the statements in the 'else' block are executed.
Question 1
Write a program to calculate and display the value of the given expression:
(a2+b2)/(a-b),when a=20, b=15
public class KboatEvalExp
{
public static void main(String args[])
{
int a = 20, b = 15;
double result;
result = (a * a + b * b) / (a - b);
System.out.println("Result = " + result);
}
}
Output
Question 2
Write a program to calculate the gross salary of an employee when
Basic Salary = Rs.8600
DA = 20% of Salary
HRA = 10% of Salary
CTA = 12% of the Salary.
Gross Salary = (Salary + DA + HRA + CTA)
Display the basic and gross salary.
public class KboatSalary
{
public static void main(String args[]) {
int sal = 8600;
double da = 20 / 100.0 * sal;
double hra = 10 / 100.0 * sal;
double cta = 12 / 100.0 * sal;
double gross = sal + da + hra + cta;
System.out.println("Gross Salary = " + gross);
}
}
Output
Question 3
Write a program to accept Principal, Rate and Time. Calculate and display the
interest accumulated for the first year, second year and the third year compound
annually.
Sample Input:
Principal = ₹5,000, Rate = 10% per annum, Time = 3 years
Sample Output:
Interest for the first year: ₹500
Interest for the second year: ₹550
Interest for the third year: ₹605
Question 4
Question 5
Write a program to input two unequal numbers. Display the numbers after
swapping their values in the variables without using a third variable.
Sample Input: a=23, b= 56
Sample Output: a=56, b=23
Question 6
Write a program to input the temperature in Celsius and then convert it into
Fahrenheit. If the temperature in Fahrenheit is more than 98.6°F then display
"Fever", otherwise "Normal".
public class KboatTemperature
{
public static void main(double cel) {
Question 7
Write a program to accept the marks, obtained in five different subjects (English,
Physics, Chemistry, Biology, Maths) by a student and find the average marks. If
the average is 80 or more, then display he/she is eligible to get "Computer
Science', otherwise "Biology".
public class KboatMarks
{
public static void main(int eng, int phy, int chem,
int bio, int math)
{
double avg = (eng + phy + chem + bio + math) / 5.0;
Output
Question 8
'Mega Market' has announced festival discounts on the purchase of items, based
on the total cost of the items purchased:
Up to ₹2,000 5%
Write a program to input the total cost. Display the discount and amount to be paid
after discount.
public class KboatDiscount
{
public static void main(double c) {
int d = 0;
if (c <= 2000)
d = 5;
else if (c <= 5000)
d = 10;
else if (c <= 10000)
d = 15;
else
d = 20;
Output
Chapter 4 Coding Unit III
Choose the correct option
Question 1
1. To display a value
2. To find square root of a number
3. To input a value
4. To find maximum of two numbers
Answer
To input a value
Reason — The Scanner class allows the user to input values of different data types.
Question 2
Answer
Reason — nextDouble( ) method receives a double type value and stores it in a double
type variable.
Question 3
1. Math.pow(a,2)
2. a*a
3. Math.sqrt(a,2)
4. a**2
Answer
Question 4
1. int
2. float
3. double
4. long
Answer
double
Question 5
Which of the following functions will find the square root of a number 'a'?
1. sqrt(a)
2. Math.sqrt(a)
3. Squareroot(a)
4. √a
Answer
Math.sqrt(a)
Reason — Math.sqrt() function is used to find the square root of a positive number.
Question 6
Which of the following package will you import to use Scanner class?
1. java_util;
2. Scanner.class;
3. java.util;
4. java.scanner.util;
Answer
java.util;
Reason — The Scanner class is available in the system package java.util. One must
import java.util package to avail the facilities of the Scanner class.
Fill in the blanks
Question 1
A class of JDK 1.5 version used to accept the values from the keyboard is known
as Scanner.
Question 2
Question 3
Question 4
Question 5
System.in receives the input from the keyboard for the Scanner object.
Question 6
Question 1
Question 2
Question 3
Question 4
Question 6
Question 1
int x = 1,y = 1;
if(n > 0)
{
x = x + 1;
y = y + 1;
}
System.out.println(x + " , " + y);
What will be the values of x and y, if the value of n is given as:
(i) 1
(ii) 0 ?
Output
(i) When n is 1:
x is 2 and y is 2
(ii) When n is 0:
x is 1 and y is 1
Explanation
When n is 1, if (n>0) is true. So the statements x=x+1; and y=y+1; are executed making
the values of x and y as 2.
When n is 0, if (n>0) is false. Statements x=x+1; and y=y+1; are not executed so values
of x and y remain 1.
Question 2
Output
20,16
Explanation
The value of a is 20 and b is 16. The condition (a > 10) is true, so the execution enters
the if block. The statement a = a++; increments the value of a by 1 after the assignment.
So a remains unchanged as we are assigning the original value of a (which is 20) back
to a. The value of b is incremented by 1 so b becomes 16.
Question 1
Math.pow( )
Answer
In Java, Math.pow( ) function returns the value of the first argument raised to the
power of the second argument.
Syntax
Question 2
Math.sqrt( )
Answer
This function is used to find the square root of a positive number. It will always return a
double type value.
Syntax
double n = Math.sqrt(25);
It will return a double type value for n as 5.0.
Question 3
Math.min( )
Answer
This function is used to return the minimum of two numbers. It returns an int value if
both of its arguments are int otherwise it returns a double value.
Syntax
The statement
Question 1
Answer
The Scanner class is one of the ways to input data values into the computer using Java
language. It is defined inside the java.util package. It provides various next methods to
accept values of different data types as input from the user through the keyboard.
Question 2
Answer
Some of the reasons why a program might need to accept input values from a user are:
Question 3
Answer
import java.util.*;
class KboatScannerExample
{
public static void main(String args[])
{
int num;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
System.out.println(num);
}
}
Question 4
The method nextInt( ) is used to input an integer number and store it in an integer type
variable.
Syntax
Question 5
Answer
The package java.util needs to be imported while using the Scanner class.
Question 6
In what way can the following data be read from the Scanner object?
Answer
(a) We can read an integer type value by using the nextInt( ) method of Scanner class.
Syntax
Syntax
Syntax
Question 1
Write a program in Java to input two numbers (say, n and m) using the Scanner class.
Display the results of n raised to the power m (n m) and mn.
import java.util.*;
public class KboatExponent
{
public static void main(String args[])
{
int n, m;
double expo;
Scanner in = new Scanner(System.in);
expo = Math.pow(n,m);
System.out.println(n + " raised to the power "
+ m + " = " + expo);
expo = Math.pow(m,n);
System.out.println(m + " raised to the power "
+ n + " = " + expo);
}
}
Output
Question 2
Write a program in Java to input perpendicular and base of a right angle triangle using
the Scanner class. Calculate and display its hypotenuse using the formula given below:
h = √(p2 + b2)
import java.util.Scanner;
Output
Question 3
import java.util.Scanner;
Output
Question 4
Write a program in Java to accept the cost price and the selling price of an article
using the Scanner class. Check whether it incurs a profit or a loss. If profit happens,
then find and display profit percent, else display loss percent.
import java.util.Scanner;
Output
Question 5
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 using the Scanner class.
Check and display whether the triangle is equable or not.
For example, a right angled triangle with perpendicular, base and height as 5, 12 and
13 respectively has its area and perimeter same as 30.
import java.util.Scanner;
double p = a + b + c;
double s = p / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
if (area == p)
System.out.println("Entered triangle is equable.");
else
System.out.println("Entered triangle is not equable.");
}
}
Output
Question 6
A special two-digit number is such that when the sum of its digits is added to the
product of its digits, the result is equal to the original two-digit number.
Write a program to accept a two-digit number using the Scanner class. Check and
display whether it is a special two-digit number or not.
Sample Input: 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 .
Hence, 59 is a special two digit number.
import java.util.*;
if (sum == num) {
System.out.println(num + " is a Special 2-digit number");
}
else {
System.out.println(num + " is not a Special 2-digit number");
}
}
}
Output
Question 7
A library charges a fine for returning a book late after the due date as per the
conditions given below:
Design a program in Java assuming that a book is returned N days late. Input the value
of N using the Scanner class. Calculate and display the fine to be paid to the library.
import java.util.*;
if (n <= 5)
fine = n * 2.0 ;
else if (n <= 10)
fine = 10 + (n - 5) * 5.0 ;
else
fine = 10 + 25 + (n - 10) * 10 ;
Output
Case-Study Based Question
Question 1
Mohit wanted to design a program using scanner class. Due to some confusion, he
could not complete the program and has left some places marked with (i), (ii), (iii)
and (iv) to be filled with the keywords/expression, as given below:
(i) java.util;
class Sample
{
public static void main(String args[])
{
(ii) num;
Scanner inp = (iii) Scanner(System.in);
System.out.println("Enter a number:");
num=(iv);
if(n % 2 == 0):
System.out.println("Even number");
else:
System.out.println("Odd number");
}
}
Help him to complete the program by answering the following questions:
Answer
(a) import
(b) int
(c) new
(d) inp.nextInt();
Question 1
Math.pow( )
Answer
In Java, Math.pow( ) function returns the value of the first argument raised to the
power of the second argument.
Syntax
<Return data type> <variable> = Function name (argument 1,
argument 2);
Question 2
Math.sqrt( )
Answer
This function is used to find the square root of a positive number. It will always return
a double type value.
Syntax
<Return data type><variable> = Function name (Positive
number);
Question 3
Math.min( )
Answer
This function is used to return the minimum of two numbers. It returns an int value if
both of its arguments are int otherwise it returns a double value.
Syntax
<Return data type><variable> = Function name (argument 1,
argument 2);
The statement
double d = Math.min(52, 89.7);
will return a double type value for d as 52.0