Chapter 5

I. Name the following:

1. a package needed to import Scanner class

2. a method that accepts a character through Scanner object

3. a package needed to import StreamReader class

4. a method to accept an exponential value through Scanner object

5. a method that accepts an integer token through Scanner object


1. java.util

2. next( ).charAt( )


4. nextDouble();

5. nextInt( )

II. Write down the syntax with reference to Java programming:

1. to accept an integral value ‘p’ through Stream class

2. to accept a fractional value (float) ‘m’ through Scanner class

3. to accept the character ‘d’ through Stream class

4. to accept a fraction value ‘n’ in double data type through Stream class

5. to accept a word ‘wd’ through Stream class

6. to create a Scanner object.


Note: BufferedReader br=new BufferedReader(new InputStreamReader(;

1. int p = Integer.parseInt( br.readLine( ));

2. float m=ob.nextFloat( );

3. char ch = (char) ( ));

4. double n = Double.parseDouble(br.readLine( ));

5. String str = br.readLine( );

6. Scanner ob=new Scanner(;

III. Differentiate between the following:

1. nextInt( ) and nextFloat( )methods

Ans. nextInt( ) receives and returns the token as a int data type whereas nextFloat( ) receives and returns the token as a float data type.

2. Syntax and Logical errors

Syntax error

  • These errors occur when the rules or the grammar of the programming language is not followed.
  • The output is not obtained since the program does not execute due to compiler errors.
  • For example, missing semicolon, undefined variables, misspelt keywords, missing brackets etc

Logical error

  • It is the error in planning the program’s logic. The computer does not know that an error has been made.
  • The system simply follows the instructions and compiles without errors, but the execution does not yield the desired output.
  • For example, to find the product instead of using ‘*’ sign, the programmer might have used ‘+’ sign which yields the incorrect result.

IV Answer the following:

1. What do you mean by Scanner class?

Ans. Scanner class is available in the system package java.util which must be imported. After importing this package and creating a Scanner object, the user can avail various methods provided in the Scanner class to manipulate input data. String manipulation is easier in Scanner class as each word can be obtained as a token and handled separately. 

2. What are the different ways to give inputs in Java programming?

Ans. Input in Java can be obtained by three different methods:

i) By Using Command Line Arguments

Here, the data values are passed through arguments at the time of execution. The values passed through the console are received by a String type args[ ]array (subscript wise) as arguments to the parse function. These values are further converted to the required data type for storage in the corresponding variables.

Example 1

int  a = Integer.parseInt( args[0] );

float b= Float.parseFloat( args[1]);

ii) By Using Input Stream

InputStream requires Buffer ( a temporary storage) for the data values to be stored through an object. However, it requires the importing of package to perform all input output operations.


InputStreamReader ir=new InputStreamReader(;

BufferedReader br=new BufferedReader(ir);


BufferedReader br=new BufferedReader (new InputStreamReader(;

This object br can be used to invoke the various input methods of the BufferedReader class as follows:

String s = br. readLine( );

int n = Integer.parseInt( br.readLine( ));

float f = Float.parseFloat( br.readLine( ));

double d = Double.parseDouble(br.readLine( ));

iii) By Using Scanner class

To accept the input using this method, first import the java.util package and then create the object of the Scanner class. Then invoke any of the methods of the Scanner class through the Scanner object.


Scanner sn=new Scanner (;

double d = sn.nextDouble( );

3. What is the use of the keyword ‘import’?

Ans. The keyword ‘import’ is used to import a package into the current program. When a package is imported, all the classes and methods available in the package can be used in the program.

4. What is a package? Give an example.

Ans.  A package in Java is a collection of logically related classes. For example, all mathematical functions are included in a class called ‘Math’ that is a part of java.lang package which is a default package that is automatically imported into every program.

5. What is the use of the keyword ‘import’ in Java programming?

Ans. The keyword import is used to import a complete package or a particular class of a package into the program.

Example: import java.util.*   [or]   import java.util.Scanner

6. What is a compound statement? Give an example.


A compound statement refers to a set of statements enclosed within curly brackets.


if (a>b)

{sum = a+b;

  Pdt = a*b;


7. Write down the syntax to input a character through Scanner class with an example.


char ch = ).charAt(0);

8. What do you understand by ‘Run Time’ error? Explain with an example.


Sometimes, the program does not produce the desired results even after the compilation errors are removed. This is due to incorrect mathematical tasks or due to input of incorrect data. Since the compiler does not respond properly while executing a statement, it is called a runtime error. For example, when a number is divided by 0, it results in a runtime error.

9. What are the different types of errors that take place during the execution of a program?


Generally, there are three types of errors that occur in a computer program. They are as follows:

  • Syntax errors
  • Logical errors
  • Runtime errors

10. Distinguish between:

a) Testing and Debugging

b) Syntax error and Logical error – repeated – Refer to III main 2nd question


a)Testing and Debugging


i) Testing is a process in which a program is validated.

ii) Testing is complete when all desired verifications against specifications have been performed.


i)  Debugging is a process in which the errors in the program are removed.

ii) Debugging is finished when there are no errors and the program executes producing the desired result.

b) Syntax error and Logical error – repeated – Refer to III main 2nd question

V Java Programming

  1. The time period of a Simple Pendulum is given by the formula:

Write a program to calculate the time period of a Simple Pendulum by taking length (l) and acceleration due to gravity(g) as inputs. [


class Q1{

void main(double l, double g)  //Input of Length and Acceleration due to gravity


double T,pi=22/7.0;


System.out.println(“Time Period=”+T);


  • Write a program by using class ‘Employee’ to accept Basic Pay of an employee. Calculate the allowances/deductions as given below. Finally find and print the Gross and Net Pay.

Allowances /Deduction rate

Dearness Allowance (DA)        : 30% of the Basic Pay

House Rent Allowance(HRA) : 15% of the Basic Pay

Provident Fund                        : 12.5% of the Basic Pay

Gross Pay=Basic Pay + Dearness Allowance + House Rent Allowance.

Net Pay=Gross Pay-Provident Fund


class Employee{

void main(double basic)


double da,hra,pf,gross,net;

da=30/100.0 * basic;

hra=15/100.0 * basic;

pf=12.5/100 * basic;

gross=basic +da+hra;


System.out.println(“Gross Pay=”+gross);

System.out.println(“Net Pay=”+net);


  • A shopkeeper offers 10% discount on the printed price of a Digital Camera. However, a customer has to pay 6% GST on the remaining amount. Write a program in Java to calculate the amount to be paid by the customer taking printed price as an input.


class Q3{

void main(double price)

{double dis,gst,amt1,amt2;

dis=10/100.0 * price;


gst=6/100.0 * amt1;


System.out.println(“The amount after discount and GST=”+amt2);


  • A shopkeeper offers 30% discount on purchasing articles whereas the other shopkeeper offers two successive discounts 20% and 10% for purchasing the same articles. Write a program in Java to compute and display the discounts. Take the price of the article as the input.


import java.util.*;

public class Q4{

static void main()


Scanner sr=new Scanner(;

double price,xamt,yamt1,yamt2;

System.out.println(“Enter the price of the article”);


xamt=price – 30/100.0 * price;

yamt1=price – 20/100.0 *price;

yamt2= yamt1- 10/100.0* yamt1;

System.out.println(“Price in Shop1=”+xamt);

System.out.println(“Price in Shop2=”+yamt2);


  • Mr.Agarwal invests certain sum at 5% per annum compound interest for three years. Write a program in Java to calculate:

a) the interest for the first year

b) the interest for the second year

c) the amount after three years

Take sum as an input from the user.

Sample Input    : Principal = Rs.5000, Rate = 10% , Time = 3years

Sample Output :

Interest for the first year    = Rs.500

Interest for the second year=Rs.550

Interest for the third year  =Rs.605


class Q5


void main(double p,double r,double t)

{ double si,amt;

t=1;                          //time is set always as one year since it is a yearly calculation

//YEAR 1


System.out.println(“Interest for the first year=”+si);


//YEAR 2

p=amt;                   // 1st year’s amt is 2nd year’s principal


System.out.println(“Interest for the second year=”+si);


//YEAR 3

p=amt;                 // 2nd year’s amt is 3rd year’s principal


System.out.println(“Interest for the third year=”+si);


  • A business man wishes to accumulate 3000 shares of a company. However, he already has some shares of that company valuing Rs.10 (nominal value) which yield 10% dividend per annum and receive Rs.2000 as dividend at the end of the year. Write a program in Java to calculate the number of shares he has and how many more shares to be purchased to make his target.

Hint : No. of Share = Annual dividend *100

                                     Nominal value *div%


import java.util.*;

class Q6{

static void main()

{Scanner sr=new Scanner(;

double nv,div,ad,s,ns,nns;







System.out.println(“The number of shares already possessed=”+(int)ns);

System.out.println(“The number of shares to be purchased=”+(int)nns);


  • Write a program to input the time in seconds. Display the time after converting them into hours, minutes and seconds.

Sample Input    : Time in seconds  5420

Sample Output : 1 Hour 30 Minutes 20 Seconds


class Q7{

static void main(long sec)


long hr,min,rem;









  • 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


import java.util.*;

class Q8_101{

static void main()

{Scanner sr=new Scanner(;

int a,b;

System.out.println(“Enter the values of a and b”);




b=a-b;                                                              //This means b=a+b – b. So b gets a’s value

a=a-b;                                                               //This means a=a+b – a. So now a gets b’s value

System.out.println(“The numbers after swapping are shown below”);

System.out.println(“a=” +a);

System.out.println(“b=” +b);


  • A certain amount is invested at the rate of 10% per annum for 3 years. Find the difference between Compound Interest (CI) and Simple Interest (SI). Write a program to take amount as an input.

Hint : SI= P*R*T        A = P*(1+ R/100)T    and CI=A-P



import java.util.*;

class Q9{

static void main()


double p,r,t,si,ci,a,y,diff;

Scanner sr=new Scanner(;

System.out.println(“Enter the value of P”);





System.out.println(“Simple Interest=”+si);


a= p * Math.pow(y,t);


System.out.println(“Compound Interest=”+ci);


System.out.println(“Difference between compound interest and simple interest=”+diff);


  1. A shopkeeper sells two calculators for the same price. He earns 20% profit on one and suffers a loss of 20% on the other. Write a program to find his total cost price of the calculators by taking selling price as an input.


CP =    SP                                        

            (1+profit/100)      (when profit)

CP =    SP                                         

            (1+loss/100)      (when loss)


import java.util.*;

class Q10{

static void main()


Scanner sr=new Scanner(;

double sp,profit=20,loss=20,cp1,cp2,tot;

System.out.println(“Enter the S.P.”);



cp2=sp/(1- loss/100);


System.out.println(“The C.P. of the first calculator with 20% profit=”+(float)cp1);

System.out.println(“The C.P. of the second calculator with 20% loss=”+(float)cp2);

System.out.println(“The total cost of both the calculators=”+(float)tot);



%d bloggers like this: